gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
// Copyright 2011 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.enterprise.adaptor;
import static java.util.AbstractMap.SimpleEntry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Tests for {@link Journal}.
*/
public class JournalTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private static SimpleEntry<GroupPrincipal, Collection<Principal>>
makePair(GroupPrincipal g, Collection<Principal> members) {
return new SimpleEntry<GroupPrincipal, Collection<Principal>>(g, members);
}
@Test
public void testPushCounts() {
Journal journal = new Journal(new MockTimeProvider());
DocId id = new DocId("id1");
DocId id2 = new DocId("id2");
DocId id3 = new DocId("id3");
DocId id4 = new DocId("id4");
GroupPrincipal g1 = new GroupPrincipal("group1");
GroupPrincipal g2 = new GroupPrincipal("group2");
GroupPrincipal g3 = new GroupPrincipal("group3");
Principal u1 = new UserPrincipal("user1");
Principal u2 = new UserPrincipal("user2");
ArrayList<DocIdPusher.Record> docs = new ArrayList<DocIdPusher.Record>();
docs.add(new DocIdPusher.Record.Builder(id).build());
docs.add(new DocIdPusher.Record.Builder(id2).build());
docs.add(new DocIdPusher.Record.Builder(id3).build());
ArrayList<Map.Entry<GroupPrincipal, Collection<Principal>>> groups =
new ArrayList<Map.Entry<GroupPrincipal, Collection<Principal>>>();
List<Principal> g1members = new ArrayList<Principal>();
List<Principal> g2members = new ArrayList<Principal>();
List<Principal> g3members = new ArrayList<Principal>();
g1members.add(new UserPrincipal("Marc"));
g1members.add(new UserPrincipal("John"));
g2members.add(new UserPrincipal("PJ"));
g3members.add(new UserPrincipal("Bill"));
g3members.add(new UserPrincipal("Tony"));
groups.add(makePair(g1, g1members));
groups.add(makePair(g2, g2members));
journal.recordDocIdPush(docs);
assertEquals(3, journal.getSnapshot().numUniqueDocIdsPushed);
journal.recordDocIdPush(docs);
assertEquals(3, journal.getSnapshot().numUniqueDocIdsPushed);
docs.add(new DocIdPusher.Record.Builder(id4).build());
journal.recordDocIdPush(docs);
assertEquals(4, journal.getSnapshot().numUniqueDocIdsPushed);
journal.recordGroupPush(groups);
assertEquals(2, journal.getSnapshot().numTotalGroupsPushed);
assertEquals(2, journal.getSnapshot().numUniqueGroupsPushed);
assertEquals(3, journal.getSnapshot().numTotalGroupMembersPushed);
journal.recordGroupPush(groups);
assertEquals(4, journal.getSnapshot().numTotalGroupsPushed);
assertEquals(2, journal.getSnapshot().numUniqueGroupsPushed);
assertEquals(6, journal.getSnapshot().numTotalGroupMembersPushed);
groups.add(makePair(g3, g3members));
journal.recordGroupPush(groups);
assertEquals(7, journal.getSnapshot().numTotalGroupsPushed);
assertEquals(3, journal.getSnapshot().numUniqueGroupsPushed);
assertEquals(11, journal.getSnapshot().numTotalGroupMembersPushed);
}
@Test
public void testDisabledPushCounts() {
Journal journal = new Journal(true, new MockTimeProvider());
journal.recordDocIdPush(Collections.singletonList(
new DocIdPusher.Record.Builder(new DocId("id")).build()));
assertEquals(-1, journal.getSnapshot().numUniqueDocIdsPushed);
assertEquals(-1, journal.getSnapshot().numUniqueGroupsPushed);
assertEquals(0, journal.getSnapshot().numTotalGroupsPushed);
assertEquals(0, journal.getSnapshot().numTotalGroupMembersPushed);
}
@Test
public void testUnsupportedDocIdPush() {
class UnsupportedItem implements DocIdSender.Item {};
Journal journal = new Journal(true, new MockTimeProvider());
thrown.expect(IllegalArgumentException.class);
journal.recordDocIdPush(Collections.singletonList(new UnsupportedItem()));
}
@Test
public void testRequestCounts() {
Journal journal = new Journal(new MockTimeProvider());
Journal.JournalSnapshot snapshot = journal.getSnapshot();
assertEquals(0, snapshot.numUniqueGsaRequests);
assertEquals(0, snapshot.numTotalGsaRequests);
assertEquals(0, snapshot.numUniqueNonGsaRequests);
assertEquals(0, snapshot.numTotalNonGsaRequests);
DocId doc1 = new DocId("1");
DocId doc2 = new DocId("2");
journal.recordGsaContentRequest(doc1);
snapshot = journal.getSnapshot();
assertEquals(1, snapshot.numUniqueGsaRequests);
assertEquals(1, snapshot.numTotalGsaRequests);
journal.recordGsaContentRequest(doc1);
snapshot = journal.getSnapshot();
assertEquals(1, snapshot.numUniqueGsaRequests);
assertEquals(2, snapshot.numTotalGsaRequests);
journal.recordGsaContentRequest(doc2);
snapshot = journal.getSnapshot();
assertEquals(2, snapshot.numUniqueGsaRequests);
assertEquals(3, snapshot.numTotalGsaRequests);
assertEquals(0, snapshot.numUniqueNonGsaRequests);
assertEquals(0, snapshot.numTotalNonGsaRequests);
journal.recordNonGsaContentRequest(doc1);
snapshot = journal.getSnapshot();
assertEquals(1, snapshot.numUniqueNonGsaRequests);
assertEquals(1, snapshot.numTotalNonGsaRequests);
journal.recordNonGsaContentRequest(doc1);
snapshot = journal.getSnapshot();
assertEquals(1, snapshot.numUniqueNonGsaRequests);
assertEquals(2, snapshot.numTotalNonGsaRequests);
journal.recordNonGsaContentRequest(doc2);
snapshot = journal.getSnapshot();
assertEquals(2, snapshot.numUniqueNonGsaRequests);
assertEquals(3, snapshot.numTotalNonGsaRequests);
assertEquals(2, snapshot.numUniqueGsaRequests);
assertEquals(3, snapshot.numTotalGsaRequests);
}
@Test
public void testStats() throws InterruptedException {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
timeProvider.autoIncrement = false;
timeProvider.time
= journal.getSnapshot().timeStats[0].pendingStatPeriodEnd;
journal.recordRequestProcessingStart();
Thread thread = new Thread() {
public void run() {
timeProvider.time += 2;
journal.recordRequestProcessingStart();
timeProvider.time += 2;
journal.recordRequestProcessingEnd(10);
}
};
thread.start();
thread.join();
journal.recordRequestProcessingEnd(8);
Journal.JournalSnapshot snapshot = journal.getSnapshot();
Journal.Stat stat
= snapshot.timeStats[0].stats[snapshot.timeStats[0].currentStat];
assertEquals(2, stat.requestProcessingsCount);
assertEquals(6, stat.requestProcessingsDurationSum);
assertEquals(4, stat.requestProcessingsMaxDuration);
assertEquals(18, stat.requestProcessingsThroughput);
// Did it swap out to a new stat correctly?
journal.recordRequestProcessingStart();
long previousTime = timeProvider.time;
timeProvider.time
= journal.getSnapshot().timeStats[0].pendingStatPeriodEnd;
journal.recordRequestProcessingEnd(101);
snapshot = journal.getSnapshot();
stat = snapshot.timeStats[0].stats[snapshot.timeStats[0].currentStat];
assertEquals(1, stat.requestProcessingsCount);
assertEquals(timeProvider.time - previousTime,
stat.requestProcessingsDurationSum);
assertEquals(timeProvider.time - previousTime,
stat.requestProcessingsMaxDuration);
assertEquals(101, stat.requestProcessingsThroughput);
// Does it still have correct values for previous stat?
stat = snapshot.timeStats[0].stats[(snapshot.timeStats[0].currentStat - 1)
% snapshot.timeStats[0].stats.length];
assertEquals(2, stat.requestProcessingsCount);
assertEquals(6, stat.requestProcessingsDurationSum);
assertEquals(4, stat.requestProcessingsMaxDuration);
assertEquals(18, stat.requestProcessingsThroughput);
// Did it clear out everything after a long time?
// Subtract off a reasonable amount of time to prevevent overflow.
timeProvider.time = Long.MAX_VALUE - 1000 * 60 * 60 * 24 * 7;
journal.recordRequestProcessingStart();
journal.recordRequestProcessingEnd(1);
snapshot = journal.getSnapshot();
for (int i = 0; i < snapshot.timeStats[0].stats.length; i++) {
if (i == snapshot.timeStats[0].currentStat) {
continue;
}
stat = snapshot.timeStats[0].stats[i];
assertEquals(0, stat.requestProcessingsCount);
assertEquals(0, stat.requestProcessingsDurationSum);
assertEquals(0, stat.requestProcessingsMaxDuration);
assertEquals(0, stat.requestProcessingsThroughput);
}
}
@Test
public void testFullPushStats() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
timeProvider.autoIncrement = false;
timeProvider.time = 1;
journal.recordFullPushStarted();
timeProvider.time = 2;
journal.recordFullPushSuccessful();
Journal.JournalSnapshot snapshot = journal.getSnapshot();
assertEquals(1, snapshot.lastSuccessfulFullPushStart);
assertEquals(2, snapshot.lastSuccessfulFullPushEnd);
timeProvider.time = 5;
journal.recordFullPushStarted();
timeProvider.time = 7;
journal.recordFullPushInterrupted();
snapshot = journal.getSnapshot();
assertEquals(1, snapshot.lastSuccessfulFullPushStart);
assertEquals(2, snapshot.lastSuccessfulFullPushEnd);
timeProvider.time = 8;
journal.recordFullPushStarted();
timeProvider.time = 9;
journal.recordFullPushFailed();
snapshot = journal.getSnapshot();
assertEquals(1, snapshot.lastSuccessfulFullPushStart);
assertEquals(2, snapshot.lastSuccessfulFullPushEnd);
timeProvider.time = 11;
journal.recordFullPushStarted();
timeProvider.time = 15;
journal.recordFullPushSuccessful();
snapshot = journal.getSnapshot();
assertEquals(11, snapshot.lastSuccessfulFullPushStart);
assertEquals(15, snapshot.lastSuccessfulFullPushEnd);
}
@Test
public void testFullPushStartDouble() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
// Make sure we are past epoch, because that is a special value in the
// journaling code.
timeProvider.time = 1;
journal.recordFullPushStarted();
thrown.expect(IllegalStateException.class);
journal.recordFullPushStarted();
}
@Test
public void testFullPushInterruptedPremature() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
// Make sure we are past epoch, because that is a special value in the
// journaling code.
timeProvider.time = 1;
thrown.expect(IllegalStateException.class);
journal.recordFullPushInterrupted();
}
@Test
public void testFullPushFailedPremature() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
// Make sure we are past epoch, because that is a special value in the
// journaling code.
timeProvider.time = 1;
thrown.expect(IllegalStateException.class);
journal.recordFullPushFailed();
}
@Test
public void testIncrementalPushStats() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
timeProvider.autoIncrement = false;
timeProvider.time = 1;
journal.recordIncrementalPushStarted();
timeProvider.time = 2;
journal.recordIncrementalPushSuccessful();
Journal.JournalSnapshot snapshot = journal.getSnapshot();
assertEquals(1, snapshot.lastSuccessfulIncrementalPushStart);
assertEquals(2, snapshot.lastSuccessfulIncrementalPushEnd);
timeProvider.time = 5;
journal.recordIncrementalPushStarted();
timeProvider.time = 7;
journal.recordIncrementalPushInterrupted();
snapshot = journal.getSnapshot();
assertEquals(1, snapshot.lastSuccessfulIncrementalPushStart);
assertEquals(2, snapshot.lastSuccessfulIncrementalPushEnd);
timeProvider.time = 8;
journal.recordIncrementalPushStarted();
timeProvider.time = 9;
journal.recordIncrementalPushFailed();
snapshot = journal.getSnapshot();
assertEquals(1, snapshot.lastSuccessfulIncrementalPushStart);
assertEquals(2, snapshot.lastSuccessfulIncrementalPushEnd);
timeProvider.time = 11;
journal.recordIncrementalPushStarted();
timeProvider.time = 15;
journal.recordIncrementalPushSuccessful();
snapshot = journal.getSnapshot();
assertEquals(11, snapshot.lastSuccessfulIncrementalPushStart);
assertEquals(15, snapshot.lastSuccessfulIncrementalPushEnd);
}
@Test
public void testIncrementalPushStartDouble() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
// Make sure we are past epoch, because that is a special value in the
// journaling code.
timeProvider.time = 1;
journal.recordIncrementalPushStarted();
thrown.expect(IllegalStateException.class);
journal.recordIncrementalPushStarted();
}
@Test
public void testIncrementalPushInterruptedPremature() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
// Make sure we are past epoch, because that is a special value in the
// journaling code.
timeProvider.time = 1;
thrown.expect(IllegalStateException.class);
journal.recordIncrementalPushInterrupted();
}
@Test
public void testIncrementalPushFailedPremature() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
// Make sure we are past epoch, because that is a special value in the
// journaling code.
timeProvider.time = 1;
thrown.expect(IllegalStateException.class);
journal.recordIncrementalPushFailed();
}
@Test
public void testStatsNoStart() {
Journal journal = new Journal(new MockTimeProvider());
thrown.expect(IllegalStateException.class);
journal.recordRequestProcessingEnd(1);
}
@Test
public void testDefaultTimeProvider() {
new Journal(false);
}
@Test
public void testLastFullPushStatus() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
assertEquals(Journal.CompletionStatus.SUCCESS,
journal.getLastFullPushStatus());
journal.recordFullPushStarted();
journal.recordFullPushInterrupted();
assertEquals(Journal.CompletionStatus.INTERRUPTION,
journal.getLastFullPushStatus());
journal.recordFullPushStarted();
journal.recordFullPushFailed();
assertEquals(Journal.CompletionStatus.FAILURE,
journal.getLastFullPushStatus());
journal.recordFullPushStarted();
journal.recordFullPushSuccessful();
assertEquals(Journal.CompletionStatus.SUCCESS,
journal.getLastFullPushStatus());
}
@Test
public void testLastIncrementalPushStatus() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
assertEquals(Journal.CompletionStatus.SUCCESS,
journal.getLastIncrementalPushStatus());
journal.recordIncrementalPushStarted();
journal.recordIncrementalPushInterrupted();
assertEquals(Journal.CompletionStatus.INTERRUPTION,
journal.getLastIncrementalPushStatus());
journal.recordIncrementalPushStarted();
journal.recordIncrementalPushFailed();
assertEquals(Journal.CompletionStatus.FAILURE,
journal.getLastIncrementalPushStatus());
journal.recordIncrementalPushStarted();
journal.recordIncrementalPushSuccessful();
assertEquals(Journal.CompletionStatus.SUCCESS,
journal.getLastIncrementalPushStatus());
}
@Test
public void testLastGroupPushStatus() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
assertEquals(Journal.CompletionStatus.SUCCESS,
journal.getLastGroupPushStatus());
journal.recordGroupPushStarted();
journal.recordGroupPushInterrupted();
assertEquals(Journal.CompletionStatus.INTERRUPTION,
journal.getLastGroupPushStatus());
journal.recordGroupPushStarted();
journal.recordGroupPushFailed();
assertEquals(Journal.CompletionStatus.FAILURE,
journal.getLastGroupPushStatus());
journal.recordGroupPushStarted();
journal.recordGroupPushSuccessful();
assertEquals(Journal.CompletionStatus.SUCCESS,
journal.getLastGroupPushStatus());
// attempt to start two simultaneous group pushes
try {
journal.recordGroupPushStarted();
journal.recordGroupPushStarted();
fail ("Second group push should have thrown IllegalStateException");
} catch (IllegalStateException e) {
journal.recordGroupPushSuccessful(); // resets currentGroupPushStart
}
// attempt to interrupt a group push (when it was never started)
try {
journal.recordGroupPushInterrupted();
fail ("Interrupting non-existing group push shouldn't have worked");
} catch (IllegalStateException e) {
// ignore expected exception
}
// attempt to mark a group push as a failure (when it was never started)
try {
journal.recordGroupPushFailed();
fail ("Failing non-existing group push shouldn't have worked");
} catch (IllegalStateException e) {
// ignore expected exception
}
}
@Test
public void testRetrieverStatusSource() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
timeProvider.autoIncrement = false;
DocId docId = new DocId("");
final long hourInMillis = 1000 * 60 * 60;
double rate = journal.getRetrieverErrorRate(10);
assertEquals(0., rate, 0.);
journal.recordRequestProcessingStart();
journal.recordRequestProcessingFailure();
rate = journal.getRetrieverErrorRate(10);
assertEquals(1., rate, 0.);
timeProvider.time += hourInMillis;
for (int i = 0; i < 7; i++) {
journal.recordRequestProcessingStart();
journal.recordRequestProcessingEnd(0);
}
rate = journal.getRetrieverErrorRate(10);
assertEquals(1. / 8., rate, 0.);
timeProvider.time += hourInMillis;
for (int i = 0; i < 7; i++) {
journal.recordRequestProcessingStart();
journal.recordRequestProcessingFailure();
}
rate = journal.getRetrieverErrorRate(10);
assertEquals(1. / 2., rate, 0.);
rate = journal.getRetrieverErrorRate(7);
assertEquals(1., rate, 0.);
timeProvider.time += hourInMillis;
for (int i = 0; i < 10; i++) {
journal.recordRequestProcessingStart();
journal.recordRequestProcessingEnd(0);
}
rate = journal.getRetrieverErrorRate(10);
assertEquals(0., rate, 0.);
}
@Test
public void testGsaCrawlingStatusSource() {
final MockTimeProvider timeProvider = new MockTimeProvider();
final Journal journal = new Journal(timeProvider);
timeProvider.autoIncrement = false;
DocId docId = new DocId("");
assertFalse(journal.hasGsaCrawledWithinLastDay());
journal.recordGsaContentRequest(docId);
assertTrue(journal.hasGsaCrawledWithinLastDay());
final long dayInMillis = 1000 * 60 * 60 * 24;
timeProvider.time += 2 * dayInMillis;
assertFalse(journal.hasGsaCrawledWithinLastDay());
}
}
| |
/*
* Copyright (c) Facebook, Inc. and 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 com.facebook.buck.features.apple.project;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter;
import com.facebook.buck.core.util.log.Logger;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.rules.args.Arg;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
/** Generates a set of Xcode build configurations from given cxxPlatform */
class CxxPlatformXcodeConfigGenerator {
public static final String SDKROOT = "SDKROOT";
public static final String CLANG_CXX_LANGUAGE_STANDARD = "CLANG_CXX_LANGUAGE_STANDARD";
public static final String CLANG_CXX_LIBRARY = "CLANG_CXX_LIBRARY";
public static final String OTHER_CPLUSPLUSFLAGS = "OTHER_CPLUSPLUSFLAGS";
public static final String ARCHS = "ARCHS";
public static final String DEBUG_BUILD_CONFIGURATION_NAME = "Debug";
public static final String PROFILE_BUILD_CONFIGURATION_NAME = "Profile";
public static final String RELEASE_BUILD_CONFIGURATION_NAME = "Release";
private static final Logger LOG = Logger.get(CxxPlatformXcodeConfigGenerator.class);
private CxxPlatformXcodeConfigGenerator() {}
public static ImmutableMap<String, String> getAppleXcodeTargetBuildConfigurationsFromCxxPlatform(
CxxPlatform cxxPlatform,
Map<String, String> appendedConfig,
SourcePathResolverAdapter pathResolver) {
ArrayList<String> notProcessedCxxFlags =
new ArrayList<>(Arg.stringify(cxxPlatform.getCxxflags(), pathResolver));
LinkedHashMap<String, String> notProcessedAppendedConfig = new LinkedHashMap<>(appendedConfig);
ImmutableMap.Builder<String, String> configBuilder = ImmutableMap.builder();
setSdkRootAndDeploymentTargetValues(
configBuilder, cxxPlatform, notProcessedCxxFlags, notProcessedAppendedConfig);
removeArchsValue(notProcessedCxxFlags, notProcessedAppendedConfig);
return configBuilder.build();
}
public static ImmutableMap<String, String> getCxxXcodeTargetBuildConfigurationsFromCxxPlatform(
CxxPlatform cxxPlatform,
Map<String, String> appendedConfig,
SourcePathResolverAdapter pathResolver) {
ArrayList<String> notProcessedCxxFlags =
new ArrayList<>(Arg.stringify(cxxPlatform.getCxxflags(), pathResolver));
LinkedHashMap<String, String> notProcessedAppendedConfig = new LinkedHashMap<>(appendedConfig);
ImmutableMap.Builder<String, String> configBuilder = ImmutableMap.builder();
setSdkRootAndDeploymentTargetValues(
configBuilder, cxxPlatform, notProcessedCxxFlags, notProcessedAppendedConfig);
removeArchsValue(notProcessedCxxFlags, notProcessedAppendedConfig);
setLanguageStandardValue(configBuilder, notProcessedCxxFlags, notProcessedAppendedConfig);
setCxxLibraryValue(notProcessedCxxFlags, notProcessedAppendedConfig, configBuilder);
setOtherCplusplusFlagsValue(configBuilder, notProcessedCxxFlags, notProcessedAppendedConfig);
setFlagsFromNotProcessedAppendedConfig(configBuilder, notProcessedAppendedConfig);
return configBuilder.build();
}
public static ImmutableMap<String, ImmutableMap<String, String>>
getDefaultXcodeBuildConfigurationsFromCxxPlatform(
CxxPlatform cxxPlatform,
Map<String, String> appendedConfig,
SourcePathResolverAdapter pathResolver) {
ImmutableMap<String, String> config =
getCxxXcodeTargetBuildConfigurationsFromCxxPlatform(
cxxPlatform, appendedConfig, pathResolver);
return new ImmutableMap.Builder<String, ImmutableMap<String, String>>()
.put(DEBUG_BUILD_CONFIGURATION_NAME, config)
.put(PROFILE_BUILD_CONFIGURATION_NAME, config)
.put(RELEASE_BUILD_CONFIGURATION_NAME, config)
.build();
}
private static void setFlagsFromNotProcessedAppendedConfig(
ImmutableMap.Builder<String, String> configBuilder,
Map<String, String> notProcessedAppendedConfig) {
for (Map.Entry<String, String> entry :
ImmutableSet.copyOf(notProcessedAppendedConfig.entrySet())) {
if (entry.getValue().length() > 0) {
configBuilder.put(entry);
}
notProcessedAppendedConfig.remove(entry.getKey());
}
}
private static void setOtherCplusplusFlagsValue(
ImmutableMap.Builder<String, String> configBuilder,
List<String> notProcessedCxxFlags,
Map<String, String> notProcessedAppendedConfig) {
if (notProcessedCxxFlags.isEmpty()) {
return;
}
String otherCplusplusFlagsValue =
getOtherCplusplusFlags(notProcessedAppendedConfig, notProcessedCxxFlags);
configBuilder.put(OTHER_CPLUSPLUSFLAGS, otherCplusplusFlagsValue);
notProcessedAppendedConfig.remove(OTHER_CPLUSPLUSFLAGS);
}
private static void setCxxLibraryValue(
List<String> notProcessedCxxFlags,
Map<String, String> notProcessedAppendedConfig,
ImmutableMap.Builder<String, String> configBuilder) {
String clangCxxLibraryValue =
getConfigValueForKey(
CLANG_CXX_LIBRARY,
notProcessedCxxFlags,
"-stdlib=",
Optional.empty(),
notProcessedAppendedConfig);
if (clangCxxLibraryValue != null) {
configBuilder.put(CLANG_CXX_LIBRARY, clangCxxLibraryValue);
notProcessedAppendedConfig.remove(CLANG_CXX_LIBRARY);
}
}
private static void setSdkRootAndDeploymentTargetValues(
ImmutableMap.Builder<String, String> configBuilder,
CxxPlatform cxxPlatform,
List<String> notProcessedCxxFlags,
Map<String, String> notProcessedAppendedConfig) {
String sdkRootValue = getSdkRoot(cxxPlatform, notProcessedCxxFlags, notProcessedAppendedConfig);
if (sdkRootValue != null) {
configBuilder.put(SDKROOT, sdkRootValue);
notProcessedAppendedConfig.remove(SDKROOT);
setDeploymentTargetValue(
configBuilder, sdkRootValue, notProcessedCxxFlags, notProcessedAppendedConfig);
}
}
private static void removeArchsValue(
List<String> notProcessedCxxFlags, Map<String, String> notProcessedAppendedConfig) {
// we need to get rid of ARCH setting so Xcode would be able to let user switch between
// iOS simulator and iOS device without forcing the ARCH of resulting binary
getArchs(notProcessedAppendedConfig, notProcessedCxxFlags);
notProcessedAppendedConfig.remove(ARCHS);
}
private static void setLanguageStandardValue(
ImmutableMap.Builder<String, String> configBuilder,
List<String> notProcessedCxxFlags,
Map<String, String> notProcessedAppendedConfig) {
String clangCxxLanguageStandardValue =
getConfigValueForKey(
CLANG_CXX_LANGUAGE_STANDARD,
notProcessedCxxFlags,
"-std=",
Optional.empty(),
notProcessedAppendedConfig);
if (clangCxxLanguageStandardValue != null) {
configBuilder.put(CLANG_CXX_LANGUAGE_STANDARD, clangCxxLanguageStandardValue);
notProcessedAppendedConfig.remove(CLANG_CXX_LANGUAGE_STANDARD);
}
}
private static void setDeploymentTargetValue(
ImmutableMap.Builder<String, String> configBuilder,
String sdkRootValue,
List<String> notProcessedCxxFlags,
Map<String, String> notProcessedAppendedConfig) {
String deploymentTargetKey = sdkRootValue.toUpperCase() + "_DEPLOYMENT_TARGET"; // magic
String deploymentTargetValue =
getConfigValueForKey(
deploymentTargetKey,
notProcessedCxxFlags,
"-m", // format is like "-mmacosx-version-min=10.9"
Optional.of("-version-min="),
notProcessedAppendedConfig);
if (deploymentTargetValue != null) {
configBuilder.put(deploymentTargetKey, deploymentTargetValue);
notProcessedAppendedConfig.remove(deploymentTargetKey);
}
}
private static String getOtherCplusplusFlags(
Map<String, String> appendedConfig, List<String> notProcessesCxxFlags) {
String value = appendedConfig.get(OTHER_CPLUSPLUSFLAGS);
ArrayList<String> cPlusPlusFlags = new ArrayList<String>();
if (value != null) {
cPlusPlusFlags.add(value);
}
cPlusPlusFlags.addAll(notProcessesCxxFlags);
value = Joiner.on(" ").join(cPlusPlusFlags);
notProcessesCxxFlags.removeAll(cPlusPlusFlags);
return value;
}
@Nullable
private static String getArchs(
Map<String, String> appendedConfig, List<String> notProcessesCxxFlags) {
String value = appendedConfig.get(ARCHS);
if (value == null) {
int indexOfArch = notProcessesCxxFlags.indexOf("-arch");
if (indexOfArch != -1) {
value = notProcessesCxxFlags.get(indexOfArch + 1);
notProcessesCxxFlags.remove(indexOfArch + 1);
notProcessesCxxFlags.remove(indexOfArch);
} else {
LOG.debug("Can't determine ARCH value");
}
}
return value;
}
@Nullable
private static String getSdkRoot(
CxxPlatform cxxPlatform,
List<String> notProcessesCxxFlags,
Map<String, String> appendedConfig) {
String value = appendedConfig.get(SDKROOT);
if (value == null) {
if (cxxPlatform.getFlavor().getName().startsWith("iphone")) {
value = "iphoneos";
} else if (cxxPlatform.getFlavor().getName().startsWith("macosx")) {
value = "macosx";
} else {
LOG.debug("Can't determine %s", SDKROOT);
}
int indexOfSysroot = notProcessesCxxFlags.indexOf("-isysroot");
if (indexOfSysroot != -1) {
notProcessesCxxFlags.remove(indexOfSysroot + 1);
notProcessesCxxFlags.remove(indexOfSysroot);
}
}
return value;
}
/**
* If appendedConfig has value for given key, it will be used. Otherwise, this method will attempt
* to extract value from cxxFlags.
*/
@Nullable
private static String getConfigValueForKey(
String key,
List<String> cxxFlags,
String prefix,
Optional<String> containmentString,
Map<String, String> appendedConfig) {
String value = appendedConfig.get(key);
if (value == null) {
int indexOfCxxLibrarySpec = -1;
for (String item : cxxFlags) {
if (containmentString.isPresent() && !item.contains(containmentString.get())) {
continue;
}
if (item.startsWith(prefix)) {
indexOfCxxLibrarySpec = cxxFlags.indexOf(item);
value = item.substring(item.indexOf('=') + 1);
break;
}
}
if (indexOfCxxLibrarySpec != -1) {
cxxFlags.remove(indexOfCxxLibrarySpec);
} else {
LOG.debug("Cannot determine value of %s", key);
}
}
return value;
}
}
| |
/**
*/
package substationStandard.LNNodes.LNGroupP.util;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.util.Switch;
import substationStandard.LNNodes.DomainLNs.DomainLN;
import substationStandard.LNNodes.LNGroupP.*;
/**
* <!-- begin-user-doc -->
* The <b>Switch</b> for the model's inheritance hierarchy.
* It supports the call {@link #doSwitch(EObject) doSwitch(object)}
* to invoke the <code>caseXXX</code> method for each class of the model,
* starting with the actual class of the object
* and proceeding up the inheritance hierarchy
* until a non-null result is returned,
* which is the result of the switch.
* <!-- end-user-doc -->
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage
* @generated
*/
public class LNGroupPSwitch<T> extends Switch<T> {
/**
* The cached model package
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static LNGroupPPackage modelPackage;
/**
* Creates an instance of the switch.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LNGroupPSwitch() {
if (modelPackage == null) {
modelPackage = LNGroupPPackage.eINSTANCE;
}
}
/**
* Checks whether this is a switch for the given package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param ePackage the package in question.
* @return whether this is a switch for the given package.
* @generated
*/
@Override
protected boolean isSwitchFor(EPackage ePackage) {
return ePackage == modelPackage;
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
@Override
protected T doSwitch(int classifierID, EObject theEObject) {
switch (classifierID) {
case LNGroupPPackage.GROUP_P: {
GroupP groupP = (GroupP)theEObject;
T result = caseGroupP(groupP);
if (result == null) result = caseDomainLN(groupP);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PDIF: {
PDIF pdif = (PDIF)theEObject;
T result = casePDIF(pdif);
if (result == null) result = caseGroupP(pdif);
if (result == null) result = caseDomainLN(pdif);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PDIR: {
PDIR pdir = (PDIR)theEObject;
T result = casePDIR(pdir);
if (result == null) result = caseGroupP(pdir);
if (result == null) result = caseDomainLN(pdir);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PFRC: {
PFRC pfrc = (PFRC)theEObject;
T result = casePFRC(pfrc);
if (result == null) result = caseGroupP(pfrc);
if (result == null) result = caseDomainLN(pfrc);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PHAR: {
PHAR phar = (PHAR)theEObject;
T result = casePHAR(phar);
if (result == null) result = caseGroupP(phar);
if (result == null) result = caseDomainLN(phar);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.POPF: {
POPF popf = (POPF)theEObject;
T result = casePOPF(popf);
if (result == null) result = caseGroupP(popf);
if (result == null) result = caseDomainLN(popf);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PPAM: {
PPAM ppam = (PPAM)theEObject;
T result = casePPAM(ppam);
if (result == null) result = caseGroupP(ppam);
if (result == null) result = caseDomainLN(ppam);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PDIS: {
PDIS pdis = (PDIS)theEObject;
T result = casePDIS(pdis);
if (result == null) result = caseGroupP(pdis);
if (result == null) result = caseDomainLN(pdis);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PDOP: {
PDOP pdop = (PDOP)theEObject;
T result = casePDOP(pdop);
if (result == null) result = caseGroupP(pdop);
if (result == null) result = caseDomainLN(pdop);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PHIZ: {
PHIZ phiz = (PHIZ)theEObject;
T result = casePHIZ(phiz);
if (result == null) result = caseGroupP(phiz);
if (result == null) result = caseDomainLN(phiz);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PIOC: {
PIOC pioc = (PIOC)theEObject;
T result = casePIOC(pioc);
if (result == null) result = caseGroupP(pioc);
if (result == null) result = caseDomainLN(pioc);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PMRI: {
PMRI pmri = (PMRI)theEObject;
T result = casePMRI(pmri);
if (result == null) result = caseGroupP(pmri);
if (result == null) result = caseDomainLN(pmri);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PMSS: {
PMSS pmss = (PMSS)theEObject;
T result = casePMSS(pmss);
if (result == null) result = caseGroupP(pmss);
if (result == null) result = caseDomainLN(pmss);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PSCH: {
PSCH psch = (PSCH)theEObject;
T result = casePSCH(psch);
if (result == null) result = caseGroupP(psch);
if (result == null) result = caseDomainLN(psch);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PSDE: {
PSDE psde = (PSDE)theEObject;
T result = casePSDE(psde);
if (result == null) result = caseGroupP(psde);
if (result == null) result = caseDomainLN(psde);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PDUP: {
PDUP pdup = (PDUP)theEObject;
T result = casePDUP(pdup);
if (result == null) result = caseGroupP(pdup);
if (result == null) result = caseDomainLN(pdup);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PTEF: {
PTEF ptef = (PTEF)theEObject;
T result = casePTEF(ptef);
if (result == null) result = caseGroupP(ptef);
if (result == null) result = caseDomainLN(ptef);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PTOC: {
PTOC ptoc = (PTOC)theEObject;
T result = casePTOC(ptoc);
if (result == null) result = caseGroupP(ptoc);
if (result == null) result = caseDomainLN(ptoc);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PTOF: {
PTOF ptof = (PTOF)theEObject;
T result = casePTOF(ptof);
if (result == null) result = caseGroupP(ptof);
if (result == null) result = caseDomainLN(ptof);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PTOV: {
PTOV ptov = (PTOV)theEObject;
T result = casePTOV(ptov);
if (result == null) result = caseGroupP(ptov);
if (result == null) result = caseDomainLN(ptov);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PTTR: {
PTTR pttr = (PTTR)theEObject;
T result = casePTTR(pttr);
if (result == null) result = caseGroupP(pttr);
if (result == null) result = caseDomainLN(pttr);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PTUC: {
PTUC ptuc = (PTUC)theEObject;
T result = casePTUC(ptuc);
if (result == null) result = caseGroupP(ptuc);
if (result == null) result = caseDomainLN(ptuc);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PTUF: {
PTUF ptuf = (PTUF)theEObject;
T result = casePTUF(ptuf);
if (result == null) result = caseGroupP(ptuf);
if (result == null) result = caseDomainLN(ptuf);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PVOC: {
PVOC pvoc = (PVOC)theEObject;
T result = casePVOC(pvoc);
if (result == null) result = caseGroupP(pvoc);
if (result == null) result = caseDomainLN(pvoc);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PVPH: {
PVPH pvph = (PVPH)theEObject;
T result = casePVPH(pvph);
if (result == null) result = caseGroupP(pvph);
if (result == null) result = caseDomainLN(pvph);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PTRC: {
PTRC ptrc = (PTRC)theEObject;
T result = casePTRC(ptrc);
if (result == null) result = caseGroupP(ptrc);
if (result == null) result = caseDomainLN(ptrc);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PTUV: {
PTUV ptuv = (PTUV)theEObject;
T result = casePTUV(ptuv);
if (result == null) result = caseGroupP(ptuv);
if (result == null) result = caseDomainLN(ptuv);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PUPF: {
PUPF pupf = (PUPF)theEObject;
T result = casePUPF(pupf);
if (result == null) result = caseGroupP(pupf);
if (result == null) result = caseDomainLN(pupf);
if (result == null) result = defaultCase(theEObject);
return result;
}
case LNGroupPPackage.PZSU: {
PZSU pzsu = (PZSU)theEObject;
T result = casePZSU(pzsu);
if (result == null) result = caseGroupP(pzsu);
if (result == null) result = caseDomainLN(pzsu);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
}
/**
* Returns the result of interpreting the object as an instance of '<em>Group P</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Group P</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseGroupP(GroupP object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PDIF</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PDIF</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePDIF(PDIF object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PDIR</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PDIR</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePDIR(PDIR object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PFRC</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PFRC</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePFRC(PFRC object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PHAR</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PHAR</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePHAR(PHAR object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>POPF</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>POPF</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePOPF(POPF object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PPAM</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PPAM</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePPAM(PPAM object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PDIS</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PDIS</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePDIS(PDIS object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PDOP</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PDOP</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePDOP(PDOP object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PHIZ</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PHIZ</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePHIZ(PHIZ object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PIOC</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PIOC</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePIOC(PIOC object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PMRI</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PMRI</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePMRI(PMRI object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PMSS</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PMSS</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePMSS(PMSS object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PSCH</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PSCH</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePSCH(PSCH object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PSDE</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PSDE</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePSDE(PSDE object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PDUP</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PDUP</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePDUP(PDUP object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PTEF</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PTEF</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePTEF(PTEF object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PTOC</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PTOC</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePTOC(PTOC object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PTOF</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PTOF</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePTOF(PTOF object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PTOV</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PTOV</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePTOV(PTOV object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PTTR</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PTTR</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePTTR(PTTR object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PTUC</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PTUC</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePTUC(PTUC object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PTUF</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PTUF</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePTUF(PTUF object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PVOC</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PVOC</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePVOC(PVOC object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PVPH</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PVPH</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePVPH(PVPH object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PTRC</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PTRC</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePTRC(PTRC object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PTUV</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PTUV</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePTUV(PTUV object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PUPF</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PUPF</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePUPF(PUPF object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>PZSU</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>PZSU</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T casePZSU(PZSU object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Domain LN</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Domain LN</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseDomainLN(DomainLN object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch, but this is the last case anyway.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>EObject</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject)
* @generated
*/
@Override
public T defaultCase(EObject object) {
return null;
}
} //LNGroupPSwitch
| |
package controlP5;
/**
* controlP5 is a processing gui library.
*
* 2006-2012 by Andreas Schlegel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*
* @author Andreas Schlegel (http://www.sojamo.de)
* @modified 05/30/2012
* @version 0.7.5
*
*/
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import processing.core.PApplet;
/**
* A matrix is a 2d array with a pointer that traverses through the matrix in a timed interval. if
* an item of a matrix-column is active, the x and y position of the corresponding cell will trigger
* an event and notify the program. see the ControlP5matrix example for more information.
*
* @example controllers/ControlP5matrix
*/
public class Matrix extends Controller<Matrix> {
protected int cnt;
protected int[][] _myCells;
protected int stepX;
protected int stepY;
protected int cellX;
protected int cellY;
protected boolean isPressed;
protected int _myCellX;
protected int _myCellY;
protected int sum;
protected int _myInterval = 100;
protected int currentX = -1;
protected int currentY = -1;
protected int _myMode = SINGLE_ROW;
private Thread t;
protected int gapX = 1;
protected int gapY = 1;
private Object _myPlug;
private String _myPlugName;
/**
* Convenience constructor to extend Matrix.
*
* @example use/ControlP5extendController
* @param theControlP5
* @param theName
*/
public Matrix(ControlP5 theControlP5, String theName) {
this(theControlP5, theControlP5.getDefaultTab(), theName, 10, 10, 0, 0, 100, 100);
theControlP5.register(theControlP5.papplet, theName, this);
}
public Matrix(ControlP5 theControlP5, ControllerGroup<?> theParent, String theName, int theCellX, int theCellY, int theX, int theY, int theWidth, int theHeight) {
super(theControlP5, theParent, theName, theX, theY, theWidth, theHeight);
_myInterval = 100;
setGrid(theCellX, theCellY);
_myPlug = cp5.papplet;
_myPlugName = getName();
_myCaptionLabel.align(ControlP5.LEFT, ControlP5.BOTTOM_OUTSIDE);
_myCaptionLabel.setPadding(0, 4);
runThread();
}
public Matrix setGrid(int theCellX, int theCellY) {
_myCellX = theCellX;
_myCellY = theCellY;
sum = _myCellX * _myCellY;
stepX = width / _myCellX;
stepY = height / _myCellY;
_myCells = new int[_myCellX][_myCellY];
for (int x = 0; x < _myCellX; x++) {
for (int y = 0; y < _myCellY; y++) {
_myCells[x][y] = 0;
}
}
return this;
}
/**
* set the speed of intervals in millis iterating through the matrix.
*
* @param theInterval int
* @return Matrix
*/
public Matrix setInterval(int theInterval) {
_myInterval = theInterval;
return this;
}
public int getInterval() {
return _myInterval;
}
@ControlP5.Invisible
public Matrix updateInternalEvents(PApplet theApplet) {
setIsInside(inside());
if (getIsInside()) {
if (isPressed) {
int tX = (int) ((theApplet.mouseX - position.x) / stepX);
int tY = (int) ((theApplet.mouseY - position.y) / stepY);
if (tX != currentX || tY != currentY) {
tX = PApplet.min(PApplet.max(0, tX), _myCellX);
tY = PApplet.min(PApplet.max(0, tY), _myCellY);
boolean isMarkerActive = (_myCells[tX][tY] == 1) ? true : false;
switch (_myMode) {
default:
case (SINGLE_COLUMN):
for (int i = 0; i < _myCellY; i++) {
_myCells[tX][i] = 0;
}
_myCells[tX][tY] = (!isMarkerActive) ? 1 : _myCells[tX][tY];
break;
case (SINGLE_ROW):
for (int i = 0; i < _myCellY; i++) {
_myCells[tX][i] = 0;
}
_myCells[tX][tY] = (!isMarkerActive) ? 1 : _myCells[tX][tY];
break;
case (MULTIPLES):
_myCells[tX][tY] = (_myCells[tX][tY] == 1) ? 0 : 1;
break;
}
currentX = tX;
currentY = tY;
}
}
}
return this;
}
protected void onEnter() {
isActive = true;
}
protected void onLeave() {
isActive = false;
}
@ControlP5.Invisible
public void mousePressed() {
isActive = getIsInside();
if (getIsInside()) {
isPressed = true;
}
}
protected void mouseReleasedOutside() {
mouseReleased();
}
@ControlP5.Invisible
public void mouseReleased() {
if (isActive) {
isActive = false;
}
isPressed = false;
currentX = -1;
currentY = -1;
}
@Override
public Matrix setValue(float theValue) {
_myValue = theValue;
broadcast(FLOAT);
return this;
}
@Override
public Matrix update() {
return setValue(_myValue);
}
public Matrix setGap(int theX, int theY) {
gapX = theX;
gapY = theY;
return this;
}
public Matrix plugTo(Object theObject) {
_myPlug = theObject;
return this;
}
public Matrix plugTo(Object theObject, String thePlugName) {
_myPlug = theObject;
_myPlugName = thePlugName;
return this;
}
/**
* set the state of a particular cell inside a matrix. use true or false for parameter theValue
*
* @param theX
* @param theY
* @param theValue
* @return Matrix
*/
public Matrix set(int theX, int theY, boolean theValue) {
_myCells[theX][theY] = (theValue == true) ? 1 : 0;
return this;
}
public boolean get(int theX, int theY) {
return _myCells[theX][theY] == 1 ? true : false;
}
public Matrix clear() {
for (int x = 0; x < _myCells.length; x++) {
for (int y = 0; y < _myCells[x].length; y++) {
_myCells[x][y] = 0;
}
}
return this;
}
public static int getX(int thePosition) {
return ((thePosition >> 0) & 0xff);
}
public static int getY(int thePosition) {
return ((thePosition >> 8) & 0xff);
}
public static int getX(float thePosition) {
return (((int) thePosition >> 0) & 0xff);
}
public static int getY(float thePosition) {
return (((int) thePosition >> 8) & 0xff);
}
public Matrix setCells(int[][] theCells) {
setGrid(theCells.length, theCells[0].length);
_myCells = theCells;
return this;
}
public int[][] getCells() {
return _myCells;
}
private void triggerEventFromThread() {
cnt += 1;
cnt %= _myCellX;
for (int i = 0; i < _myCellY; i++) {
if (_myCells[cnt][i] == 1) {
_myValue = 0;
_myValue = (cnt << 0) + (i << 8);
setValue(_myValue);
try {
Method method = _myPlug.getClass().getMethod(_myPlugName, int.class, int.class);
method.setAccessible(true);
method.invoke(_myPlug, cnt, i);
} catch (SecurityException ex) {
ex.printStackTrace();
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
}
}
}
}
private void runThread() {
if (t == null) {
t = new Thread(getName()) {
public void run() {
while (true) {
triggerEventFromThread();
try {
sleep(_myInterval);
} catch (InterruptedException e) {
// throw new RuntimeException(e);
}
}
}
};
t.start();
}
}
@Override
public void remove() {
if (t != null) {
t.interrupt();
}
super.remove();
}
/**
* use setMode to change the cell-activation which by default is ControlP5.SINGLE_ROW, 1 active
* cell per row, but can be changed to ControlP5.SINGLE_COLUMN or ControlP5.MULTIPLES
*
* @param theMode return Matrix
*/
public Matrix setMode(int theMode) {
_myMode = theMode;
return this;
}
public int getMode() {
return _myMode;
}
@Override
@ControlP5.Invisible
public Matrix updateDisplayMode(int theMode) {
_myDisplayMode = theMode;
switch (theMode) {
case (DEFAULT):
_myControllerView = new MatrixView();
break;
case (IMAGE):
case (SPRITE):
case (CUSTOM):
default:
break;
}
return this;
}
class MatrixView implements ControllerView<Matrix> {
public void display(PApplet theApplet, Matrix theController) {
theApplet.noStroke();
for (int x = 0; x < _myCellX; x++) {
for (int y = 0; y < _myCellY; y++) {
if (_myCells[x][y] == 1) {
theApplet.fill(color.getActive());
theApplet.rect(x * stepX, y * stepY, stepX - gapX, stepY - gapY);
} else {
theApplet.fill(color.getBackground());
theApplet.rect(x * stepX, y * stepY, stepX - gapX, stepY - gapY);
}
}
}
if (isInside()) {
int x = (int) ((theApplet.mouseX - position.x) / stepX);
int y = (int) ((theApplet.mouseY - position.y) / stepY);
if (x >= 0 && x < _myCellX && y >= 0 && y < _myCellY) {
theApplet.fill(_myCells[x][y] == 1 ? color.getActive() : color.getForeground());
theApplet.rect(x * stepX, y * stepY, stepX - gapX, stepY - gapY);
}
}
theApplet.fill(color.getActive());
theApplet.rect(cnt * stepX, 0, 1, height - gapY);
if (isLabelVisible) {
_myCaptionLabel.draw(theApplet, 0, 0, theController);
}
}
}
}
| |
/*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.android;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import com.facebook.buck.android.dalvik.EstimateDexWeightStep;
import com.facebook.buck.android.toolchain.AndroidPlatformTarget;
import com.facebook.buck.core.build.buildable.context.FakeBuildableContext;
import com.facebook.buck.core.build.context.BuildContext;
import com.facebook.buck.core.build.context.FakeBuildContext;
import com.facebook.buck.core.build.execution.context.ExecutionContext;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.rules.TestBuildRuleParams;
import com.facebook.buck.core.rules.attr.BuildOutputInitializer;
import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver;
import com.facebook.buck.core.sourcepath.resolver.impl.DefaultSourcePathResolver;
import com.facebook.buck.core.toolchain.tool.impl.testutil.SimpleTool;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.jvm.core.JavaLibrary;
import com.facebook.buck.jvm.java.DefaultJavaLibrary;
import com.facebook.buck.jvm.java.FakeJavaLibrary;
import com.facebook.buck.jvm.java.JavaLibraryBuilder;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.TestExecutionContext;
import com.facebook.buck.testutil.MoreAsserts;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
public class DexProducedFromJavaLibraryThatContainsClassFilesTest {
@Test
public void testGetBuildStepsWhenThereAreClassesToDex() throws IOException, InterruptedException {
ProjectFilesystem filesystem = FakeProjectFilesystem.createJavaOnlyFilesystem();
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
SourcePathResolver pathResolver =
DefaultSourcePathResolver.from(new SourcePathRuleFinder(graphBuilder));
FakeJavaLibrary javaLibraryRule =
new FakeJavaLibrary(
BuildTargetFactory.newInstance(filesystem.getRootPath(), "//foo:bar"),
filesystem,
ImmutableSortedSet.of()) {
@Override
public ImmutableSortedMap<String, HashCode> getClassNamesToHashes() {
return ImmutableSortedMap.of("com/example/Foo", HashCode.fromString("cafebabe"));
}
};
graphBuilder.addToIndex(javaLibraryRule);
Path jarOutput =
BuildTargetPaths.getGenPath(filesystem, javaLibraryRule.getBuildTarget(), "%s.jar");
javaLibraryRule.setOutputFile(jarOutput.toString());
BuildContext context =
FakeBuildContext.withSourcePathResolver(pathResolver)
.withBuildCellRootPath(filesystem.getRootPath());
FakeBuildableContext buildableContext = new FakeBuildableContext();
Path dexOutput =
BuildTargetPaths.getGenPath(
filesystem,
javaLibraryRule.getBuildTarget().withFlavors(AndroidBinaryGraphEnhancer.DEX_FLAVOR),
"%s.dex.jar");
createFiles(filesystem, dexOutput.toString(), jarOutput.toString());
AndroidPlatformTarget androidPlatformTarget =
AndroidPlatformTarget.of(
"android",
Paths.get(""),
Collections.emptyList(),
() -> new SimpleTool(""),
() -> new SimpleTool(""),
Paths.get(""),
Paths.get(""),
Paths.get(""),
Paths.get("/usr/bin/dx"),
Paths.get(""),
Paths.get(""),
Paths.get(""),
Paths.get(""));
BuildTarget buildTarget =
BuildTargetFactory.newInstance(filesystem.getRootPath(), "//foo:bar#dex");
BuildRuleParams params = TestBuildRuleParams.create();
DexProducedFromJavaLibrary preDex =
new DexProducedFromJavaLibrary(
buildTarget, filesystem, androidPlatformTarget, params, javaLibraryRule, DxStep.DX);
List<Step> steps = preDex.getBuildSteps(context, buildableContext);
ExecutionContext executionContext = TestExecutionContext.newBuilder().build();
String expectedDxCommand =
String.format(
"%s --dex --no-optimize --force-jumbo --output %s %s",
Paths.get("/usr/bin/dx"), filesystem.resolve(dexOutput), filesystem.resolve(jarOutput));
MoreAsserts.assertSteps(
"Generate bar.dex.jar.",
ImmutableList.of(
String.format("rm -f %s", dexOutput),
String.format("mkdir -p %s", dexOutput.getParent()),
"estimate_dex_weight",
"(cd " + filesystem.getRootPath() + " && " + expectedDxCommand + ")",
String.format("zip-scrub %s", filesystem.resolve(dexOutput)),
"record_dx_success"),
steps,
executionContext);
((EstimateDexWeightStep) steps.get(2)).setWeightEstimateForTesting(250);
Step recordArtifactAndMetadataStep = steps.get(5);
int exitCode = recordArtifactAndMetadataStep.execute(executionContext).getExitCode();
assertEquals(0, exitCode);
MoreAsserts.assertContainsOne(
"The generated .dex.jar file should be in the set of recorded artifacts.",
buildableContext.getRecordedArtifacts(),
BuildTargetPaths.getGenPath(filesystem, buildTarget, "%s.dex.jar"));
BuildOutputInitializer<DexProducedFromJavaLibrary.BuildOutput> outputInitializer =
preDex.getBuildOutputInitializer();
outputInitializer.initializeFromDisk(pathResolver);
assertEquals(250, outputInitializer.getBuildOutput().weightEstimate);
}
private void createFiles(ProjectFilesystem filesystem, String... paths) throws IOException {
Path root = filesystem.getRootPath();
for (String path : paths) {
Path resolved = root.resolve(path);
Files.createDirectories(resolved.getParent());
Files.write(resolved, "".getBytes(UTF_8));
}
}
@Test
public void testGetBuildStepsWhenThereAreNoClassesToDex() throws Exception {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
DefaultJavaLibrary javaLibrary =
JavaLibraryBuilder.createBuilder("//foo:bar").build(graphBuilder);
javaLibrary
.getBuildOutputInitializer()
.setBuildOutputForTests(new JavaLibrary.Data(ImmutableSortedMap.of()));
BuildContext context = FakeBuildContext.NOOP_CONTEXT;
FakeBuildableContext buildableContext = new FakeBuildableContext();
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
BuildTarget buildTarget = BuildTargetFactory.newInstance("//foo:bar#dex");
BuildRuleParams params = TestBuildRuleParams.create();
DexProducedFromJavaLibrary preDex =
new DexProducedFromJavaLibrary(
buildTarget,
projectFilesystem,
TestAndroidPlatformTargetFactory.create(),
params,
javaLibrary,
DxStep.DX);
List<Step> steps = preDex.getBuildSteps(context, buildableContext);
Path dexOutput = BuildTargetPaths.getGenPath(projectFilesystem, buildTarget, "%s.dex.jar");
ExecutionContext executionContext = TestExecutionContext.newBuilder().build();
MoreAsserts.assertSteps(
"Do not generate a .dex.jar file.",
ImmutableList.of(
String.format("rm -f %s", dexOutput),
String.format("mkdir -p %s", dexOutput.getParent()),
"record_empty_dx"),
steps,
executionContext);
Step recordArtifactAndMetadataStep = steps.get(2);
assertThat(recordArtifactAndMetadataStep.getShortName(), startsWith("record_"));
int exitCode = recordArtifactAndMetadataStep.execute(executionContext).getExitCode();
assertEquals(0, exitCode);
}
@Test
public void testObserverMethods() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
DefaultJavaLibrary accumulateClassNames =
JavaLibraryBuilder.createBuilder("//foo:bar").build(graphBuilder);
accumulateClassNames
.getBuildOutputInitializer()
.setBuildOutputForTests(
new JavaLibrary.Data(
ImmutableSortedMap.of("com/example/Foo", HashCode.fromString("cafebabe"))));
BuildTarget buildTarget = BuildTargetFactory.newInstance("//foo:bar");
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
BuildRuleParams params = TestBuildRuleParams.create();
DexProducedFromJavaLibrary preDexWithClasses =
new DexProducedFromJavaLibrary(
buildTarget,
projectFilesystem,
TestAndroidPlatformTargetFactory.create(),
params,
accumulateClassNames,
DxStep.DX);
assertNull(preDexWithClasses.getSourcePathToOutput());
assertEquals(
BuildTargetPaths.getGenPath(projectFilesystem, buildTarget, "%s.dex.jar"),
preDexWithClasses.getPathToDex());
}
@Test
public void testComputeAbiKey() {
ImmutableSortedMap<String, HashCode> classNamesAndHashes =
ImmutableSortedMap.of(
"com/example/Foo", HashCode.fromString("e4fccb7520b7795e632651323c63217c9f59f72a"),
"com/example/Bar", HashCode.fromString("087b7707a5f8e0a2adf5652e3cd2072d89a197dc"),
"com/example/Baz", HashCode.fromString("62b1c2510840c0de55c13f66065a98a719be0f19"));
String observedSha1 = DexProducedFromJavaLibrary.computeAbiKey(classNamesAndHashes).getHash();
String expectedSha1 =
Hashing.sha1()
.newHasher()
.putUnencodedChars("com/example/Bar")
.putByte((byte) 0)
.putUnencodedChars("087b7707a5f8e0a2adf5652e3cd2072d89a197dc")
.putByte((byte) 0)
.putUnencodedChars("com/example/Baz")
.putByte((byte) 0)
.putUnencodedChars("62b1c2510840c0de55c13f66065a98a719be0f19")
.putByte((byte) 0)
.putUnencodedChars("com/example/Foo")
.putByte((byte) 0)
.putUnencodedChars("e4fccb7520b7795e632651323c63217c9f59f72a")
.putByte((byte) 0)
.hash()
.toString();
assertEquals(expectedSha1, observedSha1);
}
}
| |
/*
* Copyright 2016 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.blockly.android.ui.fieldview;
import android.content.Context;
import android.database.DataSetObserver;
import android.os.Handler;
import android.support.annotation.IntDef;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.AppCompatSpinner;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import com.google.blockly.android.R;
import com.google.blockly.android.control.NameManager;
import com.google.blockly.model.Field;
import com.google.blockly.model.FieldVariable;
import com.google.blockly.utils.LangUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.SortedSet;
/**
* Renders a dropdown field containing the workspace's variables as part of a Block.
*/
public class BasicFieldVariableView extends AppCompatSpinner
implements FieldView, VariableChangeView {
protected Field.Observer mFieldObserver = new Field.Observer() {
@Override
public void onValueChanged(Field field, String oldValue, String newValue) {
refreshSelection();
}
};
protected FieldVariable mVariableField;
protected VariableViewAdapter mAdapter;
protected VariableRequestCallback mCallback;
private final Handler mMainHandler;
/**
* Constructs a new {@link BasicFieldVariableView}.
*
* @param context The application's context.
*/
public BasicFieldVariableView(Context context) {
super(context);
mMainHandler = new Handler(context.getMainLooper());
}
public BasicFieldVariableView(Context context, AttributeSet attrs) {
super(context, attrs);
mMainHandler = new Handler(context.getMainLooper());
}
public BasicFieldVariableView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mMainHandler = new Handler(context.getMainLooper());
}
@Override
public void setField(Field field) {
FieldVariable variableField = (FieldVariable) field;
if (mVariableField == variableField) {
return;
}
if (mVariableField != null) {
mVariableField.unregisterObserver(mFieldObserver);
}
mVariableField = variableField;
if (mVariableField != null) {
// Update immediately.
refreshSelection();
mVariableField.registerObserver(mFieldObserver);
} else {
setSelection(0);
}
}
@Override
public Field getField() {
return mVariableField;
}
@Override
public void setSelection(int position) {
if (position == getSelectedItemPosition()) {
return;
}
if (mVariableField == null) {
return;
}
int type = ((VariableViewAdapter)getAdapter()).getVariableAction(position);
switch (type) {
case VariableViewAdapter.ACTION_SELECT_VARIABLE:
super.setSelection(position);
if (mVariableField != null) {
String varName = getAdapter().getItem(position).toString();
mVariableField.setVariable(varName);
}
break;
case VariableViewAdapter.ACTION_RENAME_VARIABLE:
if (mCallback != null) {
mCallback.onVariableRequest(VariableRequestCallback.REQUEST_RENAME,
mVariableField.getVariable());
}
break;
case VariableViewAdapter.ACTION_DELETE_VARIABLE:
if (mCallback != null) {
mCallback.onVariableRequest(VariableRequestCallback.REQUEST_DELETE,
mVariableField.getVariable());
}
break;
}
}
@Override
public void setAdapter(SpinnerAdapter adapter) {
mAdapter = (VariableViewAdapter) adapter;
super.setAdapter(adapter);
if (mAdapter != null) {
refreshSelection();
mAdapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
refreshSelection();
}
});
}
}
@Override
public void unlinkField() {
setField(null);
}
@Override
public void setVariableRequestCallback(VariableRequestCallback requestCallback) {
mCallback = requestCallback;
}
/**
* Updates the selection from the field. This is used when the indices may have changed to
* ensure the correct index is selected.
*/
private void refreshSelection() {
if (mAdapter != null) {
// Because this may change the available indices, we want to make sure each assignment
// is in its own event tick.
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (mVariableField != null) {
setSelection(
mAdapter.getOrCreateVariableIndex(mVariableField.getVariable()));
}
}
});
}
}
/**
* An implementation of {@link ArrayAdapter} that wraps the
* {@link NameManager.VariableNameManager} to create the variable item views.
*/
public static class VariableViewAdapter extends FieldAdapter<String> {
@Retention(RetentionPolicy.SOURCE)
@IntDef({ACTION_SELECT_VARIABLE, ACTION_RENAME_VARIABLE, ACTION_DELETE_VARIABLE})
public @interface VariableAdapterType{}
public static final int ACTION_SELECT_VARIABLE = 0;
public static final int ACTION_RENAME_VARIABLE = 1;
public static final int ACTION_DELETE_VARIABLE = 2;
private final NameManager mVariableNameManager;
private final SortedSet<String> mVars;
private final String mRenameString;
private AppCompatSpinner mSpinner;
/**
* @param variableNameManager The name manager containing the variables.
* @param context A context for inflating layouts.
* @param resource The {@link TextView} layout to use when inflating items.
* @param mSpinner Spinner this is being used in
*/
public VariableViewAdapter(Context context, NameManager variableNameManager,
@LayoutRes int resource, AppCompatSpinner mSpinner) {
super(context, resource, mSpinner);
this.mSpinner = mSpinner;
mVariableNameManager = variableNameManager;
mVars = mVariableNameManager.getUsedNames();
refreshVariables();
variableNameManager.registerObserver(new DataSetObserver() {
@Override
public void onChanged() {
refreshVariables();
}
});
mRenameString = LangUtils.interpolate("%{BKY_RENAME_VARIABLE}");
}
/**
* This constructor is for compatibility reasons, or for whe it is not in a Spinner.
*
* @param variableNameManager The name manager containing the variables.
* @param context A context for inflating layouts.
* @param resource The {@link TextView} layout to use when inflating items.
*/
public VariableViewAdapter(Context context, NameManager variableNameManager,
@LayoutRes int resource) {
this(context, variableNameManager, resource, null);
}
/**
* Retrieves the index for the given variable name, creating a new variable if it is not
* found.
*
* @param variableName The name of the variable to retrieve.
* @return The index of the variable.
*/
public int getOrCreateVariableIndex(String variableName) {
String existing = mVariableNameManager.getExisting(variableName);
if (existing != null) {
return getIndexForVarName(existing);
} else {
// No match found. Create it.
variableName = mVariableNameManager.makeValidName(
/* suggested */ variableName, /* fallback */ variableName);
mVariableNameManager.addName(variableName);
int insertionIndex = getIndexForVarName(variableName);
notifyDataSetChanged();
return insertionIndex;
}
}
private int getIndexForVarName(String expected) {
int i = 0;
for (String varName : mVars) {
if (varName.equals(expected)) {
return i;
}
++i;
}
throw new IllegalArgumentException(
"Expected variable name \"" + expected + "\" not found.");
}
@Override
public int getCount() {
int count = super.getCount();
return count == 0 ? 0 : count + 2;
}
@Override
public String getItem(int index) {
if (index == -1) {
index = 0;
}
int count = super.getCount();
if (index >= count + 2 || index < 0) {
throw new IndexOutOfBoundsException("There is no item at index " + index
+ ". Count is " + count);
}
if (index < count) {
return super.getItem(index);
}
if (index == count) {
return mRenameString;
} else {
return LangUtils.interpolate("%{BKY_DELETE_VARIABLE}").replace("%1", mSpinner != null && mSpinner.getSelectedItemPosition() != -1 ? getItem(mSpinner.getSelectedItemPosition()) : "");
}
}
public @VariableAdapterType
int getVariableAction(int index) {
int count = super.getCount();
if (index >= count + 2 || index < 0) {
throw new IndexOutOfBoundsException("There is no item at index " + index + "."
+ " Count is " + count);
}
if (index < count) {
return ACTION_SELECT_VARIABLE;
} else if (index == count) {
return ACTION_RENAME_VARIABLE;
} else {
return ACTION_DELETE_VARIABLE;
}
}
/**
* Updates the ArrayAdapter internal list with the latest list from the NameManager.
*/
private void refreshVariables() {
clear();
for (String varName : mVars) {
add(varName);
}
notifyDataSetChanged();
}
}
}
| |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package de.hub.clickwatch.specificmodels.brn.lt_routes.impl;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.impl.EPackageImpl;
import de.hub.clickwatch.model.ClickWatchModelPackage;
import de.hub.clickwatch.specificmodels.brn.BrnPackage;
import de.hub.clickwatch.specificmodels.brn.device_wifi_data_power_systempower.Device_wifi_data_power_systempowerPackage;
import de.hub.clickwatch.specificmodels.brn.device_wifi_data_power_systempower.impl.Device_wifi_data_power_systempowerPackageImpl;
import de.hub.clickwatch.specificmodels.brn.device_wifi_link_stat_bcast_stats.Device_wifi_link_stat_bcast_statsPackage;
import de.hub.clickwatch.specificmodels.brn.device_wifi_link_stat_bcast_stats.impl.Device_wifi_link_stat_bcast_statsPackageImpl;
import de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Device_wifi_wifidevice_cst_statsPackage;
import de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.impl.Device_wifi_wifidevice_cst_statsPackageImpl;
import de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_sc_systemchannel.Device_wifi_wifidevice_sc_systemchannelPackage;
import de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_sc_systemchannel.impl.Device_wifi_wifidevice_sc_systemchannelPackageImpl;
import de.hub.clickwatch.specificmodels.brn.gps_cart_coord.Gps_cart_coordPackage;
import de.hub.clickwatch.specificmodels.brn.gps_cart_coord.impl.Gps_cart_coordPackageImpl;
import de.hub.clickwatch.specificmodels.brn.gps_gps_coord.Gps_gps_coordPackage;
import de.hub.clickwatch.specificmodels.brn.gps_gps_coord.impl.Gps_gps_coordPackageImpl;
import de.hub.clickwatch.specificmodels.brn.impl.BrnPackageImpl;
import de.hub.clickwatch.specificmodels.brn.lease_tab_leases.Lease_tab_leasesPackage;
import de.hub.clickwatch.specificmodels.brn.lease_tab_leases.impl.Lease_tab_leasesPackageImpl;
import de.hub.clickwatch.specificmodels.brn.lt_links.Lt_linksPackage;
import de.hub.clickwatch.specificmodels.brn.lt_links.impl.Lt_linksPackageImpl;
import de.hub.clickwatch.specificmodels.brn.lt_routes.Link;
import de.hub.clickwatch.specificmodels.brn.lt_routes.Lt_routesFactory;
import de.hub.clickwatch.specificmodels.brn.lt_routes.Lt_routesPackage;
import de.hub.clickwatch.specificmodels.brn.lt_routes.Route;
import de.hub.clickwatch.specificmodels.brn.lt_routes.Routes;
import de.hub.clickwatch.specificmodels.brn.lt_routes.Routetable;
import de.hub.clickwatch.specificmodels.brn.routing_dsr_stats_stats.Routing_dsr_stats_statsPackage;
import de.hub.clickwatch.specificmodels.brn.routing_dsr_stats_stats.impl.Routing_dsr_stats_statsPackageImpl;
import de.hub.clickwatch.specificmodels.brn.seismo_localchannelinfo.Seismo_localchannelinfoPackage;
import de.hub.clickwatch.specificmodels.brn.seismo_localchannelinfo.impl.Seismo_localchannelinfoPackageImpl;
import de.hub.clickwatch.specificmodels.brn.sf_stats.Sf_statsPackage;
import de.hub.clickwatch.specificmodels.brn.sf_stats.impl.Sf_statsPackageImpl;
import de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.Sys_info_systeminfoPackage;
import de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Sys_info_systeminfoPackageImpl;
import de.hub.clickwatch.specificmodels.brn.tsi_syncinfo.Tsi_syncinfoPackage;
import de.hub.clickwatch.specificmodels.brn.tsi_syncinfo.impl.Tsi_syncinfoPackageImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Package</b>.
* <!-- end-user-doc -->
* @generated
*/
public class Lt_routesPackageImpl extends EPackageImpl implements Lt_routesPackage {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass linkEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass routeEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass routesEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass routetableEClass = null;
/**
* Creates an instance of the model <b>Package</b>, registered with
* {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
* package URI value.
* <p>Note: the correct way to create the package is via the static
* factory method {@link #init init()}, which also performs
* initialization of the package, or returns the registered package,
* if one already exists.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.eclipse.emf.ecore.EPackage.Registry
* @see de.hub.clickwatch.specificmodels.brn.lt_routes.Lt_routesPackage#eNS_URI
* @see #init()
* @generated
*/
private Lt_routesPackageImpl() {
super(eNS_URI, Lt_routesFactory.eINSTANCE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static boolean isInited = false;
/**
* Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends.
*
* <p>This method is used to initialize {@link Lt_routesPackage#eINSTANCE} when that field is accessed.
* Clients should not invoke it directly. Instead, they should simply access that field to obtain the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #eNS_URI
* @see #createPackageContents()
* @see #initializePackageContents()
* @generated
*/
public static Lt_routesPackage init() {
if (isInited) return (Lt_routesPackage)EPackage.Registry.INSTANCE.getEPackage(Lt_routesPackage.eNS_URI);
// Obtain or create and register package
Lt_routesPackageImpl theLt_routesPackage = (Lt_routesPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof Lt_routesPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new Lt_routesPackageImpl());
isInited = true;
// Initialize simple dependencies
ClickWatchModelPackage.eINSTANCE.eClass();
// Obtain or create and register interdependencies
BrnPackageImpl theBrnPackage = (BrnPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(BrnPackage.eNS_URI) instanceof BrnPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(BrnPackage.eNS_URI) : BrnPackage.eINSTANCE);
Sys_info_systeminfoPackageImpl theSys_info_systeminfoPackage = (Sys_info_systeminfoPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Sys_info_systeminfoPackage.eNS_URI) instanceof Sys_info_systeminfoPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Sys_info_systeminfoPackage.eNS_URI) : Sys_info_systeminfoPackage.eINSTANCE);
Device_wifi_data_power_systempowerPackageImpl theDevice_wifi_data_power_systempowerPackage = (Device_wifi_data_power_systempowerPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Device_wifi_data_power_systempowerPackage.eNS_URI) instanceof Device_wifi_data_power_systempowerPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Device_wifi_data_power_systempowerPackage.eNS_URI) : Device_wifi_data_power_systempowerPackage.eINSTANCE);
Device_wifi_wifidevice_sc_systemchannelPackageImpl theDevice_wifi_wifidevice_sc_systemchannelPackage = (Device_wifi_wifidevice_sc_systemchannelPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Device_wifi_wifidevice_sc_systemchannelPackage.eNS_URI) instanceof Device_wifi_wifidevice_sc_systemchannelPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Device_wifi_wifidevice_sc_systemchannelPackage.eNS_URI) : Device_wifi_wifidevice_sc_systemchannelPackage.eINSTANCE);
Lease_tab_leasesPackageImpl theLease_tab_leasesPackage = (Lease_tab_leasesPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Lease_tab_leasesPackage.eNS_URI) instanceof Lease_tab_leasesPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Lease_tab_leasesPackage.eNS_URI) : Lease_tab_leasesPackage.eINSTANCE);
Gps_gps_coordPackageImpl theGps_gps_coordPackage = (Gps_gps_coordPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Gps_gps_coordPackage.eNS_URI) instanceof Gps_gps_coordPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Gps_gps_coordPackage.eNS_URI) : Gps_gps_coordPackage.eINSTANCE);
Gps_cart_coordPackageImpl theGps_cart_coordPackage = (Gps_cart_coordPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Gps_cart_coordPackage.eNS_URI) instanceof Gps_cart_coordPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Gps_cart_coordPackage.eNS_URI) : Gps_cart_coordPackage.eINSTANCE);
Lt_linksPackageImpl theLt_linksPackage = (Lt_linksPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Lt_linksPackage.eNS_URI) instanceof Lt_linksPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Lt_linksPackage.eNS_URI) : Lt_linksPackage.eINSTANCE);
Device_wifi_link_stat_bcast_statsPackageImpl theDevice_wifi_link_stat_bcast_statsPackage = (Device_wifi_link_stat_bcast_statsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Device_wifi_link_stat_bcast_statsPackage.eNS_URI) instanceof Device_wifi_link_stat_bcast_statsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Device_wifi_link_stat_bcast_statsPackage.eNS_URI) : Device_wifi_link_stat_bcast_statsPackage.eINSTANCE);
Device_wifi_wifidevice_cst_statsPackageImpl theDevice_wifi_wifidevice_cst_statsPackage = (Device_wifi_wifidevice_cst_statsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Device_wifi_wifidevice_cst_statsPackage.eNS_URI) instanceof Device_wifi_wifidevice_cst_statsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Device_wifi_wifidevice_cst_statsPackage.eNS_URI) : Device_wifi_wifidevice_cst_statsPackage.eINSTANCE);
Sf_statsPackageImpl theSf_statsPackage = (Sf_statsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Sf_statsPackage.eNS_URI) instanceof Sf_statsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Sf_statsPackage.eNS_URI) : Sf_statsPackage.eINSTANCE);
Routing_dsr_stats_statsPackageImpl theRouting_dsr_stats_statsPackage = (Routing_dsr_stats_statsPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Routing_dsr_stats_statsPackage.eNS_URI) instanceof Routing_dsr_stats_statsPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Routing_dsr_stats_statsPackage.eNS_URI) : Routing_dsr_stats_statsPackage.eINSTANCE);
Seismo_localchannelinfoPackageImpl theSeismo_localchannelinfoPackage = (Seismo_localchannelinfoPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Seismo_localchannelinfoPackage.eNS_URI) instanceof Seismo_localchannelinfoPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Seismo_localchannelinfoPackage.eNS_URI) : Seismo_localchannelinfoPackage.eINSTANCE);
Tsi_syncinfoPackageImpl theTsi_syncinfoPackage = (Tsi_syncinfoPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(Tsi_syncinfoPackage.eNS_URI) instanceof Tsi_syncinfoPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(Tsi_syncinfoPackage.eNS_URI) : Tsi_syncinfoPackage.eINSTANCE);
// Create package meta-data objects
theLt_routesPackage.createPackageContents();
theBrnPackage.createPackageContents();
theSys_info_systeminfoPackage.createPackageContents();
theDevice_wifi_data_power_systempowerPackage.createPackageContents();
theDevice_wifi_wifidevice_sc_systemchannelPackage.createPackageContents();
theLease_tab_leasesPackage.createPackageContents();
theGps_gps_coordPackage.createPackageContents();
theGps_cart_coordPackage.createPackageContents();
theLt_linksPackage.createPackageContents();
theDevice_wifi_link_stat_bcast_statsPackage.createPackageContents();
theDevice_wifi_wifidevice_cst_statsPackage.createPackageContents();
theSf_statsPackage.createPackageContents();
theRouting_dsr_stats_statsPackage.createPackageContents();
theSeismo_localchannelinfoPackage.createPackageContents();
theTsi_syncinfoPackage.createPackageContents();
// Initialize created meta-data
theLt_routesPackage.initializePackageContents();
theBrnPackage.initializePackageContents();
theSys_info_systeminfoPackage.initializePackageContents();
theDevice_wifi_data_power_systempowerPackage.initializePackageContents();
theDevice_wifi_wifidevice_sc_systemchannelPackage.initializePackageContents();
theLease_tab_leasesPackage.initializePackageContents();
theGps_gps_coordPackage.initializePackageContents();
theGps_cart_coordPackage.initializePackageContents();
theLt_linksPackage.initializePackageContents();
theDevice_wifi_link_stat_bcast_statsPackage.initializePackageContents();
theDevice_wifi_wifidevice_cst_statsPackage.initializePackageContents();
theSf_statsPackage.initializePackageContents();
theRouting_dsr_stats_statsPackage.initializePackageContents();
theSeismo_localchannelinfoPackage.initializePackageContents();
theTsi_syncinfoPackage.initializePackageContents();
// Mark meta-data to indicate it can't be changed
theLt_routesPackage.freeze();
// Update the registry and return the package
EPackage.Registry.INSTANCE.put(Lt_routesPackage.eNS_URI, theLt_routesPackage);
return theLt_routesPackage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getLink() {
return linkEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getLink_EContainer_link() {
return (EReference)linkEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getLink_From() {
return (EAttribute)linkEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getLink_To() {
return (EAttribute)linkEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getLink_Metric() {
return (EAttribute)linkEClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getLink_Seq() {
return (EAttribute)linkEClass.getEStructuralFeatures().get(4);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getLink_Age() {
return (EAttribute)linkEClass.getEStructuralFeatures().get(5);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getRoute() {
return routeEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getRoute_EContainer_route() {
return (EReference)routeEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getRoute_Text() {
return (EAttribute)routeEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getRoute_Link() {
return (EReference)routeEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getRoute_From() {
return (EAttribute)routeEClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getRoute_To() {
return (EAttribute)routeEClass.getEStructuralFeatures().get(4);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getRoutes() {
return routesEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getRoutes_Routetable() {
return (EReference)routesEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getRoutetable() {
return routetableEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getRoutetable_EContainer_routetable() {
return (EReference)routetableEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getRoutetable_Text() {
return (EAttribute)routetableEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getRoutetable_Route() {
return (EReference)routetableEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getRoutetable_Id() {
return (EAttribute)routetableEClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Lt_routesFactory getLt_routesFactory() {
return (Lt_routesFactory)getEFactoryInstance();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isCreated = false;
/**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createPackageContents() {
if (isCreated) return;
isCreated = true;
// Create classes and their features
linkEClass = createEClass(LINK);
createEReference(linkEClass, LINK__ECONTAINER_LINK);
createEAttribute(linkEClass, LINK__FROM);
createEAttribute(linkEClass, LINK__TO);
createEAttribute(linkEClass, LINK__METRIC);
createEAttribute(linkEClass, LINK__SEQ);
createEAttribute(linkEClass, LINK__AGE);
routeEClass = createEClass(ROUTE);
createEReference(routeEClass, ROUTE__ECONTAINER_ROUTE);
createEAttribute(routeEClass, ROUTE__TEXT);
createEReference(routeEClass, ROUTE__LINK);
createEAttribute(routeEClass, ROUTE__FROM);
createEAttribute(routeEClass, ROUTE__TO);
routesEClass = createEClass(ROUTES);
createEReference(routesEClass, ROUTES__ROUTETABLE);
routetableEClass = createEClass(ROUTETABLE);
createEReference(routetableEClass, ROUTETABLE__ECONTAINER_ROUTETABLE);
createEAttribute(routetableEClass, ROUTETABLE__TEXT);
createEReference(routetableEClass, ROUTETABLE__ROUTE);
createEAttribute(routetableEClass, ROUTETABLE__ID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isInitialized = false;
/**
* Complete the initialization of the package and its meta-model. This
* method is guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void initializePackageContents() {
if (isInitialized) return;
isInitialized = true;
// Initialize package
setName(eNAME);
setNsPrefix(eNS_PREFIX);
setNsURI(eNS_URI);
// Obtain other dependent packages
ClickWatchModelPackage theClickWatchModelPackage = (ClickWatchModelPackage)EPackage.Registry.INSTANCE.getEPackage(ClickWatchModelPackage.eNS_URI);
// Create type parameters
// Set bounds for type parameters
// Add supertypes to classes
routesEClass.getESuperTypes().add(theClickWatchModelPackage.getHandler());
// Initialize classes and features; add operations and parameters
initEClass(linkEClass, Link.class, "Link", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getLink_EContainer_link(), this.getRoute(), this.getRoute_Link(), "eContainer_link", null, 0, 1, Link.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getLink_From(), ecorePackage.getEString(), "from", null, 0, 1, Link.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getLink_To(), ecorePackage.getEString(), "to", null, 0, 1, Link.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getLink_Metric(), ecorePackage.getEInt(), "metric", null, 0, 1, Link.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getLink_Seq(), ecorePackage.getEInt(), "seq", null, 0, 1, Link.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getLink_Age(), ecorePackage.getEInt(), "age", null, 0, 1, Link.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(routeEClass, Route.class, "Route", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getRoute_EContainer_route(), this.getRoutetable(), this.getRoutetable_Route(), "eContainer_route", null, 0, 1, Route.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getRoute_Text(), ecorePackage.getEString(), "text", null, 0, -1, Route.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, !IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getRoute_Link(), this.getLink(), this.getLink_EContainer_link(), "link", null, 0, -1, Route.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getRoute_From(), ecorePackage.getEString(), "from", null, 0, 1, Route.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getRoute_To(), ecorePackage.getEString(), "to", null, 0, 1, Route.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(routesEClass, Routes.class, "Routes", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getRoutes_Routetable(), this.getRoutetable(), this.getRoutetable_EContainer_routetable(), "routetable", null, 0, 1, Routes.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(routetableEClass, Routetable.class, "Routetable", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getRoutetable_EContainer_routetable(), this.getRoutes(), this.getRoutes_Routetable(), "eContainer_routetable", null, 0, 1, Routetable.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getRoutetable_Text(), ecorePackage.getEString(), "text", null, 0, -1, Routetable.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, !IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getRoutetable_Route(), this.getRoute(), this.getRoute_EContainer_route(), "route", null, 0, -1, Routetable.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getRoutetable_Id(), ecorePackage.getEString(), "id", null, 0, 1, Routetable.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
// Create annotations
// http://de.hub.clickwatch.specificmodels
createDeAnnotations();
}
/**
* Initializes the annotations for <b>http://de.hub.clickwatch.specificmodels</b>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void createDeAnnotations() {
String source = "http://de.hub.clickwatch.specificmodels";
addAnnotation
(this,
source,
new String[] {
"handler_class", "Routes",
"handler_name", "lt/routes"
});
addAnnotation
(linkEClass,
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/route|route:Route|EObject/link|link:Link|EObject"
});
addAnnotation
(getLink_From(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/route|route:Route|EObject/link|link:Link|EObject/from|from:"
});
addAnnotation
(getLink_To(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/route|route:Route|EObject/link|link:Link|EObject/to|to:"
});
addAnnotation
(getLink_Metric(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/route|route:Route|EObject/link|link:Link|EObject/metric|metric:"
});
addAnnotation
(getLink_Seq(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/route|route:Route|EObject/link|link:Link|EObject/seq|seq:"
});
addAnnotation
(getLink_Age(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/route|route:Route|EObject/link|link:Link|EObject/age|age:"
});
addAnnotation
(routeEClass,
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/route|route:Route|EObject"
});
addAnnotation
(getRoute_Text(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/route|route:Route|EObject/text|text:"
});
addAnnotation
(getRoute_Link(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/route|route:Route|EObject/link|link:Link|EObject",
"IsCopy", "false"
});
addAnnotation
(getRoute_From(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/route|route:Route|EObject/from|from:"
});
addAnnotation
(getRoute_To(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/route|route:Route|EObject/to|to:"
});
addAnnotation
(routesEClass,
source,
new String[] {
"target_id", "Routes|Handler"
});
addAnnotation
(getRoutes_Routetable(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject",
"IsCopy", "false"
});
addAnnotation
(routetableEClass,
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject"
});
addAnnotation
(getRoutetable_Text(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/text|text:"
});
addAnnotation
(getRoutetable_Route(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/route|route:Route|EObject",
"IsCopy", "false"
});
addAnnotation
(getRoutetable_Id(),
source,
new String[] {
"target_id", "Routes|Handler/routetable|routetable:Routetable|EObject/id|id:"
});
}
} //Lt_routesPackageImpl
| |
/*
Class org.apache.derby.optional.lucene.LuceneListIndexesVTI
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.derby.optional.lucene;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Properties;
import org.apache.derby.database.Database;
import org.apache.derby.io.StorageFactory;
import org.apache.derby.io.StorageFile;
import org.apache.derby.shared.common.reference.SQLState;
import org.apache.derby.vti.StringColumnVTI;
/**
* Provides a table interface to the Lucene indexes in this database.
* See org.apache.derby.optional.lucene.LuceneSupport.listIndexes.
*
*/
class LuceneListIndexesVTI extends StringColumnVTI
{
private Connection connection;
private StorageFile[] indexes;
private int row = -1;
private String schema;
private String table;
private String column;
private Properties rowProperties;
/**
* Return a new LuceneListIndexesVTI.
*/
public LuceneListIndexesVTI()
throws SQLException
{
super
( new String[]
{
"SCHEMANAME",
"TABLENAME",
"COLUMNNAME",
"LASTUPDATED",
"LUCENEVERSION",
"ANALYZER",
"INDEXDESCRIPTORMAKER",
}
);
connection = LuceneSupport.getDefaultConnection();
StorageFactory dir = LuceneSupport.getStorageFactory( connection );
StorageFile luceneDir = dir.newStorageFile( Database.LUCENE_DIR );
ArrayList<StorageFile> allIndexes = new ArrayList<StorageFile>();
StorageFile[] schemas = listDirectories( dir, luceneDir );
if ( schemas != null )
{
for ( StorageFile schema : schemas )
{
StorageFile[] tables = listDirectories( dir, schema );
for ( StorageFile table : tables )
{
StorageFile[] indexes = listDirectories( dir, table );
for ( StorageFile index : indexes )
{
allIndexes.add( index );
}
}
}
}
indexes = new StorageFile[ allIndexes.size() ];
allIndexes.toArray( indexes );
}
public void close() throws SQLException
{
connection = null;
indexes = null;
schema = null;
table = null;
column = null;
rowProperties = null;
}
public boolean next() throws SQLException
{
schema = null;
table = null;
column = null;
rowProperties = null;
row++;
if (row < indexes.length) {
return true;
}
return false;
}
/**
* columns:
* 1 == id
* 2 == schema
* 3 == table
* 4 == column name
* 5 == last modified
*/
protected String getRawColumn( int col ) throws SQLException
{
readSchemaTableColumn();
switch( col )
{
case 1: return schema;
case 2: return table;
case 3: return column;
case 5: return getProperty( LuceneSupport.LUCENE_VERSION );
case 6: return getProperty( LuceneSupport.ANALYZER );
case 7: return getProperty( LuceneSupport.INDEX_DESCRIPTOR_MAKER );
default:
throw LuceneSupport.newSQLException
(
SQLState.LANG_INVALID_COLUMN_POSITION,
new Integer( col ),
new Integer( getColumnCount() )
);
}
}
/** Get the timestamp value of the 1-based column id */
public Timestamp getTimestamp( int col ) throws SQLException
{
if ( col != 4 )
{
throw LuceneSupport.newSQLException
(
SQLState.LANG_INVALID_COLUMN_POSITION,
new Integer( col ),
new Integer( getColumnCount() )
);
}
try {
long timestampMillis = Long.parseLong( getProperty( LuceneSupport.UPDATE_TIMESTAMP ) );
return new Timestamp( timestampMillis );
}
catch (NumberFormatException nfe) { throw LuceneSupport.wrap( nfe ); }
}
/** Fill in the schema, table, and column names */
private void readSchemaTableColumn()
throws SQLException
{
if ( column != null ) { return; }
StorageFile columnDir = indexes[ row ];
column = columnDir.getName();
StorageFile tableDir = columnDir.getParentDir();
table = tableDir.getName();
StorageFile schemaDir = tableDir.getParentDir();
schema = schemaDir.getName();
}
/** get the string value of a property from the row properties */
private String getProperty( String key )
throws SQLException
{
return getRowProperties().getProperty( key );
}
/** get the properties of the current row */
private Properties getRowProperties()
throws SQLException
{
if ( rowProperties == null )
{
try {
readSchemaTableColumn();
String delimitedColumnName = LuceneSupport.delimitID( column );
StorageFile indexPropertiesFile = LuceneSupport.getIndexPropertiesFile( connection, schema, table, delimitedColumnName );
rowProperties = readIndexProperties( indexPropertiesFile );
}
catch (IOException ioe) { throw LuceneSupport.wrap( ioe ); }
catch (PrivilegedActionException pae) { throw LuceneSupport.wrap( pae ); }
}
return rowProperties;
}
/** List files */
private static StorageFile[] listDirectories( final StorageFactory storageFactory, final StorageFile dir )
{
return AccessController.doPrivileged
(
new PrivilegedAction<StorageFile[]>()
{
public StorageFile[] run()
{
ArrayList<StorageFile> subdirectories = new ArrayList<StorageFile>();
String[] fileNames = dir.list();
for ( String fileName : fileNames )
{
StorageFile candidate = storageFactory.newStorageFile( dir, fileName );
if ( candidate.isDirectory() ) { subdirectories.add( candidate ); }
}
StorageFile[] result = new StorageFile[ subdirectories.size() ];
subdirectories.toArray( result );
return result;
}
}
);
}
/** Read the index properties file */
private static Properties readIndexProperties( final StorageFile file )
throws IOException
{
try {
return AccessController.doPrivileged
(
new PrivilegedExceptionAction<Properties>()
{
public Properties run() throws IOException
{
return LuceneSupport.readIndexPropertiesNoPrivs( file );
}
}
);
} catch (PrivilegedActionException pae) {
throw (IOException) pae.getCause();
}
}
}
| |
/*
* Copyright (c) 2009-13, United States Government, as represented by the Secretary of Health and Human Services.
* 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 United States Government 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 UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.docquery.outbound;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.never;
import gov.hhs.fha.nhinc.aspect.OutboundProcessingEvent;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.HomeCommunityType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetCommunitiesType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetCommunityType;
import gov.hhs.fha.nhinc.docquery.AdhocQueryResponseAsserter;
import gov.hhs.fha.nhinc.docquery.DocQueryAuditLog;
import gov.hhs.fha.nhinc.docquery.DocQueryPolicyChecker;
import gov.hhs.fha.nhinc.docquery.DocQueryUnitTestUtil;
import gov.hhs.fha.nhinc.docquery.aspect.AdhocQueryRequestDescriptionBuilder;
import gov.hhs.fha.nhinc.docquery.aspect.AdhocQueryResponseDescriptionBuilder;
import gov.hhs.fha.nhinc.docquery.entity.Aggregate;
import gov.hhs.fha.nhinc.docquery.entity.AggregationService;
import gov.hhs.fha.nhinc.docquery.entity.AggregationStrategy;
import gov.hhs.fha.nhinc.docquery.entity.OutboundDocQueryOrchestratable;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.orchestration.OutboundOrchestratable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryRequest;
import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryResponse;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.AdhocQueryType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.SlotType1;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ValueListType;
import org.junit.Test;
/**
* @author achidamb
*/
public class StandardOutboundDocQueryTest {
final DocQueryAuditLog mockAuditLogger = mock(DocQueryAuditLog.class);
private static final String HOME_HCID = "1.0";
private static final String SENDING_HCID_FORMATTED = "1.2";
@Test
public void testrespondingGatewayCrossGatewayQueryforNullEndPoint() throws Exception {
DocQueryUnitTestUtil.setUpGatewayProperties();
AggregationStrategy strategy = mock(AggregationStrategy.class);
AdhocQueryRequest adhocQueryRequest = new AdhocQueryRequest();
adhocQueryRequest = createRequest(createSlotList());
AggregationService service = mock(AggregationService.class);
DocQueryPolicyChecker policyChecker = mock(DocQueryPolicyChecker.class);
AssertionType assertion = new AssertionType();
StandardOutboundDocQuery entitydocqueryimpl = new StandardOutboundDocQuery(strategy, service, policyChecker) {
@Override
protected DocQueryAuditLog getAuditLogger() {
return mockAuditLogger;
}
@Override
protected boolean isAuditEnabled(String propertyFile, String propertyName) {
return true;
}
};
NhinTargetCommunitiesType targets = createNhinTargetCommunites();
AdhocQueryResponse response = entitydocqueryimpl.respondingGatewayCrossGatewayQuery(adhocQueryRequest,
assertion, targets);
verify(service).createChildRequests(eq(adhocQueryRequest), eq(assertion), eq(targets));
verify(mockAuditLogger).auditDQRequest(eq(adhocQueryRequest), eq(assertion),
eq(NhincConstants.AUDIT_LOG_INBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_ENTITY_INTERFACE),
eq(SENDING_HCID_FORMATTED));
verify(mockAuditLogger).auditDQResponse(eq(response), eq(assertion),
eq(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_ENTITY_INTERFACE),
eq(SENDING_HCID_FORMATTED));
AdhocQueryResponseAsserter.assertSchemaCompliant(response);
}
/**
* This test is a StandardOutboundDocQuery test that verifies no auditing is performed
* when the property is false
*/
@Test
public void testrespondingGatewayCrossGatewayQueryforNullEndPointNoAudit() throws Exception {
DocQueryUnitTestUtil.setUpGatewayProperties();
AggregationStrategy strategy = mock(AggregationStrategy.class);
AdhocQueryRequest adhocQueryRequest = new AdhocQueryRequest();
adhocQueryRequest = createRequest(createSlotList());
AggregationService service = mock(AggregationService.class);
DocQueryPolicyChecker policyChecker = mock(DocQueryPolicyChecker.class);
AssertionType assertion = new AssertionType();
StandardOutboundDocQuery entitydocqueryimpl = new StandardOutboundDocQuery(strategy, service, policyChecker) {
@Override
protected DocQueryAuditLog getAuditLogger() {
return mockAuditLogger;
}
@Override
protected boolean isAuditEnabled(String propertyFile, String propertyName) {
return false;
}
};
NhinTargetCommunitiesType targets = createNhinTargetCommunites();
AdhocQueryResponse response = entitydocqueryimpl.respondingGatewayCrossGatewayQuery(adhocQueryRequest,
assertion, targets);
verify(service).createChildRequests(eq(adhocQueryRequest), eq(assertion), eq(targets));
verify(mockAuditLogger, never()).auditDQRequest(eq(adhocQueryRequest), eq(assertion),
eq(NhincConstants.AUDIT_LOG_INBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_ENTITY_INTERFACE),
eq(SENDING_HCID_FORMATTED));
verify(mockAuditLogger, never()).auditDQResponse(eq(response), eq(assertion),
eq(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_ENTITY_INTERFACE),
eq(SENDING_HCID_FORMATTED));
AdhocQueryResponseAsserter.assertSchemaCompliant(response);
}
@Test
public void errorResponseHasRegistryObjectList() throws Exception {
AggregationStrategy strategy = mock(AggregationStrategy.class);
AggregationService service = mock(AggregationService.class);
DocQueryPolicyChecker policyChecker = mock(DocQueryPolicyChecker.class);
StandardOutboundDocQuery docQuery = new StandardOutboundDocQuery(strategy, service, policyChecker) {
@Override
protected DocQueryAuditLog getAuditLogger() {
return mockAuditLogger;
}
@Override
protected boolean isAuditEnabled(String propertyFile, String propertyName) {
return true;
}
};
AdhocQueryRequest adhocQueryRequest = mock(AdhocQueryRequest.class);
AssertionType assertion = mock(AssertionType.class);
NhinTargetCommunitiesType targets = mock(NhinTargetCommunitiesType.class);
AdhocQueryResponse response = docQuery
.respondingGatewayCrossGatewayQuery(adhocQueryRequest, assertion, targets);
AdhocQueryResponseAsserter.assertSchemaCompliant(response);
}
private AdhocQueryRequest createRequest(List<SlotType1> slotList) {
AdhocQueryRequest adhocQueryRequest = new AdhocQueryRequest();
AdhocQueryType adhocQuery = new AdhocQueryType();
adhocQueryRequest.setAdhocQuery(adhocQuery);
adhocQuery.setHome(HOME_HCID);
adhocQuery.getSlot().addAll(slotList);
return adhocQueryRequest;
}
private List<SlotType1> createSlotList() {
List<SlotType1> slotList = new ArrayList<SlotType1>();
SlotType1 t = new SlotType1();
t.setName(NhincConstants.DOC_QUERY_XDS_PATIENT_ID_SLOT_NAME);
ValueListType value = new ValueListType();
value.getValue().add("<id>^^^&<home community id>&ISO");
t.setValueList(value);
slotList.add(t);
return slotList;
}
/**
* @param targetCommunity
* @return
*/
public NhinTargetCommunitiesType createTargetCommunities(NhinTargetCommunityType... targetCommunities) {
NhinTargetCommunitiesType targetCommunitiesType = new NhinTargetCommunitiesType();
for (NhinTargetCommunityType targetCommunity : targetCommunities)
targetCommunitiesType.getNhinTargetCommunity().add(targetCommunity);
return targetCommunitiesType;
}
/**
* @param hcid
* @param region
* @param list
* @return
*/
public NhinTargetCommunityType createTargetCommunity(String hcid, String region, String list) {
NhinTargetCommunityType targetCommunity = new NhinTargetCommunityType();
HomeCommunityType homeCommunity = new HomeCommunityType();
homeCommunity.setHomeCommunityId(hcid);
targetCommunity.setHomeCommunity(homeCommunity);
targetCommunity.setRegion(region);
targetCommunity.setList(list);
return targetCommunity;
}
private NhinTargetCommunitiesType createNhinTargetCommunites() {
return createTargetCommunities(createTargetCommunity("4.4", "US-FL", "Unimplemented"));
}
@Test
public void hasBeginOutboundProcessingEvent() throws Exception {
Class<StandardOutboundDocQuery> clazz = StandardOutboundDocQuery.class;
Method method = clazz.getMethod("respondingGatewayCrossGatewayQuery", AdhocQueryRequest.class,
AssertionType.class, NhinTargetCommunitiesType.class);
OutboundProcessingEvent annotation = method.getAnnotation(OutboundProcessingEvent.class);
assertNotNull(annotation);
assertEquals(AdhocQueryRequestDescriptionBuilder.class, annotation.beforeBuilder());
assertEquals(AdhocQueryResponseDescriptionBuilder.class, annotation.afterReturningBuilder());
assertEquals("Document Query", annotation.serviceType());
assertEquals("", annotation.version());
}
@Test
public void testWithPolicyFailures() throws Exception {
DocQueryUnitTestUtil.setUpGatewayProperties();
AggregationStrategy strategy = mock(AggregationStrategy.class);
AdhocQueryRequest adhocQueryRequest = new AdhocQueryRequest();
adhocQueryRequest = createRequest(createSlotList());
AggregationService service = mock(AggregationService.class);
DocQueryPolicyChecker policyChecker = mock(DocQueryPolicyChecker.class);
AssertionType assertion = new AssertionType();
StandardOutboundDocQuery entitydocqueryimpl = new StandardOutboundDocQuery(strategy, service, policyChecker) {
@Override
protected DocQueryAuditLog getAuditLogger() {
return mockAuditLogger;
}
@Override
protected boolean isAuditEnabled(String propertyFile, String propertyName) {
return true;
}
};
when(policyChecker.checkOutgoingPolicy(any(AdhocQueryRequest.class), any(AssertionType.class))).thenReturn(false);
NhinTargetCommunitiesType targets = createNhinTargetCommunites();
AdhocQueryResponse response = entitydocqueryimpl.respondingGatewayCrossGatewayQuery(adhocQueryRequest,
assertion, targets);
verify(service).createChildRequests(eq(adhocQueryRequest), eq(assertion), eq(targets));
verify(mockAuditLogger).auditDQRequest(eq(adhocQueryRequest), eq(assertion),
eq(NhincConstants.AUDIT_LOG_INBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_ENTITY_INTERFACE),
eq(SENDING_HCID_FORMATTED));
verify(mockAuditLogger).auditDQResponse(eq(response), eq(assertion),
eq(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_ENTITY_INTERFACE),
eq(SENDING_HCID_FORMATTED));
AdhocQueryResponseAsserter.assertSchemaCompliant(response);
}
@Test
public void testWithMixOfPolicyFailures() throws Exception {
DocQueryUnitTestUtil.setUpGatewayProperties();
AggregationStrategy strategy = mock(AggregationStrategy.class);
AdhocQueryRequest adhocQueryRequest = new AdhocQueryRequest();
adhocQueryRequest = createRequest(createSlotList());
AggregationService service = mock(AggregationService.class);
DocQueryPolicyChecker policyChecker = mock(DocQueryPolicyChecker.class);
AssertionType assertion = new AssertionType();
StandardOutboundDocQuery entitydocqueryimpl = new StandardOutboundDocQuery(strategy, service, policyChecker) {
@Override
protected DocQueryAuditLog getAuditLogger() {
return mockAuditLogger;
}
@Override
protected boolean isAuditEnabled(String propertyFile, String propertyName) {
return true;
}
};
when(policyChecker.checkOutgoingPolicy(any(AdhocQueryRequest.class), any(AssertionType.class))).thenReturn(false).thenReturn(true);
NhinTargetCommunitiesType targets = createNhinTargetCommunites();
when(service.createChildRequests(eq(adhocQueryRequest), eq(assertion), eq(targets))).thenReturn(getOutboundOrchestratableList());
AdhocQueryResponse response = entitydocqueryimpl.respondingGatewayCrossGatewayQuery(adhocQueryRequest,
assertion, targets);
verify(mockAuditLogger).auditDQRequest(eq(adhocQueryRequest), eq(assertion),
eq(NhincConstants.AUDIT_LOG_INBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_ENTITY_INTERFACE),
eq(SENDING_HCID_FORMATTED));
verify(mockAuditLogger).auditDQResponse(eq(response), eq(assertion),
eq(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_ENTITY_INTERFACE),
eq(SENDING_HCID_FORMATTED));
verify(strategy).execute(any(Aggregate.class));
}
/**
* @return
*/
private List<OutboundOrchestratable> getOutboundOrchestratableList() {
OutboundDocQueryOrchestratable orch1 = new OutboundDocQueryOrchestratable();
OutboundDocQueryOrchestratable orch2 = new OutboundDocQueryOrchestratable();
List<OutboundOrchestratable> list = new ArrayList<OutboundOrchestratable>();
list.add(orch1);
list.add(orch2);
return list;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.event.impl.jobs;
import java.util.Calendar;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.event.impl.support.Environment;
/**
* Configuration of the job handling
*
*/
public class JobManagerConfiguration {
/** Default resource path for jobs. */
public static final String DEFAULT_REPOSITORY_PATH = "/var/eventing/jobs";
/** Default background load delay. */
public static final long DEFAULT_BACKGROUND_LOAD_DELAY = 30;
/** Default for disabling the distribution. */
public static final boolean DEFAULT_DISABLE_DISTRIBUTION = false;
/** Default resource path for scheduled jobs. */
public static final String DEFAULT_SCHEDULED_JOBS_PATH = "/var/eventing/scheduled-jobs";
/** The path where all jobs are stored. */
public static final String PROPERTY_REPOSITORY_PATH = "repository.path";
/** The background loader waits this time of seconds after startup before loading events from the repository. (in secs) */
public static final String PROPERTY_BACKGROUND_LOAD_DELAY = "load.delay";
/** Configuration switch for distributing the jobs. */
public static final String PROPERTY_DISABLE_DISTRIBUTION = "job.consumermanager.disableDistribution";
/** Configuration property for the scheduled jobs path. */
public static final String PROPERTY_SCHEDULED_JOBS_PATH = "job.scheduled.jobs.path";
/** The jobs base path with a slash. */
private String jobsBasePathWithSlash;
/** The base path for assigned jobs. */
private String assignedJobsPath;
/** The base path for unassigned jobs. */
private String unassignedJobsPath;
/** The base path for assigned jobs to the current instance. */
private String localJobsPath;
/** The base path for assigned jobs to the current instance - ending with a slash. */
private String localJobsPathWithSlash;
/** The base path for locks. */
private String locksPath;
private String previousVersionAnonPath;
private String previousVersionIdentifiedPath;
/** The base path for locks - ending with a slash. */
private String locksPathWithSlash;
private long backgroundLoadDelay;
private boolean disabledDistribution;
private String storedCancelledJobsPath;
private String storedSuccessfulJobsPath;
/** The resource path where scheduled jobs are stored. */
private String scheduledJobsPath;
/** The resource path where scheduled jobs are stored - ending with a slash. */
private String scheduledJobsPathWithSlash;
public JobManagerConfiguration(final Map<String, Object> props) {
this.update(props);
this.jobsBasePathWithSlash = PropertiesUtil.toString(props.get(PROPERTY_REPOSITORY_PATH),
DEFAULT_REPOSITORY_PATH) + '/';
// create initial resources
this.assignedJobsPath = this.jobsBasePathWithSlash + "assigned";
this.unassignedJobsPath = this.jobsBasePathWithSlash + "unassigned";
this.locksPath = this.jobsBasePathWithSlash + "locks";
this.locksPathWithSlash = this.locksPath.concat("/");
this.localJobsPath = this.assignedJobsPath.concat("/").concat(Environment.APPLICATION_ID);
this.localJobsPathWithSlash = this.localJobsPath.concat("/");
this.previousVersionAnonPath = this.jobsBasePathWithSlash + "anon";
this.previousVersionIdentifiedPath = this.jobsBasePathWithSlash + "identified";
this.storedCancelledJobsPath = this.jobsBasePathWithSlash + "cancelled";
this.storedSuccessfulJobsPath = this.jobsBasePathWithSlash + "finished";
this.scheduledJobsPath = PropertiesUtil.toString(props.get(PROPERTY_SCHEDULED_JOBS_PATH),
DEFAULT_SCHEDULED_JOBS_PATH);
this.scheduledJobsPathWithSlash = this.scheduledJobsPath + "/";
}
/**
* Update with a new configuration
*/
public void update(final Map<String, Object> props) {
this.disabledDistribution = PropertiesUtil.toBoolean(props.get(PROPERTY_DISABLE_DISTRIBUTION), DEFAULT_DISABLE_DISTRIBUTION);
this.backgroundLoadDelay = PropertiesUtil.toLong(props.get(PROPERTY_BACKGROUND_LOAD_DELAY), DEFAULT_BACKGROUND_LOAD_DELAY);
}
/**
* Get the resource path for all assigned jobs.
* @return The path - does not end with a slash.
*/
public String getAssginedJobsPath() {
return this.assignedJobsPath;
}
/**
* Get the resource path for all unassigned jobs.
* @return The path - does not end with a slash.
*/
public String getUnassignedJobsPath() {
return this.unassignedJobsPath;
}
/**
* Get the resource path for all jobs assigned to the current instance
* @return The path - does not end with a slash
*/
public String getLocalJobsPath() {
return this.localJobsPath;
}
/**
* Get the resource path for all locks
* @return The path - does not end with a slash
*/
public String getLocksPath() {
return this.locksPath;
}
public long getBackgroundLoadDelay() {
return backgroundLoadDelay;
}
/** Counter for jobs without an id. */
private final AtomicLong jobCounter = new AtomicLong(0);
/**
* Create a unique job path (folder and name) for the job.
*/
public String getUniquePath(final String targetId,
final String topic,
final String jobId,
final Map<String, Object> jobProperties) {
final boolean isBridged = (jobProperties != null ? jobProperties.containsKey(JobImpl.PROPERTY_BRIDGED_EVENT) : false);
final String topicName = (isBridged ? JobImpl.PROPERTY_BRIDGED_EVENT : topic.replace('/', '.'));
final StringBuilder sb = new StringBuilder();
if ( targetId != null ) {
sb.append(this.assignedJobsPath);
sb.append('/');
sb.append(targetId);
} else {
sb.append(this.unassignedJobsPath);
}
sb.append('/');
sb.append(topicName);
sb.append('/');
sb.append(jobId);
return sb.toString();
}
/**
* Get the unique job id
*/
public String getUniqueId(final String jobTopic) {
final String convTopic = jobTopic.replace('/', '.');
final Calendar now = Calendar.getInstance();
final StringBuilder sb = new StringBuilder();
sb.append(now.get(Calendar.YEAR));
sb.append('/');
sb.append(now.get(Calendar.MONTH) + 1);
sb.append('/');
sb.append(now.get(Calendar.DAY_OF_MONTH));
sb.append('/');
sb.append(now.get(Calendar.HOUR_OF_DAY));
sb.append('/');
sb.append(now.get(Calendar.MINUTE));
sb.append('/');
sb.append(convTopic);
sb.append('_');
sb.append(Environment.APPLICATION_ID);
sb.append('_');
sb.append(jobCounter.getAndIncrement());
return sb.toString();
}
public boolean isLocalJob(final String jobPath) {
return jobPath.startsWith(this.localJobsPathWithSlash);
}
public boolean isJob(final String jobPath) {
return jobPath.startsWith(this.jobsBasePathWithSlash);
}
public boolean isLock(final String lockPath) {
return lockPath.startsWith(this.locksPathWithSlash);
}
public String getPreviousVersionAnonPath() {
return this.previousVersionAnonPath;
}
public String getPreviousVersionIdentifiedPath() {
return this.previousVersionIdentifiedPath;
}
public boolean disableDistribution() {
return this.disabledDistribution;
}
public String getStoredCancelledJobsPath() {
return this.storedCancelledJobsPath;
}
public String getStoredSuccessfulJobsPath() {
return this.storedSuccessfulJobsPath;
}
/**
* Get the storage path for finished jobs.
* @param finishedJob The finished job
* @param isSuccess Whether processing was successful or not
* @return The complete storage path
*/
public String getStoragePath(final JobImpl finishedJob, final boolean isSuccess) {
final String topicName = (finishedJob.isBridgedEvent() ? JobImpl.PROPERTY_BRIDGED_EVENT : finishedJob.getTopic().replace('/', '.'));
final StringBuilder sb = new StringBuilder();
if ( isSuccess ) {
sb.append(this.storedSuccessfulJobsPath);
} else {
sb.append(this.storedCancelledJobsPath);
}
sb.append('/');
sb.append(topicName);
sb.append('/');
sb.append(finishedJob.getId());
return sb.toString();
}
/**
* Check whether this is a storage path.
*/
public boolean isStoragePath(final String path) {
return path.startsWith(this.storedCancelledJobsPath) || path.startsWith(this.storedSuccessfulJobsPath);
}
public String getScheduledJobsPath() {
return this.scheduledJobsPath;
}
public String getScheduledJobsPathWithSlash() {
return this.scheduledJobsPathWithSlash;
}
}
| |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.reader.gtfs;
import com.carrotsearch.hppc.IntObjectHashMap;
import com.carrotsearch.hppc.IntObjectMap;
import com.google.common.collect.ArrayListMultimap;
import com.graphhopper.routing.ev.BooleanEncodedValue;
import com.graphhopper.routing.ev.DecimalEncodedValue;
import com.graphhopper.routing.ev.EnumEncodedValue;
import com.graphhopper.routing.ev.IntEncodedValue;
import com.graphhopper.routing.querygraph.VirtualEdgeIteratorState;
import com.graphhopper.routing.util.AllEdgesIterator;
import com.graphhopper.routing.util.EdgeFilter;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.storage.Graph;
import com.graphhopper.storage.IntsRef;
import com.graphhopper.storage.NodeAccess;
import com.graphhopper.storage.TurnCostStorage;
import com.graphhopper.util.*;
import com.graphhopper.util.shapes.BBox;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;
public class WrapperGraph implements Graph {
private final Graph mainGraph;
private final IntObjectMap<EdgeIteratorState> extraEdges = new IntObjectHashMap<>();
private final ArrayListMultimap<Integer, VirtualEdgeIteratorState> extraEdgesBySource = ArrayListMultimap.create();
private final ArrayListMultimap<Integer, VirtualEdgeIteratorState> extraEdgesByDestination = ArrayListMultimap.create();
public WrapperGraph(Graph mainGraph, List<VirtualEdgeIteratorState> extraEdges) {
this.mainGraph = mainGraph;
extraEdges.forEach(e -> this.extraEdges.put(e.getEdge(), e));
for (VirtualEdgeIteratorState extraEdge : extraEdges) {
if (extraEdge == null) {
throw new RuntimeException();
}
extraEdgesBySource.put(extraEdge.getBaseNode(), extraEdge);
extraEdgesByDestination.put(extraEdge.getAdjNode(), new VirtualEdgeIteratorState(extraEdge.getOriginalEdgeKey(), extraEdge.getEdge(), extraEdge.getAdjNode(),
extraEdge.getBaseNode(), extraEdge.getDistance(), extraEdge.getFlags(), extraEdge.getName(), extraEdge.fetchWayGeometry(FetchMode.ALL), true));
}
}
@Override
public Graph getBaseGraph() {
return this;
}
@Override
public int getNodes() {
return IntStream.concat(
IntStream.of(mainGraph.getNodes() - 1),
StreamSupport.stream(extraEdges.values().spliterator(), false)
.flatMapToInt(cursor -> IntStream.of(cursor.value.getBaseNode(), cursor.value.getAdjNode()))
).max().getAsInt() + 1;
}
@Override
public int getEdges() {
return getAllEdges().length();
}
@Override
public NodeAccess getNodeAccess() {
return mainGraph.getNodeAccess();
}
@Override
public BBox getBounds() {
return mainGraph.getBounds();
}
@Override
public EdgeIteratorState edge(int a, int b) {
throw new RuntimeException();
}
@Override
public EdgeIteratorState edge(int a, int b, double distance, boolean bothDirections) {
throw new RuntimeException();
}
@Override
public EdgeIteratorState getEdgeIteratorState(int edgeId, int adjNode) {
EdgeIteratorState edgeIteratorState = extraEdges.get(edgeId);
if (edgeIteratorState != null) {
return edgeIteratorState;
} else {
return mainGraph.getEdgeIteratorState(edgeId, adjNode);
}
}
@Override
public AllEdgesIterator getAllEdges() {
return new AllEdgesIterator() {
@Override
public int length() {
return IntStream.concat(
IntStream.of(mainGraph.getAllEdges().length() - 1),
StreamSupport.stream(extraEdges.values().spliterator(), false).mapToInt(cursor -> cursor.value.getEdge()))
.max().getAsInt() + 1;
}
@Override
public boolean next() {
throw new UnsupportedOperationException();
}
@Override
public int getEdge() {
throw new UnsupportedOperationException();
}
@Override
public int getOrigEdgeFirst() {
return getEdge();
}
@Override
public int getOrigEdgeLast() {
return getEdge();
}
@Override
public int getBaseNode() {
throw new UnsupportedOperationException();
}
@Override
public int getAdjNode() {
throw new UnsupportedOperationException();
}
@Override
public PointList fetchWayGeometry(FetchMode mode) {
throw new UnsupportedOperationException();
}
@Override
public EdgeIteratorState setWayGeometry(PointList list) {
throw new UnsupportedOperationException();
}
@Override
public double getDistance() {
throw new UnsupportedOperationException();
}
@Override
public EdgeIteratorState setDistance(double dist) {
throw new UnsupportedOperationException();
}
@Override
public IntsRef getFlags() {
throw new UnsupportedOperationException();
}
@Override
public EdgeIteratorState setFlags(IntsRef flags) {
throw new UnsupportedOperationException();
}
@Override
public boolean get(BooleanEncodedValue property) {
throw new UnsupportedOperationException();
}
@Override
public EdgeIteratorState set(BooleanEncodedValue property, boolean value) {
throw new UnsupportedOperationException();
}
@Override
public boolean getReverse(BooleanEncodedValue property) {
throw new UnsupportedOperationException();
}
@Override
public EdgeIteratorState setReverse(BooleanEncodedValue property, boolean value) {
throw new UnsupportedOperationException();
}
@Override
public int get(IntEncodedValue property) {
throw new UnsupportedOperationException();
}
@Override
public int getReverse(IntEncodedValue property) {
throw new UnsupportedOperationException();
}
@Override
public EdgeIteratorState set(IntEncodedValue property, int value) {
throw new UnsupportedOperationException();
}
@Override
public EdgeIteratorState setReverse(IntEncodedValue property, int value) {
throw new UnsupportedOperationException();
}
@Override
public double get(DecimalEncodedValue property) {
throw new UnsupportedOperationException();
}
@Override
public double getReverse(DecimalEncodedValue property) {
throw new UnsupportedOperationException();
}
@Override
public EdgeIteratorState set(DecimalEncodedValue property, double value) {
throw new UnsupportedOperationException();
}
@Override
public EdgeIteratorState setReverse(DecimalEncodedValue property, double value) {
throw new UnsupportedOperationException();
}
@Override
public <T extends Enum> T get(EnumEncodedValue<T> property) {
throw new UnsupportedOperationException();
}
@Override
public <T extends Enum> T getReverse(EnumEncodedValue<T> property) {
throw new UnsupportedOperationException();
}
@Override
public <T extends Enum> EdgeIteratorState set(EnumEncodedValue<T> property, T value) {
throw new UnsupportedOperationException();
}
@Override
public <T extends Enum> EdgeIteratorState setReverse(EnumEncodedValue<T> property, T value) {
throw new UnsupportedOperationException();
}
@Override
public String getName() {
throw new UnsupportedOperationException();
}
@Override
public EdgeIteratorState setName(String name) {
throw new UnsupportedOperationException();
}
@Override
public EdgeIteratorState detach(boolean reverse) {
throw new UnsupportedOperationException();
}
@Override
public EdgeIteratorState copyPropertiesFrom(EdgeIteratorState e) {
throw new UnsupportedOperationException();
}
};
}
@Override
public EdgeExplorer createEdgeExplorer(EdgeFilter filter) {
EdgeExplorer baseGraphEdgeExplorer = mainGraph.createEdgeExplorer(filter);
return new EdgeExplorer() {
@Override
public EdgeIterator setBaseNode(int baseNode) {
final List<VirtualEdgeIteratorState> extraEdges = new ArrayList<>();
extraEdges.addAll(extraEdgesBySource.get(baseNode));
extraEdges.addAll(extraEdgesByDestination.get(baseNode));
Iterator<VirtualEdgeIteratorState> iterator = extraEdges.iterator();
return new EdgeIterator() {
EdgeIteratorState current = null;
EdgeIterator baseGraphEdgeIterator = baseGraphIterator();
private EdgeIterator baseGraphIterator() {
if (baseNode < mainGraph.getNodes()) {
return baseGraphEdgeExplorer.setBaseNode(baseNode);
} else {
return null;
}
}
@Override
public boolean next() {
if (baseGraphEdgeIterator != null) {
if (baseGraphEdgeIterator.next()) {
current = baseGraphEdgeIterator;
return true;
} else {
baseGraphEdgeIterator = null;
}
}
while(iterator.hasNext()) {
current = iterator.next();
if (filter.accept(current)) {
return true;
}
}
return false;
}
@Override
public int getEdge() {
return current.getEdge();
}
@Override
public int getOrigEdgeFirst() {
return current.getOrigEdgeFirst();
}
@Override
public int getOrigEdgeLast() {
return current.getOrigEdgeLast();
}
@Override
public int getBaseNode() {
return current.getBaseNode();
}
@Override
public int getAdjNode() {
return current.getAdjNode();
}
@Override
public PointList fetchWayGeometry(FetchMode mode) {
return current.fetchWayGeometry(mode);
}
@Override
public EdgeIteratorState setWayGeometry(PointList list) {
current.setWayGeometry(list);
return this;
}
@Override
public double getDistance() {
return current.getDistance();
}
@Override
public EdgeIteratorState setDistance(double dist) {
current.setDistance(dist);
return this;
}
@Override
public IntsRef getFlags() {
return current.getFlags();
}
@Override
public EdgeIteratorState setFlags(IntsRef edgeFlags) {
current.setFlags(edgeFlags);
return this;
}
@Override
public boolean get(BooleanEncodedValue property) {
return current.get(property);
}
@Override
public EdgeIteratorState set(BooleanEncodedValue property, boolean value) {
current.set(property, value);
return this;
}
@Override
public boolean getReverse(BooleanEncodedValue property) {
return current.getReverse(property);
}
@Override
public EdgeIteratorState setReverse(BooleanEncodedValue property, boolean value) {
current.setReverse(property, value);
return this;
}
@Override
public int get(IntEncodedValue property) {
return current.get(property);
}
@Override
public EdgeIteratorState set(IntEncodedValue property, int value) {
current.set(property, value);
return this;
}
@Override
public int getReverse(IntEncodedValue property) {
return current.getReverse(property);
}
@Override
public EdgeIteratorState setReverse(IntEncodedValue property, int value) {
current.setReverse(property, value);
return this;
}
@Override
public double get(DecimalEncodedValue property) {
return current.get(property);
}
@Override
public EdgeIteratorState set(DecimalEncodedValue property, double value) {
current.set(property, value);
return this;
}
@Override
public double getReverse(DecimalEncodedValue property) {
return current.getReverse(property);
}
@Override
public EdgeIteratorState setReverse(DecimalEncodedValue property, double value) {
current.setReverse(property, value);
return this;
}
@Override
public <T extends Enum> T get(EnumEncodedValue<T> property) {
return current.get(property);
}
@Override
public <T extends Enum> EdgeIteratorState set(EnumEncodedValue<T> property, T value) {
current.set(property, value);
return this;
}
@Override
public <T extends Enum> T getReverse(EnumEncodedValue<T> property) {
return current.getReverse(property);
}
@Override
public <T extends Enum> EdgeIteratorState setReverse(EnumEncodedValue<T> property, T value) {
current.setReverse(property, value);
return this;
}
@Override
public String getName() {
return current.getName();
}
@Override
public EdgeIteratorState setName(String name) {
current.setName(name);
return this;
}
@Override
public EdgeIteratorState detach(boolean reverse) {
return current.detach(reverse);
}
@Override
public EdgeIteratorState copyPropertiesFrom(EdgeIteratorState e) {
return current.copyPropertiesFrom(e);
}
@Override
public String toString() {
return current.toString();
}
};
}
};
}
@Override
public EdgeExplorer createEdgeExplorer() {
return createEdgeExplorer(EdgeFilter.ALL_EDGES);
}
@Override
public Graph copyTo(Graph g) {
throw new RuntimeException();
}
@Override
public TurnCostStorage getTurnCostStorage() {
return mainGraph.getTurnCostStorage();
}
@Override
public Weighting wrapWeighting(Weighting weighting) {
return mainGraph.wrapWeighting(weighting);
}
@Override
public int getOtherNode(int edge, int node) {
return mainGraph.getOtherNode(edge, node);
}
@Override
public boolean isAdjacentToNode(int edge, int node) {
return mainGraph.isAdjacentToNode(edge, node);
}
}
| |
/*
* 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.runtime.metrics;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.metrics.Metric;
import org.apache.flink.metrics.MetricConfig;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.metrics.View;
import org.apache.flink.metrics.reporter.MetricReporter;
import org.apache.flink.metrics.reporter.Scheduled;
import org.apache.flink.runtime.akka.AkkaUtils;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.metrics.dump.MetricQueryService;
import org.apache.flink.runtime.metrics.groups.AbstractMetricGroup;
import org.apache.flink.runtime.metrics.groups.FrontMetricGroup;
import org.apache.flink.runtime.metrics.scope.ScopeFormats;
import org.apache.flink.runtime.util.ExecutorThreadFactory;
import org.apache.flink.util.Preconditions;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Kill;
import akka.pattern.Patterns;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.FiniteDuration;
/**
* A MetricRegistry keeps track of all registered {@link Metric Metrics}. It serves as the
* connection between {@link MetricGroup MetricGroups} and {@link MetricReporter MetricReporters}.
*/
public class MetricRegistryImpl implements MetricRegistry {
static final Logger LOG = LoggerFactory.getLogger(MetricRegistryImpl.class);
private final Object lock = new Object();
private List<MetricReporter> reporters;
private ScheduledExecutorService executor;
@Nullable
private ActorRef queryService;
@Nullable
private String metricQueryServicePath;
private ViewUpdater viewUpdater;
private final ScopeFormats scopeFormats;
private final char globalDelimiter;
private final List<Character> delimiters = new ArrayList<>();
/**
* Creates a new MetricRegistry and starts the configured reporter.
*/
public MetricRegistryImpl(MetricRegistryConfiguration config) {
this.scopeFormats = config.getScopeFormats();
this.globalDelimiter = config.getDelimiter();
// second, instantiate any custom configured reporters
this.reporters = new ArrayList<>();
List<Tuple2<String, Configuration>> reporterConfigurations = config.getReporterConfigurations();
this.executor = Executors.newSingleThreadScheduledExecutor(new ExecutorThreadFactory("Flink-MetricRegistry"));
this.queryService = null;
this.metricQueryServicePath = null;
if (reporterConfigurations.isEmpty()) {
// no reporters defined
// by default, don't report anything
LOG.info("No metrics reporter configured, no metrics will be exposed/reported.");
} else {
// we have some reporters so
for (Tuple2<String, Configuration> reporterConfiguration: reporterConfigurations) {
String namedReporter = reporterConfiguration.f0;
Configuration reporterConfig = reporterConfiguration.f1;
final String className = reporterConfig.getString(ConfigConstants.METRICS_REPORTER_CLASS_SUFFIX, null);
if (className == null) {
LOG.error("No reporter class set for reporter " + namedReporter + ". Metrics might not be exposed/reported.");
continue;
}
try {
String configuredPeriod = reporterConfig.getString(ConfigConstants.METRICS_REPORTER_INTERVAL_SUFFIX, null);
TimeUnit timeunit = TimeUnit.SECONDS;
long period = 10;
if (configuredPeriod != null) {
try {
String[] interval = configuredPeriod.split(" ");
period = Long.parseLong(interval[0]);
timeunit = TimeUnit.valueOf(interval[1]);
}
catch (Exception e) {
LOG.error("Cannot parse report interval from config: " + configuredPeriod +
" - please use values like '10 SECONDS' or '500 MILLISECONDS'. " +
"Using default reporting interval.");
}
}
Class<?> reporterClass = Class.forName(className);
MetricReporter reporterInstance = (MetricReporter) reporterClass.newInstance();
MetricConfig metricConfig = new MetricConfig();
reporterConfig.addAllToProperties(metricConfig);
LOG.info("Configuring {} with {}.", reporterClass.getSimpleName(), metricConfig);
reporterInstance.open(metricConfig);
if (reporterInstance instanceof Scheduled) {
LOG.info("Periodically reporting metrics in intervals of {} {} for reporter {} of type {}.", period, timeunit.name(), namedReporter, className);
executor.scheduleWithFixedDelay(
new MetricRegistryImpl.ReporterTask((Scheduled) reporterInstance), period, period, timeunit);
} else {
LOG.info("Reporting metrics for reporter {} of type {}.", namedReporter, className);
}
reporters.add(reporterInstance);
String delimiterForReporter = reporterConfig.getString(ConfigConstants.METRICS_REPORTER_SCOPE_DELIMITER, String.valueOf(globalDelimiter));
if (delimiterForReporter.length() != 1) {
LOG.warn("Failed to parse delimiter '{}' for reporter '{}', using global delimiter '{}'.", delimiterForReporter, namedReporter, globalDelimiter);
delimiterForReporter = String.valueOf(globalDelimiter);
}
this.delimiters.add(delimiterForReporter.charAt(0));
}
catch (Throwable t) {
LOG.error("Could not instantiate metrics reporter {}. Metrics might not be exposed/reported.", namedReporter, t);
}
}
}
}
/**
* Initializes the MetricQueryService.
*
* @param actorSystem ActorSystem to create the MetricQueryService on
* @param resourceID resource ID used to disambiguate the actor name
*/
public void startQueryService(ActorSystem actorSystem, ResourceID resourceID) {
synchronized (lock) {
Preconditions.checkState(!isShutdown(), "The metric registry has already been shut down.");
try {
queryService = MetricQueryService.startMetricQueryService(actorSystem, resourceID);
metricQueryServicePath = AkkaUtils.getAkkaURL(actorSystem, queryService);
} catch (Exception e) {
LOG.warn("Could not start MetricDumpActor. No metrics will be submitted to the WebInterface.", e);
}
}
}
/**
* Returns the address under which the {@link MetricQueryService} is reachable.
*
* @return address of the metric query service
*/
@Override
@Nullable
public String getMetricQueryServicePath() {
return metricQueryServicePath;
}
@Override
public char getDelimiter() {
return this.globalDelimiter;
}
@Override
public char getDelimiter(int reporterIndex) {
try {
return delimiters.get(reporterIndex);
} catch (IndexOutOfBoundsException e) {
LOG.warn("Delimiter for reporter index {} not found, returning global delimiter.", reporterIndex);
return this.globalDelimiter;
}
}
@Override
public int getNumberReporters() {
return reporters.size();
}
@VisibleForTesting
public List<MetricReporter> getReporters() {
return reporters;
}
/**
* Returns whether this registry has been shutdown.
*
* @return true, if this registry was shutdown, otherwise false
*/
public boolean isShutdown() {
synchronized (lock) {
return reporters == null && executor.isShutdown();
}
}
/**
* Shuts down this registry and the associated {@link MetricReporter}.
*/
public void shutdown() {
synchronized (lock) {
Future<Boolean> stopFuture = null;
FiniteDuration stopTimeout = null;
if (queryService != null) {
stopTimeout = new FiniteDuration(1L, TimeUnit.SECONDS);
try {
stopFuture = Patterns.gracefulStop(queryService, stopTimeout);
} catch (IllegalStateException ignored) {
// this can happen if the underlying actor system has been stopped before shutting
// the metric registry down
// TODO: Pull the MetricQueryService actor out of the MetricRegistry
LOG.debug("The metric query service actor has already been stopped because the " +
"underlying ActorSystem has already been shut down.");
}
}
if (reporters != null) {
for (MetricReporter reporter : reporters) {
try {
reporter.close();
} catch (Throwable t) {
LOG.warn("Metrics reporter did not shut down cleanly", t);
}
}
reporters = null;
}
shutdownExecutor();
if (stopFuture != null) {
boolean stopped = false;
try {
stopped = Await.result(stopFuture, stopTimeout);
} catch (Exception e) {
LOG.warn("Query actor did not properly stop.", e);
}
if (!stopped) {
// the query actor did not stop in time, let's kill him
queryService.tell(Kill.getInstance(), ActorRef.noSender());
}
}
}
}
private void shutdownExecutor() {
if (executor != null) {
executor.shutdown();
try {
if (!executor.awaitTermination(1L, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
}
}
}
@Override
public ScopeFormats getScopeFormats() {
return scopeFormats;
}
// ------------------------------------------------------------------------
// Metrics (de)registration
// ------------------------------------------------------------------------
@Override
public void register(Metric metric, String metricName, AbstractMetricGroup group) {
synchronized (lock) {
if (isShutdown()) {
LOG.warn("Cannot register metric, because the MetricRegistry has already been shut down.");
} else {
if (reporters != null) {
for (int i = 0; i < reporters.size(); i++) {
MetricReporter reporter = reporters.get(i);
try {
if (reporter != null) {
FrontMetricGroup front = new FrontMetricGroup<AbstractMetricGroup<?>>(i, group);
reporter.notifyOfAddedMetric(metric, metricName, front);
}
} catch (Exception e) {
LOG.warn("Error while registering metric.", e);
}
}
}
try {
if (queryService != null) {
MetricQueryService.notifyOfAddedMetric(queryService, metric, metricName, group);
}
} catch (Exception e) {
LOG.warn("Error while registering metric.", e);
}
try {
if (metric instanceof View) {
if (viewUpdater == null) {
viewUpdater = new ViewUpdater(executor);
}
viewUpdater.notifyOfAddedView((View) metric);
}
} catch (Exception e) {
LOG.warn("Error while registering metric.", e);
}
}
}
}
@Override
public void unregister(Metric metric, String metricName, AbstractMetricGroup group) {
synchronized (lock) {
if (isShutdown()) {
LOG.warn("Cannot unregister metric, because the MetricRegistry has already been shut down.");
} else {
if (reporters != null) {
for (int i = 0; i < reporters.size(); i++) {
try {
MetricReporter reporter = reporters.get(i);
if (reporter != null) {
FrontMetricGroup front = new FrontMetricGroup<AbstractMetricGroup<?>>(i, group);
reporter.notifyOfRemovedMetric(metric, metricName, front);
}
} catch (Exception e) {
LOG.warn("Error while registering metric.", e);
}
}
}
try {
if (queryService != null) {
MetricQueryService.notifyOfRemovedMetric(queryService, metric);
}
} catch (Exception e) {
LOG.warn("Error while registering metric.", e);
}
try {
if (metric instanceof View) {
if (viewUpdater != null) {
viewUpdater.notifyOfRemovedView((View) metric);
}
}
} catch (Exception e) {
LOG.warn("Error while registering metric.", e);
}
}
}
}
// ------------------------------------------------------------------------
@VisibleForTesting
@Nullable
public ActorRef getQueryService() {
return queryService;
}
// ------------------------------------------------------------------------
/**
* This task is explicitly a static class, so that it does not hold any references to the enclosing
* MetricsRegistry instance.
*
* <p>This is a subtle difference, but very important: With this static class, the enclosing class instance
* may become garbage-collectible, whereas with an anonymous inner class, the timer thread
* (which is a GC root) will hold a reference via the timer task and its enclosing instance pointer.
* Making the MetricsRegistry garbage collectible makes the java.util.Timer garbage collectible,
* which acts as a fail-safe to stop the timer thread and prevents resource leaks.
*/
private static final class ReporterTask extends TimerTask {
private final Scheduled reporter;
private ReporterTask(Scheduled reporter) {
this.reporter = reporter;
}
@Override
public void run() {
try {
reporter.report();
} catch (Throwable t) {
LOG.warn("Error while reporting metrics", t);
}
}
}
}
| |
/*
* 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.server.coordinator.helper;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.druid.client.DataSourcesSnapshot;
import org.apache.druid.client.indexing.ClientCompactQueryTuningConfig;
import org.apache.druid.client.indexing.IndexingServiceClient;
import org.apache.druid.client.indexing.NoopIndexingServiceClient;
import org.apache.druid.indexer.TaskStatusPlus;
import org.apache.druid.java.util.common.Intervals;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.server.coordinator.CoordinatorCompactionConfig;
import org.apache.druid.server.coordinator.CoordinatorRuntimeParamsTestHelpers;
import org.apache.druid.server.coordinator.CoordinatorStats;
import org.apache.druid.server.coordinator.DataSourceCompactionConfig;
import org.apache.druid.server.coordinator.DruidCoordinatorRuntimeParams;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.TimelineObjectHolder;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import org.apache.druid.timeline.partition.NumberedShardSpec;
import org.apache.druid.timeline.partition.PartitionChunk;
import org.apache.druid.timeline.partition.ShardSpec;
import org.joda.time.Interval;
import org.joda.time.Period;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
public class DruidCoordinatorSegmentCompactorTest
{
private static final String DATA_SOURCE_PREFIX = "dataSource_";
private final IndexingServiceClient indexingServiceClient = new NoopIndexingServiceClient()
{
private int compactVersionSuffix = 0;
private int idSuffix = 0;
@Override
public String compactSegments(
List<DataSegment> segments,
@Nullable Long targetCompactionSizeBytes,
int compactionTaskPriority,
ClientCompactQueryTuningConfig tuningConfig,
Map<String, Object> context
)
{
Preconditions.checkArgument(segments.size() > 1);
Collections.sort(segments);
Interval compactInterval = new Interval(
segments.get(0).getInterval().getStart(),
segments.get(segments.size() - 1).getInterval().getEnd()
);
final VersionedIntervalTimeline<String, DataSegment> timeline = dataSources.get(segments.get(0).getDataSource());
segments.forEach(
segment -> timeline.remove(
segment.getInterval(),
segment.getVersion(),
segment.getShardSpec().createChunk(segment)
)
);
final String version = "newVersion_" + compactVersionSuffix++;
final long segmentSize = segments.stream().mapToLong(DataSegment::getSize).sum() / 2;
for (int i = 0; i < 2; i++) {
DataSegment compactSegment = new DataSegment(
segments.get(0).getDataSource(),
compactInterval,
version,
null,
segments.get(0).getDimensions(),
segments.get(0).getMetrics(),
new NumberedShardSpec(i, 0),
1,
segmentSize
);
timeline.add(
compactInterval,
compactSegment.getVersion(),
compactSegment.getShardSpec().createChunk(compactSegment)
);
}
return "task_" + idSuffix++;
}
@Override
public List<TaskStatusPlus> getActiveTasks()
{
return Collections.emptyList();
}
@Override
public int getTotalWorkerCapacity()
{
return 10;
}
};
private Map<String, VersionedIntervalTimeline<String, DataSegment>> dataSources;
@Before
public void setup()
{
List<DataSegment> segments = new ArrayList<>();
for (int i = 0; i < 3; i++) {
final String dataSource = DATA_SOURCE_PREFIX + i;
for (int j : new int[] {0, 1, 2, 3, 7, 8}) {
for (int k = 0; k < 4; k++) {
segments.add(createSegment(dataSource, j, true, k));
segments.add(createSegment(dataSource, j, false, k));
}
}
}
dataSources = DataSourcesSnapshot
.fromUsedSegments(segments, ImmutableMap.of())
.getUsedSegmentsTimelinesPerDataSource();
}
private static DataSegment createSegment(String dataSource, int startDay, boolean beforeNoon, int partition)
{
final ShardSpec shardSpec = new NumberedShardSpec(partition, 2);
final Interval interval = beforeNoon ?
Intervals.of(
StringUtils.format(
"2017-01-%02dT00:00:00/2017-01-%02dT12:00:00",
startDay + 1,
startDay + 1
)
) :
Intervals.of(
StringUtils.format(
"2017-01-%02dT12:00:00/2017-01-%02dT00:00:00",
startDay + 1,
startDay + 2
)
);
return new DataSegment(
dataSource,
interval,
"version",
null,
ImmutableList.of(),
ImmutableList.of(),
shardSpec,
0,
10L
);
}
@Test
public void testRun()
{
final DruidCoordinatorSegmentCompactor compactor = new DruidCoordinatorSegmentCompactor(indexingServiceClient);
final Supplier<String> expectedVersionSupplier = new Supplier<String>()
{
private int i = 0;
@Override
public String get()
{
return "newVersion_" + i++;
}
};
int expectedCompactTaskCount = 1;
int expectedRemainingSegments = 400;
// compact for 2017-01-08T12:00:00.000Z/2017-01-09T12:00:00.000Z
assertCompactSegments(
compactor,
Intervals.of("2017-01-%02dT00:00:00/2017-01-%02dT12:00:00", 9, 9),
expectedRemainingSegments,
expectedCompactTaskCount,
expectedVersionSupplier
);
expectedRemainingSegments -= 40;
assertCompactSegments(
compactor,
Intervals.of("2017-01-%02dT12:00:00/2017-01-%02dT00:00:00", 8, 9),
expectedRemainingSegments,
expectedCompactTaskCount,
expectedVersionSupplier
);
// compact for 2017-01-07T12:00:00.000Z/2017-01-08T12:00:00.000Z
expectedRemainingSegments -= 40;
assertCompactSegments(
compactor,
Intervals.of("2017-01-%02dT00:00:00/2017-01-%02dT12:00:00", 8, 8),
expectedRemainingSegments,
expectedCompactTaskCount,
expectedVersionSupplier
);
expectedRemainingSegments -= 40;
assertCompactSegments(
compactor,
Intervals.of("2017-01-%02dT12:00:00/2017-01-%02dT00:00:00", 4, 5),
expectedRemainingSegments,
expectedCompactTaskCount,
expectedVersionSupplier
);
for (int endDay = 4; endDay > 1; endDay -= 1) {
expectedRemainingSegments -= 40;
assertCompactSegments(
compactor,
Intervals.of("2017-01-%02dT00:00:00/2017-01-%02dT12:00:00", endDay, endDay),
expectedRemainingSegments,
expectedCompactTaskCount,
expectedVersionSupplier
);
expectedRemainingSegments -= 40;
assertCompactSegments(
compactor,
Intervals.of("2017-01-%02dT12:00:00/2017-01-%02dT00:00:00", endDay - 1, endDay),
expectedRemainingSegments,
expectedCompactTaskCount,
expectedVersionSupplier
);
}
assertLastSegmentNotCompacted(compactor);
}
private CoordinatorStats runCompactor(DruidCoordinatorSegmentCompactor compactor)
{
DruidCoordinatorRuntimeParams params = CoordinatorRuntimeParamsTestHelpers
.newBuilder()
.withUsedSegmentsTimelinesPerDataSourceInTest(dataSources)
.withCompactionConfig(CoordinatorCompactionConfig.from(createCompactionConfigs()))
.build();
return compactor.run(params).getCoordinatorStats();
}
private void assertCompactSegments(
DruidCoordinatorSegmentCompactor compactor,
Interval expectedInterval,
int expectedRemainingSegments,
int expectedCompactTaskCount,
Supplier<String> expectedVersionSupplier
)
{
for (int i = 0; i < 3; i++) {
final CoordinatorStats stats = runCompactor(compactor);
Assert.assertEquals(
expectedCompactTaskCount,
stats.getGlobalStat(DruidCoordinatorSegmentCompactor.COMPACT_TASK_COUNT)
);
// One of dataSource is compacted
if (expectedRemainingSegments > 0) {
// If expectedRemainingSegments is positive, we check how many dataSources have the segments waiting for
// compaction.
long numDataSourceOfExpectedRemainingSegments = stats
.getDataSources(DruidCoordinatorSegmentCompactor.SEGMENT_SIZE_WAIT_COMPACT)
.stream()
.mapToLong(ds -> stats.getDataSourceStat(DruidCoordinatorSegmentCompactor.SEGMENT_SIZE_WAIT_COMPACT, ds))
.filter(stat -> stat == expectedRemainingSegments)
.count();
Assert.assertEquals(i + 1, numDataSourceOfExpectedRemainingSegments);
} else {
// Otherwise, we check how many dataSources are in the coordinator stats.
Assert.assertEquals(
2 - i,
stats.getDataSources(DruidCoordinatorSegmentCompactor.SEGMENT_SIZE_WAIT_COMPACT).size()
);
}
}
for (int i = 0; i < 3; i++) {
final String dataSource = DATA_SOURCE_PREFIX + i;
List<TimelineObjectHolder<String, DataSegment>> holders = dataSources.get(dataSource).lookup(expectedInterval);
Assert.assertEquals(1, holders.size());
List<PartitionChunk<DataSegment>> chunks = Lists.newArrayList(holders.get(0).getObject());
Assert.assertEquals(2, chunks.size());
final String expectedVersion = expectedVersionSupplier.get();
for (PartitionChunk<DataSegment> chunk : chunks) {
Assert.assertEquals(expectedInterval, chunk.getObject().getInterval());
Assert.assertEquals(expectedVersion, chunk.getObject().getVersion());
}
}
}
private void assertLastSegmentNotCompacted(DruidCoordinatorSegmentCompactor compactor)
{
// Segments of the latest interval should not be compacted
for (int i = 0; i < 3; i++) {
final String dataSource = DATA_SOURCE_PREFIX + i;
final Interval interval = Intervals.of(StringUtils.format("2017-01-09T12:00:00/2017-01-10"));
List<TimelineObjectHolder<String, DataSegment>> holders = dataSources.get(dataSource).lookup(interval);
Assert.assertEquals(1, holders.size());
for (TimelineObjectHolder<String, DataSegment> holder : holders) {
List<PartitionChunk<DataSegment>> chunks = Lists.newArrayList(holder.getObject());
Assert.assertEquals(4, chunks.size());
for (PartitionChunk<DataSegment> chunk : chunks) {
DataSegment segment = chunk.getObject();
Assert.assertEquals(interval, segment.getInterval());
Assert.assertEquals("version", segment.getVersion());
}
}
}
// Emulating realtime dataSource
final String dataSource = DATA_SOURCE_PREFIX + 0;
addMoreData(dataSource, 9);
CoordinatorStats stats = runCompactor(compactor);
Assert.assertEquals(
1,
stats.getGlobalStat(DruidCoordinatorSegmentCompactor.COMPACT_TASK_COUNT)
);
addMoreData(dataSource, 10);
stats = runCompactor(compactor);
Assert.assertEquals(
1,
stats.getGlobalStat(DruidCoordinatorSegmentCompactor.COMPACT_TASK_COUNT)
);
}
private void addMoreData(String dataSource, int day)
{
for (int i = 0; i < 2; i++) {
DataSegment newSegment = createSegment(dataSource, day, true, i);
dataSources.get(dataSource).add(
newSegment.getInterval(),
newSegment.getVersion(),
newSegment.getShardSpec().createChunk(newSegment)
);
newSegment = createSegment(dataSource, day, false, i);
dataSources.get(dataSource).add(
newSegment.getInterval(),
newSegment.getVersion(),
newSegment.getShardSpec().createChunk(newSegment)
);
}
}
private static List<DataSourceCompactionConfig> createCompactionConfigs()
{
final List<DataSourceCompactionConfig> compactionConfigs = new ArrayList<>();
for (int i = 0; i < 3; i++) {
final String dataSource = DATA_SOURCE_PREFIX + i;
compactionConfigs.add(
new DataSourceCompactionConfig(
dataSource,
0,
50L,
20L,
null,
null,
new Period("PT1H"), // smaller than segment interval
null,
null
)
);
}
return compactionConfigs;
}
}
| |
package tests.unit.BusinessObjects.serialization;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.HashMap;
import org.junit.Test;
import serialization.ISerializer;
import serialization.Serializer;
import tests.unit.UnitTestBase;
import tests.unit.BusinessObjects.serialization.dataContracts.ComplexDataContract;
import tests.unit.BusinessObjects.serialization.dataContracts.DataContractWithArrays;
import tests.unit.BusinessObjects.serialization.dataContracts.DataContractWithFinalField;
import tests.unit.BusinessObjects.serialization.dataContracts.ISomeInterface;
import tests.unit.BusinessObjects.serialization.dataContracts.PrimitiveTypesDataContract;
import tests.unit.BusinessObjects.serialization.dataContracts.SimpleDataContract;
import tests.unit.BusinessObjects.serialization.dataContracts.SomeInterfaceImplementation;
import tests.unit.BusinessObjects.serialization.dataContracts.SubDataContract;
import tests.unit.BusinessObjects.serialization.dataContracts.SubSubDataContract;
import dataContracts.BusinessObject;
public class JsonSerializerTest extends UnitTestBase {
private ISerializer serializer = new Serializer();
@Test
public void testSimpleDataContract()
{
SimpleDataContract simpleDataContract = new SimpleDataContract();
simpleDataContract.setStringField("zzz");
String serialized = serializer.stringify(simpleDataContract);
System.out.println(serialized);
SimpleDataContract afterDeserialize = serializer.deserialize(serialized, SimpleDataContract.class);
assertEquals("zzz", afterDeserialize.getStringField());
}
@Test
public void testSimpleDataContractNull()
{
SimpleDataContract simpleDataContract = new SimpleDataContract();
String serialized = serializer.stringify(simpleDataContract);
System.out.println(serialized);
SimpleDataContract afterDeserialize = serializer.deserialize(serialized, SimpleDataContract.class);
assertEquals(simpleDataContract.getStringField(), afterDeserialize.getStringField());
}
@Test
public void testComplexDataContract()
{
SubSubDataContract subSubDataContract = new SubSubDataContract();
subSubDataContract.setBooleanField(true);
SubDataContract subDataContract = new SubDataContract();
subDataContract.setIntField(123);
subDataContract.setSubSubDataContractField(subSubDataContract);
ComplexDataContract complexDataContract = new ComplexDataContract();
complexDataContract.setStringField("zzz");
complexDataContract.setSubDataContractField(subDataContract);
String serialized = serializer.stringify(complexDataContract);
System.out.println(serialized);
ComplexDataContract afterDeserialize = serializer.deserialize(serialized, ComplexDataContract.class);
assertEquals(complexDataContract.getStringField(), afterDeserialize.getStringField());
assertEquals(complexDataContract.getSubDataContractField().getIntField(),
afterDeserialize.getSubDataContractField().getIntField());
assertEquals(complexDataContract.getSubDataContractField().getSubSubDataContractField().isBooleanField(),
afterDeserialize.getSubDataContractField().getSubSubDataContractField().isBooleanField());
}
@Test
public void testComplexDataContractNull()
{
SubDataContract subDataContract = new SubDataContract();
ComplexDataContract complexDataContract = new ComplexDataContract();
complexDataContract.setStringField("zzz");
complexDataContract.setSubDataContractField(subDataContract);
String serialized = serializer.stringify(complexDataContract);
System.out.println(serialized);
ComplexDataContract afterDeserialize = serializer.deserialize(serialized, ComplexDataContract.class);
assertEquals(complexDataContract.getStringField(), afterDeserialize.getStringField());
assertEquals(0, afterDeserialize.getSubDataContractField().getIntField());
assertNull(afterDeserialize.getSubDataContractField().getSubSubDataContractField());
}
@Test
public void testDeserializeEmpty()
{
ComplexDataContract emptyDeserialized = serializer.deserialize("{}", ComplexDataContract.class);
assertNull(emptyDeserialized.getStringField());
assertNull(emptyDeserialized.getSubDataContractField());
}
@Test
public void testDeserializeEmptyPrimitiveTypes()
{
PrimitiveTypesDataContract emptyDeserialized = serializer.deserialize("{}", PrimitiveTypesDataContract.class);
assertEquals(0, emptyDeserialized.getIntField());
assertEquals(0, emptyDeserialized.getLongField());
assertEquals(0, emptyDeserialized.getShortField());
assertEquals(0, emptyDeserialized.getByteField());
assertEquals(0, emptyDeserialized.getCharField());
assertEquals(false, emptyDeserialized.isBooleanField());
}
@Test
public void testDataContractWithFinalField()
{
DataContractWithFinalField dataContractWithFinalField = new DataContractWithFinalField(123);
dataContractWithFinalField.setStringField("zzz");
String serialized = serializer.stringify(dataContractWithFinalField);
System.out.println(serialized);
DataContractWithFinalField afterDeserialize = serializer.deserialize(serialized, DataContractWithFinalField.class);
assertEquals(dataContractWithFinalField.intField, afterDeserialize.intField);
assertEquals(dataContractWithFinalField.getStringField(), afterDeserialize.getStringField());
}
@Test
public void testDataContractWithArrays()
{
DataContractWithArrays dataContractWithArrays = new DataContractWithArrays();
dataContractWithArrays.setByteArray(new byte[]{1, 2, 3, 4, 5, 6});
dataContractWithArrays.setIntArray(new int[]{10, 20, 30, 40});
SimpleDataContract[] simpleDataContractArray = new SimpleDataContract[3];
simpleDataContractArray[0] = new SimpleDataContract();
simpleDataContractArray[0].setStringField("1");
simpleDataContractArray[2] = new SimpleDataContract();
simpleDataContractArray[2].setStringField("3");
dataContractWithArrays.setSimpleDataContract(simpleDataContractArray);
String serialized = serializer.stringify(dataContractWithArrays);
System.out.println(serialized);
DataContractWithArrays afterDeserialize = serializer.deserialize(serialized, DataContractWithArrays.class);
assertArrayEquals(dataContractWithArrays.getByteArray(), afterDeserialize.getByteArray());
assertArrayEquals(dataContractWithArrays.getIntArray(), afterDeserialize.getIntArray());
assertArrayEquals(dataContractWithArrays.getSimpleDataContract(), afterDeserialize.getSimpleDataContract());
}
@Test
public void testClassImplementsInterface()
{
SomeInterfaceImplementation interfaceImplementation = new SomeInterfaceImplementation();
interfaceImplementation.setIntField(123);
interfaceImplementation.setStringField("zzz");
ISomeInterface someInterface = interfaceImplementation;
String serialized = serializer.stringify(someInterface);
System.out.println(serialized);
SomeInterfaceImplementation afterDeserialize = serializer.deserialize(serialized, SomeInterfaceImplementation.class);
assertEquals(interfaceImplementation.getIntField(), afterDeserialize.getIntField());
assertEquals(interfaceImplementation.getStringField(), afterDeserialize.getStringField());
}
@Test
public void testSerializeHashmap() {
HashMap<String, String> map = new HashMap<>();
map.put("key1", "val1");
map.put("key2", "val2");
String serialized = serializer.stringify(map);
System.out.println(serialized);
HashMap<String, String> actuals = serializer.deserialize(serialized, HashMap.class);
assertEquals(2, actuals.size());
assertEquals("val1", actuals.get("key1"));
assertEquals("val2", actuals.get("key2"));
}
@Test
public void testSerializeBaseClass() {
SimpleDataContract contract = new SimpleDataContract();
contract.setId("testId");
contract.setLastPersistMillis(10);
contract.setStringField("something");
String serialized = serializer.stringify(contract, BusinessObject.class);
SimpleDataContract actuals = serializer.deserialize(serialized, SimpleDataContract.class);
assertEquals(contract.getId(), actuals.getId());
assertEquals(contract.getLastPersistMillis(), actuals.getLastPersistMillis());
assertEquals(null, actuals.getStringField());
}
@Test(expected = IllegalArgumentException.class)
public void testSerializeWithInvalidBaseClass() {
serializer.stringify(new SimpleDataContract(), SubDataContract.class);
}
@Test
public void testSerializeNull() {
String serialized = serializer.stringify(null);
Object actual = serializer.deserialize(serialized, BusinessObject.class);
assertEquals(null, actual);
serialized = serializer.stringify(null, BusinessObject.class);
actual = serializer.deserialize(serialized, BusinessObject.class);
assertEquals(null, actual);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.dht.tokenallocator;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.locator.AbstractReplicationStrategy;
import org.apache.cassandra.locator.IEndpointSnitch;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.locator.NetworkTopologyStrategy;
import org.apache.cassandra.locator.SimpleStrategy;
import org.apache.cassandra.locator.TokenMetadata;
import org.apache.cassandra.locator.TokenMetadata.Topology;
public class TokenAllocation
{
private static final Logger logger = LoggerFactory.getLogger(TokenAllocation.class);
public static Collection<Token> allocateTokens(final TokenMetadata tokenMetadata,
final AbstractReplicationStrategy rs,
final InetAddressAndPort endpoint,
int numTokens)
{
TokenMetadata tokenMetadataCopy = tokenMetadata.cloneOnlyTokenMap();
StrategyAdapter strategy = getStrategy(tokenMetadataCopy, rs, endpoint);
Collection<Token> tokens = create(tokenMetadata, strategy).addUnit(endpoint, numTokens);
tokens = adjustForCrossDatacenterClashes(tokenMetadata, strategy, tokens);
if (logger.isWarnEnabled())
{
logger.warn("Selected tokens {}", tokens);
SummaryStatistics os = replicatedOwnershipStats(tokenMetadataCopy, rs, endpoint);
tokenMetadataCopy.updateNormalTokens(tokens, endpoint);
SummaryStatistics ns = replicatedOwnershipStats(tokenMetadataCopy, rs, endpoint);
logger.warn("Replicated node load in datacenter before allocation {}", statToString(os));
logger.warn("Replicated node load in datacenter after allocation {}", statToString(ns));
// TODO: Is it worth doing the replicated ownership calculation always to be able to raise this alarm?
if (ns.getStandardDeviation() > os.getStandardDeviation())
logger.warn("Unexpected growth in standard deviation after allocation.");
}
return tokens;
}
private static Collection<Token> adjustForCrossDatacenterClashes(final TokenMetadata tokenMetadata,
StrategyAdapter strategy, Collection<Token> tokens)
{
List<Token> filtered = Lists.newArrayListWithCapacity(tokens.size());
for (Token t : tokens)
{
while (tokenMetadata.getEndpoint(t) != null)
{
InetAddressAndPort other = tokenMetadata.getEndpoint(t);
if (strategy.inAllocationRing(other))
throw new ConfigurationException(String.format("Allocated token %s already assigned to node %s. Is another node also allocating tokens?", t, other));
t = t.increaseSlightly();
}
filtered.add(t);
}
return filtered;
}
// return the ratio of ownership for each endpoint
public static Map<InetAddressAndPort, Double> evaluateReplicatedOwnership(TokenMetadata tokenMetadata, AbstractReplicationStrategy rs)
{
Map<InetAddressAndPort, Double> ownership = Maps.newHashMap();
List<Token> sortedTokens = tokenMetadata.sortedTokens();
Iterator<Token> it = sortedTokens.iterator();
Token current = it.next();
while (it.hasNext())
{
Token next = it.next();
addOwnership(tokenMetadata, rs, current, next, ownership);
current = next;
}
addOwnership(tokenMetadata, rs, current, sortedTokens.get(0), ownership);
return ownership;
}
static void addOwnership(final TokenMetadata tokenMetadata, final AbstractReplicationStrategy rs, Token current, Token next, Map<InetAddressAndPort, Double> ownership)
{
double size = current.size(next);
Token representative = current.getPartitioner().midpoint(current, next);
for (InetAddressAndPort n : rs.calculateNaturalReplicas(representative, tokenMetadata).endpoints())
{
Double v = ownership.get(n);
ownership.put(n, v != null ? v + size : size);
}
}
public static String statToString(SummaryStatistics stat)
{
return String.format("max %.2f min %.2f stddev %.4f", stat.getMax() / stat.getMean(), stat.getMin() / stat.getMean(), stat.getStandardDeviation());
}
public static SummaryStatistics replicatedOwnershipStats(TokenMetadata tokenMetadata,
AbstractReplicationStrategy rs, InetAddressAndPort endpoint)
{
SummaryStatistics stat = new SummaryStatistics();
StrategyAdapter strategy = getStrategy(tokenMetadata, rs, endpoint);
for (Map.Entry<InetAddressAndPort, Double> en : evaluateReplicatedOwnership(tokenMetadata, rs).entrySet())
{
// Filter only in the same datacentre.
if (strategy.inAllocationRing(en.getKey()))
stat.addValue(en.getValue() / tokenMetadata.getTokens(en.getKey()).size());
}
return stat;
}
static TokenAllocator<InetAddressAndPort> create(TokenMetadata tokenMetadata, StrategyAdapter strategy)
{
NavigableMap<Token, InetAddressAndPort> sortedTokens = new TreeMap<>();
for (Map.Entry<Token, InetAddressAndPort> en : tokenMetadata.getNormalAndBootstrappingTokenToEndpointMap().entrySet())
{
if (strategy.inAllocationRing(en.getValue()))
sortedTokens.put(en.getKey(), en.getValue());
}
return TokenAllocatorFactory.createTokenAllocator(sortedTokens, strategy, tokenMetadata.partitioner);
}
interface StrategyAdapter extends ReplicationStrategy<InetAddressAndPort>
{
// return true iff the provided endpoint occurs in the same virtual token-ring we are allocating for
// i.e. the set of the nodes that share ownership with the node we are allocating
// alternatively: return false if the endpoint's ownership is independent of the node we are allocating tokens for
boolean inAllocationRing(InetAddressAndPort other);
}
static StrategyAdapter getStrategy(final TokenMetadata tokenMetadata, final AbstractReplicationStrategy rs, final InetAddressAndPort endpoint)
{
if (rs instanceof NetworkTopologyStrategy)
return getStrategy(tokenMetadata, (NetworkTopologyStrategy) rs, rs.snitch, endpoint);
if (rs instanceof SimpleStrategy)
return getStrategy(tokenMetadata, (SimpleStrategy) rs, endpoint);
throw new ConfigurationException("Token allocation does not support replication strategy " + rs.getClass().getSimpleName());
}
static StrategyAdapter getStrategy(final TokenMetadata tokenMetadata, final SimpleStrategy rs, final InetAddressAndPort endpoint)
{
final int replicas = rs.getReplicationFactor().allReplicas;
return new StrategyAdapter()
{
@Override
public int replicas()
{
return replicas;
}
@Override
public Object getGroup(InetAddressAndPort unit)
{
return unit;
}
@Override
public boolean inAllocationRing(InetAddressAndPort other)
{
return true;
}
};
}
static StrategyAdapter getStrategy(final TokenMetadata tokenMetadata, final NetworkTopologyStrategy rs, final IEndpointSnitch snitch, final InetAddressAndPort endpoint)
{
final String dc = snitch.getDatacenter(endpoint);
final int replicas = rs.getReplicationFactor(dc).allReplicas;
if (replicas == 0 || replicas == 1)
{
// No replication, each node is treated as separate.
return new StrategyAdapter()
{
@Override
public int replicas()
{
return 1;
}
@Override
public Object getGroup(InetAddressAndPort unit)
{
return unit;
}
@Override
public boolean inAllocationRing(InetAddressAndPort other)
{
return dc.equals(snitch.getDatacenter(other));
}
};
}
Topology topology = tokenMetadata.getTopology();
int racks = topology.getDatacenterRacks().get(dc).asMap().size();
if (racks >= replicas)
{
return new StrategyAdapter()
{
@Override
public int replicas()
{
return replicas;
}
@Override
public Object getGroup(InetAddressAndPort unit)
{
return snitch.getRack(unit);
}
@Override
public boolean inAllocationRing(InetAddressAndPort other)
{
return dc.equals(snitch.getDatacenter(other));
}
};
}
else if (racks == 1)
{
// One rack, each node treated as separate.
return new StrategyAdapter()
{
@Override
public int replicas()
{
return replicas;
}
@Override
public Object getGroup(InetAddressAndPort unit)
{
return unit;
}
@Override
public boolean inAllocationRing(InetAddressAndPort other)
{
return dc.equals(snitch.getDatacenter(other));
}
};
}
else
throw new ConfigurationException(
String.format("Token allocation failed: the number of racks %d in datacenter %s is lower than its replication factor %d.",
racks, dc, replicas));
}
}
| |
/***
Copyright (c) 2014 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
Covered in detail in the book _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.diceware;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.UriPermission;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.TextView;
import android.widget.Toast;
import com.commonsware.cwac.document.DocumentFileCompat;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
public class PassphraseFragment extends Fragment {
private static final String ASSET_FILENAME="eff_short_wordlist_2_0.txt";
private static final int REQUEST_OPEN=1337;
private static final int REQUEST_GET=REQUEST_OPEN + 1;
private static final String PREF_URI="uri";
private static final String STATE_WORD_COUNT="wordCount";
private static final int[] WORD_COUNT_MENU_IDS={
R.id.word_count_4,
R.id.word_count_5,
R.id.word_count_6,
R.id.word_count_7,
R.id.word_count_8,
R.id.word_count_9,
R.id.word_count_10
};
private Observable<List<String>> wordsObservable;
private Disposable wordsSub;
private Observable<DocumentFileCompat> docObservable;
private Disposable docSub;
private SecureRandom random=new SecureRandom();
private SharedPreferences prefs;
private TextView passphrase;
private int wordCount=6;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return(inflater.inflate(R.layout.activity_main, container, false));
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
passphrase=view.findViewById(R.id.passphrase);
if (savedInstanceState!=null) {
wordCount=savedInstanceState.getInt(STATE_WORD_COUNT);
}
if (docObservable!=null) {
docSub();
}
else {
loadWords(false, wordsObservable==null);
}
}
@Override
public void onDestroy() {
unsubDoc();
unsubWords();
super.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_WORD_COUNT, wordCount);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.actions, menu);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT) {
menu.findItem(R.id.open).setEnabled(true);
}
MenuItem checkable=menu.findItem(WORD_COUNT_MENU_IDS[wordCount-4]);
if (checkable!=null) {
checkable.setChecked(true);
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.open:
open();
return(true);
case R.id.get:
get();
return(true);
case R.id.refresh:
loadWords(false, true);
return(true);
case R.id.reset:
prefs.edit().clear().apply();
loadWords(true, true);
return(true);
case R.id.word_count_4:
case R.id.word_count_5:
case R.id.word_count_6:
case R.id.word_count_7:
case R.id.word_count_8:
case R.id.word_count_9:
case R.id.word_count_10:
item.setChecked(!item.isChecked());
int temp=Integer.parseInt(item.getTitle().toString());
if (temp!=wordCount) {
wordCount=temp;
loadWords(false, true);
}
return(true);
}
return(super.onOptionsItemSelected(item));
}
@Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (resultCode==Activity.RESULT_OK) {
docObservable=Observable
.defer(() -> (Observable.just(createDurableContent(resultData))))
.subscribeOn(Schedulers.io())
.cache()
.observeOn(AndroidSchedulers.mainThread());
docSub();
}
}
private void unsubWords() {
if (wordsSub!=null && !wordsSub.isDisposed()) {
wordsSub.dispose();
}
}
private void unsubDoc() {
if (docSub!=null && !docSub.isDisposed()) {
docSub.dispose();
}
}
private void loadWords(boolean forceReload, boolean regenPassphrase) {
if (wordsObservable==null || forceReload) {
final Application app=getActivity().getApplication();
wordsObservable=Observable
.defer(() -> (Observable.just(PreferenceManager
.getDefaultSharedPreferences(app))))
.subscribeOn(Schedulers.io())
.map(sharedPreferences -> {
PassphraseFragment.this.prefs=sharedPreferences;
return(sharedPreferences.getString(PREF_URI, ""));
})
.map(s -> {
InputStream in;
if (s.length()==0) {
in=app.getAssets().open(ASSET_FILENAME);
}
else {
in=app.getContentResolver().openInputStream(Uri.parse(s));
}
return(readWords(in));
})
.cache()
.observeOn(AndroidSchedulers.mainThread());
}
unsubWords();
if (regenPassphrase) {
wordsSub=wordsObservable.subscribe(this::rollDemBones, error -> {
Toast
.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG)
.show();
Log.e(getClass().getSimpleName(), "Exception processing request",
error);
});
}
}
private static List<String> readWords(InputStream in) throws IOException {
InputStreamReader isr=new InputStreamReader(in);
BufferedReader reader=new BufferedReader(isr);
String line;
List<String> result=new ArrayList<>();
while ((line = reader.readLine())!=null) {
String[] pieces=line.split("\\s");
if (pieces.length==2) {
result.add(pieces[1]);
}
}
return(result);
}
private void rollDemBones(List<String> words) {
StringBuilder buf=new StringBuilder();
int size=words.size();
for (int i=0;i<wordCount;i++) {
if (buf.length()>0) {
buf.append(' ');
}
buf.append(words.get(random.nextInt(size)));
}
passphrase.setText(buf.toString());
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private void open() {
Intent i=
new Intent()
.setType("text/plain")
.setAction(Intent.ACTION_OPEN_DOCUMENT)
.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(i, REQUEST_OPEN);
}
private void get() {
Intent i=
new Intent()
.setType("text/plain")
.setAction(Intent.ACTION_GET_CONTENT)
.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(i, REQUEST_GET);
}
private void docSub() {
docSub=docObservable.subscribe(documentFile -> {
docObservable=null;
loadWords(true, true);
});
}
private DocumentFileCompat createDurableContent(Intent result) throws IOException {
Uri document=result.getData();
ContentResolver resolver=getActivity().getContentResolver();
boolean weHaveDurablePermission=obtainDurablePermission(resolver, document);
if (!weHaveDurablePermission) {
document=makeLocalCopy(getActivity(), resolver, document);
}
if (weHaveDurablePermission || document!=null) {
prefs
.edit()
.putString(PREF_URI, document.toString())
.commit();
return(buildDocFileForUri(getActivity(), document));
}
throw new IllegalStateException("Could not get durable permission or make copy");
}
private static boolean obtainDurablePermission(ContentResolver resolver,
Uri document) {
boolean weHaveDurablePermission=false;
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT) {
int perms=Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
try {
resolver.takePersistableUriPermission(document, perms);
for (UriPermission perm : resolver.getPersistedUriPermissions()) {
if (perm.getUri().equals(document)) {
weHaveDurablePermission=true;
}
}
}
catch (SecurityException e) {
// OK, we were not offered any persistable permissions
}
}
return(weHaveDurablePermission);
}
private static Uri makeLocalCopy(Context ctxt, ContentResolver resolver,
Uri document)
throws IOException {
DocumentFileCompat docFile=buildDocFileForUri(ctxt, document);
Uri result=null;
if (docFile.getName()!=null) {
String ext=
MimeTypeMap.getSingleton().getExtensionFromMimeType(docFile.getType());
if (ext!=null) {
ext="."+ext;
}
File f=File.createTempFile("cw_", ext, ctxt.getFilesDir());
docFile.copyTo(f);
result=Uri.fromFile(f);
}
return(result);
}
private static DocumentFileCompat buildDocFileForUri(Context ctxt, Uri document) {
DocumentFileCompat docFile;
if (document.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
docFile=DocumentFileCompat.fromSingleUri(ctxt, document);
}
else {
docFile=DocumentFileCompat.fromFile(new File(document.getPath()));
}
return(docFile);
}
}
| |
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content.browser;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Rect;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import org.chromium.content.R;
/**
* An ActionMode.Callback for in-page selection. This class handles both the editable and
* non-editable cases.
*/
public class SelectActionModeCallback implements ActionMode.Callback {
/**
* An interface to retrieve information about the current selection, and also to perform
* actions based on the selection or when the action bar is dismissed.
*/
public interface ActionHandler {
/**
* Perform a select all action.
*/
void selectAll();
/**
* Perform a copy (to clipboard) action.
*/
void copy();
/**
* Perform a cut (to clipboard) action.
*/
void cut();
/**
* Perform a paste action.
*/
void paste();
/**
* Perform a share action.
*/
void share();
/**
* Perform a search action.
*/
void search();
/**
* @return true iff the current selection is editable (e.g. text within an input field).
*/
boolean isSelectionEditable();
/**
* Called when the onDestroyActionMode of the SelectActionmodeCallback is called.
*/
void onDestroyActionMode();
/**
* Called when the onGetContentRect of the SelectActionModeCallback is called.
* @param outRect The Rect to be populated with the content position.
*/
void onGetContentRect(Rect outRect);
/**
* @return Whether or not share is available.
*/
boolean isShareAvailable();
/**
* @return Whether or not web search is available.
*/
boolean isWebSearchAvailable();
/**
* @return true if the current selection is of password type.
*/
boolean isSelectionPassword();
/**
* @return true if the current selection is an insertion point.
*/
boolean isInsertion();
/**
* @return true if the current selection is for incognito content.
* Note: This should remain constant for the callback's lifetime.
*/
boolean isIncognito();
}
protected final ActionHandler mActionHandler;
private final Context mContext;
private boolean mEditable;
private boolean mIsPasswordType;
private boolean mIsInsertion;
public SelectActionModeCallback(Context context, ActionHandler actionHandler) {
mContext = context;
mActionHandler = actionHandler;
}
protected Context getContext() {
return mContext;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle(null);
mode.setSubtitle(null);
mEditable = mActionHandler.isSelectionEditable();
mIsPasswordType = mActionHandler.isSelectionPassword();
mIsInsertion = mActionHandler.isInsertion();
createActionMenu(mode, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
boolean isEditableNow = mActionHandler.isSelectionEditable();
boolean isPasswordNow = mActionHandler.isSelectionPassword();
boolean isInsertionNow = mActionHandler.isInsertion();
if (mEditable != isEditableNow || mIsPasswordType != isPasswordNow
|| mIsInsertion != isInsertionNow) {
mEditable = isEditableNow;
mIsPasswordType = isPasswordNow;
mIsInsertion = isInsertionNow;
menu.clear();
createActionMenu(mode, menu);
return true;
}
return false;
}
private void createActionMenu(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.select_action_menu, menu);
if (mIsInsertion) {
menu.removeItem(R.id.select_action_menu_select_all);
menu.removeItem(R.id.select_action_menu_cut);
menu.removeItem(R.id.select_action_menu_copy);
menu.removeItem(R.id.select_action_menu_share);
menu.removeItem(R.id.select_action_menu_web_search);
return;
}
if (!mEditable || !canPaste()) {
menu.removeItem(R.id.select_action_menu_paste);
}
if (!mEditable) {
menu.removeItem(R.id.select_action_menu_cut);
}
if (mEditable || !mActionHandler.isShareAvailable()) {
menu.removeItem(R.id.select_action_menu_share);
}
if (mEditable || mActionHandler.isIncognito() || !mActionHandler.isWebSearchAvailable()) {
menu.removeItem(R.id.select_action_menu_web_search);
}
if (mIsPasswordType) {
menu.removeItem(R.id.select_action_menu_copy);
menu.removeItem(R.id.select_action_menu_cut);
}
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int id = item.getItemId();
if (id == R.id.select_action_menu_select_all) {
mActionHandler.selectAll();
} else if (id == R.id.select_action_menu_cut) {
mActionHandler.cut();
mode.finish();
} else if (id == R.id.select_action_menu_copy) {
mActionHandler.copy();
mode.finish();
} else if (id == R.id.select_action_menu_paste) {
mActionHandler.paste();
mode.finish();
} else if (id == R.id.select_action_menu_share) {
mActionHandler.share();
mode.finish();
} else if (id == R.id.select_action_menu_web_search) {
mActionHandler.search();
mode.finish();
} else {
return false;
}
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
mActionHandler.onDestroyActionMode();
}
/**
* Called when an ActionMode needs to be positioned on screen, potentially occluding view
* content. Note this may be called on a per-frame basis.
*
* @param mode The ActionMode that requires positioning.
* @param view The View that originated the ActionMode, in whose coordinates the Rect should
* be provided.
* @param outRect The Rect to be populated with the content position.
*/
public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
mActionHandler.onGetContentRect(outRect);
}
private boolean canPaste() {
ClipboardManager clipMgr = (ClipboardManager)
getContext().getSystemService(Context.CLIPBOARD_SERVICE);
return clipMgr.hasPrimaryClip();
}
}
| |
package com.sjtools.tictactoe.app;
import com.sjtools.tictactoe.board.decors.TicTacToeBoardDecorIfc;
import com.sjtools.tictactoe.board.decors.TicTacToeDefaultBoardDecor;
import com.sjtools.tictactoe.board.decors.TicTacToeDefaultBoardGridCellDecor;
import com.sjtools.tictactoe.board.decors.TicTacToeDefaultBoardGridDecor;
import com.sjtools.tictactoe.board.decors.*;
import com.sjtools.tictactoe.board.ifc.TicTacToeBoardIfc;
import com.sjtools.tictactoe.board.impl.TicTacToeBoard;
import com.sjtools.tictactoe.game.impl.TicTacToeGame;
import com.sjtools.tictactoe.player.TicTacToePlayerFactory;
import com.sjtools.tictactoe.player.TicTacToePlayerType;
import com.sjtools.tictactoe.player.ifc.TicTacToePlayerIfc;
import com.sjtools.tictactoe.utils.TicTacToeGameConsoleInput;
import com.sjtools.tictactoe.utils.TicTacToeGameInputIfc;
import java.util.HashMap;
import java.util.Map;
/**
* Created by sjtools on 11.02.2017.
*/
public class TicTacToeGameApp
{
TicTacToeGame game = null;
TicTacToeBoardIfc board = null;
TicTacToeBoardDecorIfc boardDisplayDecor = null;
TicTacToeGameInputIfc inputScanner;
Map<Integer, TicTacToePlayerIfc> gamePlayers = new HashMap<>();
public TicTacToeGameApp()
{
game = null;
}
public void setInputScanner(TicTacToeGameInputIfc scanner)
{
inputScanner = scanner;
}
protected boolean initialize()
{
int players = -1;
int rows = 0;
int cols = 0;
System.out.println("\n");
while (players < TicTacToeGame.DEFAULT_PLAYERS || players > 10) {
System.out.print("Tell the number of players (2-10):");
try {
players = Integer.parseInt(getInput());
} catch (NumberFormatException e) {
System.out.println(e);
//nothing to do
}
}
initPlayers(players);
while (rows <3) {
System.out.print("Tell the board rows (3-255):");
try {
rows = Integer.parseInt(getInput());
} catch (NumberFormatException e) {
//nothing to do
}
}
while (cols<3) {
System.out.print("Tell the board columns (3-255):");
try {
cols = Integer.parseInt(getInput());
} catch (NumberFormatException e) {
//nothing to do
}
}
System.out.print("Press <f> for fancy display. Default will be used otherwise.");
setDisplayDecor("f".equalsIgnoreCase(getInput()));
boolean result = false;
try {
board = new TicTacToeBoard(rows, cols);
game = new TicTacToeGame(players,board);
result = true;
} catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
game = null;
board = null;
}
return result;
}
private void initPlayers(int players)
{
if (players<=0)
this.gamePlayers.clear();
else
{
for(int i=0;i<players;i++)
{
TicTacToePlayerIfc player = TicTacToePlayerFactory.getInstance().createPlayer(
players%2==1 ? TicTacToePlayerType.COMPUTER : TicTacToePlayerType.HUMAN
);
gamePlayers.put(i,player);
}
}
}
private void setDisplayDecor(boolean fancyDecor)
{
TicTacToeDefaultBoardGridDecor gridDecor = new TicTacToeDefaultBoardGridDecor(
new TicTacToeDefaultBoardGridCellDecor());
boardDisplayDecor = new TicTacToeDefaultBoardDecor(gridDecor);
if (fancyDecor)
{
gridDecor.setCellDelim("||");
}
}
public TicTacToeGame getGame() {
return game;
}
protected boolean nextCheck()
{
game.setCurrentPlayer(game.getNextPlayer());
int nextWinnigOptionsStill = game.getNumOfWinningOptionAvailableForPlayer(game.getCurrentPlayer());
System.out.println("Player <" + game.getCurrentPlayer() + "> it's your move.");
if (nextWinnigOptionsStill==0)
{
System.out.println("Unfortunately you cannot win. But, you can make game harder for other players.");
}
while (true) {
System.out.println("Press <q> to finish the game or <row,col> (e.g. 0,0) to check a cell:");
String in = getInput();
if ("q".equalsIgnoreCase(in))
{
return false;
}
int coords[] = {-1,-1};
getCoord(in, coords);
if (!game.isCoordsInBoardRange(coords[0],coords[1]))
{
System.out.println("Coordinates are not in board's range.");
continue;
}
if (!game.isEmptyCell(coords[0],coords[1]))
{
System.out.println("Cell is already checked.");
continue;
}
if (game.play(game.getCurrentPlayer(), coords[0], coords[1]))
{//checked
break;
}
}
return true;
}
protected void getCoord(String in, int[] coords)
{
if (coords==null || coords.length!=2)
return;
try
{
String s[] = in.split(",");
coords[0] = Integer.parseInt(s[0]);
coords[1] = Integer.parseInt(s[1]);
}
catch(NumberFormatException e)
{
//nothing to do
}
}
protected void printResult()
{
System.out.println("GAME FINISHED");
if (game.isGameWon())
{
System.out.println("Player <" + game.getWinner() + "> won. Congratulations!!!!");
}
else
{
if (!game.isWinningOptionAvailable())
System.out.println("No more winning options available for players.");
if (game.getNumberOfPossibleChecks() == 0)
System.out.println("Board is full.");
}
}
protected void displayBoard()
{
boardDisplayDecor.displayBoard(System.out, board);
}
protected String getInput()
{
if (inputScanner == null)
{
return null;
}
return inputScanner.getInput();
}
public void playTicTacToeGame()
{
System.out.println("\n\n");
System.out.println("==============================================================================");
System.out.println(" Welcome to TicTacToe game.");
System.out.println("==============================================================================");
System.out.println("Number of players: 2 to 10.");
System.out.println(" Player Id will be from <0> to <number_of_players - 1>");
System.out.println("Board size: 3x3 to 255x255 (rows x columns).");
System.out.println(" Cell coordinates: top-right=(0,0) -> bottom-left=(rows-1, columns-1).");
System.out.println("\n\n");
while(true) {
while (true) {
System.out.println("Press <n> to start a new game.");
System.out.print("Press <q> to quit.");
String in = getInput();
if ("n".equalsIgnoreCase(in)) {
if (initialize())
{
break;
}
}
if ("q".equals(in)) {
System.out.printf("BYE");
return;
}
}
while (getGame().canPlay()) {
displayBoard();
if (!nextCheck()) {
break;
}
}
displayBoard();
printResult();
System.out.printf("\n");
}
}
public static void main(String[] args)
{
TicTacToeGameApp app = new TicTacToeGameApp();
app.setInputScanner(new TicTacToeGameConsoleInput());
app.playTicTacToeGame();
}
}
| |
package org.jabref.logic.openoffice;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jabref.logic.layout.Layout;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.UnknownField;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.beans.XPropertySet;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.text.ControlCharacter;
import com.sun.star.text.XParagraphCursor;
import com.sun.star.text.XText;
import com.sun.star.text.XTextCursor;
import com.sun.star.uno.UnoRuntime;
/**
* Utility methods for processing OO Writer documents.
*/
public class OOUtil {
private static final String CHAR_STRIKEOUT = "CharStrikeout";
private static final String CHAR_UNDERLINE = "CharUnderline";
private static final String PARA_STYLE_NAME = "ParaStyleName";
private static final String CHAR_CASE_MAP = "CharCaseMap";
private static final String CHAR_POSTURE = "CharPosture";
private static final String CHAR_WEIGHT = "CharWeight";
private static final String CHAR_ESCAPEMENT_HEIGHT = "CharEscapementHeight";
private static final String CHAR_ESCAPEMENT = "CharEscapement";
public enum Formatting {
BOLD,
ITALIC,
SMALLCAPS,
SUPERSCRIPT,
SUBSCRIPT,
UNDERLINE,
STRIKEOUT,
MONOSPACE
}
private static final Pattern HTML_TAG = Pattern.compile("</?[a-z]+>");
private static final Field UNIQUEFIER_FIELD = new UnknownField("uniq");
private OOUtil() {
// Just to hide the public constructor
}
/**
* Insert a reference, formatted using a Layout, at the position of a given cursor.
* @param text The text to insert in.
* @param cursor The cursor giving the insert location.
* @param layout The Layout to format the reference with.
* @param parStyle The name of the paragraph style to use.
* @param entry The entry to insert.
* @param database The database the entry belongs to.
* @param uniquefier Uniqiefier letter, if any, to append to the entry's year.
*/
public static void insertFullReferenceAtCurrentLocation(XText text, XTextCursor cursor,
Layout layout, String parStyle, BibEntry entry, BibDatabase database, String uniquefier)
throws UndefinedParagraphFormatException, UnknownPropertyException, PropertyVetoException,
WrappedTargetException, IllegalArgumentException {
// Backup the value of the uniq field, just in case the entry already has it:
Optional<String> oldUniqVal = entry.getField(UNIQUEFIER_FIELD);
// Set the uniq field with the supplied uniquefier:
if (uniquefier == null) {
entry.clearField(UNIQUEFIER_FIELD);
} else {
entry.setField(UNIQUEFIER_FIELD, uniquefier);
}
// Do the layout for this entry:
String formattedText = layout.doLayout(entry, database);
// Afterwards, reset the old value:
if (oldUniqVal.isPresent()) {
entry.setField(UNIQUEFIER_FIELD, oldUniqVal.get());
} else {
entry.clearField(UNIQUEFIER_FIELD);
}
// Insert the formatted text:
OOUtil.insertOOFormattedTextAtCurrentLocation(text, cursor, formattedText, parStyle);
}
/**
* Insert a text with formatting indicated by HTML-like tags, into a text at
* the position given by a cursor.
* @param text The text to insert in.
* @param cursor The cursor giving the insert location.
* @param lText The marked-up text to insert.
* @param parStyle The name of the paragraph style to use.
* @throws WrappedTargetException
* @throws PropertyVetoException
* @throws UnknownPropertyException
* @throws IllegalArgumentException
*/
public static void insertOOFormattedTextAtCurrentLocation(XText text, XTextCursor cursor, String lText,
String parStyle) throws UndefinedParagraphFormatException, UnknownPropertyException, PropertyVetoException,
WrappedTargetException, IllegalArgumentException {
XParagraphCursor parCursor = UnoRuntime.queryInterface(
XParagraphCursor.class, cursor);
XPropertySet props = UnoRuntime.queryInterface(
XPropertySet.class, parCursor);
try {
props.setPropertyValue(PARA_STYLE_NAME, parStyle);
} catch (IllegalArgumentException ex) {
throw new UndefinedParagraphFormatException(parStyle);
}
List<Formatting> formatting = new ArrayList<>();
// We need to extract formatting. Use a simple regexp search iteration:
int piv = 0;
Matcher m = OOUtil.HTML_TAG.matcher(lText);
while (m.find()) {
String currentSubstring = lText.substring(piv, m.start());
if (!currentSubstring.isEmpty()) {
OOUtil.insertTextAtCurrentLocation(text, cursor, currentSubstring, formatting);
}
String tag = m.group();
// Handle tags:
if ("<b>".equals(tag)) {
formatting.add(Formatting.BOLD);
} else if ("</b>".equals(tag)) {
formatting.remove(Formatting.BOLD);
} else if ("<i>".equals(tag) || "<em>".equals(tag)) {
formatting.add(Formatting.ITALIC);
} else if ("</i>".equals(tag) || "</em>".equals(tag)) {
formatting.remove(Formatting.ITALIC);
} else if ("<tt>".equals(tag)) {
formatting.add(Formatting.MONOSPACE);
} else if ("</tt>".equals(tag)) {
formatting.remove(Formatting.MONOSPACE);
} else if ("<smallcaps>".equals(tag)) {
formatting.add(Formatting.SMALLCAPS);
} else if ("</smallcaps>".equals(tag)) {
formatting.remove(Formatting.SMALLCAPS);
} else if ("<sup>".equals(tag)) {
formatting.add(Formatting.SUPERSCRIPT);
} else if ("</sup>".equals(tag)) {
formatting.remove(Formatting.SUPERSCRIPT);
} else if ("<sub>".equals(tag)) {
formatting.add(Formatting.SUBSCRIPT);
} else if ("</sub>".equals(tag)) {
formatting.remove(Formatting.SUBSCRIPT);
} else if ("<u>".equals(tag)) {
formatting.add(Formatting.UNDERLINE);
} else if ("</u>".equals(tag)) {
formatting.remove(Formatting.UNDERLINE);
} else if ("<s>".equals(tag)) {
formatting.add(Formatting.STRIKEOUT);
} else if ("</s>".equals(tag)) {
formatting.remove(Formatting.STRIKEOUT);
}
piv = m.end();
}
if (piv < lText.length()) {
OOUtil.insertTextAtCurrentLocation(text, cursor, lText.substring(piv), formatting);
}
cursor.collapseToEnd();
}
public static void insertParagraphBreak(XText text, XTextCursor cursor) throws IllegalArgumentException {
text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true);
cursor.collapseToEnd();
}
public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, String string,
List<Formatting> formatting)
throws UnknownPropertyException, PropertyVetoException, WrappedTargetException,
IllegalArgumentException {
text.insertString(cursor, string, true);
// Access the property set of the cursor, and set the currently selected text
// (which is the string we just inserted) to be bold
XPropertySet xCursorProps = UnoRuntime.queryInterface(
XPropertySet.class, cursor);
if (formatting.contains(Formatting.BOLD)) {
xCursorProps.setPropertyValue(CHAR_WEIGHT,
com.sun.star.awt.FontWeight.BOLD);
} else {
xCursorProps.setPropertyValue(CHAR_WEIGHT,
com.sun.star.awt.FontWeight.NORMAL);
}
if (formatting.contains(Formatting.ITALIC)) {
xCursorProps.setPropertyValue(CHAR_POSTURE,
com.sun.star.awt.FontSlant.ITALIC);
} else {
xCursorProps.setPropertyValue(CHAR_POSTURE,
com.sun.star.awt.FontSlant.NONE);
}
if (formatting.contains(Formatting.SMALLCAPS)) {
xCursorProps.setPropertyValue(CHAR_CASE_MAP,
com.sun.star.style.CaseMap.SMALLCAPS);
} else {
xCursorProps.setPropertyValue(CHAR_CASE_MAP,
com.sun.star.style.CaseMap.NONE);
}
// TODO: the <monospace> tag doesn't work
/*
if (formatting.contains(Formatting.MONOSPACE)) {
xCursorProps.setPropertyValue("CharFontPitch",
com.sun.star.awt.FontPitch.FIXED);
}
else {
xCursorProps.setPropertyValue("CharFontPitch",
com.sun.star.awt.FontPitch.VARIABLE);
} */
if (formatting.contains(Formatting.SUBSCRIPT)) {
xCursorProps.setPropertyValue(CHAR_ESCAPEMENT,
(byte) -101);
xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT,
(byte) 58);
} else if (formatting.contains(Formatting.SUPERSCRIPT)) {
xCursorProps.setPropertyValue(CHAR_ESCAPEMENT,
(byte) 101);
xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT,
(byte) 58);
} else {
xCursorProps.setPropertyValue(CHAR_ESCAPEMENT,
(byte) 0);
xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT,
(byte) 100);
}
if (formatting.contains(Formatting.UNDERLINE)) {
xCursorProps.setPropertyValue(CHAR_UNDERLINE, com.sun.star.awt.FontUnderline.SINGLE);
} else {
xCursorProps.setPropertyValue(CHAR_UNDERLINE, com.sun.star.awt.FontUnderline.NONE);
}
if (formatting.contains(Formatting.STRIKEOUT)) {
xCursorProps.setPropertyValue(CHAR_STRIKEOUT, com.sun.star.awt.FontStrikeout.SINGLE);
} else {
xCursorProps.setPropertyValue(CHAR_STRIKEOUT, com.sun.star.awt.FontStrikeout.NONE);
}
cursor.collapseToEnd();
}
public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, String string, String parStyle)
throws WrappedTargetException, PropertyVetoException, UnknownPropertyException,
UndefinedParagraphFormatException {
text.insertString(cursor, string, true);
XParagraphCursor parCursor = UnoRuntime.queryInterface(
XParagraphCursor.class, cursor);
// Access the property set of the cursor, and set the currently selected text
// (which is the string we just inserted) to be bold
XPropertySet props = UnoRuntime.queryInterface(
XPropertySet.class, parCursor);
try {
props.setPropertyValue(PARA_STYLE_NAME, parStyle);
} catch (IllegalArgumentException ex) {
throw new UndefinedParagraphFormatException(parStyle);
}
cursor.collapseToEnd();
}
public static Object getProperty(Object o, String property)
throws UnknownPropertyException, WrappedTargetException {
XPropertySet props = UnoRuntime.queryInterface(
XPropertySet.class, o);
return props.getPropertyValue(property);
}
}
| |
/**
* @author Kevin Fisher
* @author Merv Fansler
* @since April 9, 2015
* @version 0.3.0
*/
package edu.millersville.cs.bitsplease.view;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javafx.beans.binding.Bindings;
import javafx.embed.swing.SwingFXUtils;
import javafx.print.Printer;
import javafx.print.PrinterJob;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.transform.Scale;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javax.imageio.ImageIO;
import org.fxmisc.undo.UndoManager;
import edu.millersville.cs.bitsplease.PUMLBuilder;
import edu.millersville.cs.bitsplease.model.UMLSymbol;
public class UMLMenu extends MenuBar {
private DocumentViewPane document;
private UndoManager undoManager;
private MenuItem undo, redo;
/**
* Creates an instance of a UMLMenu bar for the PUMLBuilder application
*/
public UMLMenu(){
super();
this.setUseSystemMenuBar(true);
/*============== FILE MENU ===============*/
Menu fileMenu = new Menu("File");
MenuItem newDoc = new MenuItem("New");
newDoc.setOnAction(newAction -> {
document.setSelectedUMLSymbol(null);
document.removeAllSymbols();
undoManager.forgetHistory();
});
MenuItem open = new MenuItem("Open");
open.setOnAction(event -> { loadDocument(); });
open.setAccelerator(new KeyCodeCombination(KeyCode.O,
KeyCombination.SHORTCUT_DOWN));
MenuItem save = new MenuItem("Save As");
save.setOnAction(event-> { saveDocument();});
save.setAccelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN));
MenuItem print = new MenuItem("Print");
print.setOnAction(event ->{
print();
});
print.setAccelerator(new KeyCodeCombination(KeyCode.P, KeyCombination.SHORTCUT_DOWN));
MenuItem export = new MenuItem("Export...");
export.setOnAction(ex ->{
exportDocument();
});
MenuItem exit = new MenuItem("Exit");
exit.setOnAction(event -> System.exit(0));
exit.setAccelerator(new KeyCodeCombination(KeyCode.W, KeyCombination.SHORTCUT_DOWN,
KeyCombination.SHIFT_DOWN ));
fileMenu.getItems().addAll(newDoc,new SeparatorMenuItem(), open,save,
new SeparatorMenuItem(),print, new SeparatorMenuItem(),
export, new SeparatorMenuItem(), exit);
/*============== EDIT MENU ===============*/
Menu editMenu = new Menu("Edit");
undo = new MenuItem("Undo");
undo.setDisable(true);
undo.setOnAction(event -> undoManager.undo());
undo.setAccelerator(new KeyCodeCombination(KeyCode.Z, KeyCombination.SHORTCUT_DOWN));
redo = new MenuItem("Redo");
redo.setDisable(true);
redo.setOnAction(event -> undoManager.redo());
redo.setAccelerator(new KeyCodeCombination(KeyCode.Y, KeyCombination.SHORTCUT_DOWN));
editMenu.getItems().addAll(undo,redo);
/*============== HELP MENU ===============*/
Menu helpMenu = new Menu("Help");
MenuItem about = new MenuItem("About");
about.setOnAction(event -> createAbout());
helpMenu.getItems().add(about);
// Put 'em all together
this.getMenus().addAll(fileMenu, editMenu, helpMenu);
}
/**
* @return The document that the menu performs operations on
*/
public DocumentViewPane getDocument(){
return this.document;
}
/**
* @param doc The document the menu will perform operations on
*/
public void setDocument(DocumentViewPane doc) {
this.document = doc;
}
/**
* @return the undoManager
*/
public UndoManager getUndoManager() {
return undoManager;
}
/**
* @param undoManager the undoManager to set
*/
public void setUndoManager(UndoManager undoManager) {
this.undoManager = undoManager;
if (this.undoManager != null) {
undo.disableProperty().bind(Bindings.not(this.undoManager.undoAvailableProperty()));
redo.disableProperty().bind(Bindings.not(this.undoManager.redoAvailableProperty()));
} else {
undo.setDisable(false);
redo.setDisable(false);
}
}
/**
* Handles the creation of the About webview
*/
private void createAbout(){
final Stage dialog = new Stage(StageStyle.UTILITY);
dialog.initModality(Modality.WINDOW_MODAL);
dialog.initOwner(getScene().getWindow());
dialog.setResizable(false);
// create view for about content
WebView aboutPage = new WebView();
// load content into view
String aboutURL = PUMLBuilder.class.getResource("/html/about.html").toExternalForm();
aboutPage.getEngine().load(aboutURL);
// load view into window
Scene dialogScene = new Scene(aboutPage, 400, 300);
dialog.setScene(dialogScene);
// display window
dialog.show();
}
/**
* Handles creation and execution of printing job to print Document
* @author Kevin Fisher
*/
private void print(){
Printer printer = Printer.getDefaultPrinter();
PrinterJob job = PrinterJob.createPrinterJob(printer);
if(job == null){
Alert noPrinterFound = new Alert(AlertType.ERROR);
noPrinterFound.setTitle("Printer Error");
noPrinterFound.setHeaderText("No Printer Found");
noPrinterFound.setContentText("Hold on let me just mail it to you or something.");
noPrinterFound.showAndWait();
}else{
boolean showDialog = job.showPrintDialog(getScene().getWindow());
if(showDialog){
document.setSelectedUMLSymbol(null);
document.getTransforms().add(new Scale(0.5, 0.5));
if(job.printPage(document)){
job.endJob();
}
}
}
document.getTransforms().clear();
}
/**
* Handles saving a UML document through FileChooser
* @author Kevin Fisher
*/
private void saveDocument(){
FileChooser fileHandler = new FileChooser();
fileHandler.getExtensionFilters().addAll(new ExtensionFilter("UML Document", "*.uml"),
new ExtensionFilter("All Files", "*.*"));
File fileToSave = fileHandler.showSaveDialog(getScene().getWindow());
if(fileToSave == null){
//User exited filechooser without saving the file
}else {
if(!fileToSave.getName().endsWith(".uml")){
fileToSave = new File(fileToSave + ".uml");
}
try{
ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream(fileToSave));
o.writeObject(document.getEntities());
o.close();
}catch(IOException e){ e.printStackTrace();}
}
}
/**
* Handles loading a .uml document in from a file
*/
private void loadDocument(){
FileChooser fileHandler = new FileChooser();
fileHandler.getExtensionFilters().addAll(new ExtensionFilter("UML Document", "*.uml"),
new ExtensionFilter("All Files", "*.*"));
File fileToLoad = fileHandler.showOpenDialog(getScene().getWindow());
if(fileToLoad == null){
// System.out.println("Hey thanks for wasting my time, cool.");
//Only load .uml files
}else if(!fileToLoad.getName().endsWith(".uml")){
Alert invalidFileType = new Alert(AlertType.ERROR);
invalidFileType.setTitle("File Open Error");
invalidFileType.setHeaderText("Invalid File Type");
invalidFileType.setContentText("Hey next time try loading a file ending in .uml. \n Cool thanks.");
invalidFileType.showAndWait();
}else{
//first remove all node currently occupying the Document View
document.removeAllSymbols();
try{
ObjectInputStream in = new ObjectInputStream(
new FileInputStream(fileToLoad));
@SuppressWarnings("unchecked")
ArrayList<UMLSymbol> loadedIn = (ArrayList<UMLSymbol>)in.readObject();
document.setEntities(loadedIn);
in.close();
}catch(Exception e){e.printStackTrace();}
}
}
/**
* exports a DocumentViewPane node to a .png file
*/
private void exportDocument(){
WritableImage image = document.snapshot(new SnapshotParameters(), null);
FileChooser fileHandler = new FileChooser();
fileHandler.setTitle("Export Document");
fileHandler.getExtensionFilters().add(new ExtensionFilter("PNG Image", "*.png"));
File exportDoc = fileHandler.showSaveDialog(getScene().getWindow());
if(exportDoc != null){
if(!exportDoc.getPath().endsWith(".png")){
exportDoc = new File(exportDoc.getPath()+ ".png");
}
try{
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", exportDoc);
}catch(IOException ioe){
}
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.notifier.server;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.notifier.ClientHandler;
import org.apache.hadoop.hdfs.notifier.ClientNotSubscribedException;
import org.apache.hadoop.hdfs.notifier.EventType;
import org.apache.hadoop.hdfs.notifier.InvalidClientIdException;
import org.apache.hadoop.hdfs.notifier.NamespaceEvent;
import org.apache.hadoop.hdfs.notifier.NamespaceEventKey;
import org.apache.hadoop.hdfs.notifier.NamespaceNotification;
import org.apache.hadoop.hdfs.notifier.NotifierUtils;
import org.apache.hadoop.hdfs.notifier.ServerHandler;
import org.apache.hadoop.hdfs.notifier.TransactionIdTooOldException;
import org.apache.hadoop.hdfs.notifier.server.metrics.NamespaceNotifierMetrics;
import org.apache.hadoop.hdfs.protocol.FSConstants;
import org.apache.hadoop.util.Daemon;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TNonblockingServerTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.TTransportFactory;
public class ServerCore implements IServerCore {
public static final Log LOG = LogFactory.getLog(ServerCore.class);
public static final String DISPATCHER_COUNT = "notifier.dispatcher.count";
public static final String LISTENING_PORT = "notifier.thrift.port";
// The timeout after which the core will stop trying to do a graceful
// shutdown and will interrupt the threads
private static final int SHUTDOWN_TIMEOUT = 5000;
private static final int SOCKET_READ_TIMEOUT = 25000;
private static final Random random = new Random();
// The number of dispatcher threads
private int dispatcherCount;
// The port on which the Thrift ServerHandler service is listening
private int listeningPort;
// For each event, we retain the list of clients which are subscribed
// for that event. If changes in subscriptions are done, a
// synchronized block should be used.
private Map<NamespaceEventKey, Set<Long>> subscriptions;
// Data structures for each registered client
private ConcurrentMap<Long, ClientData> clientsData;
// Used to generate the client id's
private Random clientIdsGenerator;
// Stores the notifications over an configurable amount of time
private IServerHistory serverHistory;
// The dispatcher which sends the notifications/heartbeats and
// keeps track of the clients
private IServerDispatcher dispatcher;
// The handler for our Thrift service
private ServerHandler.Iface handler;
// The reader of the edit log
private IServerLogReader logReader;
// The server for our Thrift service
private TServer tserver;
// Hadoop configuration
private Configuration conf;
private String serverId = null;
private volatile boolean shouldShutdown = false;
AtomicLong numTotalSubscriptions = new AtomicLong(0);
public NamespaceNotifierMetrics metrics;
// A list with all the threads the server is running
List<Thread> threads = new ArrayList<Thread>();
private volatile boolean started = false;
// work with the federation of the namenodes.
private String serviceName = "";
@Override
public String getServiceName() {
return this.serviceName;
}
public ServerCore(Configuration conf, StartupInfo info) throws ConfigurationException {
this.conf = conf;
init(this.conf);
initDataStructures();
checkAndSetServiceName(conf, info);
}
public ServerCore(StartupInfo info) throws ConfigurationException {
conf = initConfiguration();
init(conf);
initDataStructures();
checkAndSetServiceName(conf, info);
}
// only used in test cases
public ServerCore(Configuration conf) throws ConfigurationException {
this(conf, new StartupInfo(""));
}
/**
* Check if this is a fedrated cluster and set the service name.
* @throws ConfigurationException
*/
private void checkAndSetServiceName(Configuration conf, StartupInfo info)
throws ConfigurationException {
String fedrationMode = conf.get(FSConstants.DFS_FEDERATION_NAMESERVICES);
String serviceName = info.serviceName;
if (fedrationMode != null && !fedrationMode.trim().isEmpty()) {
if (serviceName == null || serviceName.trim().isEmpty()) {
throw new ConfigurationException("This is a fedrated DFS cluster, nameservice id is required.");
}
this.serviceName = serviceName;
}
}
private void initDataStructures() {
clientsData = new ConcurrentHashMap<Long, ClientData>();
subscriptions = new HashMap<NamespaceEventKey, Set<Long>>();
clientIdsGenerator = new Random();
metrics = new NamespaceNotifierMetrics(conf, serverId);
}
@Override
public void init(IServerLogReader logReader, IServerHistory serverHistory,
IServerDispatcher dispatcher, ServerHandler.Iface handler) {
this.serverHistory = serverHistory;
this.logReader = logReader;
this.dispatcher = dispatcher;
this.handler = handler;
}
@Override
public void run() {
LOG.info("Starting server ...");
LOG.info("Max heap size: " + Runtime.getRuntime().maxMemory());
// Setup the Thrift server
TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();
TTransportFactory transportFactory = new TFramedTransport.Factory();
TNonblockingServerTransport serverTransport;
ServerHandler.Processor<ServerHandler.Iface> processor =
new ServerHandler.Processor<ServerHandler.Iface>(handler);
try {
serverTransport = new TNonblockingServerSocket(listeningPort);
} catch (TTransportException e) {
LOG.error("Failed to setup the Thrift server.", e);
return;
}
TNonblockingServer.Args serverArgs =
new TNonblockingServer.Args(serverTransport);
serverArgs.processor(processor).transportFactory(transportFactory)
.protocolFactory(protocolFactory);
tserver = new TNonblockingServer(serverArgs);
// Start the worker threads
threads.add(new Thread(serverHistory, "Thread-ServerHistory"));
threads.add(new Thread(dispatcher, "Thread-Dispatcher"));
threads.add(new Thread(logReader, "Thread-LogReader"));
threads.add(new Thread(new ThriftServerRunnable(), "Thread-ThriftServer"));
LOG.info("Starting thrift server on port " + listeningPort);
for (Thread t : threads) {
t.start();
}
started = true;
try {
while (!shutdownPending()) {
// Read a notification
NamespaceNotification notification =
logReader.getNamespaceNotification();
if (notification != null) {
handleNotification(notification);
continue;
}
}
} catch (Exception e) {
LOG.error("Failed fetching transaction log data", e);
} finally {
shutdown();
}
long shuttingDownStart = System.currentTimeMillis();
for (Thread t : threads) {
long remaining = SHUTDOWN_TIMEOUT + System.currentTimeMillis() -
shuttingDownStart;
try {
if (remaining > 0) {
t.join(remaining);
}
} catch (InterruptedException e) {
LOG.error("Interrupted when closing threads at the end");
}
if (t.isAlive()) {
t.interrupt();
}
}
LOG.info("Shutdown");
}
/**
* Called when the Namespace Notifier server should shutdown.
*/
@Override
public void shutdown() {
LOG.info("Shutting down ...");
shouldShutdown = true;
if (tserver != null) {
tserver.stop();
}
started = false;
}
@Override
public void join() {
for (Thread t : threads) {
try {
t.join();
} catch (InterruptedException e) {
// do nothing
}
}
}
private void waitActive() throws InterruptedException {
while (!started) {
Thread.sleep(1000);
}
}
@Override
public boolean shutdownPending() {
return shouldShutdown;
}
private Configuration initConfiguration()
throws ConfigurationException {
Configuration.addDefaultResource("namespace-notifier-server-default.xml");
Configuration.addDefaultResource("hdfs-default.xml");
Configuration conf = new Configuration();
conf.addResource("namespace-notifier-server-site.xml");
conf.addResource("hdfs-site.xml");
return conf;
}
private void init(Configuration conf)
throws ConfigurationException {
dispatcherCount = conf.getInt(DISPATCHER_COUNT, -1);
listeningPort = conf.getInt(LISTENING_PORT, -1);
try {
serverId = generateServerID();
} catch (UnknownHostException e) {
throw new ConfigurationException("Can not generate the serverId from " +
"hostname.", e);
}
LOG.info("init the configuration: " +
dispatcherCount + " " + listeningPort + " " + serverId);
if (dispatcherCount == -1) {
throw new ConfigurationException("Invalid or missing dispatcherCount: " +
dispatcherCount);
}
if (listeningPort == -1) {
throw new ConfigurationException("Invalid or missing listeningPort: " +
listeningPort);
}
if (serverId == null || serverId.isEmpty()) {
throw new ConfigurationException("Invalid or missing serverId: " +
serverId);
}
}
private String generateServerID() throws UnknownHostException {
String hostname = InetAddress.getLocalHost().getHostName();
return hostname + "_" + random.nextLong();
}
@Override
public Configuration getConfiguration() {
return conf;
}
/**
* Adds the client to the internal data structures and connects to it.
* If the method throws an exception, then it is guaranteed it will also
* be removed from the internal structures before throwing the exception.
*
* @param host the host on which the client is running
* @param port the port on which the client is running the Thrift service
* @return the client's id.
* @throws TTransportException when something went wrong when connecting to
* the client.
*/
@Override
public long addClientAndConnect(String host, int port)
throws TTransportException, IOException {
long clientId = getNewClientId();
LOG.info("Adding client with id=" + clientId + " host=" + host +
" port=" + port + " and connecting ...");
ClientHandler.Client clientHandler;
try {
clientHandler = getClientConnection(host, port);
LOG.info("Succesfully connected to client " + clientId);
} catch (IOException e1) {
LOG.error("Failed to connect to client " + clientId, e1);
throw e1;
} catch (TTransportException e2) {
LOG.error("Failed to connect to client " + clientId, e2);
throw e2;
}
// Save the client to the internal structures
ClientData clientData = new ClientData(clientId, clientHandler, host, port);
addClient(clientData);
LOG.info("Successfully added client " + clientId + " and connected.");
return clientId;
}
/**
* Used to handle a generated notification:
* - sending the notifications to the clients which subscribed to the
* associated event.
* - saving the notification in the history.
* @param n
*/
@Override
public void handleNotification(NamespaceNotification n) {
int queuedCount = 0;
if (LOG.isDebugEnabled()) {
LOG.debug("Handling " + NotifierUtils.asString(n) + " ...");
}
// Add the notification to the queues
Set<Long> clientsForNotification = getClientsForNotification(n);
if (clientsForNotification != null && clientsForNotification.size() > 0) {
synchronized (clientsForNotification) {
for (Long clientId : clientsForNotification) {
ConcurrentLinkedQueue<NamespaceNotification> clientQueue =
clientsData.get(clientId).queue;
// Just test that the client wasn't removed meanwhile
if (clientQueue == null) {
continue;
}
clientQueue.add(n);
queuedCount ++;
}
}
ServerDispatcher.queuedNotificationsCount.addAndGet(queuedCount);
}
// Save it in history
serverHistory.storeNotification(n);
if (LOG.isDebugEnabled()) {
LOG.debug("Done handling " + NotifierUtils.asString(n));
}
}
/**
* Adds the client to the internal structures
* @param clientData the initialized client data object for this client
*/
@Override
public void addClient(ClientData clientData) {
clientsData.put(clientData.id, clientData);
dispatcher.assignClient(clientData.id);
LOG.info("Succesfully added client " + clientData);
metrics.numRegisteredClients.set(clientsData.size());
}
/**
* Removes a client from the internal data structures. This also removes
* the client from all the events to which he subscribed.
*
* @param clientId the client's id for the client we want to remove
* @return true if the client was present in the internal data structures,
* false otherwise.
*/
@Override
public boolean removeClient(long clientId) {
ClientData clientData = clientsData.get(clientId);
if (clientData == null) {
return false;
}
dispatcher.removeClient(clientId);
// Iterate over all the sets in which this client figures as subscribed
// and remove it
synchronized (subscriptions) {
for (Set<Long> subscribedSet : clientData.subscriptions) {
synchronized (subscribedSet) {
subscribedSet.remove(clientId);
}
}
}
metrics.numTotalSubscriptions.set(numTotalSubscriptions.
getAndAdd(-clientData.subscriptions.size()));
clientsData.remove(clientId);
LOG.info("Removed client " + clientData);
metrics.numRegisteredClients.set(clientsData.size());
return true;
}
/**
* Checks if the client with the given id is registered.
* @param clientId the id of the client
* @return true if registered, false otherwise.
*/
@Override
public boolean isRegistered(long clientId) {
return clientsData.containsKey(clientId);
}
/**
* Gets the ClientData object for the given client id.
*
* @param clientId
* @return the ClientData object or null if the clientId
* is invalid.
*/
@Override
public ClientData getClientData(long clientId) {
return clientsData.get(clientId);
}
/**
* Used to get the set of clients for which a notification should be sent.
* While iterating over this set, you should use synchronized() on it to
* avoid data inconsistency (or ordering problems).
*
* @param n the notification for which we want to get the set of clients
* @return the set of clients or null if there are no clients subscribed
* for this notification
*/
@Override
public Set<Long> getClientsForNotification(NamespaceNotification n) {
String eventPath = NotifierUtils.getBasePath(n);
if (LOG.isDebugEnabled()) {
LOG.debug("getClientsForNotification called for " +
NotifierUtils.asString(n) + ". Searching at path " + eventPath);
}
List<String> ancestors = NotifierUtils.getAllAncestors(eventPath);
Set<Long> clients = new HashSet<Long>();
synchronized (subscriptions) {
for (String path : ancestors) {
Set<Long> clientsOnPath = subscriptions.get(new NamespaceEventKey(path, n.type));
if (clientsOnPath != null) {
clients.addAll(clientsOnPath);
}
}
}
return clients;
}
/**
* @return the set of clients id's for all the clients that are currently
* subscribed to us. Warning: this set should not be modified directly.
*/
@Override
public Set<Long> getClients() {
return clientsData.keySet();
}
@Override
public void subscribeClient(long clientId, NamespaceEvent event, long txId)
throws TransactionIdTooOldException, InvalidClientIdException {
NamespaceEventKey eventKey = new NamespaceEventKey(event);
Set<Long> clientsForEvent;
ClientData clientData = clientsData.get(clientId);
if (clientData == null) {
LOG.warn("subscribe client called with invalid id " + clientId);
throw new InvalidClientIdException();
}
LOG.info("Subscribing client " + clientId + " to " +
NotifierUtils.asString(event) + " from txId " + txId);
synchronized (subscriptions) {
clientsForEvent = subscriptions.get(eventKey);
if (clientsForEvent == null) {
clientsForEvent = new HashSet<Long>();
subscriptions.put(eventKey, clientsForEvent);
}
synchronized (clientsForEvent) {
clientData.subscriptions.add(clientsForEvent);
}
}
// It is needed to lock this set while queue'ing the notifications, or we
// may get ordering problems. This is out of the
// synchronized(subscriptions) block because it will block all the
// subscriptions and may induce serious latency (the queueNotifications
// operations can take a lot of time).
synchronized (clientsForEvent) {
queueNotifications(clientId, event, txId);
clientsForEvent.add(clientId);
}
LOG.info(clientId + " subscribed to " + NotifierUtils.asString(event) +
" from txId " + txId);
metrics.numTotalSubscriptions.set(numTotalSubscriptions.incrementAndGet());
}
@Override
public void unsubscribeClient(long clientId, NamespaceEvent event)
throws ClientNotSubscribedException, InvalidClientIdException {
NamespaceEventKey eventKey = new NamespaceEventKey(event);
Set<Long> clientsForEvent;
ClientData clientData = clientsData.get(clientId);
if (clientData == null) {
LOG.warn("subscribe client called with invalid id " + clientId);
throw new InvalidClientIdException();
}
LOG.info("Unsubscribing client " + clientId + " from " +
NotifierUtils.asString(event));
synchronized (subscriptions) {
clientsForEvent = subscriptions.get(eventKey);
if (clientsForEvent == null) {
throw new ClientNotSubscribedException();
}
synchronized (clientsForEvent) {
if (!clientsForEvent.contains(clientId)) {
throw new ClientNotSubscribedException();
}
clientsForEvent.remove(clientId);
clientData.subscriptions.remove(clientsForEvent);
if (clientsForEvent.size() == 0) {
subscriptions.remove(eventKey);
}
}
}
LOG.info("Client " + clientId + " unsubsribed from " +
NotifierUtils.asString(event));
metrics.numTotalSubscriptions.set(numTotalSubscriptions.decrementAndGet());
}
/**
* @return the id of this server
*/
@Override
public String getId() {
return serverId;
}
/**
* Gets the queue of notifications that should be sent to a client. It is
* important to send the notifications in this queue first before sending
* any other notification, or the order will be affected.
*
* @param clientId the id of the client for which we want to get the queued
* notifications.
* @return the queue with the notifications for this client. The returned
* queue is synchronized and no other synchronization mechanisms are
* required. null if the client is not registered.
*/
@Override
public Queue<NamespaceNotification> getClientNotificationQueue(long clientId) {
ClientData clientData = clientsData.get(clientId);
return (clientData == null) ? null : clientData.queue;
}
@Override
public IServerHistory getHistory() {
return serverHistory;
}
/**
* Queues the notification for a client. The queued notifications will be sent
* asynchronously after this method returns to the specified client.
*
* The queued notifications will be notifications for the given event and
* their associated transaction id is greater then the given transaction
* id (exclusive).
*
* @param clientId the client to which the notifications should be sent
* @param event the subscribed event
* @param txId the transaction id from which we should send the
* notifications (exclusive). If this is -1, then
* nothing will be queued for this client.
* @throws TransactionIdTooOldException when the history has no records for
* the given transaction id.
* @throws InvalidClientIdException when the client isn't registered
*/
private void queueNotifications(long clientId, NamespaceEvent event, long txId)
throws TransactionIdTooOldException, InvalidClientIdException {
if (txId == -1) {
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Queueing notifications for client " + clientId + " from txId " +
txId + " at [" + event.path + ", " +
EventType.fromByteValue(event.type) + "] ...");
}
ClientData clientData = clientsData.get(clientId);
if (clientData == null) {
LOG.error("Missing the client data for client id: " + clientId);
throw new InvalidClientIdException("Missing the client data");
}
// Store the notifications in the queue for this client
serverHistory.addNotificationsToQueue(event, txId, clientData.queue);
}
/**
* Generates a new client id which is not present in the current set of ids
* for the clients which are subscribed to this server.
*
* @return A newly generated client id
*/
private long getNewClientId() {
while (true) {
long clientId = Math.abs(clientIdsGenerator.nextLong());
if (!clientsData.containsKey(clientId)) {
return clientId;
}
}
}
private ClientHandler.Client getClientConnection(String host, int port)
throws TTransportException, IOException {
TTransport transport;
TProtocol protocol;
ClientHandler.Client clientObj;
// TODO - make it user configurable
transport = new TFramedTransport(new TSocket(host, port, SOCKET_READ_TIMEOUT));
protocol = new TBinaryProtocol(transport);
clientObj = new ClientHandler.Client(protocol);
transport.open();
return clientObj;
}
@Override
public NamespaceNotifierMetrics getMetrics() {
return metrics;
}
class ThriftServerRunnable implements Runnable {
@Override
public void run() {
try {
tserver.serve();
} catch (Exception e) {
LOG.error("Thrift server failed", e);
} finally {
shutdown();
}
}
}
static IServerLogReader getReader(IServerCore core) throws IOException {
// we only support avatar version of hdfs now.
return new ServerLogReaderAvatar(core);
}
public static ServerCore createNotifier(Configuration conf, String serviceName) {
IServerDispatcher dispatcher;
IServerLogReader logReader;
IServerHistory serverHistory;
ServerCore core = null;
ServerHandler.Iface handler;
Daemon coreDaemon = null;
try {
core = new ServerCore(conf, new StartupInfo(serviceName));
serverHistory = new ServerHistory(core, false); // TODO - enable ramp-up
// we need to instantiate appropriate reader based on VERSION file
logReader = getReader(core);
if (logReader == null) {
throw new IOException("Cannot get server log reader");
}
dispatcher = new ServerDispatcher(core);
handler = new ServerHandlerImpl(core);
core.init(logReader, serverHistory, dispatcher, handler);
coreDaemon = new Daemon(core);
coreDaemon.start();
core.waitActive();
} catch (ConfigurationException e) {
e.printStackTrace();
System.err.println("Invalid configurations.");
} catch (IOException e) {
e.printStackTrace();
System.err.println("Failed reading the transaction log");
} catch (InterruptedException e) {
e.printStackTrace();
}
return core;
}
public static class StartupInfo {
String serviceName;
public StartupInfo(String serviceName) {
this.serviceName = serviceName;
}
}
private static StartupInfo parseArguments(String[] args) {
String serviceName = "";
int argsLen = (args == null) ? 0 : args.length;
for (int i = 0; i < argsLen; i++) {
String cmd = args[i];
if ("-service".equalsIgnoreCase(cmd)) {
if (++i < argsLen) {
serviceName = args[i];
} else {
return null;
}
} else {
return null;
}
}
return new StartupInfo(serviceName);
}
public static void main(String[] args) {
IServerDispatcher dispatcher;
IServerLogReader logReader;
IServerHistory serverHistory;
IServerCore core;
ServerHandler.Iface handler;
Daemon coreDaemon = null;
try {
StartupInfo info = parseArguments(args);
core = new ServerCore(info);
serverHistory = new ServerHistory(core, false); // TODO - enable ramp-up
// we need to instantiate appropriate reader based on VERSION file
logReader = getReader(core);
if (logReader == null) {
throw new IOException("Cannot get server log reader");
}
dispatcher = new ServerDispatcher(core);
handler = new ServerHandlerImpl(core);
core.init(logReader, serverHistory, dispatcher, handler);
coreDaemon = new Daemon(core);
coreDaemon.start();
coreDaemon.join();
} catch (ConfigurationException e) {
e.printStackTrace();
System.err.println("Invalid configurations.");
} catch (IOException e) {
e.printStackTrace();
System.err.println("Failed reading the transaction log");
} catch (InterruptedException e) {
e.printStackTrace();
System.err.println("Core interrupted");
}
}
}
| |
/**
*
* Copyright 2017 Florian Erhard
*
* 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 gedi.util.datastructure.charsequence;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.TreeMap;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.IntFunction;
import gedi.util.ArrayUtils;
import gedi.util.StringUtils;
import gedi.util.functions.EI;
import gedi.util.functions.ExtendedIterator;
public class CharDag {
private CharIterator text;
private SequenceVariant[] variants;
public CharDag(CharIterator text, ExtendedIterator<SequenceVariant> variants) {
this.text = text;
this.variants = variants.toArray(SequenceVariant.class);
Arrays.sort(this.variants);
}
public SequenceVariant[] getVariants() {
return variants;
}
public <R> void traverse(CharDagVisitor<R> v, BiConsumer<R,Iterator<SequenceVariant>> re) {
traverse(i->i==0?v:null, re);
}
public <R> void traverse(IntFunction<CharDagVisitor<R>> v, BiConsumer<R,Iterator<SequenceVariant>> re) {
int nextVariantIndex = 0;
int pos = -1;
ArrayList<CharDagVisitor<R>> vs = new ArrayList<CharDagVisitor<R>>();
TreeMap<Integer, ArrayList<CharDagVisitor<R>>> cont = new TreeMap<>();
while (text.hasNext()) {
pos++;
CharDagVisitor<R> vvv = v.apply(pos);
if (vvv!=null)
vs.add(vvv);
while (nextVariantIndex<variants.length && variants[nextVariantIndex].pos==pos) {
ArrayList<CharDagVisitor<R>> bvs = new ArrayList<CharDagVisitor<R>>();
for (CharDagVisitor<R> vv : vs)
bvs.add(vv.branch());
if (bvs.size()>1)
Collections.sort(bvs);
for (CharDagVisitor<R> sv : bvs)
sv.shift(pos,-variants[nextVariantIndex].from.length, variants[nextVariantIndex]);
for (char c : variants[nextVariantIndex].to) {
int index = 0;
bvs.get(0).shift(pos,1, variants[nextVariantIndex]);
Iterator<R> r = bvs.get(0).accept(c,pos);
accept(re,r, bvs.get(0));
for (int i=1; i<bvs.size(); i++) {
bvs.get(i).shift(pos,1, variants[nextVariantIndex]);
r = bvs.get(i).accept(c,pos);
if (bvs.get(i).compareTo(bvs.get(index))!=0) {
index++;
accept(re,r, bvs.get(i));
}
bvs.set(index, bvs.get(i));
}
while (bvs.size()!=index+1) {
bvs.remove(bvs.size()-1);
}
}
int conti = pos+variants[nextVariantIndex].from.length;
ArrayList<CharDagVisitor<R>> cl = cont.get(conti);
if (cl==null) cont.put(conti, bvs);
else cl.addAll(bvs);
nextVariantIndex++;
}
ArrayList<CharDagVisitor<R>> cl = cont.remove(pos);
if (cl!=null)
vs.addAll(cl);
if (vs.size()>1)
Collections.sort(vs);
char c = text.nextChar();
int index = 0;
Iterator<R> r = vs.get(0).accept(c,pos);
accept(re, r, vs.get(0));
for (int i=1; i<vs.size(); i++) {
r = vs.get(i).accept(c,pos);
if (vs.get(i).compareTo(vs.get(index))!=0) {
index++;
accept(re, r, vs.get(i));
}
vs.set(index, vs.get(i));
}
while (vs.size()!=index+1)
vs.remove(vs.size()-1);
for (CharDagVisitor<R> vv : vs)
vv.prune(pos);
}
}
private <R> void accept(BiConsumer<R,Iterator<SequenceVariant>> re, Iterator<R> r, CharDagVisitor<R> v) {
if (r!=null) {
while (r.hasNext())
re.accept(r.next(),v.getVariants());
}
}
public static interface CharDagVisitor<R> extends Comparable<CharDagVisitor<R>> {
Iterator<R> accept(char c, int pos);
Iterator<SequenceVariant> getVariants();
CharDagVisitor<R> branch();
void shift(int pos, int shift, SequenceVariant variant);
void prune(int pos);
}
public static class PosLengthVariant implements Comparable<PosLengthVariant> {
private int pos;
private int len;
private SequenceVariant variant;
public PosLengthVariant(int pos, int len, SequenceVariant variant) {
super();
this.pos = pos;
this.len = len;
this.variant = variant;
}
public int getPos() {
return pos;
}
public int getLen() {
return len;
}
public SequenceVariant getVariant() {
return variant;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + len;
result = prime * result + pos;
result = prime * result + ((variant == null) ? 0 : variant.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PosLengthVariant other = (PosLengthVariant) obj;
if (len != other.len)
return false;
if (pos != other.pos)
return false;
if (variant == null) {
if (other.variant != null)
return false;
} else if (!variant.equals(other.variant))
return false;
return true;
}
@Override
public String toString() {
return "[" + pos + ", " + len + ", " + variant + "]";
}
public void incrementLen(int shift) {
this.len+=shift;
}
@Override
public int compareTo(PosLengthVariant o) {
if (o.pos==pos) return Integer.compare(hashCode(), o.hashCode());
return Integer.compare(pos, o.pos);
}
}
public static class KmerCharDagVisitor implements CharDagVisitor<CharSequence> {
private CharRingBuffer buff;
private int n = 0;
private LinkedList<PosLengthVariant> correction = new LinkedList<PosLengthVariant>();
private KmerCharDagVisitor() {
}
public KmerCharDagVisitor(int k) {
this.buff = new CharRingBuffer(k);
}
@Override
public Iterator<CharSequence> accept(char c, int pos) {
this.buff.add(c);
if (++n>=this.buff.capacity())
return EI.singleton(this.buff.toString()+"@"+pos+", "+StringUtils.toString(correction));
return null;
}
@Override
public int compareTo(CharDagVisitor<CharSequence> o) {
return buff.compareTo(((KmerCharDagVisitor)o).buff);
}
@Override
public CharDagVisitor<CharSequence> branch() {
KmerCharDagVisitor re = new KmerCharDagVisitor();
re.buff = new CharRingBuffer(buff);
re.n = n;
re.correction.addAll(correction);
return re;
}
@Override
public void shift(int pos, int shift, SequenceVariant variant) {
if (correction.size()>0 && correction.getLast().getPos()==pos && correction.getLast().getVariant().equals(variant)) {
correction.getLast().incrementLen(shift);
if (correction.getLast().getLen()==0) correction.removeLast();
} else
correction.add(new PosLengthVariant(pos, shift,variant));
}
@Override
public void prune(int pos) {
Iterator<PosLengthVariant> it = correction.iterator();
while (it.hasNext() && it.next().getPos()<pos-buff.capacity())
it.remove();
}
@Override
public Iterator<SequenceVariant> getVariants() {
return EI.wrap(correction).map(plv->plv.getVariant());
}
}
public static class SequenceVariant implements Comparable<SequenceVariant> {
int pos;
char[] from;
char[] to;
String label;
public SequenceVariant(int pos, char[] from, char[] to, String label) {
this.pos = pos;
this.from = from;
this.to = to;
this.label = label;
}
@Override
public int compareTo(SequenceVariant o) {
return Integer.compare(pos, o.pos);
}
public int end() {
return pos+from.length;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(from);
result = prime * result + pos;
result = prime * result + Arrays.hashCode(to);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SequenceVariant other = (SequenceVariant) obj;
if (!Arrays.equals(from, other.from))
return false;
if (pos != other.pos)
return false;
if (!Arrays.equals(to, other.to))
return false;
return true;
}
@Override
public String toString() {
if (label!=null)
return label;
return pos+" "+String.valueOf(from)+">"+String.valueOf(to);
}
}
}
| |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.keymap.impl;
import com.intellij.diagnostic.EventWatcher;
import com.intellij.diagnostic.LoadingState;
import com.intellij.diagnostic.LoggableEventWatcher;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.ProhibitAWTEvents;
import com.intellij.ide.impl.DataManagerImpl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.MnemonicHelper;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.actionSystem.impl.ActionMenu;
import com.intellij.openapi.actionSystem.impl.PresentationFactory;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.keymap.KeyMapBundle;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.keymap.impl.keyGestures.KeyboardGestureProcessor;
import com.intellij.openapi.keymap.impl.ui.ShortcutTextField;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopupStep;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.ex.StatusBarEx;
import com.intellij.openapi.wm.impl.FloatingDecorator;
import com.intellij.openapi.wm.impl.IdeFrameImpl;
import com.intellij.openapi.wm.impl.IdeGlassPaneEx;
import com.intellij.ui.*;
import com.intellij.ui.popup.list.ListPopupImpl;
import com.intellij.ui.speedSearch.SpeedSearchSupply;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.KeyboardLayoutUtil;
import com.intellij.util.ui.MacUIUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.plaf.basic.ComboPopup;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.im.InputContext;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.*;
/**
* This class is automaton with finite number of state.
*
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public final class IdeKeyEventDispatcher implements Disposable {
@NonNls
private static final String GET_CACHED_STROKE_METHOD_NAME = "getCachedStroke";
private static final Logger LOG = Logger.getInstance(IdeKeyEventDispatcher.class);
private static final boolean JAVA11_ON_WINDOWS = SystemInfo.isWindows && SystemInfo.isJavaVersionAtLeast(11, 0, 0);
private KeyStroke myFirstKeyStroke;
/**
* When we "dispatch" key event via keymap, i.e. when registered action has been executed
* instead of event dispatching, then we have to consume all following KEY_RELEASED and
* KEY_TYPED event because they are not valid.
*/
private boolean myPressedWasProcessed;
private boolean myIgnoreNextKeyTypedEvent;
private KeyState myState = KeyState.STATE_INIT;
private final PresentationFactory myPresentationFactory = new PresentationFactory();
private boolean myDisposed;
private boolean myLeftCtrlPressed;
private boolean myRightAltPressed;
private final KeyboardGestureProcessor myKeyGestureProcessor = new KeyboardGestureProcessor(this);
private final KeyProcessorContext myContext = new KeyProcessorContext();
private final IdeEventQueue myQueue;
private final Alarm mySecondStrokeTimeout = new Alarm();
private final Runnable mySecondStrokeTimeoutRunnable = () -> {
if (myState == KeyState.STATE_WAIT_FOR_SECOND_KEYSTROKE) {
resetState();
final DataContext dataContext = myContext.getDataContext();
StatusBar.Info.set(null, dataContext == null ? null : CommonDataKeys.PROJECT.getData(dataContext));
}
};
private final Alarm mySecondKeystrokePopupTimeout = new Alarm();
public IdeKeyEventDispatcher(@Nullable IdeEventQueue queue){
myQueue = queue;
// Application is null on early start when e.g. license dialog is shown
Application parent = ApplicationManager.getApplication();
if (parent != null) {
Disposer.register(parent, this);
}
}
public boolean isWaitingForSecondKeyStroke(){
return getState() == KeyState.STATE_WAIT_FOR_SECOND_KEYSTROKE || isPressedWasProcessed();
}
/**
* @return {@code true} if and only if the passed event is already dispatched by the
* {@code IdeKeyEventDispatcher} and there is no need for any other processing of the event.
*/
public boolean dispatchKeyEvent(final KeyEvent e){
if (myDisposed) return false;
KeyboardLayoutUtil.storeAsciiForChar(e);
if (e.isConsumed()) {
return false;
}
if (myIgnoreNextKeyTypedEvent) {
if (KeyEvent.KEY_TYPED == e.getID()) return true;
myIgnoreNextKeyTypedEvent = false;
}
if (isSpeedSearchEditing(e)) {
return false;
}
// http://www.jetbrains.net/jira/browse/IDEADEV-12372
if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
myLeftCtrlPressed = e.getKeyLocation() == KeyEvent.KEY_LOCATION_LEFT;
}
else if (e.getID() == KeyEvent.KEY_RELEASED) {
myLeftCtrlPressed = false;
}
}
else if (e.getKeyCode() == KeyEvent.VK_ALT) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
myRightAltPressed = e.getKeyLocation() == KeyEvent.KEY_LOCATION_RIGHT;
}
else if (e.getID() == KeyEvent.KEY_RELEASED) {
myRightAltPressed = false;
}
}
KeyboardFocusManager focusManager=KeyboardFocusManager.getCurrentKeyboardFocusManager();
Component focusOwner = focusManager.getFocusOwner();
// shortcuts should not work in shortcut setup fields
if (focusOwner instanceof ShortcutTextField) {
// remove AltGr modifier to show a shortcut without AltGr in Settings
if (JAVA11_ON_WINDOWS && KeyEvent.KEY_PRESSED == e.getID()) removeAltGraph(e);
return false;
}
if (focusOwner instanceof JTextComponent && ((JTextComponent)focusOwner).isEditable()) {
if (e.getKeyChar() != KeyEvent.CHAR_UNDEFINED && e.getKeyCode() != KeyEvent.VK_ESCAPE) {
MacUIUtil.hideCursor();
}
}
MenuSelectionManager menuSelectionManager=MenuSelectionManager.defaultManager();
MenuElement[] selectedPath = menuSelectionManager.getSelectedPath();
if(selectedPath.length>0){
if (!(selectedPath[0] instanceof ComboPopup)) {
// The following couple of lines of code is a PATCH!!!
// It is needed to ignore ENTER KEY_TYPED events which sometimes can reach editor when an action
// is invoked from main menu via Enter key.
setState(KeyState.STATE_PROCESSED);
return processMenuActions(e, selectedPath[0]);
}
}
// Keymap shortcuts (i.e. not local shortcuts) should work only in:
// - main frame
// - floating focusedWindow
// - when there's an editor in contexts
Window focusedWindow = focusManager.getFocusedWindow();
boolean isModalContext = focusedWindow != null && isModalContext(focusedWindow);
if (ApplicationManager.getApplication() == null) return false; //EA-39114
final DataManager dataManager = DataManager.getInstance();
if (dataManager == null) return false;
DataContext dataContext = dataManager.getDataContext();
myContext.setDataContext(dataContext);
myContext.setFocusOwner(focusOwner);
myContext.setModalContext(isModalContext);
myContext.setInputEvent(e);
try {
if (getState() == KeyState.STATE_INIT) {
return inInitState();
}
else if (getState() == KeyState.STATE_PROCESSED) {
return inProcessedState();
}
else if (getState() == KeyState.STATE_WAIT_FOR_SECOND_KEYSTROKE) {
return inWaitForSecondStrokeState();
}
else if (getState() == KeyState.STATE_SECOND_STROKE_IN_PROGRESS) {
return inSecondStrokeInProgressState();
}
else if (getState() == KeyState.STATE_KEY_GESTURE_PROCESSOR) {
return myKeyGestureProcessor.process();
}
else if (getState() == KeyState.STATE_WAIT_FOR_POSSIBLE_ALT_GR) {
return inWaitForPossibleAltGr();
}
else {
throw new IllegalStateException("state = " + getState());
}
}
finally {
myContext.clear();
}
}
private static boolean isSpeedSearchEditing(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_BACK_SPACE) {
Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (owner instanceof JComponent) {
SpeedSearchSupply supply = SpeedSearchSupply.getSupply((JComponent)owner);
return supply != null && supply.isPopupActive();
}
}
return false;
}
/**
* @return {@code true} if and only if the {@code component} represents
* modal context.
* @throws IllegalArgumentException if {@code component} is {@code null}.
*/
public static boolean isModalContext(@NotNull Component component) {
Window window = ComponentUtil.getWindow(component);
if (window instanceof IdeFrameImpl) {
Component pane = ((JFrame)window).getGlassPane();
if (pane instanceof IdeGlassPaneEx) {
return ((IdeGlassPaneEx) pane).isInModalContext();
}
}
if (window instanceof JDialog) {
final JDialog dialog = (JDialog)window;
if (!dialog.isModal()) {
final Window owner = dialog.getOwner();
return owner != null && isModalContext(owner);
}
}
if (window instanceof JFrame) {
return false;
}
boolean isFloatingDecorator = window instanceof FloatingDecorator;
boolean isPopup = !(component instanceof JFrame) && !(component instanceof JDialog);
if (isPopup) {
if (component instanceof JWindow) {
JBPopup popup = (JBPopup)((JWindow)component).getRootPane().getClientProperty(JBPopup.KEY);
if (popup != null) {
return popup.isModalContext();
}
}
}
return !isFloatingDecorator;
}
private boolean inWaitForSecondStrokeState() {
// a key pressed means that the user starts to enter the second stroke...
if (KeyEvent.KEY_PRESSED==myContext.getInputEvent().getID()) {
setState(KeyState.STATE_SECOND_STROKE_IN_PROGRESS);
return inSecondStrokeInProgressState();
}
// looks like RELEASEs (from the first stroke) go here... skip them
return true;
}
/**
* This is hack. AWT doesn't allow to create KeyStroke with specified key code and key char
* simultaneously. Therefore we are using reflection.
*/
private static KeyStroke getKeyStrokeWithoutMouseModifiers(KeyStroke originalKeyStroke){
int modifier=originalKeyStroke.getModifiers()&~InputEvent.BUTTON1_DOWN_MASK&~InputEvent.BUTTON1_MASK&
~InputEvent.BUTTON2_DOWN_MASK&~InputEvent.BUTTON2_MASK&
~InputEvent.BUTTON3_DOWN_MASK&~InputEvent.BUTTON3_MASK;
try {
Method[] methods=AWTKeyStroke.class.getDeclaredMethods();
Method getCachedStrokeMethod=null;
for (Method method : methods) {
if (GET_CACHED_STROKE_METHOD_NAME.equals(method.getName())) {
getCachedStrokeMethod = method;
getCachedStrokeMethod.setAccessible(true);
break;
}
}
if(getCachedStrokeMethod==null){
throw new IllegalStateException("not found method with name getCachedStrokeMethod");
}
Object[] getCachedStrokeMethodArgs=
{originalKeyStroke.getKeyChar(), originalKeyStroke.getKeyCode(), modifier, originalKeyStroke.isOnKeyRelease()};
return (KeyStroke)getCachedStrokeMethod.invoke(originalKeyStroke, getCachedStrokeMethodArgs);
}
catch(Exception exc){
throw new IllegalStateException(exc.getMessage());
}
}
private boolean inWaitForPossibleAltGr() {
KeyEvent e = myContext.getInputEvent();
KeyStroke keyStroke = myFirstKeyStroke;
myFirstKeyStroke = null;
setState(KeyState.STATE_INIT);
// processing altGr
int eventId = e.getID();
if (KeyEvent.KEY_TYPED == eventId && e.isAltGraphDown()) {
return false;
} else if (KeyEvent.KEY_RELEASED == eventId) {
updateCurrentContext(myContext.getFoundComponent(), new KeyboardShortcut(keyStroke, null));
if (myContext.getActions().isEmpty()) {
return false;
}
return processActionOrWaitSecondStroke(keyStroke);
}
return false;
}
private boolean inSecondStrokeInProgressState() {
KeyEvent e = myContext.getInputEvent();
// when any key is released, we stop waiting for the second stroke
if(KeyEvent.KEY_RELEASED==e.getID()){
myFirstKeyStroke=null;
setState(KeyState.STATE_INIT);
Project project = CommonDataKeys.PROJECT.getData(myContext.getDataContext());
StatusBar.Info.set(null, project);
return false;
}
KeyStroke originalKeyStroke = KeyStrokeAdapter.getDefaultKeyStroke(e);
if (originalKeyStroke == null) {
return false;
}
KeyStroke keyStroke=getKeyStrokeWithoutMouseModifiers(originalKeyStroke);
updateCurrentContext(myContext.getFoundComponent(), new KeyboardShortcut(myFirstKeyStroke, keyStroke));
// consume the wrong second stroke and keep on waiting
if (myContext.getActions().isEmpty()) {
return true;
}
// finally user had managed to enter the second keystroke, so let it be processed
Project project = CommonDataKeys.PROJECT.getData(myContext.getDataContext());
StatusBarEx statusBar = (StatusBarEx) WindowManager.getInstance().getStatusBar(project);
if (processAction(e, myActionProcessor)) {
if (statusBar != null) {
statusBar.setInfo(null);
}
return true;
} else {
return false;
}
}
private boolean inProcessedState() {
KeyEvent e = myContext.getInputEvent();
// ignore typed events which come after processed pressed event
if (KeyEvent.KEY_TYPED == e.getID() && isPressedWasProcessed()) {
return true;
}
if (KeyEvent.KEY_RELEASED == e.getID() && KeyEvent.VK_ALT == e.getKeyCode() && isPressedWasProcessed()) {
//see IDEADEV-8615
return true;
}
setState(KeyState.STATE_INIT);
setPressedWasProcessed(false);
return inInitState();
}
private boolean inInitState() {
Component focusOwner = myContext.getFocusOwner();
boolean isModalContext = myContext.isModalContext();
DataContext dataContext = myContext.getDataContext();
KeyEvent e = myContext.getInputEvent();
if (JAVA11_ON_WINDOWS && KeyEvent.KEY_PRESSED == e.getID() && removeAltGraph(e) && e.isControlDown()) {
myFirstKeyStroke = KeyStrokeAdapter.getDefaultKeyStroke(e);
if (myFirstKeyStroke == null) return false;
setState(KeyState.STATE_WAIT_FOR_POSSIBLE_ALT_GR);
return true;
}
// http://www.jetbrains.net/jira/browse/IDEADEV-12372
boolean isCandidateForAltGr = myLeftCtrlPressed && myRightAltPressed && focusOwner != null && e.getModifiers() == (InputEvent.CTRL_MASK | InputEvent.ALT_MASK);
if (isCandidateForAltGr) {
if (Registry.is("actionSystem.force.alt.gr")) {
return false;
}
if (isAltGrLayout(focusOwner)) return false; // don't search for shortcuts
}
KeyStroke originalKeyStroke = KeyStrokeAdapter.getDefaultKeyStroke(e);
if (originalKeyStroke == null) {
return false;
}
KeyStroke keyStroke=getKeyStrokeWithoutMouseModifiers(originalKeyStroke);
if (myKeyGestureProcessor.processInitState()) {
return true;
}
if (InputEvent.ALT_DOWN_MASK == e.getModifiersEx() && (!SystemInfo.isMac || Registry.is("ide.mac.alt.mnemonic.without.ctrl"))) {
// the myIgnoreNextKeyTypedEvent changes event processing to support Alt-based mnemonics
if ((KeyEvent.KEY_TYPED == e.getID() && !IdeEventQueue.getInstance().isInputMethodEnabled()) ||
hasMnemonicInWindow(focusOwner, e)) {
myIgnoreNextKeyTypedEvent = true;
return false;
}
}
updateCurrentContext(focusOwner, new KeyboardShortcut(keyStroke, null));
if (myContext.getActions().isEmpty()) {
// there's nothing mapped for this stroke
return false;
}
// workaround for IDEA-177327
if (isCandidateForAltGr && SystemInfo.isWindows && Registry.is("actionSystem.fix.alt.gr")) {
myFirstKeyStroke = keyStroke;
setState(KeyState.STATE_WAIT_FOR_POSSIBLE_ALT_GR);
return true;
}
return processActionOrWaitSecondStroke(keyStroke);
}
private boolean processActionOrWaitSecondStroke(KeyStroke keyStroke) {
DataContext dataContext = myContext.getDataContext();
KeyEvent e = myContext.getInputEvent();
if (myContext.isHasSecondStroke()) {
myFirstKeyStroke=keyStroke;
final ArrayList<Pair<AnAction, KeyStroke>> secondKeyStrokes = getSecondKeystrokeActions();
final Project project = CommonDataKeys.PROJECT.getData(dataContext);
StringBuilder message = new StringBuilder();
message.append(KeyMapBundle.message("prefix.key.pressed.message"));
message.append(' ');
for (int i = 0; i < secondKeyStrokes.size(); i++) {
Pair<AnAction, KeyStroke> pair = secondKeyStrokes.get(i);
if (i > 0) message.append(", ");
message.append(pair.getFirst().getTemplatePresentation().getText());
message.append(" (");
message.append(KeymapUtil.getKeystrokeText(pair.getSecond()));
message.append(")");
}
StatusBar.Info.set(message.toString(), project);
mySecondStrokeTimeout.cancelAllRequests();
mySecondStrokeTimeout.addRequest(mySecondStrokeTimeoutRunnable, Registry.intValue("actionSystem.secondKeystrokeTimeout"));
if (Registry.is("actionSystem.secondKeystrokeAutoPopupEnabled")) {
mySecondKeystrokePopupTimeout.cancelAllRequests();
if (secondKeyStrokes.size() > 1) {
final DataContext oldContext = myContext.getDataContext();
mySecondKeystrokePopupTimeout.addRequest(() -> {
if (myState == KeyState.STATE_WAIT_FOR_SECOND_KEYSTROKE) {
StatusBar.Info.set(null, CommonDataKeys.PROJECT.getData(oldContext));
new SecondaryKeystrokePopup(myFirstKeyStroke, secondKeyStrokes, oldContext).showInBestPositionFor(oldContext);
}
}, Registry.intValue("actionSystem.secondKeystrokePopupTimeout"));
}
}
setState(KeyState.STATE_WAIT_FOR_SECOND_KEYSTROKE);
return true;
}
else {
return processAction(e, myActionProcessor);
}
}
private ArrayList<Pair<AnAction, KeyStroke>> getSecondKeystrokeActions() {
ArrayList<Pair<AnAction, KeyStroke>> secondKeyStrokes = new ArrayList<>();
for (AnAction action : myContext.getActions()) {
Shortcut[] shortcuts = action.getShortcutSet().getShortcuts();
for (Shortcut shortcut : shortcuts) {
if (shortcut instanceof KeyboardShortcut) {
KeyboardShortcut keyShortcut = (KeyboardShortcut)shortcut;
if (keyShortcut.getFirstKeyStroke().equals(myFirstKeyStroke)) {
secondKeyStrokes.add(Pair.create(action, keyShortcut.getSecondKeyStroke()));
}
}
}
}
return secondKeyStrokes;
}
public static boolean hasMnemonicInWindow(Component focusOwner, KeyEvent event) {
return KeyEvent.KEY_TYPED == event.getID() && hasMnemonicInWindow(focusOwner, event.getKeyChar()) ||
KeyEvent.KEY_PRESSED == event.getID() && hasMnemonicInWindow(focusOwner, event.getKeyCode());
}
private static boolean hasMnemonicInWindow(Component focusOwner, int keyCode) {
if (keyCode == KeyEvent.VK_ALT || keyCode == 0) return false; // Optimization
Container container = focusOwner == null ? null : ComponentUtil.getWindow(focusOwner);
if (container instanceof JFrame) {
ComponentWithMnemonics componentWithMnemonics = UIUtil.getParentOfType(ComponentWithMnemonics.class, focusOwner);
if (componentWithMnemonics instanceof Container) {
container = (Container)componentWithMnemonics;
}
}
return hasMnemonic(container, keyCode) || hasMnemonicInBalloons(container, keyCode);
}
private static boolean hasMnemonic(@Nullable Container container, int keyCode) {
Component component = UIUtil.uiTraverser(container)
.traverse()
.filter(Component::isEnabled)
.filter(Component::isShowing)
.find(c -> !(c instanceof ActionMenu) && MnemonicHelper.hasMnemonic(c, keyCode));
return component != null;
}
private static boolean hasMnemonicInBalloons(Container container, int code) {
Component parent = UIUtil.findUltimateParent(container);
if (parent instanceof RootPaneContainer) {
final JLayeredPane pane = ((RootPaneContainer)parent).getLayeredPane();
for (Component component : pane.getComponents()) {
if (component instanceof ComponentWithMnemonics &&
component instanceof Container &&
hasMnemonic((Container)component, code)) {
return true;
}
}
}
return false;
}
private final ActionProcessor myActionProcessor = new ActionProcessor() {
@NotNull
@Override
public AnActionEvent createEvent(final InputEvent inputEvent, @NotNull final DataContext context, @NotNull final String place, @NotNull final Presentation presentation,
@NotNull final ActionManager manager) {
return new AnActionEvent(inputEvent, context, place, presentation, manager, 0);
}
@Override
public void onUpdatePassed(final InputEvent inputEvent, @NotNull final AnAction action, @NotNull final AnActionEvent actionEvent) {
setState(KeyState.STATE_PROCESSED);
setPressedWasProcessed(inputEvent.getID() == KeyEvent.KEY_PRESSED);
}
@Override
public void performAction(@NotNull InputEvent e, @NotNull AnAction action, @NotNull AnActionEvent actionEvent) {
e.consume();
if (e instanceof KeyEvent) {
IdeEventQueue.getInstance().onActionInvoked((KeyEvent)e);
}
DataContext ctx = actionEvent.getDataContext();
if (action instanceof ActionGroup && !((ActionGroup)action).canBePerformed(ctx)) {
ActionGroup group = (ActionGroup)action;
String groupId = ActionManager.getInstance().getId(action);
JBPopupFactory.getInstance().createActionGroupPopup(
group.getTemplatePresentation().getText(), group, ctx,
JBPopupFactory.ActionSelectionAid.SPEEDSEARCH,
false, null, -1, null, ActionPlaces.getActionGroupPopupPlace(groupId))
.showInBestPositionFor(ctx);
}
else {
ActionUtil.performActionDumbAware(action, actionEvent);
}
if (Registry.is("actionSystem.fixLostTyping")) {
IdeEventQueue.getInstance().doWhenReady(() -> IdeEventQueue.getInstance().getKeyEventDispatcher().resetState());
}
}
};
public boolean processAction(final InputEvent e, @NotNull ActionProcessor processor) {
return processAction(e, processor, myContext.getDataContext(), myContext.getActions().toArray(AnAction.EMPTY_ARRAY),
myPresentationFactory);
}
private static boolean processAction(final InputEvent e,
@NotNull ActionProcessor processor,
DataContext context,
AnAction[] actions,
PresentationFactory presentationFactory) {
ActionManagerEx actionManager = ActionManagerEx.getInstanceEx();
final Project project = CommonDataKeys.PROJECT.getData(context);
final boolean dumb = project != null && DumbService.getInstance(project).isDumb();
List<AnActionEvent> nonDumbAwareAction = new ArrayList<>();
for (final AnAction action : actions) {
long startedAt = System.currentTimeMillis();
Presentation presentation = presentationFactory.getPresentation(action);
// Mouse modifiers are 0 because they have no any sense when action is invoked via keyboard
final AnActionEvent actionEvent =
processor.createEvent(e, context, ActionPlaces.KEYBOARD_SHORTCUT, presentation, ActionManager.getInstance());
try (AccessToken ignored = ProhibitAWTEvents.start("update")) {
ActionUtil.performDumbAwareUpdate(LaterInvocator.isInModalContext(), action, actionEvent, true);
}
if (dumb && !action.isDumbAware()) {
if (!Boolean.FALSE.equals(presentation.getClientProperty(ActionUtil.WOULD_BE_ENABLED_IF_NOT_DUMB_MODE))) {
nonDumbAwareAction.add(actionEvent);
}
logTimeMillis(startedAt, action);
continue;
}
if (!presentation.isEnabled()) {
logTimeMillis(startedAt, action);
continue;
}
processor.onUpdatePassed(e, action, actionEvent);
if (context instanceof DataManagerImpl.MyDataContext) { // this is not true for test data contexts
((DataManagerImpl.MyDataContext)context).setEventCount(IdeEventQueue.getInstance().getEventCount());
}
actionManager.fireBeforeActionPerformed(action, actionEvent.getDataContext(), actionEvent);
Component component = actionEvent.getData(PlatformDataKeys.CONTEXT_COMPONENT);
if (component != null && !component.isShowing()) {
logTimeMillis(startedAt, action);
return true;
}
((TransactionGuardImpl)TransactionGuard.getInstance()).performUserActivity(
() -> processor.performAction(e, action, actionEvent));
actionManager.fireAfterActionPerformed(action, actionEvent.getDataContext(), actionEvent);
logTimeMillis(startedAt, action);
return true;
}
if (!nonDumbAwareAction.isEmpty()) {
if (dumbModeWarningListener != null) {
dumbModeWarningListener.actionCanceledBecauseOfDumbMode();
if (e instanceof KeyEvent) { //IDEA-222847
IdeEventQueue.getInstance().onActionInvoked((KeyEvent)e);
}
}
IdeEventQueue.getInstance().flushDelayedKeyEvents();
showDumbModeDialogLaterIfNobodyConsumesEvent(project, e, processor, actions, presentationFactory,
nonDumbAwareAction.toArray(new AnActionEvent[0]));
}
IdeEventQueue.getInstance().flushDelayedKeyEvents();
return false;
}
private static void showDumbModeDialogLaterIfNobodyConsumesEvent(@Nullable Project project,
InputEvent e,
ActionProcessor processor,
AnAction[] actions,
PresentationFactory presentationFactory,
AnActionEvent... actionEvents) {
if (project == null) return;
ApplicationManager.getApplication().invokeLater(() -> {
if (e.isConsumed()) return;
List<String> actionNames = new ArrayList<>();
for (final AnActionEvent event : actionEvents) {
final String s = event.getPresentation().getText();
if (StringUtil.isNotEmpty(s)) {
actionNames.add(s);
}
}
if (DumbService.getInstance(project).showDumbModeDialog(actionNames)) {
//invokeLater to make sure correct dataContext is taken from focus
ApplicationManager.getApplication().invokeLater(() -> {
DataManager.getInstance().getDataContextFromFocusAsync().onSuccess(context -> {
processAction(e, processor, context, actions, presentationFactory);
});
});
}
});
}
private static DumbModeWarningListener dumbModeWarningListener = null;
public static void addDumbModeWarningListener (DumbModeWarningListener listener) {
dumbModeWarningListener = listener;
}
/**
* This method fills {@code myActions} list.
*/
public void updateCurrentContext(Component component, @NotNull Shortcut sc) {
myContext.setFoundComponent(null);
myContext.setHasSecondStroke(false);
myContext.getActions().clear();
if (isControlEnterOnDialog(component, sc)) return;
// here we try to find "local" shortcuts
for (; component != null; component = component.getParent()) {
if (!(component instanceof JComponent)) {
continue;
}
List<AnAction> listOfActions = ActionUtil.getActions((JComponent)component);
if (listOfActions.isEmpty()) {
continue;
}
for (AnAction action : listOfActions) {
addAction(action, sc);
}
// once we've found a proper local shortcut(s), we continue with non-local shortcuts
if (!myContext.getActions().isEmpty()) {
myContext.setFoundComponent((JComponent)component);
break;
}
}
addActionsFromActiveKeymap(sc);
if (!myContext.isHasSecondStroke() && sc instanceof KeyboardShortcut) {
// little trick to invoke action which second stroke is a key w/o modifiers, but user still
// holds the modifier key(s) of the first stroke
final KeyboardShortcut keyboardShortcut = (KeyboardShortcut)sc;
final KeyStroke firstKeyStroke = keyboardShortcut.getFirstKeyStroke();
final KeyStroke secondKeyStroke = keyboardShortcut.getSecondKeyStroke();
if (secondKeyStroke != null && secondKeyStroke.getModifiers() != 0 && firstKeyStroke.getModifiers() != 0) {
final KeyboardShortcut altShortCut = new KeyboardShortcut(firstKeyStroke, KeyStroke.getKeyStroke(secondKeyStroke.getKeyCode(), 0));
addActionsFromActiveKeymap(altShortCut);
}
}
List<AnAction> actions = myContext.getActions();
if (actions.size() > 1) {
rearrangeByPromoters(actions);
}
}
private void rearrangeByPromoters(List<AnAction> actions) {
List<AnAction> readOnlyActions = Collections.unmodifiableList(actions);
for (ActionPromoter promoter : ActionPromoter.EP_NAME.getExtensions()) {
List<AnAction> promoted = promoter.promote(readOnlyActions, myContext.getDataContext());
if (promoted == null || promoted.isEmpty()) continue;
actions.removeAll(promoted);
actions.addAll(0, promoted);
}
}
private void addActionsFromActiveKeymap(@NotNull Shortcut shortcut) {
if (!LoadingState.COMPONENTS_LOADED.isOccurred()) {
return;
}
ActionManager actionManager = ApplicationManager.getApplication().getServiceIfCreated(ActionManager.class);
if (actionManager == null) {
return;
}
KeymapManager keymapManager = KeymapManager.getInstance();
Keymap keymap = keymapManager == null ? null : keymapManager.getActiveKeymap();
String[] actionIds = keymap == null ? ArrayUtilRt.EMPTY_STRING_ARRAY : keymap.getActionIds(shortcut);
for (String actionId : actionIds) {
AnAction action = actionManager.getAction(actionId);
if (action != null && (!myContext.isModalContext() || action.isEnabledInModalContext())) {
addAction(action, shortcut);
}
}
if (keymap != null && actionIds.length > 0 && shortcut instanceof KeyboardShortcut) {
// user pressed keystroke and keymap has some actions assigned to sc (actions going to be executed)
// check whether this shortcut conflicts with system-wide shortcuts and notify user if necessary
// see IDEA-173174 Warn user about IDE keymap conflicts with native OS keymap
SystemShortcuts.getInstance().onUserPressedShortcut(keymap, actionIds, (KeyboardShortcut)shortcut);
}
}
private static final KeyboardShortcut CONTROL_ENTER = KeyboardShortcut.fromString("control ENTER");
private static final KeyboardShortcut CMD_ENTER = KeyboardShortcut.fromString("meta ENTER");
private static boolean isControlEnterOnDialog(Component component, Shortcut sc) {
return (CONTROL_ENTER.equals(sc) || (SystemInfo.isMac && CMD_ENTER.equals(sc)))
&& !IdeEventQueue.getInstance().isPopupActive() //avoid Control+Enter in completion
&& DialogWrapper.findInstance(component) != null;
}
private void addAction(AnAction action, @NotNull Shortcut sc) {
Shortcut[] shortcuts = action.getShortcutSet().getShortcuts();
for (Shortcut each : shortcuts) {
if (each == null) throw new NullPointerException("unexpected shortcut of action: " + action.toString());
if (!each.isKeyboard()) continue;
if (each.startsWith(sc)) {
if (!myContext.getActions().contains(action)) {
myContext.getActions().add(action);
}
if (each instanceof KeyboardShortcut && ((KeyboardShortcut)each).getSecondKeyStroke() != null) {
myContext.setHasSecondStroke(true);
}
}
}
}
public KeyProcessorContext getContext() {
return myContext;
}
@Override
public void dispose() {
myDisposed = true;
}
public KeyState getState() {
return myState;
}
public void setState(final KeyState state) {
myState = state;
if (myQueue != null) {
myQueue.maybeReady();
}
}
public void resetState() {
setState(KeyState.STATE_INIT);
setPressedWasProcessed(false);
}
public boolean isPressedWasProcessed() {
return myPressedWasProcessed;
}
private void setPressedWasProcessed(boolean pressedWasProcessed) {
myPressedWasProcessed = pressedWasProcessed;
}
public boolean isReady() {
return myState == KeyState.STATE_INIT || myState == KeyState.STATE_PROCESSED;
}
private static class SecondaryKeystrokePopup extends ListPopupImpl {
SecondaryKeystrokePopup(@NotNull KeyStroke firstKeystroke, @NotNull List<? extends Pair<AnAction, KeyStroke>> actions, DataContext context) {
super(CommonDataKeys.PROJECT.getData(context), buildStep(actions, context));
registerActions(firstKeystroke, actions, context);
}
private void registerActions(@NotNull final KeyStroke firstKeyStroke, @NotNull final List<? extends Pair<AnAction, KeyStroke>> actions, final DataContext ctx) {
ContainerUtil.process(actions, pair -> {
final String actionText = pair.getFirst().getTemplatePresentation().getText();
final AbstractAction a = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
cancel();
invokeAction(pair.getFirst(), ctx);
}
};
final KeyStroke keyStroke = pair.getSecond();
if (keyStroke != null) {
registerAction(actionText, keyStroke, a);
if (keyStroke.getModifiers() == 0) {
// do a little trick here, so if I will press Command+R and the second keystroke is just 'R',
// I want to be able to hold the Command while pressing 'R'
final KeyStroke additionalKeyStroke = KeyStroke.getKeyStroke(keyStroke.getKeyCode(), firstKeyStroke.getModifiers());
final String _existing = getActionForKeyStroke(additionalKeyStroke);
if (_existing == null) registerAction("__additional__" + actionText, additionalKeyStroke, a);
}
}
return true;
});
}
private static void invokeAction(@NotNull final AnAction action, final DataContext ctx) {
AnActionEvent event =
new AnActionEvent(null, ctx, ActionPlaces.UNKNOWN, action.getTemplatePresentation().clone(),
ActionManager.getInstance(), 0);
if (ActionUtil.lastUpdateAndCheckDumb(action, event, true)) {
ActionUtil.performActionDumbAware(action, event);
}
}
@Override
protected ListCellRenderer getListElementRenderer() {
return new ActionListCellRenderer();
}
private static ListPopupStep buildStep(@NotNull final List<? extends Pair<AnAction, KeyStroke>> actions, final DataContext ctx) {
return new BaseListPopupStep<Pair<AnAction, KeyStroke>>("Choose an action", ContainerUtil.findAll(actions, pair -> {
final AnAction action = pair.getFirst();
final Presentation presentation = action.getTemplatePresentation().clone();
AnActionEvent event = new AnActionEvent(null, ctx,
ActionPlaces.UNKNOWN,
presentation,
ActionManager.getInstance(),
0);
ActionUtil.performDumbAwareUpdate(LaterInvocator.isInModalContext(), action, event, true);
return presentation.isEnabled() && presentation.isVisible();
})) {
@Override
public PopupStep onChosen(Pair<AnAction, KeyStroke> selectedValue, boolean finalChoice) {
invokeAction(selectedValue.getFirst(), ctx);
return FINAL_CHOICE;
}
};
}
private static class ActionListCellRenderer extends ColoredListCellRenderer {
@Override
protected void customizeCellRenderer(@NotNull final JList list, final Object value, final int index, final boolean selected, final boolean hasFocus) {
if (value instanceof Pair) {
//noinspection unchecked
final Pair<AnAction, KeyStroke> pair = (Pair<AnAction, KeyStroke>) value;
append(KeymapUtil.getShortcutText(new KeyboardShortcut(pair.getSecond(), null)), SimpleTextAttributes.GRAY_ATTRIBUTES);
appendTextPadding(30);
final String text = pair.getFirst().getTemplatePresentation().getText();
if (text != null) {
append(text, SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
}
}
}
}
private static final String POPUP_MENU_PREFIX = "PopupMenu-"; // see PlatformActions.xml
private static boolean processMenuActions(KeyEvent event, MenuElement element) {
if (KeyEvent.KEY_PRESSED != event.getID() || !Registry.is("ide.popup.navigation.via.actions")) {
return false;
}
KeymapManager manager = KeymapManager.getInstance();
if (manager == null) {
return false;
}
JRootPane pane = getMenuActionsHolder(element.getComponent());
if (pane == null) {
return false;
}
Keymap keymap = manager.getActiveKeymap();
// iterate through actions for the specified event
for (String id : keymap.getActionIds(KeyStroke.getKeyStrokeForEvent(event))) {
if (id.startsWith(POPUP_MENU_PREFIX)) {
String actionId = id.substring(POPUP_MENU_PREFIX.length());
Action action = pane.getActionMap().get(actionId);
if (action != null) {
action.actionPerformed(new ActionEvent(pane, ActionEvent.ACTION_PERFORMED, actionId));
event.consume();
return true; // notify dispatcher that event is processed
}
}
}
return false;
}
private static JRootPane getMenuActionsHolder(Component component) {
if (component instanceof JPopupMenu) {
// BasicPopupMenuUI.MenuKeyboardHelper#stateChanged
JPopupMenu menu = (JPopupMenu)component;
return SwingUtilities.getRootPane(menu.getInvoker());
}
return SwingUtilities.getRootPane(component);
}
private static void logTimeMillis(long startedAt, @NotNull AnAction action) {
EventWatcher watcher = EventWatcher.getInstance();
if (watcher instanceof LoggableEventWatcher) {
((LoggableEventWatcher)watcher).logTimeMillis(action.toString(), startedAt);
}
}
public static boolean removeAltGraph(InputEvent e) {
if (e.isAltGraphDown()) {
try {
Field field = InputEvent.class.getDeclaredField("modifiers");
field.setAccessible(true);
field.setInt(e, ~InputEvent.ALT_GRAPH_MASK & ~InputEvent.ALT_GRAPH_DOWN_MASK & field.getInt(e));
return true;
}
catch (Exception ignored) {
}
}
return false;
}
public static boolean isAltGrLayout(Component component) {
if (component == null) return false;
InputContext context = component.getInputContext();
if (context == null) return false;
Locale locale = context.getLocale();
if (locale == null) return false;
String language = locale.getLanguage();
boolean contains = !"en".equals(language)
? ALT_GR_LANGUAGES.contains(language)
: ALT_GR_COUNTRIES.contains(locale.getCountry());
LOG.debug("AltGr", contains ? "" : " not", " supported for ", locale);
return contains;
}
// http://www.oracle.com/technetwork/java/javase/documentation/jdk12locales-5294582.html
@NonNls private static final Set<String> ALT_GR_LANGUAGES = ContainerUtil.set(
"da", // Danish
"de", // German
"es", // Spanish
"et", // Estonian
"fi", // Finnish
"fr", // French
"hr", // Croatian
"hu", // Hungarian
"it", // Italian
"lv", // Latvian
"mk", // Macedonian
"nl", // Dutch
"no", // Norwegian
"pl", // Polish
"pt", // Portuguese
"ro", // Romanian
"sk", // Slovak
"sl", // Slovenian
"sr", // Serbian
"sv", // Swedish
"tr" // Turkish
);
@NonNls private static final Set<String> ALT_GR_COUNTRIES = ContainerUtil.set(
"DK", // Denmark
"DE", // Germany
"FI", // Finland
"NL", // Netherlands
"SL", // Slovenia
"SE" // Sweden
);
}
| |
/*
* File: ListDatastreams.java
*
* Copyright 2009 2DC
*
* 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.server.security.xacml.pep.rest.objectshandlers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.fcrepo.common.Constants;
import org.fcrepo.server.security.xacml.MelcoeXacmlException;
import org.fcrepo.server.security.xacml.pep.PEPException;
import org.fcrepo.server.security.xacml.pep.ResourceAttributes;
import org.fcrepo.server.security.xacml.pep.rest.filters.AbstractFilter;
import org.fcrepo.server.security.xacml.pep.rest.filters.DataResponseWrapper;
import org.fcrepo.server.security.xacml.pep.rest.filters.ResponseHandlingRESTFilter;
import org.fcrepo.server.security.xacml.util.ContextUtil;
import org.fcrepo.server.security.xacml.util.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.tidy.Tidy;
import com.sun.xacml.attr.AnyURIAttribute;
import com.sun.xacml.attr.AttributeValue;
import com.sun.xacml.attr.DateTimeAttribute;
import com.sun.xacml.attr.StringAttribute;
import com.sun.xacml.ctx.RequestCtx;
import com.sun.xacml.ctx.ResponseCtx;
import com.sun.xacml.ctx.Result;
import com.sun.xacml.ctx.Status;
/**
* Handles the ListDatastreams operation.
*
* @author nish.naidoo@gmail.com
*/
public class ListDatastreams
extends AbstractFilter implements ResponseHandlingRESTFilter{
private static final Logger logger =
LoggerFactory.getLogger(ListDatastreams.class);
private ContextUtil m_contextUtil = null;
private Transformer xFormer = null;
private Tidy tidy = null;
/**
* Default constructor.
*
* @throws PEPException
*/
public ListDatastreams()
throws PEPException {
super();
try {
TransformerFactory xFactory = TransformerFactory.newInstance();
xFormer = xFactory.newTransformer();
} catch (TransformerConfigurationException tce) {
throw new PEPException("Error initialising SearchFilter", tce);
}
tidy = new Tidy();
tidy.setShowWarnings(false);
tidy.setQuiet(true);
}
public void setContextUtil(ContextUtil contextUtil) {
m_contextUtil = contextUtil;
}
/*
* (non-Javadoc)
* @see
* org.fcrepo.server.security.xacml.pep.rest.filters.RESTFilter#handleRequest(javax.servlet
* .http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public RequestCtx handleRequest(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
if (logger.isDebugEnabled()) {
logger.debug("{}/handleRequest!", this.getClass().getName());
}
String asOfDateTime = request.getParameter("asOfDateTime");
if (!isDate(asOfDateTime)) {
asOfDateTime = null;
}
RequestCtx req = null;
Map<URI, AttributeValue> actions = new HashMap<URI, AttributeValue>();
Map<URI, AttributeValue> resAttr;
try {
String[] parts = getPathParts(request);
resAttr = ResourceAttributes.getResources(parts);
if (asOfDateTime != null && !"".equals(asOfDateTime)) {
resAttr.put(Constants.DATASTREAM.AS_OF_DATETIME.getURI(),
DateTimeAttribute.getInstance(asOfDateTime));
}
actions.put(Constants.ACTION.ID.getURI(),
Constants.ACTION.LIST_DATASTREAMS
.getStringAttribute());
actions.put(Constants.ACTION.API.getURI(),
Constants.ACTION.APIA.getStringAttribute());
req =
getContextHandler().buildRequest(getSubjects(request),
actions,
resAttr,
getEnvironment(request));
String pid = resAttr.get(Constants.OBJECT.PID.getURI()).toString();
LogUtil.statLog(request.getRemoteUser(),
Constants.ACTION.LIST_DATASTREAMS.uri,
pid,
null);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
return req;
}
/*
* (non-Javadoc)
* @see
* org.fcrepo.server.security.xacml.pep.rest.filters.RESTFilter#handleResponse(javax.servlet
* .http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public RequestCtx handleResponse(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
DataResponseWrapper res = (DataResponseWrapper) response;
byte[] data = res.getData();
String result = null;
String body = new String(data);
if (body.startsWith("<html>")) {
if (logger.isDebugEnabled()) {
logger.debug("filtering html");
}
result = filterHTML(request, res);
} else if (body.startsWith("<?xml")) {
if (logger.isDebugEnabled()) {
logger.debug("filtering html");
}
result = filterXML(request, res);
} else {
if (logger.isDebugEnabled()) {
logger.debug("not filtering due to unexpected output: " + body);
}
result = body;
}
res.setData(result.getBytes());
return null;
}
/**
* Parses an HTML based response and removes the items that are not
* permitted.
*
* @param request
* the http servlet request
* @param response
* the http servlet response
* @return the new response body without non-permissable objects.
* @throws ServletException
*/
private String filterHTML(HttpServletRequest request,
DataResponseWrapper response)
throws ServletException {
String path = request.getPathInfo();
String[] parts = path.split("/");
String pid = parts[1];
String body = new String(response.getData());
InputStream is = new ByteArrayInputStream(body.getBytes());
Document doc = tidy.parseDOM(is, null);
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList rows = null;
try {
rows =
(NodeList) xpath.evaluate("//table[2]/tr",
doc,
XPathConstants.NODESET);
if (logger.isDebugEnabled()) {
logger.debug("number of rows found: " + rows.getLength());
}
} catch (XPathExpressionException xpe) {
throw new ServletException("Error parsing HTML for search results: ",
xpe);
}
// only the header row, no results.
if (rows.getLength() < 2) {
if (logger.isDebugEnabled()) {
logger.debug("No results to filter.");
}
return body;
}
Map<String, Node> dsids = new HashMap<String, Node>();
for (int x = 1; x < rows.getLength(); x++) {
NodeList elements = rows.item(x).getChildNodes();
String dsid = elements.item(0).getFirstChild().getNodeValue();
if (logger.isDebugEnabled()) {
logger.debug("dsid: " + dsid);
}
dsids.put(dsid, rows.item(x));
}
Set<Result> results =
evaluatePids(dsids.keySet(), pid, request, response);
for (Result r : results) {
if (r.getResource() == null || "".equals(r.getResource())) {
logger.warn("This resource has no resource identifier in the xacml response results!");
} else if (logger.isDebugEnabled()) {
logger.debug("Checking: " + r.getResource());
}
String[] ridComponents = r.getResource().split("\\/");
String rid = ridComponents[ridComponents.length - 1];
if (r.getStatus().getCode().contains(Status.STATUS_OK)
&& r.getDecision() != Result.DECISION_PERMIT) {
Node node = dsids.get(rid);
node.getParentNode().removeChild(node);
if (logger.isDebugEnabled()) {
logger.debug("Removing: " + r.getResource() + "[" + rid + "]");
}
}
}
Source src = new DOMSource(doc);
ByteArrayOutputStream os = new ByteArrayOutputStream();
javax.xml.transform.Result dst = new StreamResult(os);
try {
xFormer.transform(src, dst);
} catch (TransformerException te) {
throw new ServletException("error generating output", te);
}
return new String(os.toByteArray());
}
/**
* Parses an XML based response and removes the items that are not
* permitted.
*
* @param request
* the http servlet request
* @param response
* the http servlet response
* @return the new response body without non-permissable objects.
* @throws ServletException
*/
private String filterXML(HttpServletRequest request,
DataResponseWrapper response)
throws ServletException {
String body = new String(response.getData());
DocumentBuilder docBuilder = null;
Document doc = null;
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
docBuilder =
docBuilderFactory.newDocumentBuilder();
doc =
docBuilder.parse(new ByteArrayInputStream(response
.getData()));
} catch (Exception e) {
throw new ServletException(e);
}
XPath xpath = XPathFactory.newInstance().newXPath();
String pid = null;
NodeList datastreams = null;
try {
pid = xpath.evaluate("/objectDatastreams/@pid", doc);
if (logger.isDebugEnabled()) {
logger.debug("filterXML: pid = [" + pid + "]");
}
datastreams =
(NodeList) xpath.evaluate("/objectDatastreams/datastream",
doc,
XPathConstants.NODESET);
} catch (XPathExpressionException xpe) {
throw new ServletException("Error parsing HTML for search results: ",
xpe);
}
if (datastreams.getLength() == 0) {
if (logger.isDebugEnabled()) {
logger.debug("No results to filter.");
}
return body;
}
Map<String, Node> dsids = new HashMap<String, Node>();
for (int x = 0; x < datastreams.getLength(); x++) {
String dsid =
datastreams.item(x).getAttributes().getNamedItem("dsid")
.getNodeValue();
dsids.put(dsid, datastreams.item(x));
}
Set<Result> results =
evaluatePids(dsids.keySet(), pid, request, response);
for (Result r : results) {
if (r.getResource() == null || "".equals(r.getResource())) {
logger.warn("This resource has no resource identifier in the xacml response results!");
} else if (logger.isDebugEnabled()) {
logger.debug("Checking: " + r.getResource());
}
String[] ridComponents = r.getResource().split("\\/");
String rid = ridComponents[ridComponents.length - 1];
if (r.getStatus().getCode().contains(Status.STATUS_OK)
&& r.getDecision() != Result.DECISION_PERMIT) {
Node node = dsids.get(rid);
node.getParentNode().removeChild(node);
if (logger.isDebugEnabled()) {
logger.debug("Removing: " + r.getResource() + "[" + rid + "]");
}
}
}
Source src = new DOMSource(doc);
ByteArrayOutputStream os = new ByteArrayOutputStream();
javax.xml.transform.Result dst = new StreamResult(os);
try {
xFormer.transform(src, dst);
} catch (TransformerException te) {
throw new ServletException("error generating output", te);
}
return new String(os.toByteArray());
}
/**
* Takes a given list of PID's and evaluates them.
*
* @param dsids
* the list of pids to check
* @param request
* the http servlet request
* @param response
* the http servlet resposne
* @return a set of XACML results.
* @throws ServletException
*/
private Set<Result> evaluatePids(Set<String> dsids,
String pid,
HttpServletRequest request,
DataResponseWrapper response)
throws ServletException {
Set<String> requests = new HashSet<String>();
for (String dsid : dsids) {
if (logger.isDebugEnabled()) {
logger.debug("Checking: " + pid + "/" + dsid);
}
Map<URI, AttributeValue> actions =
new HashMap<URI, AttributeValue>();
Map<URI, AttributeValue> resAttr;
try {
actions.put(Constants.ACTION.ID.getURI(),
Constants.ACTION.GET_DATASTREAM
.getStringAttribute());
resAttr = ResourceAttributes.getResources(pid);
resAttr.put(Constants.DATASTREAM.ID.getURI(),
new StringAttribute(dsid));
RequestCtx req =
getContextHandler()
.buildRequest(getSubjects(request),
actions,
resAttr,
getEnvironment(request));
String r = m_contextUtil.makeRequestCtx(req);
if (logger.isDebugEnabled()) {
logger.debug(r);
}
requests.add(r);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
}
String res = null;
ResponseCtx resCtx = null;
try {
if (logger.isDebugEnabled()) {
logger.debug("Number of requests: " + requests.size());
}
res =
getContextHandler().evaluateBatch(requests
.toArray(new String[requests.size()]));
if (logger.isDebugEnabled()) {
logger.debug("Response: " + res);
}
resCtx = m_contextUtil.makeResponseCtx(res);
} catch (MelcoeXacmlException pe) {
throw new ServletException("Error evaluating pids: "
+ pe.getMessage(), pe);
}
@SuppressWarnings("unchecked")
Set<Result> results = resCtx.getResults();
return results;
}
}
| |
package com.github.dockerjava.api.command;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.dockerjava.api.model.ContainerConfig;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.NetworkSettings;
import com.github.dockerjava.api.model.Volume;
import com.github.dockerjava.api.model.VolumeBind;
import com.github.dockerjava.api.model.VolumeBinds;
import com.github.dockerjava.api.model.VolumeRW;
import com.github.dockerjava.api.model.VolumesRW;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import javax.annotation.CheckForNull;
import java.util.List;
import java.util.Map;
/**
*
* @author Konstantin Pelykh (kpelykh@gmail.com)
*
*/
@EqualsAndHashCode
@ToString
public class InspectContainerResponse {
@JsonProperty("Args")
private String[] args;
@JsonProperty("Config")
private ContainerConfig config;
@JsonProperty("Created")
private String created;
@JsonProperty("Driver")
private String driver;
@JsonProperty("ExecDriver")
private String execDriver;
@JsonProperty("HostConfig")
private HostConfig hostConfig;
@JsonProperty("HostnamePath")
private String hostnamePath;
@JsonProperty("HostsPath")
private String hostsPath;
/**
* @since {@link RemoteApiVersion#VERSION_1_17}
*/
@JsonProperty("LogPath")
private String logPath;
@JsonProperty("Id")
private String id;
@JsonProperty("SizeRootFs")
private Integer sizeRootFs;
@JsonProperty("Image")
private String imageId;
@JsonProperty("MountLabel")
private String mountLabel;
@JsonProperty("Name")
private String name;
/**
* @since {@link RemoteApiVersion#VERSION_1_17}
*/
@JsonProperty("RestartCount")
private Integer restartCount;
@JsonProperty("NetworkSettings")
private NetworkSettings networkSettings;
@JsonProperty("Path")
private String path;
@JsonProperty("ProcessLabel")
private String processLabel;
@JsonProperty("ResolvConfPath")
private String resolvConfPath;
@JsonProperty("ExecIDs")
private List<String> execIds;
@JsonProperty("State")
private ContainerState state;
@JsonProperty("Volumes")
private VolumeBinds volumes;
@JsonProperty("VolumesRW")
private VolumesRW volumesRW;
@JsonProperty("Node")
private Node node;
@JsonProperty("Mounts")
private List<Mount> mounts;
@JsonProperty("GraphDriver")
private GraphDriver graphDriver;
/**
* @since {@link RemoteApiVersion#VERSION_1_30}
*/
@JsonProperty("Platform")
private String platform;
public String getId() {
return id;
}
public Integer getSizeRootFs() {
return sizeRootFs;
}
public String getCreated() {
return created;
}
public String getPath() {
return path;
}
public String getProcessLabel() {
return processLabel;
}
public String[] getArgs() {
return args;
}
public ContainerConfig getConfig() {
return config;
}
public ContainerState getState() {
return state;
}
public String getImageId() {
return imageId;
}
public NetworkSettings getNetworkSettings() {
return networkSettings;
}
public String getResolvConfPath() {
return resolvConfPath;
}
@JsonIgnore
public VolumeBind[] getVolumes() {
return volumes == null ? null : volumes.getBinds();
}
/**
* @deprecated As of {@link RemoteApiVersion#VERSION_1_20} use {@link #getMounts()} instead
*/
@JsonIgnore
@Deprecated
@CheckForNull
public VolumeRW[] getVolumesRW() {
return volumesRW == null ? null : volumesRW.getVolumesRW();
}
public String getHostnamePath() {
return hostnamePath;
}
public String getHostsPath() {
return hostsPath;
}
@CheckForNull
public String getLogPath() {
return logPath;
}
public String getName() {
return name;
}
public Integer getRestartCount() {
return restartCount;
}
public String getDriver() {
return driver;
}
public HostConfig getHostConfig() {
return hostConfig;
}
public String getExecDriver() {
return execDriver;
}
public String getMountLabel() {
return mountLabel;
}
/**
* @since {@link RemoteApiVersion#VERSION_1_20}
*/
@CheckForNull
public List<Mount> getMounts() {
return mounts;
}
public List<String> getExecIds() {
return execIds;
}
/**
* Get the underlying swarm node info. This property does only contains a value in swarm-classic
* @return The underlying swarm-classic node info
* @CheckForNull
*/
public Node getNode() {
return node;
}
/**
* @see #graphDriver
*/
@CheckForNull
public GraphDriver getGraphDriver() {
return graphDriver;
}
/**
* @see #platform
*/
@CheckForNull
public String getPlatform() {
return platform;
}
@EqualsAndHashCode
@ToString
public class ContainerState {
/**
* @since {@link RemoteApiVersion#VERSION_1_20}
*/
@CheckForNull
@JsonProperty("Status")
private String status;
/**
* @since < {@link RemoteApiVersion#VERSION_1_16}
*/
@CheckForNull
@JsonProperty("Running")
private Boolean running;
/**
* @since {@link RemoteApiVersion#VERSION_1_17}
*/
@CheckForNull
@JsonProperty("Paused")
private Boolean paused;
/**
* @since {@link RemoteApiVersion#VERSION_1_17}
*/
@CheckForNull
@JsonProperty("Restarting")
private Boolean restarting;
/**
* @since {@link RemoteApiVersion#VERSION_1_17}
*/
@CheckForNull
@JsonProperty("OOMKilled")
private Boolean oomKilled;
/**
* <a href="https://github.com/docker/docker/pull/18127">Unclear</a>
*
* @since {@link RemoteApiVersion#UNKNOWN_VERSION}
*/
@CheckForNull
@JsonProperty("Dead")
private Boolean dead;
/**
* @since < {@link RemoteApiVersion#VERSION_1_16}
*/
@CheckForNull
@JsonProperty("Pid")
private Long pid;
/**
* @since < {@link RemoteApiVersion#VERSION_1_16}
*/
@CheckForNull
@JsonProperty("ExitCode")
private Long exitCode;
/**
* @since {@link RemoteApiVersion#VERSION_1_17}
*/
@CheckForNull
@JsonProperty("Error")
private String error;
/**
* @since < {@link RemoteApiVersion#VERSION_1_16}
*/
@CheckForNull
@JsonProperty("StartedAt")
private String startedAt;
/**
* @since {@link RemoteApiVersion#VERSION_1_17}
*/
@CheckForNull
@JsonProperty("FinishedAt")
private String finishedAt;
/**
* @since Docker version 1.12
*/
@JsonProperty("Health")
private HealthState health;
/**
* See {@link #status}
*/
@CheckForNull
public String getStatus() {
return status;
}
/**
* See {@link #running}
*/
@CheckForNull
public Boolean getRunning() {
return running;
}
/**
* See {@link #paused}
*/
@CheckForNull
public Boolean getPaused() {
return paused;
}
/**
* See {@link #restarting}
*/
@CheckForNull
public Boolean getRestarting() {
return restarting;
}
/**
* See {@link #oomKilled}
*/
@CheckForNull
public Boolean getOOMKilled() {
return oomKilled;
}
/**
* See {@link #dead}
*/
@CheckForNull
public Boolean getDead() {
return dead;
}
/**
* See {@link #pid}
*
* @deprecated use {@link #getPidLong()}
*/
@Deprecated
@CheckForNull
public Integer getPid() {
return pid != null ? pid.intValue() : null;
}
/**
* See {@link #pid}
*/
@CheckForNull
public Long getPidLong() {
return pid;
}
/**
* See {@link #exitCode}
*
* @deprecated use {@link #getExitCodeLong()}
*/
@Deprecated
@CheckForNull
public Integer getExitCode() {
return exitCode != null ? exitCode.intValue() : null;
}
/**
* See {@link #exitCode}
*/
@CheckForNull
public Long getExitCodeLong() {
return exitCode;
}
/**
* See {@link #error}
*/
@CheckForNull
public String getError() {
return error;
}
/**
* See {@link #startedAt}
*/
@CheckForNull
public String getStartedAt() {
return startedAt;
}
/**
* See {@link #finishedAt}
*/
@CheckForNull
public String getFinishedAt() {
return finishedAt;
}
public HealthState getHealth() {
return health;
}
}
@EqualsAndHashCode
@ToString
public static class Mount {
/**
* @since {@link RemoteApiVersion#VERSION_1_20}
*/
@CheckForNull
@JsonProperty("Name")
private String name;
/**
* @since {@link RemoteApiVersion#VERSION_1_20}
*/
@CheckForNull
@JsonProperty("Source")
private String source;
/**
* @since {@link RemoteApiVersion#VERSION_1_20}
*/
@CheckForNull
@JsonProperty("Destination")
private Volume destination;
/**
* @since {@link RemoteApiVersion#VERSION_1_20}
*/
@CheckForNull
@JsonProperty("Driver")
private String driver;
/**
* @since {@link RemoteApiVersion#VERSION_1_20}
*/
@CheckForNull
@JsonProperty("Mode")
private String mode;
/**
* @since {@link RemoteApiVersion#VERSION_1_20}
*/
@CheckForNull
@JsonProperty("RW")
private Boolean rw;
@CheckForNull
public String getName() {
return name;
}
@CheckForNull
public String getSource() {
return source;
}
@CheckForNull
public Volume getDestination() {
return destination;
}
@CheckForNull
public String getDriver() {
return driver;
}
@CheckForNull
public String getMode() {
return mode;
}
@CheckForNull
public Boolean getRW() {
return rw;
}
/**
* @see #destination
*/
public Mount withDestination(Volume destination) {
this.destination = destination;
return this;
}
/**
* @see #driver
*/
public Mount withDriver(String driver) {
this.driver = driver;
return this;
}
/**
* @see #mode
*/
public Mount withMode(String mode) {
this.mode = mode;
return this;
}
/**
* @see #name
*/
public Mount withName(String name) {
this.name = name;
return this;
}
/**
* @see #rw
*/
public Mount withRw(Boolean rw) {
this.rw = rw;
return this;
}
/**
* @see #source
*/
public Mount withSource(String source) {
this.source = source;
return this;
}
}
@EqualsAndHashCode
@ToString
public class Node {
@JsonProperty("ID")
private String id;
@JsonProperty("IP")
private String ip;
@JsonProperty("Addr")
private String addr;
@JsonProperty("Name")
private String name;
@JsonProperty("Cpus")
private Integer cpus;
@JsonProperty("Memory")
private Long memory;
@JsonProperty("Labels")
private Map<String, String> labels;
public String getId() {
return id;
}
public String getIp() {
return ip;
}
public String getAddr() {
return addr;
}
public String getName() {
return name;
}
public Integer getCpus() {
return cpus;
}
public Long getMemory() {
return memory;
}
public Map<String, String> getLabels() {
return labels;
}
}
}
| |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core.database;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.pentaho.di.core.KettleClientEnvironment;
import org.pentaho.di.core.database.map.DatabaseConnectionMap;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.logging.LoggingObjectInterface;
import org.pentaho.di.junit.rules.RestorePDIEnvironment;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
/**
* @author Andrey Khayrutdinov
*/
public class DatabaseConnectingTest {
@ClassRule public static RestorePDIEnvironment env = new RestorePDIEnvironment();
private static final String GROUP = "group";
private static final String ANOTHER_GROUP = "another-group";
@BeforeClass
public static void setUp() throws Exception {
KettleClientEnvironment.init();
}
@After
public void removeFromSharedConnectionMap() {
removeFromSharedConnectionMap( GROUP );
}
private void removeFromSharedConnectionMap( String group ) {
DatabaseConnectionMap.getInstance().removeConnection( group, null, createStubDatabase( null ) );
}
@Test
public void connect_GroupIsNull() throws Exception {
Connection connection1 = mock( Connection.class );
DatabaseStub db1 = createStubDatabase( connection1 );
Connection connection2 = mock( Connection.class );
DatabaseStub db2 = createStubDatabase( connection2 );
db1.connect();
db2.connect();
assertEquals( connection1, db1.getConnection() );
assertEquals( connection2, db2.getConnection() );
}
@Test
public void connect_GroupIsEqual_Consequently() throws Exception {
Connection shared = mock( Connection.class );
DatabaseStub db1 = createStubDatabase( shared );
db1.connect( GROUP, null );
DatabaseStub db2 = createStubDatabase( shared );
db2.connect( GROUP, null );
assertSharedAmongTheGroup( shared, db1, db2 );
}
@Test
public void connect_GroupIsEqual_InParallel() throws Exception {
final Connection shared = mock( Connection.class );
final int dbsAmount = 300;
final int threadsAmount = 50;
List<DatabaseStub> dbs = new ArrayList<DatabaseStub>( dbsAmount );
Set<Integer> copies = new HashSet<Integer>( dbsAmount );
ExecutorService pool = Executors.newFixedThreadPool( threadsAmount );
try {
CompletionService<DatabaseStub> service = new ExecutorCompletionService<DatabaseStub>( pool );
for ( int i = 0; i < dbsAmount; i++ ) {
service.submit( createStubDatabase( shared ) );
copies.add( i + 1 );
}
for ( int i = 0; i < dbsAmount; i++ ) {
DatabaseStub db = service.take().get();
assertEquals( shared, db.getConnection() );
dbs.add( db );
}
} finally {
pool.shutdown();
}
for ( DatabaseStub db : dbs ) {
String message =
String.format( "There should be %d shares of the connection, but found %d", dbsAmount, db.getOpened() );
// 0 is for those instances that use the shared connection
assertTrue( message, db.getOpened() == 0 || db.getOpened() == dbsAmount );
assertTrue( "Each instance should have a unique 'copy' value", copies.remove( db.getCopy() ) );
}
assertTrue( copies.isEmpty() );
}
@Test
public void connect_TwoGroups() throws Exception {
try {
Connection shared1 = mock( Connection.class );
Connection shared2 = mock( Connection.class );
DatabaseStub db11 = createStubDatabase( shared1 );
DatabaseStub db12 = createStubDatabase( shared1 );
DatabaseStub db21 = createStubDatabase( shared2 );
DatabaseStub db22 = createStubDatabase( shared2 );
db11.connect( GROUP, null );
db12.connect( GROUP, null );
db21.connect( ANOTHER_GROUP, null );
db22.connect( ANOTHER_GROUP, null );
assertSharedAmongTheGroup( shared1, db11, db12 );
assertSharedAmongTheGroup( shared2, db21, db22 );
} finally {
removeFromSharedConnectionMap( ANOTHER_GROUP );
}
}
private void assertSharedAmongTheGroup( Connection shared, DatabaseStub db1, DatabaseStub db2 ) {
assertEquals( shared, db1.getConnection() );
assertEquals( shared, db2.getConnection() );
assertEquals( 2, db1.getOpened() );
assertEquals( 0, db2.getOpened() );
}
@Test
public void connect_ManyGroups_Simultaneously() throws Exception {
final int groupsAmount = 30;
Map<String, Connection> groups = new HashMap<String, Connection>( groupsAmount );
for ( int i = 0; i < groupsAmount; i++ ) {
groups.put( Integer.toString( i ), mock( Connection.class ) );
}
try {
ExecutorService pool = Executors.newFixedThreadPool( groupsAmount );
try {
CompletionService<DatabaseStub> service = new ExecutorCompletionService<DatabaseStub>( pool );
Map<DatabaseStub, String> mapping = new HashMap<DatabaseStub, String>( groupsAmount );
for ( Map.Entry<String, Connection> entry : groups.entrySet() ) {
DatabaseStub stub = createStubDatabase( entry.getValue() );
mapping.put( stub, entry.getKey() );
service.submit( stub );
}
Set<String> unmatchedGroups = new HashSet<String>( groups.keySet() );
for ( int i = 0; i < groupsAmount; i++ ) {
DatabaseStub stub = service.take().get();
assertTrue( unmatchedGroups.remove( mapping.get( stub ) ) );
}
assertTrue( unmatchedGroups.isEmpty() );
} finally {
pool.shutdown();
}
} finally {
for ( String group : groups.keySet() ) {
removeFromSharedConnectionMap( group );
}
}
}
private DatabaseStub createStubDatabase( Connection sharedConnection ) {
DatabaseMeta meta = new DatabaseMeta( "test", "H2", "", "", "", "", "", "" );
return new DatabaseStub( null, meta, sharedConnection );
}
private static class DatabaseStub extends Database implements Callable<DatabaseStub> {
private final Connection sharedConnection;
private boolean connected;
public DatabaseStub( LoggingObjectInterface parentObject,
DatabaseMeta databaseMeta, Connection sharedConnection ) {
super( parentObject, databaseMeta );
this.sharedConnection = sharedConnection;
this.connected = false;
}
@Override
public synchronized void normalConnect( String partitionId ) throws KettleDatabaseException {
if ( !connected ) {
// make a delay to emulate real scenario
try {
Thread.sleep( 250 );
} catch ( InterruptedException e ) {
fail( e.getMessage() );
}
setConnection( sharedConnection );
connected = true;
}
}
@Override
public DatabaseStub call() throws Exception {
connect( GROUP, null );
return this;
}
}
}
| |
package com.marshalchen.common.uimodule.foldablelayout;
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.marshalchen.common.uimodule.foldablelayout.shading.FoldShading;
/**
* Layout that provides basic funcitionality: splitting view into 2 parts, splitted parts syncronouse rotations and so on
*/
public class FoldableItemLayout extends FrameLayout {
private static final int CAMERA_DISTANCE = 48;
private static final float CAMERA_DISTANCE_MAGIC_FACTOR = 8f / CAMERA_DISTANCE;
private boolean mIsAutoScaleEnabled;
private BaseLayout mBaseLayout;
private PartView mTopPart, mBottomPart;
private int mWidth, mHeight;
private Bitmap mCacheBitmap;
private boolean mIsInTransformation;
private float mFoldRotation;
private float mScale;
private float mRollingDistance;
public FoldableItemLayout(Context context) {
super(context);
init(context);
}
public FoldableItemLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public FoldableItemLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
mBaseLayout = new BaseLayout(this);
mTopPart = new PartView(this, Gravity.TOP);
mBottomPart = new PartView(this, Gravity.BOTTOM);
setInTransformation(false);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mBaseLayout.moveInflatedChildren(this, 3); // skipping mBaseLayout & mTopPart & mBottomPart views
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
if (mCacheBitmap != null) {
mCacheBitmap.recycle();
mCacheBitmap = null;
}
mCacheBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mBaseLayout.setCacheCanvas(new Canvas(mCacheBitmap));
mTopPart.setCacheBitmap(mCacheBitmap);
mBottomPart.setCacheBitmap(mCacheBitmap);
}
/**
* Fold rotation value in degrees
*/
public void setFoldRotation(float rotation) {
mFoldRotation = rotation;
mTopPart.applyFoldRotation(rotation);
mBottomPart.applyFoldRotation(rotation);
setInTransformation(rotation != 0);
if (mIsAutoScaleEnabled) {
float viewScale = 1.0f;
if (mWidth > 0) {
float dW = (float) (mHeight * Math.abs(Math.sin(Math.toRadians(rotation)))) * CAMERA_DISTANCE_MAGIC_FACTOR;
viewScale = mWidth / (mWidth + dW);
}
setScale(viewScale);
}
}
public float getFoldRotation() {
return mFoldRotation;
}
public void setScale(float scale) {
mScale = scale;
mTopPart.applyScale(scale);
mBottomPart.applyScale(scale);
}
public float getScale() {
return mScale;
}
/**
* Translation preserving middle line splitting
*/
public void setRollingDistance(float distance) {
mRollingDistance = distance;
mTopPart.applyRollingDistance(distance, mScale);
mBottomPart.applyRollingDistance(distance, mScale);
}
public float getRollingDistance() {
return mRollingDistance;
}
private void setInTransformation(boolean isInTransformation) {
if (mIsInTransformation == isInTransformation) return;
mIsInTransformation = isInTransformation;
mBaseLayout.setDrawToCache(isInTransformation);
mTopPart.setVisibility(isInTransformation ? VISIBLE : INVISIBLE);
mBottomPart.setVisibility(isInTransformation ? VISIBLE : INVISIBLE);
}
public void setAutoScaleEnabled(boolean isAutoScaleEnabled) {
mIsAutoScaleEnabled = isAutoScaleEnabled;
}
public FrameLayout getBaseLayout() {
return mBaseLayout;
}
public void setLayoutVisibleBounds(Rect visibleBounds) {
mTopPart.setVisibleBounds(visibleBounds);
mBottomPart.setVisibleBounds(visibleBounds);
}
public void setFoldShading(FoldShading shading) {
mTopPart.setFoldShading(shading);
mBottomPart.setFoldShading(shading);
}
/**
* View holder layout that can draw itself into given canvas
*/
private static class BaseLayout extends FrameLayout {
private Canvas mCacheCanvas;
private boolean mIsDrawToCache;
@SuppressWarnings("deprecation")
private BaseLayout(FoldableItemLayout layout) {
super(layout.getContext());
int matchParent = ViewGroup.LayoutParams.MATCH_PARENT;
LayoutParams params = new LayoutParams(matchParent, matchParent);
layout.addView(this, params);
// Moving background
this.setBackgroundDrawable(layout.getBackground());
layout.setBackgroundDrawable(null);
setWillNotDraw(false);
}
private void moveInflatedChildren(FoldableItemLayout layout, int firstSkippedItems) {
while (layout.getChildCount() > firstSkippedItems) {
View view = layout.getChildAt(firstSkippedItems);
LayoutParams params = (LayoutParams) view.getLayoutParams();
layout.removeViewAt(firstSkippedItems);
addView(view, params);
}
}
@Override
public void draw(Canvas canvas) {
if (mIsDrawToCache) {
mCacheCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
super.draw(mCacheCanvas);
} else {
super.draw(canvas);
}
}
private void setCacheCanvas(Canvas cacheCanvas) {
mCacheCanvas = cacheCanvas;
}
private void setDrawToCache(boolean drawToCache) {
if (mIsDrawToCache == drawToCache) return;
mIsDrawToCache = drawToCache;
invalidate();
}
}
/**
* Splitted part view. It will draw top or bottom part of cached bitmap and overlay shadows.
* Also it contains main logic for all transformations (fold rotation, scale, "rolling distance").
*/
private static class PartView extends View {
private final int mGravity;
private Bitmap mBitmap;
private final Rect mBitmapBounds = new Rect();
private float mClippingFactor = 0.5f;
private final Paint mBitmapPaint;
private Rect mVisibleBounds;
private int mInternalVisibility;
private int mExtrenalVisibility;
private float mLocalFoldRotation;
private FoldShading mShading;
public PartView(FoldableItemLayout parent, int gravity) {
super(parent.getContext());
mGravity = gravity;
final int matchParent = LayoutParams.MATCH_PARENT;
parent.addView(this, new LayoutParams(matchParent, matchParent));
setCameraDistance(CAMERA_DISTANCE * getResources().getDisplayMetrics().densityDpi);
mBitmapPaint = new Paint();
mBitmapPaint.setDither(true);
mBitmapPaint.setFilterBitmap(true);
setWillNotDraw(false);
}
private void setCacheBitmap(Bitmap bitmap) {
mBitmap = bitmap;
calculateBitmapBounds();
}
private void setVisibleBounds(Rect visibleBounds) {
mVisibleBounds = visibleBounds;
calculateBitmapBounds();
}
private void setFoldShading(FoldShading shading) {
mShading = shading;
}
private void calculateBitmapBounds() {
if (mBitmap == null) {
mBitmapBounds.set(0, 0, 0, 0);
} else {
int h = mBitmap.getHeight();
int w = mBitmap.getWidth();
int top = mGravity == Gravity.TOP ? 0 : (int) (h * (1 - mClippingFactor) - 0.5f);
int bottom = mGravity == Gravity.TOP ? (int) (h * mClippingFactor + 0.5f) : h;
mBitmapBounds.set(0, top, w, bottom);
if (mVisibleBounds != null) {
if (!mBitmapBounds.intersect(mVisibleBounds)) {
mBitmapBounds.set(0, 0, 0, 0); // no intersection
}
}
}
invalidate();
}
private void applyFoldRotation(float rotation) {
float position = rotation;
while (position < 0) position += 360;
position %= 360;
if (position > 180) position -= 360; // now poistion within (-180; 180]
float rotationX = 0;
boolean isVisible = true;
if (mGravity == Gravity.TOP) {
if (position <= -90 || position == 180) { // (-180; -90] || {180} - will not show
isVisible = false;
} else if (position < 0) { // (-90; 0) - applying rotation
rotationX = position;
}
// [0; 180) - holding still
} else {
if (position >= 90) { // [90; 180] - will not show
isVisible = false;
} else if (position > 0) { // (0; 90) - applying rotation
rotationX = position;
}
// else: (-180; 0] - holding still
}
setRotationX(rotationX);
mInternalVisibility = isVisible ? VISIBLE : INVISIBLE;
applyVisibility();
mLocalFoldRotation = position;
invalidate(); // needed to draw shadow overlay
}
private void applyScale(float scale) {
setScaleX(scale);
setScaleY(scale);
}
private void applyRollingDistance(float distance, float scale) {
// applying translation
setTranslationY((int) (distance * scale + 0.5f));
// computing clipping for top view (bottom clipping will be 1 - topClipping)
final int h = getHeight() / 2;
final float topClipping = h == 0 ? 0.5f : (h - distance) / h / 2;
mClippingFactor = mGravity == Gravity.TOP ? topClipping : 1f - topClipping;
calculateBitmapBounds();
}
@Override
public void setVisibility(int visibility) {
mExtrenalVisibility = visibility;
applyVisibility();
}
private void applyVisibility() {
super.setVisibility(mExtrenalVisibility == VISIBLE ? mInternalVisibility : mExtrenalVisibility);
}
@Override
public void draw(Canvas canvas) {
if (mShading != null) mShading.onPreDraw(canvas, mBitmapBounds, mLocalFoldRotation, mGravity);
if (mBitmap != null) canvas.drawBitmap(mBitmap, mBitmapBounds, mBitmapBounds, mBitmapPaint);
if (mShading != null) mShading.onPostDraw(canvas, mBitmapBounds, mLocalFoldRotation, mGravity);
}
}
}
| |
/*
* 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.formats.parquet.utils;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.common.typeinfo.BasicArrayTypeInfo;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.core.fs.Path;
import org.apache.flink.formats.parquet.generated.ArrayItem;
import org.apache.flink.formats.parquet.generated.Bar;
import org.apache.flink.formats.parquet.generated.MapItem;
import org.apache.flink.formats.parquet.generated.NestedRecord;
import org.apache.flink.formats.parquet.generated.SimpleRecord;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.types.Row;
import org.apache.avro.Schema;
import org.apache.avro.generic.IndexedRecord;
import org.apache.avro.specific.SpecificRecord;
import org.apache.parquet.avro.AvroParquetWriter;
import org.apache.parquet.hadoop.ParquetWriter;
import org.junit.ClassRule;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mockito;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Utilities for testing schema conversion and test parquet file creation.
*/
public class TestUtil {
private static final TypeInformation<Row[]> nestedArray = Types.OBJECT_ARRAY(Types.ROW_NAMED(
new String[] {"type", "value"}, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.LONG_TYPE_INFO));
@SuppressWarnings("unchecked")
private static final TypeInformation<Map<String, Row>> nestedMap = Types.MAP(BasicTypeInfo.STRING_TYPE_INFO,
Types.ROW_NAMED(new String[] {"type", "value"},
BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO));
@ClassRule
public static TemporaryFolder tempRoot = new TemporaryFolder();
public static final Schema NESTED_SCHEMA = getTestSchema("nested.avsc");
public static final Schema SIMPLE_SCHEMA = getTestSchema("simple.avsc");
public static final TypeInformation<Row> SIMPLE_ROW_TYPE = Types.ROW_NAMED(new String[] {"foo", "bar", "arr"},
BasicTypeInfo.LONG_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO, BasicArrayTypeInfo.LONG_ARRAY_TYPE_INFO);
@SuppressWarnings("unchecked")
public static final TypeInformation<Row> NESTED_ROW_TYPE = Types.ROW_NAMED(
new String[] {"foo", "spamMap", "bar", "arr", "strArray", "nestedMap", "nestedArray"},
BasicTypeInfo.LONG_TYPE_INFO,
Types.MAP(BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO),
Types.ROW_NAMED(new String[] {"spam"}, BasicTypeInfo.LONG_TYPE_INFO),
BasicArrayTypeInfo.LONG_ARRAY_TYPE_INFO,
BasicArrayTypeInfo.STRING_ARRAY_TYPE_INFO,
nestedMap,
nestedArray);
public static Path createTempParquetFile(File folder, Schema schema, List<IndexedRecord> records) throws IOException {
Path path = new Path(folder.getPath(), UUID.randomUUID().toString());
ParquetWriter<IndexedRecord> writer = AvroParquetWriter.<IndexedRecord>builder(
new org.apache.hadoop.fs.Path(path.toUri())).withSchema(schema).withRowGroupSize(10).build();
for (IndexedRecord record : records) {
writer.write(record);
}
writer.close();
return path;
}
public static Tuple3<Class<? extends SpecificRecord>, SpecificRecord, Row> getSimpleRecordTestData() {
Long[] longArray = {1L};
final SimpleRecord simpleRecord = SimpleRecord.newBuilder()
.setBar("test_simple")
.setFoo(1L)
.setArr(Arrays.asList(longArray)).build();
final Row simpleRow = new Row(3);
simpleRow.setField(0, 1L);
simpleRow.setField(1, "test_simple");
simpleRow.setField(2, longArray);
final Tuple3<Class<? extends SpecificRecord>, SpecificRecord, Row> t = new Tuple3<>();
t.f0 = SimpleRecord.class;
t.f1 = simpleRecord;
t.f2 = simpleRow;
return t;
}
public static Tuple3<Class<? extends SpecificRecord>, SpecificRecord, Row> getNestedRecordTestData() {
final Bar bar = Bar.newBuilder()
.setSpam(1L).build();
final ArrayItem arrayItem = ArrayItem.newBuilder()
.setType("color")
.setValue(1L).build();
final MapItem mapItem = MapItem.newBuilder()
.setType("map")
.setValue("hashMap").build();
List<ArrayItem> nestedArray = new ArrayList<>();
nestedArray.add(arrayItem);
Map<CharSequence, MapItem> nestedMap = new HashMap<>();
nestedMap.put("mapItem", mapItem);
List<Long> longArray = new ArrayList<>();
longArray.add(1L);
List<CharSequence> stringArray = new ArrayList<>();
stringArray.add("String");
Long[] primitiveLongArray = {1L};
String[] primitiveStringArray = {"String"};
final NestedRecord nestedRecord = NestedRecord.newBuilder()
.setBar(bar)
.setNestedArray(nestedArray)
.setStrArray(stringArray)
.setNestedMap(nestedMap)
.setArr(longArray).build();
final Row barRow = new Row(1);
barRow.setField(0, 1L);
final Row arrayItemRow = new Row(2);
arrayItemRow.setField(0, "color");
arrayItemRow.setField(1, 1L);
final Row mapItemRow = new Row(2);
mapItemRow.setField(0, "map");
mapItemRow.setField(1, "hashMap");
Row[] nestedRowArray = {arrayItemRow};
Map<String, Row> nestedRowMap = new HashMap<>();
nestedRowMap.put("mapItem", mapItemRow);
final Row nestedRow = new Row(7);
nestedRow.setField(2, barRow);
nestedRow.setField(3, primitiveLongArray);
nestedRow.setField(4, primitiveStringArray);
nestedRow.setField(5, nestedRowMap);
nestedRow.setField(6, nestedRowArray);
final Tuple3<Class<? extends SpecificRecord>, SpecificRecord, Row> t = new Tuple3<>();
t.f0 = NestedRecord.class;
t.f1 = nestedRecord;
t.f2 = nestedRow;
return t;
}
/**
* Create a list of NestedRecord with the NESTED_SCHEMA.
*/
public static List<IndexedRecord> createRecordList(long numberOfRows) {
List<IndexedRecord> records = new ArrayList<>(0);
for (long i = 0; i < numberOfRows; i++) {
final Bar bar = Bar.newBuilder()
.setSpam(i).build();
final ArrayItem arrayItem = ArrayItem.newBuilder()
.setType("color")
.setValue(i).build();
final MapItem mapItem = MapItem.newBuilder()
.setType("map")
.setValue("hashMap").build();
List<ArrayItem> nestedArray = new ArrayList<>();
nestedArray.add(arrayItem);
Map<CharSequence, MapItem> nestedMap = new HashMap<>();
nestedMap.put("mapItem", mapItem);
List<Long> longArray = new ArrayList<>();
longArray.add(i);
List<CharSequence> stringArray = new ArrayList<>();
stringArray.add("String");
final NestedRecord nestedRecord = NestedRecord.newBuilder()
.setFoo(1L)
.setBar(bar)
.setNestedArray(nestedArray)
.setStrArray(stringArray)
.setNestedMap(nestedMap)
.setArr(longArray).build();
records.add(nestedRecord);
}
return records;
}
public static RuntimeContext getMockRuntimeContext() {
RuntimeContext mockContext = Mockito.mock(RuntimeContext.class);
Mockito.doReturn(UnregisteredMetricGroups.createUnregisteredOperatorMetricGroup())
.when(mockContext).getMetricGroup();
return mockContext;
}
public static Schema getTestSchema(String schemaName) {
try {
InputStream inputStream = TestUtil.class.getClassLoader()
.getResourceAsStream("avro/" + schemaName);
return new Schema.Parser().parse(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| |
/**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.registry.core.entities.workspacecatalog;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name="WORKSPACE_USER_PROFILE")
public class UserProfileEntity {
private String airavataInternalUserId;
private String userId;
private String gatewayId;
private String userModelVersion;
private String userName;
private String orcidId;
private String country;
private String homeOrganization;
private String orginationAffiliation;
private long creationTime;
private long lastAccessTime;
private long validUntil;
private String state;
private String comments;
private List<String> labeledURI;
private String gpgKey;
private String timeZone;
private List<String> nationality;
private List<String> emails;
private List<String> phones;
private NSFDemographicsEntity nsfDemographics;
@Id
@Column(name = "AIRAVATA_INTERNAL_USER_ID")
public String getAiravataInternalUserId() {
return airavataInternalUserId;
}
public void setAiravataInternalUserId(String id) {
this.airavataInternalUserId = id;
}
@Column(name = "USER_ID")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Column(name = "GATEWAY_ID")
public String getGatewayId() {
return gatewayId;
}
public void setGatewayId(String gatewayId) {
this.gatewayId = gatewayId;
}
@Column(name = "USER_MODEL_VERSION")
public String getUserModelVersion() {
return userModelVersion;
}
public void setUserModelVersion(String userModelVersion) {
this.userModelVersion = userModelVersion;
}
@ElementCollection
@CollectionTable(name="USER_PROFILE_EMAIL", joinColumns = @JoinColumn(name="AIRAVATA_INTERNAL_USER_ID"))
public List<String> getEmails() {
return emails;
}
public void setEmails(List<String> emails) {
this.emails = emails;
}
@Column(name = "USER_NAME")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "ORCID_ID")
public String getOrcidId() {
return orcidId;
}
public void setOrcidId(String orcidId) {
this.orcidId = orcidId;
}
@ElementCollection
@CollectionTable(name="USER_PROFILE_PHONE", joinColumns = @JoinColumn(name="AIRAVATA_INTERNAL_USER_ID"))
public List<String> getPhones() {
return phones;
}
public void setPhones(List<String> phones) {
this.phones = phones;
}
@Column(name = "COUNTRY")
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@ElementCollection
@CollectionTable(name="USER_PROFILE_NATIONALITY", joinColumns = @JoinColumn(name="AIRAVATA_INTERNAL_USER_ID"))
public List<String> getNationality() {
return nationality;
}
public void setNationality(List<String> nationality) {
this.nationality = nationality;
}
@Column(name = "HOME_ORGANIZATION")
public String getHomeOrganization() {
return homeOrganization;
}
public void setHomeOrganization(String homeOrganization) {
this.homeOrganization = homeOrganization;
}
@Column(name = "ORIGINATION_AFFILIATION")
public String getOrginationAffiliation() {
return orginationAffiliation;
}
public void setOrginationAffiliation(String orginationAffiliation) {
this.orginationAffiliation = orginationAffiliation;
}
@Column(name="CREATION_TIME")
public long getCreationTime() {
return creationTime;
}
public void setCreationTime(long creationTime) {
this.creationTime = creationTime;
}
@Column(name = "LAST_ACCESS_TIME")
public long getLastAccessTime() {
return lastAccessTime;
}
public void setLastAccessTime(long lastAccessTime) {
this.lastAccessTime = lastAccessTime;
}
@Column(name = "VALID_UNTIL")
public long getValidUntil() {
return validUntil;
}
public void setValidUntil(long validUntil) {
this.validUntil = validUntil;
}
@Column(name = "STATE")
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Lob
@Column(name = "COMMENTS")
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
@ElementCollection
@CollectionTable(name="USER_PROFILE_LABELED_URI", joinColumns = @JoinColumn(name="AIRAVATA_INTERNAL_USER_ID"))
public List<String> getLabeledURI() {
return labeledURI;
}
public void setLabeledURI(List<String> labeledURI) {
this.labeledURI = labeledURI;
}
@Lob
@Column(name = "GPG_KEY")
public String getGpgKey() {
return gpgKey;
}
public void setGpgKey(String gpgKey) {
this.gpgKey = gpgKey;
}
@Column(name = "TIME_ZONE")
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
@OneToOne(targetEntity = NSFDemographicsEntity.class, cascade = CascadeType.ALL, mappedBy = "userProfile")
public NSFDemographicsEntity getNsfDemographics() {
return nsfDemographics;
}
public void setNsfDemographics(NSFDemographicsEntity nsfDemographics) {
this.nsfDemographics = nsfDemographics;
}
}
| |
/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.apple;
import static com.facebook.buck.apple.project_generator.ProjectGeneratorTestUtils.createDescriptionArgWithDefaults;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.cxx.CxxDescriptionEnhancer;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.model.Either;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildTargetSourcePath;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.FakeBuildRuleParamsBuilder;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.TargetNode;
import com.facebook.buck.shell.GenruleBuilder;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.testutil.TargetGraphFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import org.junit.Test;
import java.util.Optional;
public class AppleBuildRulesTest {
@Test
public void testAppleLibraryIsXcodeTargetBuildRuleType() throws Exception {
assertTrue(AppleBuildRules.isXcodeTargetBuildRuleType(AppleLibraryDescription.TYPE));
}
@Test
public void testIosResourceIsNotXcodeTargetBuildRuleType() throws Exception {
assertFalse(AppleBuildRules.isXcodeTargetBuildRuleType(AppleResourceDescription.TYPE));
}
@Test
public void testAppleTestIsXcodeTargetTestBuildRuleType() throws Exception {
BuildRuleResolver resolver =
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
AppleTestBuilder appleTestBuilder = new AppleTestBuilder(
BuildTargetFactory.newInstance("//foo:xctest#iphoneos-i386"))
.setContacts(ImmutableSortedSet.of())
.setLabels(ImmutableSortedSet.of())
.setDeps(ImmutableSortedSet.of());
TargetNode<?> appleTestNode = appleTestBuilder.build();
BuildRule testRule = appleTestBuilder.build(
resolver,
new FakeProjectFilesystem(),
TargetGraphFactory.newInstance(ImmutableSet.of(appleTestNode)));
assertTrue(AppleBuildRules.isXcodeTargetTestBuildRule(testRule));
}
@Test
public void testAppleLibraryIsNotXcodeTargetTestBuildRuleType() throws Exception {
BuildRuleParams params = new FakeBuildRuleParamsBuilder("//foo:lib").build();
AppleLibraryDescription.Arg arg =
createDescriptionArgWithDefaults(FakeAppleRuleDescriptions.LIBRARY_DESCRIPTION);
BuildRule libraryRule = FakeAppleRuleDescriptions
.LIBRARY_DESCRIPTION
.createBuildRule(
TargetGraph.EMPTY,
params,
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()),
arg);
assertFalse(AppleBuildRules.isXcodeTargetTestBuildRule(libraryRule));
}
@Test
public void testXctestIsTestBundleExtension() throws Exception {
assertTrue(AppleBuildRules.isXcodeTargetTestBundleExtension(AppleBundleExtension.XCTEST));
}
@Test
public void testRecursiveTargetsIncludesBundleBinaryFromOutsideBundle() throws Exception {
BuildTarget libraryTarget = BuildTargetFactory.newInstance("//foo:lib");
TargetNode<?> libraryNode = AppleLibraryBuilder
.createBuilder(libraryTarget)
.build();
BuildTarget bundleTarget = BuildTargetFactory.newInstance("//foo:bundle");
TargetNode<?> bundleNode = AppleBundleBuilder
.createBuilder(bundleTarget)
.setExtension(Either.ofLeft(AppleBundleExtension.XCTEST))
.setBinary(libraryTarget)
.build();
BuildTarget rootTarget = BuildTargetFactory.newInstance("//foo:root");
TargetNode<?> rootNode = AppleLibraryBuilder
.createBuilder(rootTarget)
.setDeps(ImmutableSortedSet.of(libraryTarget, bundleTarget))
.build();
Iterable<TargetNode<?>> rules = AppleBuildRules.getRecursiveTargetNodeDependenciesOfTypes(
TargetGraphFactory.newInstance(ImmutableSet.of(libraryNode, bundleNode, rootNode)),
AppleBuildRules.RecursiveDependenciesMode.BUILDING,
rootNode,
Optional.empty());
assertTrue(Iterables.elementsEqual(ImmutableSortedSet.of(libraryNode, bundleNode), rules));
}
@Test
public void exportedDepsOfDylibsAreCollectedForLinking() throws Exception {
BuildTarget fooLibTarget =
BuildTargetFactory.newInstance("//foo:lib#" + CxxDescriptionEnhancer.SHARED_FLAVOR);
TargetNode<?> fooLibNode = AppleLibraryBuilder
.createBuilder(fooLibTarget)
.build();
BuildTarget fooFrameworkTarget = BuildTargetFactory.newInstance("//foo:framework");
TargetNode<?> fooFrameworkNode = AppleBundleBuilder
.createBuilder(fooFrameworkTarget)
.setExtension(Either.ofLeft(AppleBundleExtension.FRAMEWORK))
.setBinary(fooLibTarget)
.build();
BuildTarget barLibTarget =
BuildTargetFactory.newInstance("//bar:lib#" + CxxDescriptionEnhancer.SHARED_FLAVOR);
TargetNode<?> barLibNode = AppleLibraryBuilder
.createBuilder(barLibTarget)
.setDeps(ImmutableSortedSet.of(fooFrameworkTarget))
.setExportedDeps(ImmutableSortedSet.of(fooFrameworkTarget))
.build();
BuildTarget barFrameworkTarget = BuildTargetFactory.newInstance("//bar:framework");
TargetNode<?> barFrameworkNode = AppleBundleBuilder
.createBuilder(barFrameworkTarget)
.setExtension(Either.ofLeft(AppleBundleExtension.FRAMEWORK))
.setBinary(barLibTarget)
.build();
BuildTarget rootTarget = BuildTargetFactory.newInstance("//foo:root");
TargetNode<?> rootNode = AppleLibraryBuilder
.createBuilder(rootTarget)
.setDeps(ImmutableSortedSet.of(barFrameworkTarget))
.build();
Iterable<TargetNode<?>> rules = AppleBuildRules.getRecursiveTargetNodeDependenciesOfTypes(
TargetGraphFactory.newInstance(
ImmutableSet.of(
rootNode,
fooLibNode,
fooFrameworkNode,
barLibNode,
barFrameworkNode)),
AppleBuildRules.RecursiveDependenciesMode.LINKING,
rootNode,
Optional.empty());
assertEquals(
ImmutableSortedSet.of(
barFrameworkNode,
fooFrameworkNode),
ImmutableSortedSet.copyOf(rules));
}
@Test
public void exportedDepsAreCollectedForCopying() throws Exception {
BuildTarget fooLibTarget =
BuildTargetFactory.newInstance("//foo:lib#" + CxxDescriptionEnhancer.SHARED_FLAVOR);
TargetNode<?> fooLibNode = AppleLibraryBuilder
.createBuilder(fooLibTarget)
.build();
BuildTarget fooFrameworkTarget = BuildTargetFactory.newInstance("//foo:framework");
TargetNode<?> fooFrameworkNode = AppleBundleBuilder
.createBuilder(fooFrameworkTarget)
.setExtension(Either.ofLeft(AppleBundleExtension.FRAMEWORK))
.setBinary(fooLibTarget)
.build();
BuildTarget barLibTarget =
BuildTargetFactory.newInstance("//bar:lib#" + CxxDescriptionEnhancer.SHARED_FLAVOR);
TargetNode<?> barLibNode = AppleLibraryBuilder
.createBuilder(barLibTarget)
.setDeps(ImmutableSortedSet.of(fooFrameworkTarget))
.setExportedDeps(ImmutableSortedSet.of(fooFrameworkTarget))
.build();
BuildTarget barFrameworkTarget = BuildTargetFactory.newInstance("//bar:framework");
TargetNode<?> barFrameworkNode = AppleBundleBuilder
.createBuilder(barFrameworkTarget)
.setExtension(Either.ofLeft(AppleBundleExtension.FRAMEWORK))
.setBinary(barLibTarget)
.build();
BuildTarget bazLibTarget =
BuildTargetFactory.newInstance("//baz:lib#" + CxxDescriptionEnhancer.SHARED_FLAVOR);
TargetNode<?> bazLibNode = AppleLibraryBuilder
.createBuilder(bazLibTarget)
.setDeps(ImmutableSortedSet.of(barFrameworkTarget))
.build();
BuildTarget bazFrameworkTarget = BuildTargetFactory.newInstance("//baz:framework");
TargetNode<?> bazFrameworkNode = AppleBundleBuilder
.createBuilder(bazFrameworkTarget)
.setExtension(Either.ofLeft(AppleBundleExtension.FRAMEWORK))
.setBinary(bazLibTarget)
.build();
ImmutableSet<TargetNode<?>> targetNodes =
ImmutableSet.<TargetNode<?>>builder()
.add(
fooLibNode,
fooFrameworkNode,
barLibNode,
barFrameworkNode,
bazLibNode,
bazFrameworkNode)
.build();
Iterable<TargetNode<?>> rules = AppleBuildRules.getRecursiveTargetNodeDependenciesOfTypes(
TargetGraphFactory.newInstance(targetNodes),
AppleBuildRules.RecursiveDependenciesMode.COPYING,
bazFrameworkNode,
Optional.empty());
assertEquals(
ImmutableSortedSet.of(
barFrameworkNode,
fooFrameworkNode),
ImmutableSortedSet.copyOf(rules));
}
@Test
public void linkingStopsAtGenruleDep() throws Exception {
// Pass a random static lib in a genrule and make sure a framework
// depending on the genrule doesn't link against or copy in the static lib.
BuildTarget fooLibTarget = BuildTargetFactory.newInstance("//foo:lib");
TargetNode<?> fooLibNode = AppleLibraryBuilder
.createBuilder(fooLibTarget)
.build();
BuildTarget fooGenruleTarget = BuildTargetFactory.newInstance("//foo:genrule");
TargetNode<?> fooGenruleNode = GenruleBuilder
.newGenruleBuilder(fooGenruleTarget)
.setOut("foo")
.setCmd("echo hi > $OUT")
.setSrcs(ImmutableList.of(new BuildTargetSourcePath(fooLibTarget)))
.build();
BuildTarget barLibTarget =
BuildTargetFactory.newInstance("//bar:lib#" + CxxDescriptionEnhancer.SHARED_FLAVOR);
TargetNode<?> barLibNode = AppleLibraryBuilder
.createBuilder(barLibTarget)
.setDeps(ImmutableSortedSet.of(fooGenruleTarget))
.build();
BuildTarget barFrameworkTarget = BuildTargetFactory.newInstance("//bar:framework");
TargetNode<?> barFrameworkNode = AppleBundleBuilder
.createBuilder(barFrameworkTarget)
.setExtension(Either.ofLeft(AppleBundleExtension.FRAMEWORK))
.setBinary(barLibTarget)
.build();
ImmutableSet<TargetNode<?>> targetNodes =
ImmutableSet.<TargetNode<?>>builder()
.add(
fooLibNode,
fooGenruleNode,
barLibNode,
barFrameworkNode)
.build();
Iterable<TargetNode<?>> rules = AppleBuildRules.getRecursiveTargetNodeDependenciesOfTypes(
TargetGraphFactory.newInstance(targetNodes),
AppleBuildRules.RecursiveDependenciesMode.LINKING,
barFrameworkNode,
Optional.empty());
assertEquals(
ImmutableSortedSet.of(fooGenruleNode),
ImmutableSortedSet.copyOf(rules));
}
@Test
public void copyingStopsAtGenruleDep() throws Exception {
// Pass a random static lib in a genrule and make sure a framework
// depending on the genrule doesn't link against or copy in the static lib.
BuildTarget fooLibTarget = BuildTargetFactory.newInstance("//foo:lib");
TargetNode<?> fooLibNode = AppleLibraryBuilder
.createBuilder(fooLibTarget)
.build();
BuildTarget fooGenruleTarget = BuildTargetFactory.newInstance("//foo:genrule");
TargetNode<?> fooGenruleNode = GenruleBuilder
.newGenruleBuilder(fooGenruleTarget)
.setOut("foo")
.setCmd("echo hi > $OUT")
.setSrcs(ImmutableList.of(new BuildTargetSourcePath(fooLibTarget)))
.build();
BuildTarget barLibTarget =
BuildTargetFactory.newInstance("//bar:lib#" + CxxDescriptionEnhancer.SHARED_FLAVOR);
TargetNode<?> barLibNode = AppleLibraryBuilder
.createBuilder(barLibTarget)
.setDeps(ImmutableSortedSet.of(fooGenruleTarget))
.build();
BuildTarget barFrameworkTarget = BuildTargetFactory.newInstance("//bar:framework");
TargetNode<?> barFrameworkNode = AppleBundleBuilder
.createBuilder(barFrameworkTarget)
.setExtension(Either.ofLeft(AppleBundleExtension.FRAMEWORK))
.setBinary(barLibTarget)
.build();
ImmutableSet<TargetNode<?>> targetNodes =
ImmutableSet.<TargetNode<?>>builder()
.add(
fooLibNode,
fooGenruleNode,
barLibNode,
barFrameworkNode)
.build();
Iterable<TargetNode<?>> rules = AppleBuildRules.getRecursiveTargetNodeDependenciesOfTypes(
TargetGraphFactory.newInstance(targetNodes),
AppleBuildRules.RecursiveDependenciesMode.COPYING,
barFrameworkNode,
Optional.empty());
assertEquals(
ImmutableSortedSet.of(fooGenruleNode),
ImmutableSortedSet.copyOf(rules));
}
@Test
public void buildingStopsAtGenruleDepButNotAtBundleDep() throws Exception {
// Pass a random static lib in a genrule and make sure a framework
// depending on the genrule doesn't build the dependencies of that genrule.
BuildTarget fooLibTarget = BuildTargetFactory.newInstance("//foo:lib");
TargetNode<?> fooLibNode = AppleLibraryBuilder
.createBuilder(fooLibTarget)
.build();
BuildTarget fooGenruleTarget = BuildTargetFactory.newInstance("//foo:genrule");
TargetNode<?> fooGenruleNode = GenruleBuilder
.newGenruleBuilder(fooGenruleTarget)
.setOut("foo")
.setCmd("echo hi > $OUT")
.setSrcs(ImmutableList.of(new BuildTargetSourcePath(fooLibTarget)))
.build();
BuildTarget barLibTarget =
BuildTargetFactory.newInstance("//bar:lib#" + CxxDescriptionEnhancer.SHARED_FLAVOR);
TargetNode<?> barLibNode = AppleLibraryBuilder
.createBuilder(barLibTarget)
.setDeps(ImmutableSortedSet.of(fooGenruleTarget))
.build();
BuildTarget barFrameworkTarget = BuildTargetFactory.newInstance("//bar:framework");
TargetNode<?> barFrameworkNode = AppleBundleBuilder
.createBuilder(barFrameworkTarget)
.setExtension(Either.ofLeft(AppleBundleExtension.FRAMEWORK))
.setBinary(barLibTarget)
.build();
BuildTarget bazLibTarget =
BuildTargetFactory.newInstance("//baz:lib#" + CxxDescriptionEnhancer.SHARED_FLAVOR);
TargetNode<?> bazLibNode = AppleLibraryBuilder
.createBuilder(bazLibTarget)
.setDeps(ImmutableSortedSet.of(barFrameworkTarget))
.build();
BuildTarget bazFrameworkTarget = BuildTargetFactory.newInstance("//baz:framework");
TargetNode<?> bazFrameworkNode = AppleBundleBuilder
.createBuilder(bazFrameworkTarget)
.setExtension(Either.ofLeft(AppleBundleExtension.FRAMEWORK))
.setBinary(bazLibTarget)
.build();
ImmutableSet<TargetNode<?>> targetNodes =
ImmutableSet.<TargetNode<?>>builder()
.add(
fooLibNode,
fooGenruleNode,
barLibNode,
barFrameworkNode,
bazLibNode,
bazFrameworkNode)
.build();
Iterable<TargetNode<?>> rules = AppleBuildRules.getRecursiveTargetNodeDependenciesOfTypes(
TargetGraphFactory.newInstance(targetNodes),
AppleBuildRules.RecursiveDependenciesMode.BUILDING,
bazFrameworkNode,
Optional.empty());
assertEquals(
ImmutableSortedSet.of(barFrameworkNode, fooGenruleNode),
ImmutableSortedSet.copyOf(rules));
}
}
| |
package et.test.naruto;
import java.util.ArrayList;
import java.util.TreeSet;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import et.naruto.base.Util;
import et.naruto.base.Util.DIAG;
import et.naruto.base.Util.ZKArgs;
import et.naruto.elect.Args;
import et.naruto.process.zk.ChildsFetcher;
import et.naruto.process.zk.ValueFetcher;
import et.naruto.process.zk.ValueRegister;
import et.naruto.process.zk.ZKProcess;
import et.naruto.register.RegistersClient;
import et.naruto.register.RegistersUpdater;
import et.naruto.register.sync.NodeSync;
import et.naruto.register.sync.RegistersSync;
import et.naruto.register.sync.ServerSync;
import et.naruto.resolutionsurface.RSArgs;
import et.naruto.resolutionsurface.ResolutionSurface;
public class MainTest {
public static ZKArgs zkargs=new ZKArgs("localhost:2181");
public static String base_path="/naruto_test";
public static ZooKeeper zk=zkargs.Create();
public static Args CreateArgs(final int seq) {
return new Args(base_path,"floor4:localhost", "server("+seq+")");
}
@Before
public void setUp() {
Util.ForceDeleteNode(zk,base_path);
}
@After
public void tearDown() {
Util.ForceDeleteNode(zk,base_path);
}
@Test
public void testValueFetcher() {
ZKProcess process=new ZKProcess("test",zkargs);
ValueFetcher vf=new ValueFetcher(process,base_path);
process.Start();
Util.Sleep(3*1000);
Assert.assertTrue(vf.result().value.equals(""));
Util.ForceCreateNode(process.zk,base_path,"hello");
Util.Sleep(3*1000);
Assert.assertTrue(vf.result().value.equals("hello"));
Util.ForceDeleteNode(process.zk,base_path);
Util.Sleep(3*1000);
Assert.assertTrue(vf.result().value.equals(""));
process.close();
}
@Test
public void testChildsFetcher() {
ZKProcess process=new ZKProcess("test",zkargs);
ValueFetcher vf=new ValueFetcher(process,base_path);
ChildsFetcher cf=new ChildsFetcher(process,base_path);
process.Start();
Util.Sleep(3*1000);
Assert.assertTrue(vf.result().value.equals(""));
Util.ForceCreateNode(process.zk,base_path,"hello",true);
Util.Sleep(3*1000);
Assert.assertTrue(vf.result().value.equals("hello"));
Util.ForceCreateNode(process.zk,base_path+"/sub_test_1","hello1");
Util.ForceCreateNode(process.zk,base_path+"/sub_test_2","hello2");
Util.ForceCreateNode(process.zk,base_path+"/sub_test_3","hello3");
Util.Sleep(3*1000);
Assert.assertTrue(cf.result().childs.size()==3);
Util.Sleep(3*1000);
Util.ForceDeleteNode(process.zk,base_path);
Util.Sleep(3*1000);
Assert.assertTrue(vf.result().value.equals(""));
process.close();
}
@Test
public void testValueRegister() {
ZKProcess process=new ZKProcess("test",zkargs);
ValueFetcher vf=new ValueFetcher(process,base_path);
Util.ForceDeleteNode(process.zk,base_path);
process.Start();
Util.Sleep(3*1000);
Assert.assertTrue(vf.result().value.equals(""));
ValueRegister vr=new ValueRegister(process,new ValueRegister.Request(base_path,"hello",CreateMode.EPHEMERAL));
Util.Sleep(3*1000);
Assert.assertTrue(vf.result().value.equals("hello"));
process.close();
Util.ForceDeleteNode(process.zk,base_path);
}
@Test
public void testRegistersSync() {
Util.ForceCreateNode(zk,base_path,"registers_sync_test",true);
ZKProcess process=new ZKProcess("test",zkargs);
Args args=CreateArgs(0);
RegistersSync nf=new RegistersSync(process,args);
process.Start();
Util.ForceCreateNode(zk,args.GetRegistersPath(),"registers_test",true);
Util.ForceCreateNode(zk,args.GetNodePath(),"node_test",true);
Util.ForceCreateNode(zk,args.GetServerPath(),"server_test",true);
Util.ForceCreateNode(zk,args.GetActivePath(),"active_test",false);
Util.Sleep(3*1000);
NodeSync node_sync=nf.dealer.result().get(args.node_path);
Assert.assertTrue(node_sync!=null);
ServerSync server_sync=node_sync.dealer.result().get(args.server_num);
Assert.assertTrue(server_sync!=null);
Assert.assertTrue(server_sync.active_fetcher.result().value.equals("active_test"));
process.close();
nf.close();
}
private static int register_active_count=0;
@Test
public void testRegistersUpdater() {
Util.ForceCreateNode(zk,base_path,"registers_sync_test",true);
ZKProcess process=new ZKProcess("test",zkargs);
Args args=CreateArgs(0);
RegistersUpdater nf=new RegistersUpdater(process,args) {
protected byte[] DoGetActiveInfo() {
return (""+(register_active_count++)).getBytes();
}
};
process.Start();
Util.Sleep(3*1000+30*1000);
Assert.assertTrue(Integer.valueOf(Util.GetNodeData(zk,args.GetActivePath()),10)>0);
process.close();
nf.Close();
}
private static class RegistersClientTest {
public final Args args;
public final RegistersClient register_client;
public final RegistersUpdater register_updater;
public RegistersClientTest(final int i) {
this.args=MainTest.CreateArgs(i);
this.register_client=new RegistersClient(args,zkargs);
this.register_updater=new RegistersUpdater(this.register_client.zkprocess,args) {
protected byte[] DoGetActiveInfo() {
return args.GetServerId().getBytes();
}
};
}
}
@Test
public void testRegistersClient() {
Util.ForceCreateNode(zk,base_path,"test_registers_client",true);
final ArrayList<RegistersClientTest> ss=new ArrayList();
long length=30;
for(int i=0;i<length;i++) {
ss.add(new RegistersClientTest(i));
}
for(RegistersClientTest s:ss) {
s.register_client.Start();
}
Util.Sleep(3000);
TreeSet<String> nodes=Util.GetNodeChilds(zk,this.base_path+"/Registers");
Assert.assertTrue(nodes.size()==1);
TreeSet<String> servers=Util.GetNodeChilds(zk,this.base_path+"/Registers/"+nodes.first());
Assert.assertTrue(servers.size()==length);
for(RegistersClientTest s:ss) {
Assert.assertTrue(s.register_client.registers_sync.dealer.result().get(s.args.node_path).
dealer.result().get(s.args.server_num).
active_fetcher.result().value.equals(s.args.GetServerId()));
s.register_client.close();
}
}
@Test
public void testResolutionSurface() {
Util.ForceCreateNode(zk,base_path,"resolution_surface_sync_test",true);
ZKProcess process=new ZKProcess("test",zkargs);
ArrayList<ResolutionSurface> rss=new ArrayList();
long length=50;
for(int i=0;i<length;i++) {
rss.add(new ResolutionSurface(process,new RSArgs(base_path+"/Resolutions","hello"+i)));
}
process.Start();
Util.Sleep(3*1000);
Assert.assertTrue(Util.GetNodeData(zk,base_path+"/Resolutions").length()>0);
Assert.assertTrue(Util.GetNodeData(zk,base_path+"/ResolutionsClosed").length()>0);
Assert.assertTrue(rss.get(0).out_handleable().result.resolution.seq==-1);
Assert.assertTrue(rss.get(0).out_handleable().result.succ==false);
ResolutionSurface succ_rs=null;
int l=10;
for(int j=0;j<=l;j++) {
for(int i=0;i<rss.size();i++) {
if(succ_rs!=rss.get(i)) {
if(j==l-1) {
rss.get(i).Regist(new ResolutionSurface.Request(null,j));
} else {
rss.get(i).Regist(new ResolutionSurface.Request(("hello"+i).getBytes(),j));
}
Util.Sleep(10);
}
}
succ_rs=null;
Util.Sleep(3*1000);
int succ_count=0;
int fail_count=0;
int result_seq_j=0;
int no_result_seq_j=0;
int closed_count=0;
for(int i=0;i<rss.size();i++) {
ResolutionSurface.Result result=rss.get(i).out_handleable().result;
if(result.resolution.seq==j) {
result_seq_j++;
if(result.succ) {
succ_count++;
succ_rs=rss.get(i);
} else {
fail_count++;
}
} else {
no_result_seq_j++;
}
if(result.resolution.data.is_determined_for_closed()) {
closed_count++;
}
if(j!=l) {
Assert.assertTrue(rss.get(i).out_handleable().result.resolution.seq==j);
} else {
Assert.assertTrue(rss.get(i).out_handleable().result.resolution.seq==(j-1));
}
}
if(j==l) {
Assert.assertTrue(no_result_seq_j==length);
Assert.assertTrue(closed_count==length);
} else {
DIAG.Log.d.info(String.format("*********************testResolutionSurfaceSurface j is %s ,token is %s*****************************",j,succ_rs.args.token));
Assert.assertTrue(no_result_seq_j==0);
Assert.assertTrue(result_seq_j==length);
Assert.assertTrue(succ_count==1);
Assert.assertTrue(fail_count==length-1);
if(j==l-1) {
Assert.assertTrue(closed_count==length);
}
}
}
process.close();
for(int i=0;i<rss.size();i++) {
rss.get(i).close();
}
}
@Test
public void testElectServer() {
Util.ForceCreateNode(zk,base_path,"server_test",true);
final ArrayList<et.naruto.elect.Server> ss=new ArrayList();
long length=80;
for(int i=0;i<length;i++) {
ss.add(new et.naruto.elect.Server(CreateArgs(i),zkargs));
}
for(et.naruto.elect.Server s:ss) {
s.Start();
}
Util.Sleep(500);
String resolutions_data=Util.GetNodeData(zk,base_path+"/Resolutions");
Assert.assertTrue(!resolutions_data.isEmpty());
int pure_pre_leader_count=0;
while(true) {
Util.Sleep(50);
int pre_leader_count=0;
int leader_count=0;
et.naruto.elect.Server pre_leader=null;
et.naruto.elect.Server leader=null;
for(et.naruto.elect.Server s:ss) {
if(s.master.IsPreLeader()) {
pre_leader_count++;
pre_leader=s;
}
if(s.master.IsLeader()) {
leader_count++;
leader=s;
}
}
if(pre_leader_count>1) {
Assert.assertTrue(false);
}
if(leader_count>1) {
Assert.assertTrue(false);
}
if(ss.size()%2==1) {
if(pre_leader_count>=1) {
if(ss.size()==21) {
int i=0;
i++;
}
DIAG.Log.d.info(String.format("**************************Stop the pre_leader server: %s**************************", pre_leader));
pre_leader.close();
if(!pre_leader.master.IsLeader()) {
pure_pre_leader_count++;
}
ss.remove(pre_leader);
}
} else {
if(leader_count>=1) {
DIAG.Log.d.info(String.format("**************************Stop the leader server: %s************************", leader));
leader.close();
ss.remove(leader);
}
}
if(ss.size()==0) {
break;
}
}
Assert.assertTrue(Util.GetNodeChilds(zk,base_path+"/Resolutions").size()>=(length-pure_pre_leader_count));
Assert.assertTrue(Util.GetNodeChilds(zk,base_path+"/ResolutionsClosed").size()>=(length-1-pure_pre_leader_count));
}
@Test
public void RegisterTest() {
}
}
| |
package blazemeter.jmeter.plugins.websocket.sampler.gui;
import java.awt.Component;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.config.gui.ArgumentsPanel;
import org.apache.jmeter.protocol.http.gui.HTTPArgumentsPanel;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
public class WebSocketConnectionSamplerPanel extends javax.swing.JPanel {
private JPanel webServerPanel = new JPanel();
private JLabel serverLabel = new JLabel();
private JTextField server = new JTextField();
private JLabel portLabel = new JLabel();
private JTextField port = new JTextField();
private JPanel timeoutPanel = new JPanel();
private JLabel connectTimeoutLabel = new JLabel();
private JTextField connectionTimeout = new JTextField();
private JPanel requestPanel = new JPanel();
private JLabel protocolLabel = new JLabel();
private JTextField protocol = new JTextField();
private JLabel pathLabel = new JLabel();
private JTextField path = new JTextField();
private JLabel contentEncodingLabel = new JLabel();
private JTextField contentEncoding = new JTextField();
private JLabel connectionIdLabel = new JLabel();
private JTextField connectionId = new JTextField();
private JLabel implementationLabel = new JLabel();
private JComboBox implementationComboBox = new JComboBox();
private HTTPArgumentsPanel attributePanel;
private JPanel querystringAttributesPanel = new JPanel();
private JPanel responsePanel = new JPanel();
private JPanel querystringPatternsPanel = new JPanel();
private ArgumentsPanel patternsPanel;
private JLabel closePatternLabel = new JLabel();
private JTextField closePattern = new JTextField();
public WebSocketConnectionSamplerPanel() {
initComponents();
attributePanel = new HTTPArgumentsPanel();
patternsPanel = new ArgumentsPanel("Response Patterns");
querystringAttributesPanel.add(attributePanel);
querystringPatternsPanel.add(patternsPanel);
}
private void initComponents() {
webServerPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(JMeterUtils.getResString("web_server")));
serverLabel.setText(JMeterUtils.getResString("web_server_domain"));
portLabel.setText(JMeterUtils.getResString("web_server_port"));
javax.swing.GroupLayout webServerPanelLayout = new javax.swing.GroupLayout(webServerPanel);
webServerPanel.setLayout(webServerPanelLayout);
webServerPanelLayout.setHorizontalGroup(
webServerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(webServerPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(serverLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(server)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(portLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
webServerPanelLayout.setVerticalGroup(
webServerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(webServerPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(webServerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(serverLabel)
.addComponent(server, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(portLabel)
.addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
timeoutPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(JMeterUtils.getResString("timeout_title")));
connectTimeoutLabel.setText(JMeterUtils.getResString("web_server_timeout_connect"));
javax.swing.GroupLayout timeoutPanelLayout = new javax.swing.GroupLayout(timeoutPanel);
timeoutPanel.setLayout(timeoutPanelLayout);
timeoutPanelLayout.setHorizontalGroup(
timeoutPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(timeoutPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(connectTimeoutLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(connectionTimeout)
.addContainerGap())
);
timeoutPanelLayout.setVerticalGroup(
timeoutPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(timeoutPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(timeoutPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(connectTimeoutLabel)
.addComponent(connectionTimeout, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
requestPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("WebSocket Request"));
protocolLabel.setText("Protocol [ws/wss]:");
pathLabel.setText(JMeterUtils.getResString("path"));
contentEncodingLabel.setText(JMeterUtils.getResString("content_encoding"));
connectionIdLabel.setText("Connection Id:");
querystringAttributesPanel.setLayout(new javax.swing.BoxLayout(querystringAttributesPanel, javax.swing.BoxLayout.LINE_AXIS));
implementationLabel.setText(JMeterUtils.getResString("http_implementation"));
implementationComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Jetty" }));
javax.swing.GroupLayout requestPanelLayout = new javax.swing.GroupLayout(requestPanel);
requestPanel.setLayout(requestPanelLayout);
requestPanelLayout.setHorizontalGroup(
requestPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(requestPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(requestPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(querystringAttributesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(requestPanelLayout.createSequentialGroup()
.addComponent(implementationLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(implementationComboBox, 0, 1, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(protocolLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(protocol, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(contentEncodingLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(contentEncoding, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(connectionIdLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(connectionId))
.addGroup(requestPanelLayout.createSequentialGroup()
.addComponent(pathLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(path)))
.addContainerGap())
);
requestPanelLayout.setVerticalGroup(
requestPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(requestPanelLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(requestPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(protocolLabel)
.addComponent(protocol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(contentEncodingLabel)
.addComponent(contentEncoding, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(connectionIdLabel)
.addComponent(connectionId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(implementationLabel)
.addComponent(implementationComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(requestPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(pathLabel)
.addComponent(path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(querystringAttributesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE)
.addGap(8, 8, 8)
.addContainerGap())
);
responsePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("WebSocket Response"));
closePatternLabel.setText("Close Connection Pattern");
javax.swing.GroupLayout responsePanelLayout = new javax.swing.GroupLayout(responsePanel);
responsePanel.setLayout(responsePanelLayout);
responsePanelLayout.setHorizontalGroup(
responsePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(responsePanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(responsePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(responsePanelLayout.createSequentialGroup()
.addComponent(closePatternLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(closePattern))
.addComponent(querystringPatternsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
responsePanelLayout.setVerticalGroup(
responsePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(responsePanelLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(responsePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(closePatternLabel)
.addComponent(closePattern, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(querystringPatternsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE)
.addGap(8, 8, 8)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(requestPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(responsePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(webServerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(timeoutPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(timeoutPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(webServerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(requestPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(responsePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}
public void initFields() {
}
public void setConnectionId(String connectionIdParam) {
connectionId.setText(connectionIdParam);
}
public String getConnectionId() {
return connectionId.getText();
}
public void setContentEncoding(String contentEncodingParam) {
contentEncoding.setText(contentEncodingParam);
}
public String getContentEncoding() {
return contentEncoding.getText();
}
public void setPath(String contextPathParam) {
path.setText(contextPathParam);
}
public String getPath() {
return path.getText();
}
public void setProtocol(String protocolParam) {
protocol.setText(protocolParam);
}
public String getProtocol() {
return protocol.getText();
}
public void setConnectionTimeout(String connectionTimeoutParam) {
connectionTimeout.setText(connectionTimeoutParam);
}
public String getConnectionTimeout() {
return connectionTimeout.getText();
}
public void setServer(String serverAddressParam) {
server.setText(serverAddressParam);
}
public String getServer() {
return server.getText();
}
public void setPort(String serverPortParam) {
port.setText(serverPortParam);
}
public String getPort() {
return port.getText();
}
public void setImplementation(String implementationParam) {
implementationComboBox.setSelectedItem(implementationParam);
}
public String getImplementation() {
return (String) implementationComboBox.getSelectedItem();
}
/**
* @return the attributePanel
*/
public ArgumentsPanel getAttributePanel() {
return attributePanel;
}
public ArgumentsPanel getPatternsPanel() {
return patternsPanel;
}
public void setCloseConnectionPattern(String closeConnectionPattern) {
closePattern.setText(closeConnectionPattern);
}
public String getCloseConnectionPattern() {
return closePattern.getText();
}
}
| |
/*
* 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.
*/
// From: http://www.halley.cc/code/?java/CSVReader.java
package com.intellij.execution.process.impl;
import com.intellij.util.ArrayUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
/**
* A very simple CSV reader released under a commercial-friendly license.
*
* @author Glen Smith
*
*/
class CSVReader {
private BufferedReader br;
private boolean hasNext = true;
private char separator;
private char quotechar;
private int skipLines;
private boolean linesSkiped;
/** The default separator to use if none is supplied to the constructor. */
public static final char DEFAULT_SEPARATOR = ',';
/**
* The default quote character to use if none is supplied to the
* constructor.
*/
public static final char DEFAULT_QUOTE_CHARACTER = '"';
/**
* The default line to start reading.
*/
public static final int DEFAULT_SKIP_LINES = 0;
/**
* Constructs CSVReader using a comma for the separator.
*
* @param reader
* the reader to an underlying CSV source.
*/
public CSVReader(Reader reader) {
this(reader, DEFAULT_SEPARATOR);
}
/**
* Constructs CSVReader with supplied separator.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries.
*/
public CSVReader(Reader reader, char separator) {
this(reader, separator, DEFAULT_QUOTE_CHARACTER);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
*/
public CSVReader(Reader reader, char separator, char quotechar) {
this(reader, separator, quotechar, DEFAULT_SKIP_LINES);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param line
* the line number to skip for start reading
*/
public CSVReader(Reader reader, char separator, char quotechar, int line) {
this.br = new BufferedReader(reader);
this.separator = separator;
this.quotechar = quotechar;
this.skipLines = line;
}
/**
* Reads the entire file into a List with each element being a String[] of
* tokens.
*
* @return a List of String[], with each String[] representing a line of the
* file.
*
* @throws IOException
* if bad things happen during the read
*/
public List<String[]> readAll() throws IOException {
List<String[]> allElements = new ArrayList<>();
while (hasNext) {
String[] nextLineAsTokens = readNext();
if (nextLineAsTokens != null) {
allElements.add(nextLineAsTokens);
}
}
return allElements;
}
/**
* Reads the next line from the buffer and converts to a string array.
*
* @return a string array with each comma-separated element as a separate
* entry.
*
* @throws IOException
* if bad things happen during the read
*/
public String[] readNext() throws IOException {
String nextLine = getNextLine();
return hasNext ? parseLine(nextLine) : null;
}
/**
* Reads the next line from the file.
*
* @return the next line from the file without trailing newline
* @throws IOException
* if bad things happen during the read
*/
private String getNextLine() throws IOException {
if (!this.linesSkiped) {
for (int i = 0; i < skipLines; i++) {
br.readLine();
}
this.linesSkiped = true;
}
String nextLine = br.readLine();
if (nextLine == null) {
hasNext = false;
}
return hasNext ? nextLine : null;
}
/**
* Parses an incoming String and returns an array of elements.
*
* @param nextLine
* the string to parse
* @return the comma-tokenized list of elements, or null if nextLine is null
* @throws IOException if bad things happen during the read
*/
public String[] parseLine(String nextLine) throws IOException {
if (nextLine == null) {
return null;
}
List<String> tokensOnThisLine = new ArrayList<>();
StringBuffer sb = new StringBuffer();
boolean inQuotes = false;
do {
if (inQuotes) {
// continuing a quoted section, reappend newline
sb.append("\n");
nextLine = getNextLine();
if (nextLine == null) {
break;
}
}
for (int i = 0; i < nextLine.length(); i++) {
char c = nextLine.charAt(i);
if (c == quotechar) {
// this gets complex... the quote may end a quoted block, or escape another quote.
// do a 1-char lookahead:
if (inQuotes // we are in quotes, therefore there can be escaped quotes in here.
&& nextLine.length() > (i + 1) // there is indeed another character to check.
&& nextLine.charAt(i + 1) == quotechar) { // ..and that char. is a quote also.
// we have two quote chars in a row == one quote char, so consume them both and
// put one on the token. we do *not* exit the quoted text.
sb.append(nextLine.charAt(i + 1));
i++;
} else {
inQuotes = !inQuotes;
// the tricky case of an embedded quote in the middle: a,bc"d"ef,g
if (i > 2 //not on the begining of the line
&& nextLine.charAt(i - 1) != this.separator //not at the begining of an escape sequence
&& nextLine.length() > (i + 1) &&
nextLine.charAt(i + 1) != this.separator //not at the end of an escape sequence
) {
sb.append(c);
}
}
} else if (c == separator && !inQuotes) {
tokensOnThisLine.add(sb.toString());
sb = new StringBuffer(); // start work on next token
} else {
sb.append(c);
}
}
} while (inQuotes);
tokensOnThisLine.add(sb.toString());
return ArrayUtil.toStringArray(tokensOnThisLine);
}
/**
* Closes the underlying reader.
*
* @throws IOException if the close fails
*/
public void close() throws IOException {
br.close();
}
}
| |
/*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.http;
import com.netflix.client.netty.LoadBalancingRxClient;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixObservableCommand;
import com.netflix.hystrix.HystrixObservableCommand.Setter;
import com.netflix.ribbon.CacheProvider;
import com.netflix.ribbon.RequestTemplate;
import com.netflix.ribbon.ResourceGroup.TemplateBuilder;
import com.netflix.ribbon.ResponseValidator;
import com.netflix.ribbon.hystrix.FallbackHandler;
import com.netflix.ribbon.template.ParsedTemplate;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.reactivex.netty.protocol.http.client.HttpClient;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import java.util.HashMap;
import java.util.Map;
/**
* Provides API to construct a request template for HTTP resource.
* <p>
* <b>Note:</b> This class is not thread safe. It is advised that the template is created and
* constructed in same thread at initialization of the application. Users can call {@link #requestBuilder()}
* later on which returns a {@link RequestBuilder} which is thread safe.
*
* @author Allen Wang
*
* @param <T> Type for the return Object of the Http resource
*/
public class HttpRequestTemplate<T> extends RequestTemplate<T, HttpClientResponse<ByteBuf>> {
public static final String CACHE_HYSTRIX_COMMAND_SUFFIX = "_cache";
public static final int DEFAULT_CACHE_TIMEOUT = 20;
public static class Builder<T> extends TemplateBuilder<T, HttpClientResponse<ByteBuf>, HttpRequestTemplate<T>> {
private String name;
private HttpResourceGroup resourceGroup;
private Class<? extends T> classType;
private FallbackHandler<T> fallbackHandler;
private HttpMethod method;
private ParsedTemplate parsedUriTemplate;
private ParsedTemplate cacheKeyTemplate;
private CacheProviderWithKeyTemplate<T> cacheProvider;
private HttpHeaders headers;
private Setter setter;
private Map<String, ParsedTemplate> parsedTemplates;
private ResponseValidator<HttpClientResponse<ByteBuf>> validator;
private Builder(String name, HttpResourceGroup resourceGroup, Class<? extends T> classType) {
this.name = name;
this.resourceGroup = resourceGroup;
this.classType = classType;
headers = new DefaultHttpHeaders();
headers.add(resourceGroup.getHeaders());
parsedTemplates = new HashMap<String, ParsedTemplate>();
}
private ParsedTemplate createParsedTemplate(String template) {
ParsedTemplate parsedTemplate = parsedTemplates.get(template);
if (parsedTemplate == null) {
parsedTemplate = ParsedTemplate.create(template);
parsedTemplates.put(template, parsedTemplate);
}
return parsedTemplate;
}
public static <T> Builder<T> newBuilder(String templateName, HttpResourceGroup group, Class<? extends T> classType) {
return new Builder(templateName, group, classType);
}
@Override
public Builder<T> withFallbackProvider(FallbackHandler<T> fallbackHandler) {
this.fallbackHandler = fallbackHandler;
return this;
}
@Override
public Builder<T> withResponseValidator(ResponseValidator<HttpClientResponse<ByteBuf>> validator) {
this.validator = validator;
return this;
}
public Builder<T> withMethod(String method) {
this.method = HttpMethod.valueOf(method);
return this;
}
public Builder<T> withUriTemplate(String uriTemplate) {
this.parsedUriTemplate = createParsedTemplate(uriTemplate);
return this;
}
@Override
public Builder<T> withRequestCacheKey(String cacheKeyTemplate) {
this.cacheKeyTemplate = createParsedTemplate(cacheKeyTemplate);
return this;
}
@Override
public Builder<T> withCacheProvider(String keyTemplate, CacheProvider<T> cacheProvider) {
ParsedTemplate template = createParsedTemplate(keyTemplate);
this.cacheProvider = new CacheProviderWithKeyTemplate<T>(template, cacheProvider);
return this;
}
public Builder<T> withHeader(String name, String value) {
headers.add(name, value);
return this;
}
@Override
public Builder<T> withHystrixProperties(
Setter propertiesSetter) {
this.setter = propertiesSetter;
return this;
}
public HttpRequestTemplate<T> build() {
return new HttpRequestTemplate<T>(name, resourceGroup, classType, setter, method, headers, parsedUriTemplate, fallbackHandler, validator, cacheProvider, cacheKeyTemplate);
}
}
private final HttpClient<ByteBuf, ByteBuf> client;
private final int maxResponseTime;
private final HystrixObservableCommand.Setter setter;
private final HystrixObservableCommand.Setter cacheSetter;
private final FallbackHandler<T> fallbackHandler;
private final ParsedTemplate parsedUriTemplate;
private final ResponseValidator<HttpClientResponse<ByteBuf>> validator;
private final HttpMethod method;
private final String name;
private final CacheProviderWithKeyTemplate<T> cacheProvider;
private final ParsedTemplate hystrixCacheKeyTemplate;
private final Class<? extends T> classType;
private final int concurrentRequestLimit;
private final HttpHeaders headers;
private final HttpResourceGroup group;
public static class CacheProviderWithKeyTemplate<T> {
private final ParsedTemplate keyTemplate;
private final CacheProvider<T> provider;
public CacheProviderWithKeyTemplate(ParsedTemplate keyTemplate,
CacheProvider<T> provider) {
this.keyTemplate = keyTemplate;
this.provider = provider;
}
public final ParsedTemplate getKeyTemplate() {
return keyTemplate;
}
public final CacheProvider<T> getProvider() {
return provider;
}
}
protected HttpRequestTemplate(String name, HttpResourceGroup group, Class<? extends T> classType, HystrixObservableCommand.Setter setter,
HttpMethod method, HttpHeaders headers, ParsedTemplate uriTemplate,
FallbackHandler<T> fallbackHandler, ResponseValidator<HttpClientResponse<ByteBuf>> validator, CacheProviderWithKeyTemplate<T> cacheProvider,
ParsedTemplate hystrixCacheKeyTemplate) {
this.group = group;
this.name = name;
this.classType = classType;
this.method = method;
this.parsedUriTemplate = uriTemplate;
this.fallbackHandler = fallbackHandler;
this.validator = validator;
this.cacheProvider = cacheProvider;
this.hystrixCacheKeyTemplate = hystrixCacheKeyTemplate;
this.client = group.getClient();
this.headers = headers;
if (client instanceof LoadBalancingRxClient) {
LoadBalancingRxClient ribbonClient = (LoadBalancingRxClient) client;
maxResponseTime = ribbonClient.getResponseTimeOut();
concurrentRequestLimit = ribbonClient.getMaxConcurrentRequests();
} else {
maxResponseTime = -1;
concurrentRequestLimit = -1;
}
String cacheName = name + CACHE_HYSTRIX_COMMAND_SUFFIX;
cacheSetter = HystrixObservableCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(cacheName))
.andCommandKey(HystrixCommandKey.Factory.asKey(cacheName));
HystrixCommandProperties.Setter cacheCommandProps = HystrixCommandProperties.Setter();
cacheCommandProps.withExecutionIsolationThreadTimeoutInMilliseconds(DEFAULT_CACHE_TIMEOUT);
cacheSetter.andCommandPropertiesDefaults(cacheCommandProps);
if (setter != null) {
this.setter = setter;
} else {
this.setter = HystrixObservableCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(client.name()))
.andCommandKey(HystrixCommandKey.Factory.asKey(name()));
HystrixCommandProperties.Setter commandProps = HystrixCommandProperties.Setter();
if (maxResponseTime > 0) {
commandProps.withExecutionIsolationThreadTimeoutInMilliseconds(maxResponseTime);
}
if (concurrentRequestLimit > 0) {
commandProps.withExecutionIsolationSemaphoreMaxConcurrentRequests(concurrentRequestLimit);
}
this.setter.andCommandPropertiesDefaults(commandProps);
}
}
@Override
public HttpRequestBuilder<T> requestBuilder() {
return new HttpRequestBuilder<T>(this);
}
protected final ParsedTemplate hystrixCacheKeyTemplate() {
return hystrixCacheKeyTemplate;
}
protected final CacheProviderWithKeyTemplate<T> cacheProvider() {
return cacheProvider;
}
protected final ResponseValidator<HttpClientResponse<ByteBuf>> responseValidator() {
return validator;
}
protected final FallbackHandler<T> fallbackHandler() {
return fallbackHandler;
}
protected final ParsedTemplate uriTemplate() {
return parsedUriTemplate;
}
protected final HttpMethod method() {
return method;
}
protected final Class<? extends T> getClassType() {
return this.classType;
}
protected final HttpHeaders getHeaders() {
return this.headers;
}
@Override
public String name() {
return name;
}
@Override
public HttpRequestTemplate<T> copy(String name) {
HttpRequestTemplate<T> newTemplate = new HttpRequestTemplate<T>(name, group, classType, setter, method, headers, parsedUriTemplate, fallbackHandler, validator, cacheProvider, hystrixCacheKeyTemplate);
return newTemplate;
}
protected final Setter hystrixProperties() {
return this.setter;
}
protected final Setter cacheHystrixProperties() {
return cacheSetter;
}
protected final HttpClient<ByteBuf, ByteBuf> getClient() {
return this.client;
}
}
| |
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://duracloud.org/license/
*/
package org.duracloud.account.app.controller;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.duracloud.account.app.controller.GroupsForm.Action;
import org.duracloud.account.db.model.DuracloudGroup;
import org.duracloud.account.db.model.DuracloudUser;
import org.duracloud.account.db.util.DuracloudGroupService;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.validation.BindingResult;
/**
* @author Daniel Bernstein
* Date: Nov 12, 2011
*/
public class AccountGroupsControllerTest extends AmaControllerTestBase {
private static final String TEST_GROUP_NAME = "test";
private AccountGroupsController accountGroupsController;
private DuracloudGroupService groupService;
private Long accountId = AmaControllerTestBase.TEST_ACCOUNT_ID;
@Before
public void before() throws Exception {
super.before();
groupService =
createMock(DuracloudGroupService.class);
accountGroupsController = new AccountGroupsController();
accountGroupsController.setAccountManagerService(accountManagerService);
accountGroupsController.setUserService(userService);
accountGroupsController.setDuracloudGroupService(groupService);
result = null;
setupGenericAccountAndUserServiceMocks(accountId);
}
private Set<DuracloudGroup> createGroups() {
Long groupId = 2L;
String groupName = DuracloudGroup.PREFIX + TEST_GROUP_NAME;
DuracloudGroup group = createGroup(groupId, groupName, accountId);
group.setUsers(new HashSet<DuracloudUser>());
group.getUsers().add(createUser());
Set<DuracloudGroup> set = new HashSet<DuracloudGroup>();
set.add(group);
return set;
}
@Test
public void testGetGroups() throws Exception {
expectGroupGroups(1);
replayMocks();
String view = this.accountGroupsController.getGroups(accountId, model);
Assert.assertEquals(AccountGroupsController.GROUPS_VIEW_ID, view);
}
private void expectGroupGroups(int times) {
EasyMock.expect(groupService.getGroups(accountId))
.andReturn(createGroups())
.times(times);
}
@Test
public void testGetGroupsAddGroup() throws Exception {
Long groupId = 3L;
String groupName = DuracloudGroup.PREFIX + "group2";
DuracloudGroup group = createGroup(groupId, groupName, accountId);
EasyMock.expect(groupService.createGroup(
DuracloudGroup.PREFIX + groupName, accountId)).andReturn(group);
result = EasyMock.createMock("BindingResult", BindingResult.class);
EasyMock.expect(result.hasFieldErrors()).andReturn(false);
replayMocks();
GroupsForm form = new GroupsForm();
form.setAction(Action.ADD);
form.setGroupName(groupName);
String view = this.accountGroupsController.modifyGroups(accountId,
model,
form,
result);
Assert.assertTrue(view.contains(groupName));
}
@Test
public void testGetGroupsRemoveGroups() throws Exception {
expectGroupGroups(1);
DuracloudGroup group = createGroups().iterator().next();
groupService.deleteGroup(group, accountId);
EasyMock.expectLastCall().once();
EasyMock.expect(groupService.getGroup(group.getName(), accountId))
.andReturn(group)
.once();
replayMocks();
GroupsForm form = new GroupsForm();
form.setAction(Action.REMOVE);
form.setGroupNames(new String[] {DuracloudGroup.PREFIX + TEST_GROUP_NAME});
String view = this.accountGroupsController.modifyGroups(accountId,
model,
form,
result);
Assert.assertEquals(AccountGroupsController.GROUPS_VIEW_ID, view);
}
private Object getModelAttribute(String name) {
return model.asMap().get(name);
}
@Test
public void testGetGroup() throws Exception {
expectGroupGroups(1);
replayMocks();
String view =
this.accountGroupsController.getGroup(accountId,
DuracloudGroup.PREFIX + TEST_GROUP_NAME,
model);
Assert.assertEquals(AccountGroupsController.GROUP_VIEW_ID, view);
Assert.assertNotNull(getModelAttribute(AccountGroupsController.GROUP_KEY));
Assert.assertNotNull(getModelAttribute(AccountGroupsController.GROUP_USERS_KEY));
}
@Test
public void testGetGroupEdit() throws Exception {
expectGroupGroups(1);
HttpServletRequest request =
EasyMock.createMock(HttpServletRequest.class);
HttpSession session = EasyMock.createMock(HttpSession.class);
EasyMock.expect(request.getSession()).andReturn(session).once();
session.removeAttribute(AccountGroupsController.GROUP_USERS_KEY);
EasyMock.expectLastCall().once();
EasyMock.expect(session.getAttribute(AccountGroupsController.GROUP_USERS_KEY))
.andReturn(null)
.once();
session.setAttribute(EasyMock.anyObject(String.class),
(Collection<DuracloudUser>) EasyMock.anyObject());
EasyMock.expectLastCall().once();
EasyMock.replay(request, session);
replayMocks();
String view =
this.accountGroupsController.editGroup(accountId,
DuracloudGroup.PREFIX + TEST_GROUP_NAME,
request,
model);
Assert.assertEquals(AccountGroupsController.GROUP_EDIT_VIEW_ID, view);
Assert.assertNotNull(getModelAttribute(AccountGroupsController.GROUP_KEY));
Assert.assertNotNull(getModelAttribute(AccountGroupsController.GROUP_USERS_KEY));
Assert.assertNotNull(getModelAttribute(AccountGroupsController.AVAILABLE_USERS_KEY));
}
@Test
public void testSaveGroup() throws Exception {
expectGroupGroups(1);
HttpServletRequest request =
EasyMock.createMock(HttpServletRequest.class);
HttpSession session = EasyMock.createMock(HttpSession.class);
EasyMock.expect(request.getSession()).andReturn(session).once();
session.removeAttribute(AccountGroupsController.GROUP_USERS_KEY);
EasyMock.expectLastCall().once();
EasyMock.expect(session.getAttribute(AccountGroupsController.GROUP_USERS_KEY))
.andReturn(null)
.once();
session.setAttribute(EasyMock.anyObject(String.class),
(Collection<DuracloudUser>) EasyMock.anyObject());
EasyMock.expectLastCall().once();
this.groupService
.updateGroupUsers(EasyMock.anyObject(DuracloudGroup.class),
(Set<DuracloudUser>) EasyMock.anyObject(),
EasyMock.anyLong());
EasyMock.expectLastCall().once();
EasyMock.replay(request, session);
replayMocks();
GroupForm form = new GroupForm();
form.setAction(GroupForm.Action.SAVE);
String view =
this.accountGroupsController.editGroup(accountId,
DuracloudGroup.PREFIX + TEST_GROUP_NAME,
form,
request,
model);
Assert.assertTrue(view.contains(TEST_GROUP_NAME));
Assert.assertFalse(view.endsWith("edit"));
Assert.assertNotNull(getModelAttribute(AccountGroupsController.GROUP_KEY));
Assert.assertNotNull(getModelAttribute(AccountGroupsController.GROUP_USERS_KEY));
}
@Test
public void testAddRemoveUser() throws Exception {
expectGroupGroups(2);
HttpServletRequest request =
EasyMock.createMock(HttpServletRequest.class);
HttpSession session = EasyMock.createMock(HttpSession.class);
EasyMock.expect(request.getSession()).andReturn(session).anyTimes();
List<DuracloudUser> groupUsers =
new LinkedList<DuracloudUser>(Arrays.asList(new DuracloudUser[] {createUser()}));
EasyMock.expect(session.getAttribute(AccountGroupsController.GROUP_USERS_KEY))
.andReturn(groupUsers)
.once();
EasyMock.expect(session.getAttribute(AccountGroupsController.GROUP_USERS_KEY))
.andReturn(groupUsers)
.once();
session.setAttribute(EasyMock.anyObject(String.class),
(Collection<DuracloudUser>) EasyMock.anyObject());
EasyMock.expectLastCall().once();
EasyMock.replay(request, session);
replayMocks();
String testUsername = groupUsers.get(0).getUsername();
GroupForm form = new GroupForm();
form.setAction(GroupForm.Action.REMOVE);
form.setGroupUsernames(new String[] {testUsername});
String view =
this.accountGroupsController.editGroup(accountId,
DuracloudGroup.PREFIX + TEST_GROUP_NAME,
form,
request,
model);
Assert.assertEquals(AccountGroupsController.GROUP_EDIT_VIEW_ID, view);
Assert.assertEquals(1,
getModelAttributeSize(AccountGroupsController.AVAILABLE_USERS_KEY));
Assert.assertEquals(0,
getModelAttributeSize(AccountGroupsController.GROUP_USERS_KEY));
form = new GroupForm();
form.setAction(GroupForm.Action.ADD);
form.setAvailableUsernames(new String[] {testUsername});
this.accountGroupsController.editGroup(accountId,
DuracloudGroup.PREFIX + TEST_GROUP_NAME,
form,
request,
model);
Assert.assertEquals(AccountGroupsController.GROUP_EDIT_VIEW_ID, view);
Assert.assertEquals(0,
getModelAttributeSize(AccountGroupsController.AVAILABLE_USERS_KEY));
Assert.assertEquals(1,
getModelAttributeSize(AccountGroupsController.GROUP_USERS_KEY));
}
@SuppressWarnings("unchecked")
private int getModelAttributeSize(String name) {
return ((Collection<? extends Object>) getModelAttribute(name)).size();
}
private DuracloudGroup createGroup(Long groupId, String groupName, Long accountId) {
DuracloudGroup group = new DuracloudGroup();
group.setId(groupId);
group.setName(groupName);
group.setAccount(createAccountInfo(accountId));
return group;
}
}
| |
package com.youtube.vitess.client;
import static org.junit.Assert.assertEquals;
import com.google.common.primitives.UnsignedLong;
import com.google.protobuf.ByteString;
import com.youtube.vitess.proto.Query;
import com.youtube.vitess.proto.Query.BindVariable;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection;
@RunWith(value = Parameterized.class)
public class BindVarTest {
private Object input;
private BindVariable expected;
@Parameters
public static Collection<Object[]> testParams() {
Object[][] params = {
// SQL NULL
{null, BindVariable.newBuilder().setType(Query.Type.NULL_TYPE).build()},
// String
{
"hello world",
BindVariable.newBuilder()
.setType(Query.Type.VARCHAR)
.setValue(ByteString.copyFromUtf8("hello world"))
.build()
},
// Bytes
{
new byte[] {1, 2, 3},
BindVariable.newBuilder()
.setType(Query.Type.VARBINARY)
.setValue(ByteString.copyFrom(new byte[] {1, 2, 3}))
.build()
},
// Int
{
123,
BindVariable.newBuilder()
.setType(Query.Type.INT64)
.setValue(ByteString.copyFromUtf8("123"))
.build()
},
{
123L,
BindVariable.newBuilder()
.setType(Query.Type.INT64)
.setValue(ByteString.copyFromUtf8("123"))
.build()
},
{
(short) 1,
BindVariable.newBuilder()
.setType(Query.Type.INT64)
.setValue(ByteString.copyFromUtf8("1"))
.build()
},
{
(byte) 2,
BindVariable.newBuilder()
.setType(Query.Type.INT64)
.setValue(ByteString.copyFromUtf8("2"))
.build()
},
// Uint
{
UnsignedLong.fromLongBits(-1),
BindVariable.newBuilder()
.setType(Query.Type.UINT64)
.setValue(ByteString.copyFromUtf8("18446744073709551615"))
.build()
},
// Float
{
1.23f,
BindVariable.newBuilder()
.setType(Query.Type.FLOAT64)
.setValue(ByteString.copyFromUtf8("1.23"))
.build()
},
{
1.23,
BindVariable.newBuilder()
.setType(Query.Type.FLOAT64)
.setValue(ByteString.copyFromUtf8("1.23"))
.build()
},
// List of Bytes
{
Arrays.asList(new byte[] {1, 2, 3}, new byte[] {4, 5, 6}),
BindVariable.newBuilder()
.setType(Query.Type.TUPLE)
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.VARBINARY)
.setValue(ByteString.copyFrom(new byte[] {1, 2, 3}))
.build())
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.VARBINARY)
.setValue(ByteString.copyFrom(new byte[] {4, 5, 6}))
.build())
.build()
},
// Boolean
{
true,
BindVariable.newBuilder()
.setType(Query.Type.INT64)
.setValue(ByteString.copyFromUtf8("1"))
.build()
},
{
false,
BindVariable.newBuilder()
.setType(Query.Type.INT64)
.setValue(ByteString.copyFromUtf8("0"))
.build()
},
// BigDecimal: Check simple case. Note that BigDecimal.valueOf(0.23) is different from
// new BigDecimal(0.23). The latter will create a number with large scale due to floating
// point conversion artifacts.
{
BigDecimal.valueOf(0.23),
BindVariable.newBuilder()
.setType(Query.Type.DECIMAL)
.setValue(ByteString.copyFromUtf8("0.23"))
.build()
},
// BigDecimal: Check we don't mess with scale unnecessarily (don't add extra zeros).
{
new BigDecimal("123.123456789"),
BindVariable.newBuilder()
.setType(Query.Type.DECIMAL)
.setValue(ByteString.copyFromUtf8("123.123456789"))
.build()
},
// BigDecimal: Check round down when scale > 30 (MySQL max).
{
new BigDecimal("123.1999999999999999999999999999994"),
BindVariable.newBuilder()
.setType(Query.Type.DECIMAL)
.setValue(ByteString.copyFromUtf8("123.199999999999999999999999999999"))
.build()
},
// BigDecimal: Check round up when scale > 30 (MySQL max).
{
new BigDecimal("123.1999999999999999999999999999995"),
BindVariable.newBuilder()
.setType(Query.Type.DECIMAL)
.setValue(ByteString.copyFromUtf8("123.200000000000000000000000000000"))
.build()
},
// BigDecimal: Check that we DO NOT revert to scientific notation (e.g. "1.23E-10"),
// because MySQL will interpret that as an *approximate* DOUBLE value, rather than
// as an *exact* DECIMAL value:
// http://dev.mysql.com/doc/refman/5.6/en/precision-math-numbers.html
{
new BigDecimal("0.000000000123456789123456789"),
BindVariable.newBuilder()
.setType(Query.Type.DECIMAL)
.setValue(ByteString.copyFromUtf8("0.000000000123456789123456789"))
.build()
},
// List of Int
{
Arrays.asList(1, 2, 3),
BindVariable.newBuilder()
.setType(Query.Type.TUPLE)
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.INT64)
.setValue(ByteString.copyFromUtf8("1"))
.build())
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.INT64)
.setValue(ByteString.copyFromUtf8("2"))
.build())
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.INT64)
.setValue(ByteString.copyFromUtf8("3"))
.build())
.build()
},
{
Arrays.asList(1L, 2L, 3L),
BindVariable.newBuilder()
.setType(Query.Type.TUPLE)
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.INT64)
.setValue(ByteString.copyFromUtf8("1"))
.build())
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.INT64)
.setValue(ByteString.copyFromUtf8("2"))
.build())
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.INT64)
.setValue(ByteString.copyFromUtf8("3"))
.build())
.build()
},
// List of Uint
{
Arrays.asList(
UnsignedLong.fromLongBits(1),
UnsignedLong.fromLongBits(2),
UnsignedLong.fromLongBits(3)),
BindVariable.newBuilder()
.setType(Query.Type.TUPLE)
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.UINT64)
.setValue(ByteString.copyFromUtf8("1"))
.build())
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.UINT64)
.setValue(ByteString.copyFromUtf8("2"))
.build())
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.UINT64)
.setValue(ByteString.copyFromUtf8("3"))
.build())
.build()
},
// List of Float
{
Arrays.asList(1.2f, 3.4f, 5.6f),
BindVariable.newBuilder()
.setType(Query.Type.TUPLE)
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.FLOAT64)
.setValue(ByteString.copyFromUtf8("1.2"))
.build())
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.FLOAT64)
.setValue(ByteString.copyFromUtf8("3.4"))
.build())
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.FLOAT64)
.setValue(ByteString.copyFromUtf8("5.6"))
.build())
.build()
},
{
Arrays.asList(1.2, 3.4, 5.6),
BindVariable.newBuilder()
.setType(Query.Type.TUPLE)
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.FLOAT64)
.setValue(ByteString.copyFromUtf8("1.2"))
.build())
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.FLOAT64)
.setValue(ByteString.copyFromUtf8("3.4"))
.build())
.addValues(
Query.Value.newBuilder()
.setType(Query.Type.FLOAT64)
.setValue(ByteString.copyFromUtf8("5.6"))
.build())
.build()
}
};
return Arrays.asList(params);
}
public BindVarTest(Object input, BindVariable expected) {
this.input = input;
this.expected = expected;
}
@Test
public void testBuildBindVariable() {
assertEquals(expected, Proto.buildBindVariable(input));
}
}
| |
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package com.google.crypto.tink.subtle;
import static java.lang.Math.min;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.Arrays;
/**
* An instance of a InputStream that returns the plaintext for some ciphertext.
*
* <p>TODO(bleichen): define what the state is after an IOException.
*/
class StreamingAeadDecryptingStream extends FilterInputStream {
// Each plaintext segment has 16 bytes more of memory than the actual plaintext that it contains.
// This is a workaround for an incompatibility between Conscrypt and OpenJDK in their
// AES-GCM implementations, see b/67416642, b/31574439, and cr/170969008 for more information.
// Conscrypt refused to fix this issue, but even if they fixed it, there are always Android phones
// running old versions of Conscrypt, so we decided to take matters into our own hands.
// Why 16? Actually any number larger than 16 should work. 16 is the lower bound because it's the
// size of the tags of each AES-GCM ciphertext segment.
private static final int PLAINTEXT_SEGMENT_EXTRA_SIZE = 16;
/**
* A buffer containing ciphertext that has not yet been decrypted. The limit of ciphertextSegment
* is set such that it can contain segment plus the first character of the next segment. It is
* necessary to read a segment plus one more byte to decrypt a segment, since the last segment of
* a ciphertext is encrypted differently.
*/
private final ByteBuffer ciphertextSegment;
/**
* A buffer containing a plaintext segment. The bytes in the range plaintexSegment.position() ..
* plaintextSegment.limit() - 1 are plaintext that have been decrypted but not yet read out of
* AesGcmInputStream.
*/
private final ByteBuffer plaintextSegment;
/* Header information */
private final int headerLength;
private boolean headerRead;
/* Indicates whether the end of this InputStream has been reached. */
private boolean endOfCiphertext;
/* Indicates whether the end of the plaintext has been reached. */
private boolean endOfPlaintext;
/* Indicates whether a decyrption error has occured. */
private boolean decryptionErrorOccured;
/** The additional data that is authenticated with the ciphertext. */
private final byte[] aad;
/** The number of the current segment of ciphertext buffered in ciphertexSegment. */
private int segmentNr;
private final StreamSegmentDecrypter decrypter;
private final int ciphertextSegmentSize;
private final int firstCiphertextSegmentSize;
public StreamingAeadDecryptingStream(
NonceBasedStreamingAead streamAead, InputStream ciphertextStream, byte[] associatedData)
throws GeneralSecurityException, IOException {
super(ciphertextStream);
decrypter = streamAead.newStreamSegmentDecrypter();
headerLength = streamAead.getHeaderLength();
aad = Arrays.copyOf(associatedData, associatedData.length);
// ciphertextSegment is one byte longer than a ciphertext segment,
// so that the code can decide if the current segment is the last segment in the
// stream.
ciphertextSegmentSize = streamAead.getCiphertextSegmentSize();
ciphertextSegment = ByteBuffer.allocate(ciphertextSegmentSize + 1);
ciphertextSegment.limit(0);
firstCiphertextSegmentSize = ciphertextSegmentSize - streamAead.getCiphertextOffset();
plaintextSegment = ByteBuffer.allocate(streamAead.getPlaintextSegmentSize()
+ PLAINTEXT_SEGMENT_EXTRA_SIZE);
plaintextSegment.limit(0);
headerRead = false;
endOfCiphertext = false;
endOfPlaintext = false;
segmentNr = 0;
decryptionErrorOccured = false;
}
/**
* Reads the header of the ciphertext and sets headerRead = true.
*
* @throws IOException when an exception occurs while reading from {@code in} or when the header
* is too short.
*/
private void readHeader() throws IOException {
if (headerRead) {
setDecryptionErrorOccured();
throw new IOException("Decryption failed.");
}
ByteBuffer header = ByteBuffer.allocate(headerLength);
while (header.remaining() > 0) {
int read = in.read(header.array(), header.position(), header.remaining());
if (read == -1) {
setDecryptionErrorOccured();
throw new IOException("Ciphertext is too short");
}
if (read == 0) {
throw new IOException("Could not read bytes from the ciphertext stream");
}
header.position(header.position() + read);
}
header.flip();
try {
decrypter.init(header, aad);
} catch (GeneralSecurityException ex) {
throw new IOException(ex);
}
headerRead = true;
}
private void setDecryptionErrorOccured() {
decryptionErrorOccured = true;
plaintextSegment.limit(0);
}
/** Loads the next plaintext segment. */
private void loadSegment() throws IOException {
// Try filling the ciphertextSegment
while (!endOfCiphertext && ciphertextSegment.remaining() > 0) {
int read =
in.read(
ciphertextSegment.array(),
ciphertextSegment.position(),
ciphertextSegment.remaining());
if (read > 0) {
ciphertextSegment.position(ciphertextSegment.position() + read);
} else if (read == -1) {
endOfCiphertext = true;
} else if (read == 0) {
// We expect that read returns at least one byte.
throw new IOException("Could not read bytes from the ciphertext stream");
}
}
byte lastByte = 0;
if (!endOfCiphertext) {
lastByte = ciphertextSegment.get(ciphertextSegment.position() - 1);
ciphertextSegment.position(ciphertextSegment.position() - 1);
}
ciphertextSegment.flip();
plaintextSegment.clear();
try {
decrypter.decryptSegment(ciphertextSegment, segmentNr, endOfCiphertext, plaintextSegment);
} catch (GeneralSecurityException ex) {
// The current segment did not validate.
// Currently this means that decryption cannot resume.
setDecryptionErrorOccured();
throw new IOException(
ex.getMessage()
+ "\n"
+ toString()
+ "\nsegmentNr:"
+ segmentNr
+ " endOfCiphertext:"
+ endOfCiphertext,
ex);
}
segmentNr += 1;
plaintextSegment.flip();
ciphertextSegment.clear();
if (!endOfCiphertext) {
ciphertextSegment.clear();
ciphertextSegment.limit(ciphertextSegmentSize + 1);
ciphertextSegment.put(lastByte);
}
}
@Override
public int read() throws IOException {
byte[] oneByte = new byte[1];
int ret = read(oneByte, 0, 1);
if (ret == 1) {
return oneByte[0] & 0xff;
} else if (ret == -1) {
return ret;
} else {
throw new IOException("Reading failed");
}
}
@Override
public int read(byte[] dst) throws IOException {
return read(dst, 0, dst.length);
}
@Override
public synchronized int read(byte[] dst, int offset, int length) throws IOException {
if (decryptionErrorOccured) {
throw new IOException("Decryption failed.");
}
if (!headerRead) {
readHeader();
ciphertextSegment.clear();
ciphertextSegment.limit(firstCiphertextSegmentSize + 1);
}
if (endOfPlaintext) {
return -1;
}
int bytesRead = 0;
while (bytesRead < length) {
if (plaintextSegment.remaining() == 0) {
if (endOfCiphertext) {
endOfPlaintext = true;
break;
}
loadSegment();
}
int sliceSize = min(plaintextSegment.remaining(), length - bytesRead);
plaintextSegment.get(dst, bytesRead + offset, sliceSize);
bytesRead += sliceSize;
}
if (bytesRead == 0 && endOfPlaintext) {
return -1;
} else {
return bytesRead;
}
}
@Override
public synchronized void close() throws IOException {
super.close();
}
@Override
public synchronized int available() {
return plaintextSegment.remaining();
}
@Override
public synchronized void mark(int readlimit) {
// Mark is not supported.
}
@Override
public boolean markSupported() {
return false;
}
/**
* Skips over and discards <code>n</code> bytes of plaintext from the input stream. The
* implementation reads and decrypts the plaintext that is skipped. Hence skipping a large number
* of bytes is slow.
*
* <p>Returns the number of bytes skipped. This number can be smaller than the number of bytes
* requested. This can happend for a number of reasons: e.g., this happens when the underlying
* stream is non-blocking and not enough bytes are available or when the stream reaches the end of
* the stream.
*
* @throws IOException when an exception occurs while reading from {@code in} or when the
* ciphertext is corrupt. Currently all corrupt ciphertext will be detected. However this
* behaviour may change.
*/
@Override
public long skip(long n) throws IOException {
long maxSkipBufferSize = ciphertextSegmentSize;
long remaining = n;
if (n <= 0) {
return 0;
}
int size = (int) min(maxSkipBufferSize, remaining);
byte[] skipBuffer = new byte[size];
while (remaining > 0) {
int bytesRead = read(skipBuffer, 0, (int) min(size, remaining));
if (bytesRead <= 0) {
break;
}
remaining -= bytesRead;
}
return n - remaining;
}
/* Returns the state of the channel. */
@Override
public synchronized String toString() {
StringBuilder res = new StringBuilder();
res.append("StreamingAeadDecryptingStream")
.append("\nsegmentNr:")
.append(segmentNr)
.append("\nciphertextSegmentSize:")
.append(ciphertextSegmentSize)
.append("\nheaderRead:")
.append(headerRead)
.append("\nendOfCiphertext:")
.append(endOfCiphertext)
.append("\nendOfPlaintext:")
.append(endOfPlaintext)
.append("\ndecryptionErrorOccured:")
.append(decryptionErrorOccured)
.append("\nciphertextSgement")
.append(" position:")
.append(ciphertextSegment.position())
.append(" limit:")
.append(ciphertextSegment.limit())
.append("\nplaintextSegment")
.append(" position:")
.append(plaintextSegment.position())
.append(" limit:")
.append(plaintextSegment.limit());
return res.toString();
}
}
| |
package soot.jimple.infoflow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Central configuration class for FlowDroid
*
* @author Steven Arzt
*
*/
public class InfoflowConfiguration {
protected final Logger logger = LoggerFactory.getLogger(getClass());
/**
* Enumeration containing the callgraph algorithms supported for the use with
* the data flow tracker
*/
public enum CallgraphAlgorithm {
AutomaticSelection,
CHA,
VTA,
RTA,
SPARK,
GEOM,
OnDemand
}
/**
* Enumeration containing the aliasing algorithms supported by FlowDroid
*/
public enum AliasingAlgorithm {
/**
* A fully flow-sensitive algorithm based on Andromeda
*/
FlowSensitive,
/**
* A flow-insensitive algorithm based on Soot's point-to-sets
*/
PtsBased
}
/**
* Enumeration containing all possible modes of dead and irrelevant code
* elimination
*/
public enum CodeEliminationMode {
/**
* Do not perform any code elimination before running the taint analysis
*/
NoCodeElimination,
/**
* Perform an inter-procedural constant propagation and folding and then
* remove all code that is unreachable
*/
PropagateConstants,
/**
* In addition to the inter-procedural constant propagation and folding,
* also remove live code that cannot potentially influence the outcome
* of the taint analysis
*/
RemoveSideEffectFreeCode
}
private static int accessPathLength = 5;
private static boolean useRecursiveAccessPaths = true;
private static boolean useThisChainReduction = true;
private static boolean pathAgnosticResults = true;
private static boolean oneResultPerAccessPath = false;
private static boolean mergeNeighbors = false;
private static boolean useTypeTightening = true;
private boolean stopAfterFirstFlow = false;
private boolean enableImplicitFlows = false;
private boolean enableStaticFields = true;
private boolean enableExceptions = true;
private boolean enableArraySizeTainting = true;
private boolean flowSensitiveAliasing = true;
private boolean enableTypeChecking = true;
private boolean ignoreFlowsInSystemPackages = true;
private int maxThreadNum = -1;
private boolean writeOutputFiles = false;
private boolean logSourcesAndSinks = false;
private boolean inspectSources = false;
private boolean inspectSinks = false;
private CallgraphAlgorithm callgraphAlgorithm = CallgraphAlgorithm.AutomaticSelection;
private AliasingAlgorithm aliasingAlgorithm = AliasingAlgorithm.FlowSensitive;
private CodeEliminationMode codeEliminationMode = CodeEliminationMode.PropagateConstants;
private boolean taintAnalysisEnabled = true;
/**
* Merges the given configuration options into this configuration object
* @param config The configuration data to merge in
*/
public void merge(InfoflowConfiguration config) {
this.stopAfterFirstFlow = config.stopAfterFirstFlow;
this.enableImplicitFlows = config.enableImplicitFlows;
this.enableStaticFields = config.enableStaticFields;
this.enableExceptions = config.enableExceptions;
this.enableArraySizeTainting = config.enableArraySizeTainting;
this.flowSensitiveAliasing = config.flowSensitiveAliasing;
this.enableTypeChecking = config.enableTypeChecking;
this.ignoreFlowsInSystemPackages = config.ignoreFlowsInSystemPackages;
this.maxThreadNum = config.maxThreadNum;
this.inspectSources = config.inspectSources;
this.inspectSinks = config.inspectSinks;
this.callgraphAlgorithm = config.callgraphAlgorithm;
this.aliasingAlgorithm = config.aliasingAlgorithm;
this.codeEliminationMode = config.codeEliminationMode;
this.logSourcesAndSinks = config.logSourcesAndSinks;
}
/**
* Gets the maximum depth of the access paths. All paths will be truncated
* if they exceed the given size.
* @param accessPathLength the maximum value of an access path.
*/
public static int getAccessPathLength() {
return accessPathLength;
}
/**
* Sets the maximum depth of the access paths. All paths will be truncated
* if they exceed the given size.
* @param accessPathLength the maximum value of an access path. If it gets longer than
* this value, it is truncated and all following fields are assumed as tainted
* (which is imprecise but gains performance)
* Default value is 5.
*/
public static void setAccessPathLength(int accessPathLength) {
InfoflowConfiguration.accessPathLength = accessPathLength;
}
/**
* Sets whether results (source-to-sink connections) that only differ in their
* propagation paths shall be merged into a single result or not.
* @param pathAgnosticResults True if two results shall be regarded as equal
* if they connect the same source and sink, even if their propagation paths
* differ, otherwise false
*/
public static void setPathAgnosticResults(boolean pathAgnosticResults) {
InfoflowConfiguration.pathAgnosticResults = pathAgnosticResults;
}
/**
* Gets whether results (source-to-sink connections) that only differ in their
* propagation paths shall be merged into a single result or not.
* @return True if two results shall be regarded as equal if they connect the
* same source and sink, even if their propagation paths differ, otherwise
* false
*/
public static boolean getPathAgnosticResults() {
return InfoflowConfiguration.pathAgnosticResults;
}
/**
* Gets whether different results shall be reported if they only differ in
* the access path the reached the sink or left the source
* @return True if results shall also be distinguished based on access paths
*/
public static boolean getOneResultPerAccessPath() {
return oneResultPerAccessPath;
}
/**
* Gets whether different results shall be reported if they only differ in
* the access path the reached the sink or left the source
* @param oneResultPerAP True if results shall also be distinguished based
* on access paths
*/
public static void setOneResultPerAccessPath(boolean oneResultPerAP) {
oneResultPerAccessPath = oneResultPerAP;
}
/**
* Gets whether neighbors at the same statement shall be merged into a
* single abstraction
* @return True if equivalent neighbor shall be merged, otherwise false
*/
public static boolean getMergeNeighbors() {
return mergeNeighbors;
}
/**
* Sets whether neighbors at the same statement shall be merged into a
* single abstraction
* @param value True if equivalent neighbor shall be merged, otherwise false
*/
public static void setMergeNeighbors(boolean value) {
InfoflowConfiguration.mergeNeighbors = value;
}
/**
* Gets whether runtime type information shall be tightened as much as
* possible when deriving new taints
* @return True if the runtime type information shall automatically be
* tightened when deriving new taints, otherwise false
*/
public static boolean getUseTypeTightening() {
return InfoflowConfiguration.useTypeTightening;
}
/**
* Sets whether runtime type information shall be tightened as much as
* possible when deriving new taints
* @param useTypeTightening True if the runtime type information shall
* automatically be tightened when deriving new taints, otherwise false
*/
public static void setUseTypeTightening(boolean useTypeTightening) {
InfoflowConfiguration.useTypeTightening = useTypeTightening;
}
/**
* Gets whether recursive access paths shall be reduced, e.g. whether we
* shall propagate a.[next].data instead of a.next.next.data.
* @return True if recursive access paths shall be reduced, otherwise false
*/
public static boolean getUseRecursiveAccessPaths() {
return useRecursiveAccessPaths;
}
/**
* Sets whether recursive access paths shall be reduced, e.g. whether we
* shall propagate a.[next].data instead of a.next.next.data.
* @param useRecursiveAccessPaths True if recursive access paths shall be
* reduced, otherwise false
*/
public static void setUseRecursiveAccessPaths(boolean useRecursiveAccessPaths) {
InfoflowConfiguration.useRecursiveAccessPaths = useRecursiveAccessPaths;
}
/**
* Gets whether access paths pointing to outer objects using this$n shall be
* reduced, e.g. whether we shall propagate a.data instead of a.this$0.a.data.
* @return True if access paths including outer objects shall be reduced,
* otherwise false
*/
public static boolean getUseThisChainReduction() {
return useThisChainReduction;
}
/**
* Sets whether access paths pointing to outer objects using this$n shall be
* reduced, e.g. whether we shall propagate a.data instead of a.this$0.a.data.
* @param useThisChainReduction True if access paths including outer objects
* shall be reduced, otherwise false
*/
public static void setUseThisChainReduction(boolean useThisChainReduction) {
InfoflowConfiguration.useThisChainReduction = useThisChainReduction;
}
/**
* Sets whether the information flow analysis shall stop after the first
* flow has been found
* @param stopAfterFirstFlow True if the analysis shall stop after the
* first flow has been found, otherwise false.
*/
public void setStopAfterFirstFlow(boolean stopAfterFirstFlow) {
this.stopAfterFirstFlow = stopAfterFirstFlow;
}
/**
* Gets whether the information flow analysis shall stop after the first
* flow has been found
* @return True if the information flow analysis shall stop after the first
* flow has been found, otherwise false
*/
public boolean getStopAfterFirstFlow() {
return stopAfterFirstFlow;
}
/**
* Sets whether the implementations of source methods shall be analyzed as
* well
* @param inspect True if the implementations of source methods shall be
* analyzed as well, otherwise false
*/
public void setInspectSources(boolean inspect) {
inspectSources = inspect;
}
/**
* Gets whether the implementations of source methods shall be analyzed as
* well
* @return True if the implementations of source methods shall be analyzed
* as well, otherwise false
*/
public boolean getInspectSources() {
return inspectSources;
}
/**
* Sets whether the implementations of sink methods shall be analyzed as well
* @param inspect True if the implementations of sink methods shall be
* analyzed as well, otherwise false
*/
public void setInspectSinks(boolean inspect) {
inspectSinks = inspect;
}
/**
* Sets whether the implementations of sink methods shall be analyzed as well
* @return True if the implementations of sink methods shall be analyzed as
* well, otherwise false
*/
public boolean getInspectSinks() {
return inspectSinks;
}
/**
* Sets whether the solver shall consider implicit flows.
* @param enableImplicitFlows True if implicit flows shall be considered,
* otherwise false.
*/
public void setEnableImplicitFlows(boolean enableImplicitFlows) {
this.enableImplicitFlows = enableImplicitFlows;
}
/**
* Gets whether the solver shall consider implicit flows.
* @return True if implicit flows shall be considered, otherwise false.
*/
public boolean getEnableImplicitFlows() {
return enableImplicitFlows;
}
/**
* Sets whether the solver shall consider assignments to static fields
* @param enableStaticFields True if assignments to static fields shall be
* considered, otherwise false
*/
public void setEnableStaticFieldTracking(boolean enableStaticFields) {
this.enableStaticFields = enableStaticFields;
}
/**
* Gets whether the solver shall trak assignments to static fields
* @return True if the solver shall trak assignments to static fields,
* otherwise false
*/
public boolean getEnableStaticFieldTracking() {
return enableStaticFields;
}
/**
* Sets whether a flow sensitive aliasing algorithm shall be used
* @param flowSensitiveAliasing True if a flow sensitive aliasing algorithm
* shall be used, otherwise false
*/
public void setFlowSensitiveAliasing(boolean flowSensitiveAliasing) {
this.flowSensitiveAliasing = flowSensitiveAliasing;
}
/**
* Gets whether a flow sensitive aliasing algorithm shall be used
* @return True if a flow sensitive aliasing algorithm shall be used,
* otherwise false
*/
public boolean getFlowSensitiveAliasing() {
return flowSensitiveAliasing;
}
/**
* Sets whether the solver shall track taints of thrown exception objects
* @param enableExceptions True if taints associated with exceptions shall
* be tracked over try/catch construct, otherwise false
*/
public void setEnableExceptionTracking(boolean enableExceptions) {
this.enableExceptions = enableExceptions;
}
/**
* Gets whether the solver shall track taints of thrown exception objects
* @return True if the solver shall track taints of thrown exception objects,
* otherwise false
*/
public boolean getEnableExceptionTracking() {
return enableExceptions;
}
public void setEnableArraySizeTainting(boolean arrayLengthTainting) {
this.enableArraySizeTainting = arrayLengthTainting;
}
public boolean getEnableArraySizeTainting() {
return this.enableArraySizeTainting;
}
/**
* Sets the callgraph algorithm to be used by the data flow tracker
* @param algorithm The callgraph algorithm to be used by the data flow tracker
*/
public void setCallgraphAlgorithm(CallgraphAlgorithm algorithm) {
this.callgraphAlgorithm = algorithm;
}
/**
* Gets the callgraph algorithm to be used by the data flow tracker
* @return The callgraph algorithm to be used by the data flow tracker
*/
public CallgraphAlgorithm getCallgraphAlgorithm() {
return callgraphAlgorithm;
}
/**
* Sets the aliasing algorithm to be used by the data flow tracker
* @param algorithm The aliasing algorithm to be used by the data flow tracker
*/
public void setAliasingAlgorithm(AliasingAlgorithm algorithm) {
this.aliasingAlgorithm = algorithm;
}
/**
* Gets the aliasing algorithm to be used by the data flow tracker
* @return The aliasing algorithm to be used by the data flow tracker
*/
public AliasingAlgorithm getAliasingAlgorithm() {
return aliasingAlgorithm;
}
/**
* Sets whether type checking shall be done on casts and method calls
* @param enableTypeChecking True if type checking shall be performed,
* otherwise false
*/
public void setEnableTypeChecking(boolean enableTypeChecking) {
this.enableTypeChecking = enableTypeChecking;
}
/**
* Gets whether type checking shall be done on casts and method calls
* @return True if type checking shall be performed, otherwise false
*/
public boolean getEnableTypeChecking() {
return enableTypeChecking;
}
/**
* Sets whether flows starting or ending in system packages such as Android's
* support library shall be ignored.
* @param ignoreFlowsInSystemPackages True if flows starting or ending in
* system packages shall be ignored, otherwise false.
*/
public void setIgnoreFlowsInSystemPackages(boolean ignoreFlowsInSystemPackages) {
this.ignoreFlowsInSystemPackages = ignoreFlowsInSystemPackages;
}
/**
* Gets whether flows starting or ending in system packages such as Android's
* support library shall be ignored.
* @return True if flows starting or ending in system packages shall be ignored,
* otherwise false.
*/
public boolean getIgnoreFlowsInSystemPackages() {
return ignoreFlowsInSystemPackages;
}
/**
* Sets the maximum number of threads to be used by the solver. A value of -1
* indicates an unlimited number of threads, i.e., there will be as many threads
* as there are CPU cores on the machine.
* @param threadNum The maximum number of threads to be used by the solver,
* or -1 for an unlimited number of threads.
*/
public void setMaxThreadNum(int threadNum) {
this.maxThreadNum = threadNum;
}
/**
* Gets the maximum number of threads to be used by the solver. A value of -1
* indicates an unlimited number of threads, i.e., there will be as many threads
* as there are CPU cores on the machine.
* @return The maximum number of threads to be used by the solver, or -1 for an
* unlimited number of threads.
*/
public int getMaxThreadNum() {
return this.maxThreadNum;
}
/**
* Gets whether FlowDroid shall write the Jimple files to disk after the
* data flow analysis
* @return True if the Jimple files shall be written to disk after the data
* flow analysis, otherwise false
*/
public boolean getWriteOutputFiles() {
return this.writeOutputFiles;
}
/**
* Gets whether FlowDroid shall write the Jimple files to disk after the
* data flow analysis
* @param writeOutputFiles True if the Jimple files shall be written to disk
* after the data flow analysis, otherwise false
*/
public void setWriteOutputFiles(boolean writeOutputFiles) {
this.writeOutputFiles = writeOutputFiles;
}
/**
* Sets whether and how FlowDroid shall eliminate irrelevant code before
* running the taint propagation
* @param Mode the mode of dead and irrelevant code eliminiation to be
* used
*/
public void setCodeEliminationMode(CodeEliminationMode mode) {
this.codeEliminationMode = mode;
}
/**
* Gets whether and how FlowDroid shall eliminate irrelevant code before
* running the taint propagation
* @return the mode of dead and irrelevant code elimination to be
* used
*/
public CodeEliminationMode getCodeEliminationMode() {
return codeEliminationMode;
}
/**
* Gets whether the discovered sources and sinks shall be logged
* @return True if the discovered sources and sinks shall be logged,
* otherwise false
*/
public boolean getLogSourcesAndSinks() {
return logSourcesAndSinks;
}
/**
* Sets whether the discovered sources and sinks shall be logged
* @param logSourcesAndSinks True if the discovered sources and sinks shall
* be logged, otherwise false
*/
public void setLogSourcesAndSinks(boolean logSourcesAndSinks) {
this.logSourcesAndSinks = logSourcesAndSinks;
}
public boolean isTaintAnalysisEnabled() {
return taintAnalysisEnabled;
}
public void setTaintAnalysisEnabled(boolean taintAnalysisEnabled) {
this.taintAnalysisEnabled = taintAnalysisEnabled;
}
/**
* Prints a summary of this data flow configuration
*/
public void printSummary() {
if (!enableStaticFields)
logger.warn("Static field tracking is disabled, results may be incomplete");
if (!flowSensitiveAliasing)
logger.warn("Using flow-insensitive alias tracking, results may be imprecise");
if (enableImplicitFlows)
logger.info("Implicit flow tracking is enabled");
else
logger.info("Implicit flow tracking is NOT enabled");
if (enableExceptions)
logger.info("Exceptional flow tracking is enabled");
else
logger.info("Exceptional flow tracking is NOT enabled");
logger.info("Running with a maximum access path length of {}", getAccessPathLength());
if (pathAgnosticResults)
logger.info("Using path-agnostic result collection");
else
logger.info("Using path-sensitive result collection");
if (useRecursiveAccessPaths)
logger.info("Recursive access path shortening is enabled");
else
logger.info("Recursive access path shortening is NOT enabled");
logger.info("Taint analysis enabled: " + taintAnalysisEnabled);
}
}
| |
/*
* 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.prestosql.plugin.raptor.legacy.metadata;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;
import io.prestosql.plugin.raptor.legacy.RaptorColumnHandle;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.predicate.Domain;
import io.prestosql.spi.predicate.Range;
import io.prestosql.spi.predicate.Ranges;
import io.prestosql.spi.predicate.TupleDomain;
import io.prestosql.spi.type.Type;
import java.sql.JDBCType;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map.Entry;
import java.util.StringJoiner;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static io.prestosql.plugin.raptor.legacy.metadata.DatabaseShardManager.maxColumn;
import static io.prestosql.plugin.raptor.legacy.metadata.DatabaseShardManager.minColumn;
import static io.prestosql.plugin.raptor.legacy.storage.ColumnIndexStatsUtils.jdbcType;
import static io.prestosql.plugin.raptor.legacy.storage.ShardStats.truncateIndexValue;
import static io.prestosql.plugin.raptor.legacy.util.UuidUtil.uuidStringToBytes;
import static io.prestosql.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
class ShardPredicate
{
private final String predicate;
private final List<JDBCType> types;
private final List<Object> values;
private static final int MAX_RANGE_COUNT = 100;
private ShardPredicate(String predicate, List<JDBCType> types, List<Object> values)
{
this.predicate = requireNonNull(predicate, "predicate is null");
this.types = ImmutableList.copyOf(requireNonNull(types, "types is null"));
this.values = ImmutableList.copyOf(requireNonNull(values, "values is null"));
checkArgument(types.size() == values.size(), "types and values sizes do not match");
}
public String getPredicate()
{
return predicate;
}
public void bind(PreparedStatement statement)
throws SQLException
{
for (int i = 0; i < types.size(); i++) {
JDBCType type = types.get(i);
Object value = values.get(i);
bindValue(statement, type, value, i + 1);
}
}
@Override
public String toString()
{
return toStringHelper(this)
.addValue(predicate)
.toString();
}
public static ShardPredicate create(TupleDomain<RaptorColumnHandle> tupleDomain)
{
StringJoiner predicate = new StringJoiner(" AND ").setEmptyValue("true");
ImmutableList.Builder<JDBCType> types = ImmutableList.builder();
ImmutableList.Builder<Object> values = ImmutableList.builder();
for (Entry<RaptorColumnHandle, Domain> entry : tupleDomain.getDomains().get().entrySet()) {
Domain domain = entry.getValue();
if (domain.isNullAllowed() || domain.isAll()) {
continue;
}
RaptorColumnHandle handle = entry.getKey();
Type type = handle.getColumnType();
JDBCType jdbcType = jdbcType(type);
if (jdbcType == null) {
continue;
}
if (handle.isShardUuid()) {
predicate.add(createShardPredicate(types, values, domain, jdbcType));
continue;
}
if (!domain.getType().isOrderable()) {
continue;
}
StringJoiner columnPredicate = new StringJoiner(" OR ", "(", ")").setEmptyValue("true");
Ranges ranges = domain.getValues().getRanges();
// prevent generating complicated metadata queries
if (ranges.getRangeCount() > MAX_RANGE_COUNT) {
continue;
}
for (Range range : ranges.getOrderedRanges()) {
Object minValue = null;
Object maxValue = null;
if (range.isSingleValue()) {
minValue = range.getSingleValue();
maxValue = range.getSingleValue();
}
else {
if (!range.getLow().isLowerUnbounded()) {
minValue = range.getLow().getValue();
}
if (!range.getHigh().isUpperUnbounded()) {
maxValue = range.getHigh().getValue();
}
}
String min;
String max;
if (handle.isBucketNumber()) {
min = "bucket_number";
max = "bucket_number";
}
else {
min = minColumn(handle.getColumnId());
max = maxColumn(handle.getColumnId());
}
StringJoiner rangePredicate = new StringJoiner(" AND ", "(", ")").setEmptyValue("true");
if (minValue != null) {
rangePredicate.add(format("(%s >= ? OR %s IS NULL)", max, max));
types.add(jdbcType);
values.add(minValue);
}
if (maxValue != null) {
rangePredicate.add(format("(%s <= ? OR %s IS NULL)", min, min));
types.add(jdbcType);
values.add(maxValue);
}
columnPredicate.add(rangePredicate.toString());
}
predicate.add(columnPredicate.toString());
}
return new ShardPredicate(predicate.toString(), types.build(), values.build());
}
private static String createShardPredicate(ImmutableList.Builder<JDBCType> types, ImmutableList.Builder<Object> values, Domain domain, JDBCType jdbcType)
{
List<Range> ranges = domain.getValues().getRanges().getOrderedRanges();
// only apply predicates if all ranges are single values
if (ranges.isEmpty() || !ranges.stream().allMatch(Range::isSingleValue)) {
return "true";
}
ImmutableList.Builder<Object> valuesBuilder = ImmutableList.builder();
ImmutableList.Builder<JDBCType> typesBuilder = ImmutableList.builder();
StringJoiner rangePredicate = new StringJoiner(" OR ");
for (Range range : ranges) {
Slice uuidText = (Slice) range.getSingleValue();
try {
Slice uuidBytes = uuidStringToBytes(uuidText);
typesBuilder.add(jdbcType);
valuesBuilder.add(uuidBytes);
}
catch (IllegalArgumentException e) {
return "true";
}
rangePredicate.add("shard_uuid = ?");
}
types.addAll(typesBuilder.build());
values.addAll(valuesBuilder.build());
return rangePredicate.toString();
}
@VisibleForTesting
protected List<JDBCType> getTypes()
{
return types;
}
@VisibleForTesting
protected List<Object> getValues()
{
return values;
}
public static void bindValue(PreparedStatement statement, JDBCType type, Object value, int index)
throws SQLException
{
if (value == null) {
statement.setNull(index, type.getVendorTypeNumber());
return;
}
switch (type) {
case BOOLEAN:
statement.setBoolean(index, (boolean) value);
return;
case INTEGER:
statement.setInt(index, ((Number) value).intValue());
return;
case BIGINT:
statement.setLong(index, ((Number) value).longValue());
return;
case DOUBLE:
statement.setDouble(index, ((Number) value).doubleValue());
return;
case VARBINARY:
statement.setBytes(index, truncateIndexValue((Slice) value).getBytes());
return;
}
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unhandled type: " + type);
}
}
| |
/*
* Copyright (c) 2017. Team CMPUT301F17T02, CMPUT301, University of Alberta - All Rights Reserved. You may use, distribute, or modify this code under terms and conditions of the Code of Students Behaviour at University of Alberta.
*/
package com.example.baard.Friends;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import com.example.baard.Controllers.FileController;
import com.example.baard.Entities.User;
import com.example.baard.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Users can see who requested to follow them, and then accept or delete that request.
* @see FileController
* @author rderbysh
* @since 1.0
*/
public class FriendRequestsFragment extends Fragment {
private ExpandableListView friendRequestsView;
private MyFriendsRequestAdapter adapter;
private String username;
private FileController fileController;
private ArrayList<String> getFriendRequestsList = new ArrayList<>();
private HashMap<String, Boolean> getFriendRequestsMap = new HashMap<String, Boolean>();
private User user;
private HashMap<String, String> userMap = new HashMap<String, String>();
private ArrayList<String> fullFriendRequestsList = new ArrayList<String>();
private FriendRequestsFragment.OnFragmentInteractionListener mListener;
/**
* Required empty public constructor
*/
public FriendRequestsFragment() {
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
* @return A new instance of fragment FriendRequestsFragment.
*/
public static FriendRequestsFragment newInstance() {
FriendRequestsFragment fragment = new FriendRequestsFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
/**
* Sets the on item click listener such that habits in the list can be accessed by
* the view screen.
*
* @param inflater The layout inflater
* @param container Container for the ViewGroup
* @param savedInstanceState Bundle of the saved State
* @return View of the fragment activity
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_friend_requests, container, false);
fileController = new FileController();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
Gson gson = new Gson();
String json = sharedPrefs.getString("username", "");
username = gson.fromJson(json, new TypeToken<String>() {}.getType());
friendRequestsView = view.findViewById(R.id.friendRequestsView);
return view;
}
/**
* Called when FriendRequestsFragment activity is opened up and called again.
*/
@Override
public void onResume() {
super.onResume();
user = fileController.loadUser(getActivity().getApplicationContext(), username);
List<String> listDataHeader = new ArrayList<>();
HashMap<String, List<String>> listDataChild = new HashMap<>();
List<String> child = new ArrayList<>();
child.add("");
userMap = fileController.getAllUsers();
getFriendRequestsMap = user.getReceivedRequests();
System.out.println("getFriendRequestsMap: " + getFriendRequestsMap);
if (!(getFriendRequestsList.size()>0)) {
fullFriendRequestsList.addAll(getFriendRequestsMap.keySet());
for (int i=0; i<getFriendRequestsMap.size();i++) {
if (getFriendRequestsMap.get(fullFriendRequestsList.get(i))) {
getFriendRequestsList.add(fullFriendRequestsList.get(i));
System.out.println("getFriendRequestsList: " + getFriendRequestsList);
}
}
}
if (!getFriendRequestsMap.isEmpty()) {
System.out.println("User's received requests: " + getFriendRequestsList);
for (int j = 0; j < getFriendRequestsList.size(); j++) {
String name = userMap.get(getFriendRequestsList.get(j));
if (name != null) {
listDataHeader.add(name);
listDataChild.put(listDataHeader.get(listDataHeader.size() - 1), child);
}
}
}
adapter = new MyFriendsRequestAdapter(this.getContext(), listDataHeader, listDataChild, getFriendRequestsList, getFriendRequestsList);
friendRequestsView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
/**
* Adapter for the expandable list view so users can either accept or delete a request.
*/
private class MyFriendsRequestAdapter extends BaseExpandableListAdapter {
// Referenced and copied from https://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/
private final Context _context;
private final List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private final HashMap<String, List<String>> _listDataChild;
private final ArrayList<String> allUsersList;
private final ArrayList<String> seenUsersList;
/**
* Constructor for Expandable List Adapter
* @param context The context of the Application
* @param listDataHeader The header names for the list (Habit names)
* @param listChildData Child Strings (not used in this implementation) Pass in HashMap with Strings of Headers and a List<String> of just ""
* @param allUsersList All habits of the user
* @param seenUsersList List of Habits on the screen (Daily or All)
*/
public MyFriendsRequestAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData, ArrayList<String> allUsersList, ArrayList<String> seenUsersList) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
this.allUsersList = allUsersList;
this.seenUsersList = seenUsersList;
}
@Override
public int getGroupCount() {
return this._listDataHeader.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
@Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setText(headerTitle);
return convertView;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item_friend_request, null);
}
convertView.findViewById(R.id.acceptFriendButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String acceptPerson = seenUsersList.get(groupPosition);
allUsersList.remove(acceptPerson);
getFriendRequestsList.remove(acceptPerson);
getFriendRequestsMap.put(acceptPerson, Boolean.FALSE);
user.getReceivedRequests().put(acceptPerson, Boolean.FALSE);
Boolean test = fileController.acceptFriendRequest(getContext(), user.getUsername(), acceptPerson);
if (test) { System.out.println("Saved to server"); }
else { System.out.println("Failed"); }
fileController.saveUser(_context, user);
_listDataHeader.remove(groupPosition);
notifyDataSetChanged();
}
});
convertView.findViewById(R.id.declineFriendButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String declinedPerson = seenUsersList.get(groupPosition);
allUsersList.remove(declinedPerson);
getFriendRequestsList.remove(declinedPerson);
getFriendRequestsMap.put(declinedPerson, Boolean.FALSE);
user.getReceivedRequests().put(declinedPerson, Boolean.FALSE);
fileController.saveUser(_context, user);
_listDataHeader.remove(groupPosition);
notifyDataSetChanged();
}
});
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
| |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.rename.inplace;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.codeInsight.template.*;
import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
import com.intellij.codeInsight.template.impl.TemplateState;
import com.intellij.injected.editor.VirtualFileWindow;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageNamesValidation;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.lang.refactoring.NamesValidator;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.Shortcut;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.impl.FinishMarkAction;
import com.intellij.openapi.command.impl.StartMarkAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.BalloonBuilder;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.ProjectScope;
import com.intellij.psi.search.PsiSearchHelper;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.popup.PopupFactoryImpl;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Query;
import com.intellij.util.containers.Stack;
import com.intellij.util.ui.PositionTracker;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;
/**
* User: anna
* Date: 1/11/12
*/
public abstract class InplaceRefactoring {
protected static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.rename.inplace.VariableInplaceRenamer");
@NonNls protected static final String PRIMARY_VARIABLE_NAME = "PrimaryVariable";
@NonNls protected static final String OTHER_VARIABLE_NAME = "OtherVariable";
protected static final Stack<InplaceRefactoring> ourRenamersStack = new Stack<InplaceRefactoring>();
public static final Key<InplaceRefactoring> INPLACE_RENAMER = Key.create("EditorInplaceRenamer");
public static final Key<Boolean> INTRODUCE_RESTART = Key.create("INTRODUCE_RESTART");
protected PsiNamedElement myElementToRename;
protected final Editor myEditor;
protected final Project myProject;
protected RangeMarker myRenameOffset;
protected String myAdvertisementText;
private ArrayList<RangeHighlighter> myHighlighters;
protected String myInitialName;
protected String myOldName;
protected RangeMarker myBeforeRevert = null;
protected String myInsertedName;
protected LinkedHashSet<String> myNameSuggestions;
protected StartMarkAction myMarkAction;
protected PsiElement myScope;
protected RangeMarker myCaretRangeMarker;
protected Balloon myBalloon;
protected String myTitle;
protected RelativePoint myTarget;
public InplaceRefactoring(Editor editor, PsiNamedElement elementToRename, Project project) {
this(editor, elementToRename, project, elementToRename != null ? elementToRename.getName() : null,
elementToRename != null ? elementToRename.getName() : null);
}
public InplaceRefactoring(Editor editor, PsiNamedElement elementToRename, Project project, final String oldName) {
this(editor, elementToRename, project, elementToRename != null ? elementToRename.getName() : null, oldName);
}
public InplaceRefactoring(
Editor editor, PsiNamedElement elementToRename, Project project, String initialName, final String oldName) {
myEditor = /*(editor instanceof EditorWindow)? ((EditorWindow)editor).getDelegate() : */editor;
myElementToRename = elementToRename;
myProject = project;
myOldName = oldName;
if (myElementToRename != null) {
myInitialName = initialName;
final PsiFile containingFile = myElementToRename.getContainingFile();
if (!notSameFile(getTopLevelVirtualFile(containingFile.getViewProvider()), containingFile) &&
myElementToRename != null && myElementToRename.getTextRange() != null) {
myRenameOffset = myEditor.getDocument().createRangeMarker(myElementToRename.getTextRange());
myRenameOffset.setGreedyToRight(true);
myRenameOffset.setGreedyToLeft(true); // todo not sure if we need this
}
}
}
public static void unableToStartWarning(Project project, Editor editor) {
final StartMarkAction startMarkAction = StartMarkAction.canStart(project);
final String message = startMarkAction.getCommandName() + " is not finished yet.";
final Document oldDocument = startMarkAction.getDocument();
if (editor == null || oldDocument != editor.getDocument()) {
final int exitCode = Messages.showYesNoDialog(project, message,
RefactoringBundle.getCannotRefactorMessage(null),
"Continue Started", "Cancel Started", Messages.getErrorIcon());
navigateToStarted(oldDocument, project, exitCode);
}
else {
CommonRefactoringUtil.showErrorHint(project, editor, message, RefactoringBundle.getCannotRefactorMessage(null), null);
}
}
public void setAdvertisementText(String advertisementText) {
myAdvertisementText = advertisementText;
}
public boolean performInplaceRefactoring(final LinkedHashSet<String> nameSuggestions) {
myNameSuggestions = nameSuggestions;
if (InjectedLanguageUtil.isInInjectedLanguagePrefixSuffix(myElementToRename)) {
return false;
}
final FileViewProvider fileViewProvider = myElementToRename.getContainingFile().getViewProvider();
VirtualFile file = getTopLevelVirtualFile(fileViewProvider);
SearchScope referencesSearchScope = getReferencesSearchScope(file);
final Collection<PsiReference> refs = collectRefs(referencesSearchScope);
addReferenceAtCaret(refs);
for (PsiReference ref : refs) {
final PsiFile containingFile = ref.getElement().getContainingFile();
if (notSameFile(file, containingFile)) {
return false;
}
}
final PsiElement scope = checkLocalScope();
if (scope == null) {
return false; // Should have valid local search scope for inplace rename
}
final PsiFile containingFile = scope.getContainingFile();
if (containingFile == null) {
return false; // Should have valid local search scope for inplace rename
}
//no need to process further when file is read-only
if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, containingFile)) return true;
myEditor.putUserData(INPLACE_RENAMER, this);
ourRenamersStack.push(this);
final List<Pair<PsiElement, TextRange>> stringUsages = new ArrayList<Pair<PsiElement, TextRange>>();
collectAdditionalElementsToRename(stringUsages);
return buildTemplateAndStart(refs, stringUsages, scope, containingFile);
}
protected boolean notSameFile(@Nullable VirtualFile file, @NotNull PsiFile containingFile) {
return !Comparing.equal(getTopLevelVirtualFile(containingFile.getViewProvider()), file);
}
protected SearchScope getReferencesSearchScope(VirtualFile file) {
return file == null || ProjectRootManager.getInstance(myProject).getFileIndex().isInContent(file)
? ProjectScope.getProjectScope(myElementToRename.getProject())
: new LocalSearchScope(myElementToRename.getContainingFile());
}
@Nullable
protected PsiElement checkLocalScope() {
final SearchScope searchScope = PsiSearchHelper.SERVICE.getInstance(myElementToRename.getProject()).getUseScope(myElementToRename);
if (searchScope instanceof LocalSearchScope) {
final PsiElement[] elements = ((LocalSearchScope)searchScope).getScope();
return PsiTreeUtil.findCommonParent(elements);
}
return null;
}
protected abstract void collectAdditionalElementsToRename(final List<Pair<PsiElement, TextRange>> stringUsages);
protected abstract boolean shouldSelectAll();
protected MyLookupExpression createLookupExpression(PsiElement selectedElement) {
return new MyLookupExpression(getInitialName(), myNameSuggestions, myElementToRename, selectedElement, shouldSelectAll(), myAdvertisementText);
}
protected boolean acceptReference(PsiReference reference) {
return true;
}
protected Collection<PsiReference> collectRefs(SearchScope referencesSearchScope) {
final Query<PsiReference> search = ReferencesSearch.search(myElementToRename, referencesSearchScope, false);
final CommonProcessors.CollectProcessor<PsiReference> processor = new CommonProcessors.CollectProcessor<PsiReference>() {
@Override
protected boolean accept(PsiReference reference) {
return acceptReference(reference);
}
};
search.forEach(processor);
return processor.getResults();
}
protected boolean buildTemplateAndStart(final Collection<PsiReference> refs,
final Collection<Pair<PsiElement, TextRange>> stringUsages,
final PsiElement scope,
final PsiFile containingFile) {
final PsiElement context = InjectedLanguageManager.getInstance(containingFile.getProject()).getInjectionHost(containingFile);
myScope = context != null ? context.getContainingFile() : scope;
final TemplateBuilderImpl builder = new TemplateBuilderImpl(myScope);
PsiElement nameIdentifier = getNameIdentifier();
int offset = myEditor.getCaretModel().getOffset();
PsiElement selectedElement = getSelectedInEditorElement(nameIdentifier, refs, stringUsages, offset);
boolean subrefOnPrimaryElement = false;
boolean hasReferenceOnNameIdentifier = false;
for (PsiReference ref : refs) {
if (isReferenceAtCaret(selectedElement, ref)) {
builder.replaceElement(ref, PRIMARY_VARIABLE_NAME, createLookupExpression(selectedElement), true);
subrefOnPrimaryElement = true;
continue;
}
addVariable(ref, selectedElement, builder, offset);
hasReferenceOnNameIdentifier |= isReferenceAtCaret(nameIdentifier, ref);
}
if (nameIdentifier != null) {
hasReferenceOnNameIdentifier |= selectedElement.getTextRange().contains(nameIdentifier.getTextRange());
if (!subrefOnPrimaryElement || !hasReferenceOnNameIdentifier){
addVariable(nameIdentifier, selectedElement, builder);
}
}
for (Pair<PsiElement, TextRange> usage : stringUsages) {
addVariable(usage.first, usage.second, selectedElement, builder);
}
addAdditionalVariables(builder);
try {
myMarkAction = startRename();
}
catch (final StartMarkAction.AlreadyStartedException e) {
final Document oldDocument = e.getDocument();
if (oldDocument != myEditor.getDocument()) {
final int exitCode = Messages.showYesNoCancelDialog(myProject, e.getMessage(), getCommandName(),
"Navigate to Started", "Cancel Started", "Cancel", Messages.getErrorIcon());
if (exitCode == Messages.CANCEL) return true;
navigateToAlreadyStarted(oldDocument, exitCode);
return true;
}
else {
if (!ourRenamersStack.isEmpty() && ourRenamersStack.peek() == this) {
ourRenamersStack.pop();
if (!ourRenamersStack.empty()) {
myOldName = ourRenamersStack.peek().myOldName;
}
}
revertState();
final TemplateState templateState = TemplateManagerImpl.getTemplateState(InjectedLanguageUtil.getTopLevelEditor(myEditor));
if (templateState != null) {
templateState.gotoEnd(true);
}
}
return false;
}
beforeTemplateStart();
new WriteCommandAction(myProject, getCommandName()) {
@Override
protected void run(Result result) throws Throwable {
startTemplate(builder);
}
}.execute();
if (myBalloon == null) {
showBalloon();
}
return true;
}
protected boolean isReferenceAtCaret(PsiElement selectedElement, PsiReference ref) {
final TextRange textRange = ref.getRangeInElement().shiftRight(ref.getElement().getTextRange().getStartOffset());
if (selectedElement != null){
final TextRange selectedElementRange = selectedElement.getTextRange();
LOG.assertTrue(selectedElementRange != null, selectedElement);
if (selectedElementRange != null && selectedElementRange.contains(textRange)) return true;
}
return false;
}
protected void beforeTemplateStart() {
myCaretRangeMarker = myEditor.getDocument()
.createRangeMarker(new TextRange(myEditor.getCaretModel().getOffset(), myEditor.getCaretModel().getOffset()));
myCaretRangeMarker.setGreedyToLeft(true);
myCaretRangeMarker.setGreedyToRight(true);
}
private void startTemplate(final TemplateBuilderImpl builder) {
final Disposable disposable = Disposer.newDisposable();
DaemonCodeAnalyzer.getInstance(myProject).disableUpdateByTimer(disposable);
final MyTemplateListener templateListener = new MyTemplateListener() {
@Override
protected void restoreDaemonUpdateState() {
Disposer.dispose(disposable);
}
};
final int offset = myEditor.getCaretModel().getOffset();
Template template = builder.buildInlineTemplate();
template.setToShortenLongNames(false);
template.setToReformat(false);
TextRange range = myScope.getTextRange();
assert range != null;
myHighlighters = new ArrayList<RangeHighlighter>();
Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(myEditor);
topLevelEditor.getCaretModel().moveToOffset(range.getStartOffset());
TemplateManager.getInstance(myProject).startTemplate(topLevelEditor, template, templateListener);
restoreOldCaretPositionAndSelection(offset);
highlightTemplateVariables(template, topLevelEditor);
}
private void highlightTemplateVariables(Template template, Editor topLevelEditor) {
//add highlights
if (myHighlighters != null) { // can be null if finish is called during testing
Map<TextRange, TextAttributes> rangesToHighlight = new HashMap<TextRange, TextAttributes>();
final TemplateState templateState = TemplateManagerImpl.getTemplateState(topLevelEditor);
if (templateState != null) {
EditorColorsManager colorsManager = EditorColorsManager.getInstance();
for (int i = 0; i < templateState.getSegmentsCount(); i++) {
final TextRange segmentOffset = templateState.getSegmentRange(i);
final String name = template.getSegmentName(i);
TextAttributes attributes = null;
if (name.equals(PRIMARY_VARIABLE_NAME)) {
attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES);
}
else if (name.equals(OTHER_VARIABLE_NAME)) {
attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
}
if (attributes == null) continue;
rangesToHighlight.put(segmentOffset, attributes);
}
}
addHighlights(rangesToHighlight, topLevelEditor, myHighlighters, HighlightManager.getInstance(myProject));
}
}
private void restoreOldCaretPositionAndSelection(final int offset) {
//move to old offset
Runnable runnable = new Runnable() {
@Override
public void run() {
myEditor.getCaretModel().moveToOffset(restoreCaretOffset(offset));
restoreSelection();
}
};
final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor);
if (lookup != null && lookup.getLookupStart() <= (restoreCaretOffset(offset))) {
lookup.setFocusDegree(LookupImpl.FocusDegree.UNFOCUSED);
lookup.performGuardedChange(runnable);
}
else {
runnable.run();
}
}
protected void restoreSelection() {
}
protected int restoreCaretOffset(int offset) {
return myCaretRangeMarker.isValid() ? myCaretRangeMarker.getEndOffset() : offset;
}
protected void navigateToAlreadyStarted(Document oldDocument, int exitCode) {
navigateToStarted(oldDocument, myProject, exitCode);
}
private static void navigateToStarted(final Document oldDocument, final Project project, final int exitCode) {
final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(oldDocument);
if (file != null) {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null) {
final FileEditor[] editors = FileEditorManager.getInstance(project).getEditors(virtualFile);
for (FileEditor editor : editors) {
if (editor instanceof TextEditor) {
final Editor textEditor = ((TextEditor)editor).getEditor();
final TemplateState templateState = TemplateManagerImpl.getTemplateState(textEditor);
if (templateState != null) {
if (exitCode == DialogWrapper.OK_EXIT_CODE) {
final TextRange range = templateState.getVariableRange(PRIMARY_VARIABLE_NAME);
if (range != null) {
new OpenFileDescriptor(project, virtualFile, range.getStartOffset()).navigate(true);
return;
}
}
else if (exitCode > 0){
templateState.gotoEnd();
return;
}
}
}
}
}
}
}
@Nullable
protected PsiElement getNameIdentifier() {
return myElementToRename instanceof PsiNameIdentifierOwner ? ((PsiNameIdentifierOwner)myElementToRename).getNameIdentifier() : null;
}
@Nullable
protected StartMarkAction startRename() throws StartMarkAction.AlreadyStartedException {
final StartMarkAction[] markAction = new StartMarkAction[1];
final StartMarkAction.AlreadyStartedException[] ex = new StartMarkAction.AlreadyStartedException[1];
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
@Override
public void run() {
try {
markAction[0] = StartMarkAction.start(myEditor, myProject, getCommandName());
}
catch (StartMarkAction.AlreadyStartedException e) {
ex[0] = e;
}
}
}, getCommandName(), null);
if (ex[0] != null) throw ex[0];
return markAction[0];
}
@Nullable
protected PsiNamedElement getVariable() {
// todo we can use more specific class, shouldn't we?
//Class clazz = myElementToRename != null? myElementToRename.getClass() : PsiNameIdentifierOwner.class;
if (myElementToRename != null && myElementToRename.isValid()) {
if (Comparing.strEqual(myOldName, myElementToRename.getName())) return myElementToRename;
if (myRenameOffset != null) return PsiTreeUtil.findElementOfClassAtRange(
myElementToRename.getContainingFile(), myRenameOffset.getStartOffset(), myRenameOffset.getEndOffset(), PsiNameIdentifierOwner.class);
}
if (myRenameOffset != null) {
final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
if (psiFile != null) {
return PsiTreeUtil.findElementOfClassAtRange(psiFile, myRenameOffset.getStartOffset(), myRenameOffset.getEndOffset(), PsiNameIdentifierOwner.class);
}
}
return myElementToRename;
}
/**
* Called after the completion of the refactoring, either a successful or a failed one.
*
* @param success true if the refactoring was accepted, false if it was cancelled (by undo or Esc)
*/
protected void moveOffsetAfter(boolean success) {
if (myCaretRangeMarker != null) {
myCaretRangeMarker.dispose();
}
}
protected void addAdditionalVariables(TemplateBuilderImpl builder) {
}
protected void addReferenceAtCaret(Collection<PsiReference> refs) {
PsiFile myEditorFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
// Note, that myEditorFile can be different from myElement.getContainingFile() e.g. in injections: myElement declaration in one
// file / usage in another !
final PsiReference reference = (myEditorFile != null ?
myEditorFile : myElementToRename.getContainingFile())
.findReferenceAt(myEditor.getCaretModel().getOffset());
if (reference instanceof PsiMultiReference) {
final PsiReference[] references = ((PsiMultiReference)reference).getReferences();
for (PsiReference ref : references) {
addReferenceIfNeeded(refs, ref);
}
}
else {
addReferenceIfNeeded(refs, reference);
}
}
private void addReferenceIfNeeded(@NotNull final Collection<PsiReference> refs, @Nullable final PsiReference reference) {
if (reference != null && reference.isReferenceTo(myElementToRename) && !refs.contains(reference)) {
refs.add(reference);
}
}
protected void showDialogAdvertisement(final String actionId) {
final Keymap keymap = KeymapManager.getInstance().getActiveKeymap();
final Shortcut[] shortcuts = keymap.getShortcuts(actionId);
if (shortcuts.length > 0) {
setAdvertisementText("Press " + KeymapUtil.getShortcutText(shortcuts[0]) + " to show dialog with more options");
}
}
public String getInitialName() {
if (myInitialName == null) {
final PsiNamedElement variable = getVariable();
if (variable != null) {
return variable.getName();
}
}
return myInitialName;
}
protected void revertState() {
if (myOldName == null) return;
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
@Override
public void run() {
final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(myEditor);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
final TemplateState state = TemplateManagerImpl.getTemplateState(topLevelEditor);
assert state != null;
final int segmentsCount = state.getSegmentsCount();
final Document document = topLevelEditor.getDocument();
for (int i = 0; i < segmentsCount; i++) {
final TextRange segmentRange = state.getSegmentRange(i);
document.replaceString(segmentRange.getStartOffset(), segmentRange.getEndOffset(), myOldName);
}
}
});
if (!myProject.isDisposed() && myProject.isOpen()) {
PsiDocumentManager.getInstance(myProject).commitDocument(topLevelEditor.getDocument());
}
}
}, getCommandName(), null);
}
/**
* Returns the name of the command performed by the refactoring.
*
* @return command name
*/
protected abstract String getCommandName();
public void finish(boolean success) {
if (!ourRenamersStack.isEmpty() && ourRenamersStack.peek() == this) {
ourRenamersStack.pop();
}
if (myHighlighters != null) {
if (!myProject.isDisposed()) {
final HighlightManager highlightManager = HighlightManager.getInstance(myProject);
for (RangeHighlighter highlighter : myHighlighters) {
highlightManager.removeSegmentHighlighter(myEditor, highlighter);
}
}
myHighlighters = null;
myEditor.putUserData(INPLACE_RENAMER, null);
}
if (myBalloon != null) {
if (!isRestart()) {
myBalloon.hide();
}
}
}
protected void addHighlights(@NotNull Map<TextRange, TextAttributes> ranges,
@NotNull Editor editor,
@NotNull Collection<RangeHighlighter> highlighters,
@NotNull HighlightManager highlightManager) {
for (Map.Entry<TextRange, TextAttributes> entry : ranges.entrySet()) {
TextRange range = entry.getKey();
TextAttributes attributes = entry.getValue();
highlightManager.addOccurrenceHighlight(editor, range.getStartOffset(), range.getEndOffset(), attributes, 0, highlighters, null);
}
for (RangeHighlighter highlighter : highlighters) {
highlighter.setGreedyToLeft(true);
highlighter.setGreedyToRight(true);
}
}
protected abstract boolean performRefactoring();
private void addVariable(final PsiReference reference,
final PsiElement selectedElement,
final TemplateBuilderImpl builder,
int offset) {
final PsiElement element = reference.getElement();
if (element == selectedElement && checkRangeContainsOffset(offset, reference.getRangeInElement(), element)) {
builder.replaceElement(reference, PRIMARY_VARIABLE_NAME, createLookupExpression(selectedElement), true);
}
else {
builder.replaceElement(reference, OTHER_VARIABLE_NAME, PRIMARY_VARIABLE_NAME, false);
}
}
private void addVariable(final PsiElement element,
final PsiElement selectedElement,
final TemplateBuilderImpl builder) {
addVariable(element, null, selectedElement, builder);
}
private void addVariable(final PsiElement element,
@Nullable final TextRange textRange,
final PsiElement selectedElement,
final TemplateBuilderImpl builder) {
if (element == selectedElement) {
builder.replaceElement(element, PRIMARY_VARIABLE_NAME, createLookupExpression(myElementToRename), true);
}
else if (textRange != null) {
builder.replaceElement(element, textRange, OTHER_VARIABLE_NAME, PRIMARY_VARIABLE_NAME, false);
}
else {
builder.replaceElement(element, OTHER_VARIABLE_NAME, PRIMARY_VARIABLE_NAME, false);
}
}
public void setElementToRename(PsiNamedElement elementToRename) {
myElementToRename = elementToRename;
}
protected boolean isIdentifier(final String newName, final Language language) {
final NamesValidator namesValidator = LanguageNamesValidation.INSTANCE.forLanguage(language);
return namesValidator == null || namesValidator.isIdentifier(newName, myProject);
}
protected static VirtualFile getTopLevelVirtualFile(final FileViewProvider fileViewProvider) {
VirtualFile file = fileViewProvider.getVirtualFile();
if (file instanceof VirtualFileWindow) file = ((VirtualFileWindow)file).getDelegate();
return file;
}
@TestOnly
public static void checkCleared() {
try {
assert ourRenamersStack.isEmpty() : ourRenamersStack;
}
finally {
ourRenamersStack.clear();
}
}
private PsiElement getSelectedInEditorElement(@Nullable PsiElement nameIdentifier,
final Collection<PsiReference> refs,
Collection<Pair<PsiElement, TextRange>> stringUsages,
final int offset) {
//prefer reference in case of self-references
for (PsiReference ref : refs) {
final PsiElement element = ref.getElement();
if (checkRangeContainsOffset(offset, ref.getRangeInElement(), element)) return element;
}
if (nameIdentifier != null) {
final TextRange range = nameIdentifier.getTextRange();
if (range != null && range.containsOffset(offset)) return nameIdentifier;
}
for (Pair<PsiElement, TextRange> stringUsage : stringUsages) {
if (checkRangeContainsOffset(offset, stringUsage.second, stringUsage.first)) return stringUsage.first;
}
LOG.error(nameIdentifier + " by " + this.getClass().getName());
return null;
}
private boolean checkRangeContainsOffset(int offset, final TextRange textRange, PsiElement element) {
int startOffset = element.getTextRange().getStartOffset();
final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(myProject);
final PsiLanguageInjectionHost injectionHost = injectedLanguageManager.getInjectionHost(element);
if (injectionHost != null) {
final PsiElement nameIdentifier = getNameIdentifier();
final PsiLanguageInjectionHost initialInjectedHost = nameIdentifier != null ? injectedLanguageManager.getInjectionHost(nameIdentifier) : null;
if (initialInjectedHost != null && initialInjectedHost != injectionHost) {
return false;
}
}
return textRange.shiftRight(startOffset).containsOffset(offset);
}
protected boolean isRestart() {
final Boolean isRestart = myEditor.getUserData(INTRODUCE_RESTART);
return isRestart != null && isRestart;
}
public static boolean canStartAnotherRefactoring(Editor editor, Project project, RefactoringActionHandler handler, PsiElement... element) {
final InplaceRefactoring inplaceRefactoring = getActiveInplaceRenamer(editor);
return StartMarkAction.canStart(project) == null ||
(inplaceRefactoring != null && element.length == 1 && inplaceRefactoring.startsOnTheSameElement(handler, element[0]));
}
public static InplaceRefactoring getActiveInplaceRenamer(Editor editor) {
return editor != null ? editor.getUserData(INPLACE_RENAMER) : null;
}
protected boolean startsOnTheSameElement(RefactoringActionHandler handler, PsiElement element) {
return getVariable() == element;
}
protected void releaseResources() {
}
@Nullable
protected JComponent getComponent() {
return null;
}
protected void showBalloon() {
final JComponent component = getComponent();
if (component == null) return;
if (ApplicationManager.getApplication().isHeadlessEnvironment()) return;
final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createDialogBalloonBuilder(component, null).setSmallVariant(true);
myBalloon = balloonBuilder.createBalloon();
final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(myEditor);
Disposer.register(myProject, myBalloon);
Disposer.register(myBalloon, new Disposable() {
@Override
public void dispose() {
releaseIfNotRestart();
topLevelEditor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION, null);
}
});
topLevelEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
final JBPopupFactory popupFactory = JBPopupFactory.getInstance();
myBalloon.show(new PositionTracker<Balloon>(topLevelEditor.getContentComponent()) {
@Override
public RelativePoint recalculateLocation(Balloon object) {
if (myTarget != null && !popupFactory.isBestPopupLocationVisible(topLevelEditor)) {
return myTarget;
}
if (myCaretRangeMarker != null && myCaretRangeMarker.isValid()) {
topLevelEditor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION,
topLevelEditor.offsetToVisualPosition(myCaretRangeMarker.getStartOffset()));
}
final RelativePoint target = popupFactory.guessBestPopupLocation(topLevelEditor);
final Point screenPoint = target.getScreenPoint();
int y = screenPoint.y;
if (target.getPoint().getY() > topLevelEditor.getLineHeight() + myBalloon.getPreferredSize().getHeight()) {
y -= topLevelEditor.getLineHeight();
}
myTarget = new RelativePoint(new Point(screenPoint.x, y));
return myTarget;
}
}, Balloon.Position.above);
}
protected void releaseIfNotRestart() {
if (!isRestart()) {
releaseResources();
}
}
private abstract class MyTemplateListener extends TemplateEditingAdapter {
protected abstract void restoreDaemonUpdateState();
@Override
public void beforeTemplateFinished(final TemplateState templateState, Template template) {
try {
final TextResult value = templateState.getVariableValue(PRIMARY_VARIABLE_NAME);
myInsertedName = value != null ? value.toString() : null;
TextRange range = templateState.getCurrentVariableRange();
final int currentOffset = myEditor.getCaretModel().getOffset();
if (range == null && myRenameOffset != null) {
range = new TextRange(myRenameOffset.getStartOffset(), myRenameOffset.getEndOffset());
}
myBeforeRevert =
range != null && range.getEndOffset() >= currentOffset && range.getStartOffset() <= currentOffset
? myEditor.getDocument().createRangeMarker(range.getStartOffset(), currentOffset)
: null;
if (myBeforeRevert != null) {
myBeforeRevert.setGreedyToRight(true);
}
finish(true);
}
finally {
restoreDaemonUpdateState();
}
}
@Override
public void templateFinished(Template template, final boolean brokenOff) {
boolean bind = false;
try {
super.templateFinished(template, brokenOff);
if (!brokenOff) {
bind = performRefactoring();
}
moveOffsetAfter(!brokenOff);
}
finally {
if (!bind) {
try {
((EditorImpl)InjectedLanguageUtil.getTopLevelEditor(myEditor)).stopDumbLater();
}
finally {
FinishMarkAction.finish(myProject, myEditor, myMarkAction);
if (myBeforeRevert != null) {
myBeforeRevert.dispose();
}
}
}
}
}
@Override
public void templateCancelled(Template template) {
try {
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
documentManager.commitAllDocuments();
finish(false);
moveOffsetAfter(false);
}
finally {
try {
restoreDaemonUpdateState();
}
finally {
FinishMarkAction.finish(myProject, myEditor, myMarkAction);
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.hadoop.impl;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Joiner;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.igfs.IgfsPath;
import org.apache.ignite.internal.processors.hadoop.HadoopFileBlock;
import org.apache.ignite.internal.processors.hadoop.HadoopJobEx;
import org.apache.ignite.internal.processors.hadoop.HadoopTaskInfo;
import org.apache.ignite.internal.processors.hadoop.HadoopTaskType;
import org.apache.ignite.internal.processors.hadoop.impl.examples.HadoopWordCount2;
import org.junit.Test;
/**
* Tests of Map, Combine and Reduce task executions of any version of hadoop API.
*/
abstract class HadoopTasksVersionsAbstractTest extends HadoopAbstractWordCountTest {
/** Empty hosts array. */
private static final String[] HOSTS = new String[0];
/**
* Creates some grid hadoop job. Override this method to create tests for any job implementation.
*
* @param inFile Input file name for the job.
* @param outFile Output file name for the job.
* @return Hadoop job.
* @throws IOException If fails.
*/
public abstract HadoopJobEx getHadoopJob(String inFile, String outFile) throws Exception;
/**
* @return prefix of reducer output file name. It's "part-" for v1 and "part-r-" for v2 API
*/
public abstract String getOutputFileNamePrefix();
/**
* Tests map task execution.
*
* @throws Exception If fails.
*/
@SuppressWarnings("ConstantConditions")
@Test
public void testMapTask() throws Exception {
IgfsPath inDir = new IgfsPath(PATH_INPUT);
igfs.mkdirs(inDir);
IgfsPath inFile = new IgfsPath(inDir, HadoopWordCount2.class.getSimpleName() + "-input");
URI inFileUri = URI.create(igfsScheme() + inFile.toString());
try (PrintWriter pw = new PrintWriter(igfs.create(inFile, true))) {
pw.println("hello0 world0");
pw.println("world1 hello1");
}
HadoopFileBlock fileBlock1 = new HadoopFileBlock(HOSTS, inFileUri, 0, igfs.info(inFile).length() - 1);
try (PrintWriter pw = new PrintWriter(igfs.append(inFile, false))) {
pw.println("hello2 world2");
pw.println("world3 hello3");
}
HadoopFileBlock fileBlock2 = new HadoopFileBlock(HOSTS, inFileUri, fileBlock1.length(),
igfs.info(inFile).length() - fileBlock1.length());
HadoopJobEx gridJob = getHadoopJob(igfsScheme() + inFile.toString(), igfsScheme() + PATH_OUTPUT);
HadoopTaskInfo taskInfo = new HadoopTaskInfo(HadoopTaskType.MAP, gridJob.id(), 0, 0, fileBlock1);
HadoopTestTaskContext ctx = new HadoopTestTaskContext(taskInfo, gridJob);
ctx.mockOutput().clear();
ctx.run();
assertEquals("hello0,1; world0,1; world1,1; hello1,1", Joiner.on("; ").join(ctx.mockOutput()));
ctx.mockOutput().clear();
ctx.taskInfo(new HadoopTaskInfo(HadoopTaskType.MAP, gridJob.id(), 0, 0, fileBlock2));
ctx.run();
assertEquals("hello2,1; world2,1; world3,1; hello3,1", Joiner.on("; ").join(ctx.mockOutput()));
}
/**
* Generates input data for reduce-like operation into mock context input and runs the operation.
*
* @param gridJob Job is to create reduce task from.
* @param taskType Type of task - combine or reduce.
* @param taskNum Number of task in job.
* @param words Pairs of words and its counts.
* @return Context with mock output.
* @throws IgniteCheckedException If fails.
*/
private HadoopTestTaskContext runTaskWithInput(HadoopJobEx gridJob, HadoopTaskType taskType,
int taskNum, String... words) throws IgniteCheckedException {
HadoopTaskInfo taskInfo = new HadoopTaskInfo(taskType, gridJob.id(), taskNum, 0, null);
HadoopTestTaskContext ctx = new HadoopTestTaskContext(taskInfo, gridJob);
for (int i = 0; i < words.length; i += 2) {
List<IntWritable> valList = new ArrayList<>();
for (int j = 0; j < Integer.parseInt(words[i + 1]); j++)
valList.add(new IntWritable(1));
ctx.mockInput().put(new Text(words[i]), valList);
}
ctx.run();
return ctx;
}
/**
* Tests reduce task execution.
*
* @throws Exception If fails.
*/
@Test
public void testReduceTask() throws Exception {
HadoopJobEx gridJob = getHadoopJob(igfsScheme() + PATH_INPUT, igfsScheme() + PATH_OUTPUT);
runTaskWithInput(gridJob, HadoopTaskType.REDUCE, 0, "word1", "5", "word2", "10");
runTaskWithInput(gridJob, HadoopTaskType.REDUCE, 1, "word3", "7", "word4", "15");
assertEquals(
"word1\t5\n" +
"word2\t10\n",
readAndSortFile(PATH_OUTPUT + "/_temporary/0/task_00000000-0000-0000-0000-000000000000_0000_r_000000/" +
getOutputFileNamePrefix() + "00000")
);
assertEquals(
"word3\t7\n" +
"word4\t15\n",
readAndSortFile(PATH_OUTPUT + "/_temporary/0/task_00000000-0000-0000-0000-000000000000_0000_r_000001/" +
getOutputFileNamePrefix() + "00001")
);
}
/**
* Tests combine task execution.
*
* @throws Exception If fails.
*/
@Test
public void testCombinerTask() throws Exception {
HadoopJobEx gridJob = getHadoopJob("/", "/");
HadoopTestTaskContext ctx =
runTaskWithInput(gridJob, HadoopTaskType.COMBINE, 0, "word1", "5", "word2", "10");
assertEquals("word1,5; word2,10", Joiner.on("; ").join(ctx.mockOutput()));
ctx = runTaskWithInput(gridJob, HadoopTaskType.COMBINE, 1, "word3", "7", "word4", "15");
assertEquals("word3,7; word4,15", Joiner.on("; ").join(ctx.mockOutput()));
}
/**
* Runs chain of map-combine task on file block.
*
* @param fileBlock block of input file to be processed.
* @param gridJob Hadoop job implementation.
* @return Context of combine task with mock output.
* @throws IgniteCheckedException If fails.
*/
private HadoopTestTaskContext runMapCombineTask(HadoopFileBlock fileBlock, HadoopJobEx gridJob)
throws IgniteCheckedException {
HadoopTaskInfo taskInfo = new HadoopTaskInfo(HadoopTaskType.MAP, gridJob.id(), 0, 0, fileBlock);
HadoopTestTaskContext mapCtx = new HadoopTestTaskContext(taskInfo, gridJob);
mapCtx.run();
//Prepare input for combine
taskInfo = new HadoopTaskInfo(HadoopTaskType.COMBINE, gridJob.id(), 0, 0, null);
HadoopTestTaskContext combineCtx = new HadoopTestTaskContext(taskInfo, gridJob);
combineCtx.makeTreeOfWritables(mapCtx.mockOutput());
combineCtx.run();
return combineCtx;
}
/**
* Tests all job in complex.
* Runs 2 chains of map-combine tasks and sends result into one reduce task.
*
* @throws Exception If fails.
*/
@SuppressWarnings("ConstantConditions")
@Test
public void testAllTasks() throws Exception {
IgfsPath inDir = new IgfsPath(PATH_INPUT);
igfs.mkdirs(inDir);
IgfsPath inFile = new IgfsPath(inDir, HadoopWordCount2.class.getSimpleName() + "-input");
URI inFileUri = URI.create(igfsScheme() + inFile.toString());
generateTestFile(inFile.toString(), "red", 100, "blue", 200, "green", 150, "yellow", 70);
//Split file into two blocks
long fileLen = igfs.info(inFile).length();
Long l = fileLen / 2;
HadoopFileBlock fileBlock1 = new HadoopFileBlock(HOSTS, inFileUri, 0, l);
HadoopFileBlock fileBlock2 = new HadoopFileBlock(HOSTS, inFileUri, l, fileLen - l);
HadoopJobEx gridJob = getHadoopJob(inFileUri.toString(), igfsScheme() + PATH_OUTPUT);
HadoopTestTaskContext combine1Ctx = runMapCombineTask(fileBlock1, gridJob);
HadoopTestTaskContext combine2Ctx = runMapCombineTask(fileBlock2, gridJob);
//Prepare input for combine
HadoopTaskInfo taskInfo = new HadoopTaskInfo(HadoopTaskType.REDUCE, gridJob.id(), 0, 0, null);
HadoopTestTaskContext reduceCtx = new HadoopTestTaskContext(taskInfo, gridJob);
reduceCtx.makeTreeOfWritables(combine1Ctx.mockOutput());
reduceCtx.makeTreeOfWritables(combine2Ctx.mockOutput());
reduceCtx.run();
reduceCtx.taskInfo(new HadoopTaskInfo(HadoopTaskType.COMMIT, gridJob.id(), 0, 0, null));
reduceCtx.run();
assertEquals(
"blue\t200\n" +
"green\t150\n" +
"red\t100\n" +
"yellow\t70\n",
readAndSortFile(PATH_OUTPUT + "/" + getOutputFileNamePrefix() + "00000")
);
}
}
| |
/*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.core.util;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.kie.internal.KnowledgeBase;
import org.kie.api.KieBaseConfiguration;
import org.kie.internal.KnowledgeBaseFactory;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.internal.runtime.StatefulKnowledgeSession;
import org.kie.api.runtime.rule.FactHandle;
import static org.junit.Assert.*;
import org.drools.core.common.DefaultFactHandle;
import org.drools.core.test.model.Cheese;
import org.drools.core.util.ObjectHashMap.ObjectEntry;
public class ObjectHashMapTest {
@Test
public void testChechExistsFalse() {
final ObjectHashMap map = new ObjectHashMap();
final Cheese stilton = new Cheese( "stilton",
5 );
map.put( new Integer( 1 ),
stilton,
false );
Cheese c = (Cheese) map.get( new Integer( 1 ) );
assertSame( stilton,
c );
// we haven't told the map to check if the key exists, so we should end up with two entries.
// the second one is nolonger reacheable
final Cheese cheddar = new Cheese( "cheddar",
5 );
map.put( new Integer( 1 ),
cheddar,
false );
c = (Cheese) map.get( new Integer( 1 ) );
assertSame( cheddar,
c );
Entry entry = map.getBucket( new Integer( 1 ) );
int size = 0;
while ( entry != null ) {
size++;
entry = entry.getNext();
}
assertEquals( 2,
size );
// Check remove works, should leave one unreachable key
map.remove( new Integer( 1 ) );
entry = map.getBucket( new Integer( 1 ) );
size = 0;
while ( entry != null ) {
size++;
entry = entry.getNext();
}
assertEquals( 1,
size );
}
@Test
public void testChechExistsTrue() {
final ObjectHashMap map = new ObjectHashMap();
final Cheese stilton = new Cheese( "stilton",
5 );
map.put( new Integer( 1 ),
stilton,
true );
Cheese c = (Cheese) map.get( new Integer( 1 ) );
assertSame( stilton,
c );
// we haven't told the map to check if the key exists, so we should end up with two entries.
// the second one is nolonger reacheable
final Cheese cheddar = new Cheese( "cheddar",
5 );
map.put( new Integer( 1 ),
cheddar );
c = (Cheese) map.get( new Integer( 1 ) );
assertSame( cheddar,
c );
Entry entry = map.getBucket( new Integer( 1 ) );
int size = 0;
while ( entry != null ) {
size++;
entry = entry.getNext();
}
assertEquals( 1,
size );
// Check remove works
map.remove( new Integer( 1 ) );
entry = map.getBucket( new Integer( 1 ) );
size = 0;
while ( entry != null ) {
size++;
entry = entry.getNext();
}
assertEquals( 0,
size );
}
@Test
public void testEqualityWithResize() {
KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
kconf.setOption( EqualityBehaviorOption.EQUALITY );
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kconf);
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
int length = 1 * 300 * 1000 ;
List<FactHandle> handles = new ArrayList<FactHandle>(1000);
List<String> objects = new ArrayList<String>(1000);
for ( int i = 0; i < length; i++) {
String s = getPropertyName(i);
FactHandle handle = ksession.insert( s );
objects.add( s );
handles.add( handle );
}
for ( int i = 0; i < length; i++) {
String s = objects.get(i);
FactHandle handle = handles.get( i );
assertEquals( s, ksession.getObject( handle ) );
assertSame( handle, ksession.getFactHandle( s ) );
// now check with disconnected facthandle
handle = new DefaultFactHandle(((DefaultFactHandle)handle).toExternalForm());
assertEquals( s, ksession.getObject( handle ) );
}
for ( int i = 0; i < length; i++) {
FactHandle handle = handles.get( i );
// now retract with disconnected facthandle
handle = new DefaultFactHandle(((DefaultFactHandle)handle).toExternalForm());
ksession.retract( handle );
assertEquals( length - i -1, ksession.getObjects().size() );
assertEquals( length - i -1, ksession.getFactHandles().size() );
}
assertEquals( 0, ksession.getObjects().size() );
assertEquals( 0, ksession.getFactHandles().size() );
}
@Test
public void testIdentityWithResize() {
KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
kconf.setOption( EqualityBehaviorOption.IDENTITY );
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kconf);
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
int length = 1 * 300 * 1000 ;
List<FactHandle> handles = new ArrayList<FactHandle>(1000);
List<String> objects = new ArrayList<String>(1000);
for ( int i = 0; i < length; i++) {
String s = getPropertyName(i);
FactHandle handle = ksession.insert( s );
objects.add( s );
handles.add( handle );
}
for ( int i = 0; i < length; i++) {
String s = objects.get(i);
FactHandle handle = handles.get( i );
assertEquals( s, ksession.getObject( handle ) );
assertSame( handle, ksession.getFactHandle( s ) );
// now check with disconnected facthandle
handle = new DefaultFactHandle(((DefaultFactHandle)handle).toExternalForm());
assertEquals( s, ksession.getObject( handle ) );
}
for ( int i = 0; i < length; i++) {
FactHandle handle = handles.get( i );
// now retract with disconnected facthandle
handle = new DefaultFactHandle(((DefaultFactHandle)handle).toExternalForm());
ksession.retract( handle );
assertEquals( length - i -1, ksession.getObjects().size() );
assertEquals( length - i -1, ksession.getFactHandles().size() );
}
assertEquals( 0, ksession.getObjects().size() );
assertEquals( 0, ksession.getFactHandles().size() );
}
public String getPropertyName(int i) {
char c1 = (char) (65+(i/3));
char c2 = (char) (97+(i/3));
return c1 + "bl" + i + "" + c2 + "blah";
}
@Test
public void testEmptyIterator() {
final ObjectHashMap map = new ObjectHashMap();
final Iterator it = map.iterator();
for ( ObjectEntry entry = (ObjectEntry) it.next(); entry != null; entry = (ObjectEntry) it.next() ) {
fail( "Map is empty, there should be no iteration" );
}
}
@Test
public void testStringData() {
final ObjectHashMap map = new ObjectHashMap();
assertNotNull( map );
final int count = 1000;
for ( int idx = 0; idx < count; idx++ ) {
final String key = "key" + idx;
final String val = "value" + idx;
map.put( key,
val );
assertEquals( val,
map.get( key ) );
}
}
@Test
public void testIntegerData() {
final ObjectHashMap map = new ObjectHashMap();
assertNotNull( map );
final int count = 1000;
for ( int idx = 0; idx < count; idx++ ) {
final Integer key = new Integer( idx );
final Integer val = new Integer( idx );
map.put( key,
val );
assertEquals( val,
map.get( key ) );
}
}
@Test
public void testJUHashmap() {
final java.util.HashMap map = new java.util.HashMap();
assertNotNull( map );
final int count = 1000;
for ( int idx = 0; idx < count; idx++ ) {
final String key = "key" + idx;
final String val = "value" + idx;
map.put( key,
val );
assertEquals( val,
map.get( key ) );
}
}
@Test
public void testStringDataDupFalse() {
final ObjectHashMap map = new ObjectHashMap();
assertNotNull( map );
final int count = 10000;
for ( int idx = 0; idx < count; idx++ ) {
final String key = "key" + idx;
final String val = "value" + idx;
map.put( key,
val,
false );
assertEquals( val,
map.get( key ) );
}
}
@Test
public void testJUHashMap1() {
final int count = 100000;
final java.util.HashMap map = new java.util.HashMap();
assertNotNull( map );
final long start = System.currentTimeMillis();
for ( int idx = 0; idx < count; idx++ ) {
final String key = "key" + idx;
final String strval = "value" + idx;
map.put( key,
strval );
}
final long end = System.currentTimeMillis();
System.out.println( "java.util.HashMap put(key,value) ET - " + ((end - start)) );
}
@Test
public void testStringData2() {
final int count = 100000;
final ObjectHashMap map = new ObjectHashMap();
assertNotNull( map );
final long start = System.currentTimeMillis();
for ( int idx = 0; idx < count; idx++ ) {
final String key = "key" + idx;
final String strval = "value" + idx;
map.put( key,
strval );
}
final long end = System.currentTimeMillis();
System.out.println( "Custom ObjectHashMap put(key,value) ET - " + ((end - start)) );
}
@Test
public void testStringData3() {
final int count = 100000;
final ObjectHashMap map = new ObjectHashMap();
assertNotNull( map );
for ( int idx = 0; idx < count; idx++ ) {
final String key = "key" + idx;
final String strval = "value" + idx;
map.put( key,
strval );
}
final long start = System.currentTimeMillis();
for ( int idx = 0; idx < count; idx++ ) {
final String key = "key" + idx;
map.get( key );
}
final long end = System.currentTimeMillis();
System.out.println( "Custom ObjectHashMap get(key) ET - " + ((end - start)) );
}
@Test
public void testJUHashMap2() {
final int count = 100000;
final java.util.HashMap map = new java.util.HashMap();
assertNotNull( map );
for ( int idx = 0; idx < count; idx++ ) {
final String key = "key" + idx;
final String strval = "value" + idx;
map.put( key,
strval );
}
final long start = System.currentTimeMillis();
for ( int idx = 0; idx < count; idx++ ) {
final String key = "key" + idx;
map.get( key );
}
final long end = System.currentTimeMillis();
System.out.println( "java.util.HashMap get(key) ET - " + ((end - start)) );
}
@Test
public void testStringData4() {
final int count = 100000;
final ObjectHashMap map = new ObjectHashMap();
assertNotNull( map );
for ( int idx = 0; idx < count; idx++ ) {
final String key = "key" + idx;
final String strval = "value" + idx;
map.put( key,
strval );
}
final long start = System.currentTimeMillis();
final org.drools.core.util.Iterator itr = map.iterator();
Object val = null;
while ( (val = itr.next()) != null ) {
val.hashCode();
}
final long end = System.currentTimeMillis();
System.out.println( "Custom ObjectHashMap iterate ET - " + ((end - start)) );
}
@Test
public void testJUHashMap3() {
final int count = 100000;
final java.util.HashMap map = new java.util.HashMap();
assertNotNull( map );
for ( int idx = 0; idx < count; idx++ ) {
final String key = "key" + idx;
final String strval = "value" + idx;
map.put( key,
strval );
}
final long start = System.currentTimeMillis();
final java.util.Iterator itr = map.values().iterator();
while ( itr.hasNext() ) {
itr.next().hashCode();
}
final long end = System.currentTimeMillis();
System.out.println( "java.util.HashMap iterate ET - " + ((end - start)) );
}
@Test
public void testStringData5() {
final int count = 100000;
final ObjectHashMap map = new ObjectHashMap();
assertNotNull( map );
final long start = System.currentTimeMillis();
for ( int idx = 0; idx < count; idx++ ) {
final String key = "key" + idx;
final String strval = "value" + idx;
map.put( key,
strval,
false );
}
final long end = System.currentTimeMillis();
System.out.println( "Custom ObjectHashMap dup false ET - " + ((end - start)) );
}
}
| |
/*
* 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.action.update;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.support.replication.ReplicationRequest;
import org.elasticsearch.action.support.single.instance.InstanceShardOperationRequest;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.action.ValidateActions.addValidationError;
public class UpdateRequest extends InstanceShardOperationRequest<UpdateRequest>
implements DocWriteRequest<UpdateRequest>, WriteRequest<UpdateRequest> {
private static final DeprecationLogger DEPRECATION_LOGGER =
new DeprecationLogger(Loggers.getLogger(UpdateRequest.class));
private String type;
private String id;
@Nullable
private String routing;
@Nullable
private String parent;
@Nullable
Script script;
private String[] fields;
private FetchSourceContext fetchSourceContext;
private long version = Versions.MATCH_ANY;
private VersionType versionType = VersionType.INTERNAL;
private int retryOnConflict = 0;
private RefreshPolicy refreshPolicy = RefreshPolicy.NONE;
private ActiveShardCount waitForActiveShards = ActiveShardCount.DEFAULT;
private IndexRequest upsertRequest;
private boolean scriptedUpsert = false;
private boolean docAsUpsert = false;
private boolean detectNoop = true;
@Nullable
private IndexRequest doc;
public UpdateRequest() {
}
public UpdateRequest(String index, String type, String id) {
super(index);
this.type = type;
this.id = id;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = super.validate();
if (type == null) {
validationException = addValidationError("type is missing", validationException);
}
if (id == null) {
validationException = addValidationError("id is missing", validationException);
}
if (versionType != VersionType.INTERNAL) {
validationException = addValidationError("version type [" + versionType + "] is not supported by the update API",
validationException);
} else {
if (version != Versions.MATCH_ANY && retryOnConflict > 0) {
validationException = addValidationError("can't provide both retry_on_conflict and a specific version", validationException);
}
if (!versionType.validateVersionForWrites(version)) {
validationException = addValidationError("illegal version value [" + version + "] for version type [" + versionType.name() + "]", validationException);
}
}
if (script == null && doc == null) {
validationException = addValidationError("script or doc is missing", validationException);
}
if (script != null && doc != null) {
validationException = addValidationError("can't provide both script and doc", validationException);
}
if (doc == null && docAsUpsert) {
validationException = addValidationError("doc must be specified if doc_as_upsert is enabled", validationException);
}
return validationException;
}
/**
* The type of the indexed document.
*/
@Override
public String type() {
return type;
}
/**
* Sets the type of the indexed document.
*/
public UpdateRequest type(String type) {
this.type = type;
return this;
}
/**
* The id of the indexed document.
*/
@Override
public String id() {
return id;
}
/**
* Sets the id of the indexed document.
*/
public UpdateRequest id(String id) {
this.id = id;
return this;
}
/**
* Controls the shard routing of the request. Using this value to hash the shard
* and not the id.
*/
@Override
public UpdateRequest routing(String routing) {
if (routing != null && routing.length() == 0) {
this.routing = null;
} else {
this.routing = routing;
}
return this;
}
/**
* Controls the shard routing of the request. Using this value to hash the shard
* and not the id.
*/
@Override
public String routing() {
return this.routing;
}
/**
* The parent id is used for the upsert request.
*/
public UpdateRequest parent(String parent) {
this.parent = parent;
return this;
}
public String parent() {
return parent;
}
public ShardId getShardId() {
return this.shardId;
}
public Script script() {
return this.script;
}
/**
* The script to execute. Note, make sure not to send different script each times and instead
* use script params if possible with the same (automatically compiled) script.
*/
public UpdateRequest script(Script script) {
this.script = script;
return this;
}
/**
* @deprecated Use {@link #script()} instead
*/
@Deprecated
public String scriptString() {
return this.script == null ? null : this.script.getIdOrCode();
}
/**
* @deprecated Use {@link #script()} instead
*/
@Deprecated
public ScriptType scriptType() {
return this.script == null ? null : this.script.getType();
}
/**
* @deprecated Use {@link #script()} instead
*/
@Deprecated
public Map<String, Object> scriptParams() {
return this.script == null ? null : this.script.getParams();
}
/**
* The script to execute. Note, make sure not to send different script each
* times and instead use script params if possible with the same
* (automatically compiled) script.
*
* @deprecated Use {@link #script(Script)} instead
*/
@Deprecated
public UpdateRequest script(String script, ScriptType scriptType) {
updateOrCreateScript(script, scriptType, null, null);
return this;
}
/**
* The script to execute. Note, make sure not to send different script each
* times and instead use script params if possible with the same
* (automatically compiled) script.
*
* @deprecated Use {@link #script(Script)} instead
*/
@Deprecated
public UpdateRequest script(String script) {
updateOrCreateScript(script, ScriptType.INLINE, null, null);
return this;
}
/**
* The language of the script to execute.
*
* @deprecated Use {@link #script(Script)} instead
*/
@Deprecated
public UpdateRequest scriptLang(String scriptLang) {
updateOrCreateScript(null, null, scriptLang, null);
return this;
}
/**
* @deprecated Use {@link #script()} instead
*/
@Deprecated
public String scriptLang() {
return script == null ? null : script.getLang();
}
/**
* Add a script parameter.
*
* @deprecated Use {@link #script(Script)} instead
*/
@Deprecated
public UpdateRequest addScriptParam(String name, Object value) {
Script script = script();
if (script == null) {
HashMap<String, Object> scriptParams = new HashMap<>();
scriptParams.put(name, value);
updateOrCreateScript(null, null, null, scriptParams);
} else {
Map<String, Object> scriptParams = script.getParams();
if (scriptParams == null) {
scriptParams = new HashMap<>();
scriptParams.put(name, value);
updateOrCreateScript(null, null, null, scriptParams);
} else {
scriptParams.put(name, value);
}
}
return this;
}
/**
* Sets the script parameters to use with the script.
*
* @deprecated Use {@link #script(Script)} instead
*/
@Deprecated
public UpdateRequest scriptParams(Map<String, Object> scriptParams) {
updateOrCreateScript(null, null, null, scriptParams);
return this;
}
private void updateOrCreateScript(String scriptContent, ScriptType type, String lang, Map<String, Object> params) {
Script script = script();
if (script == null) {
script = new Script(type == null ? ScriptType.INLINE : type, lang, scriptContent == null ? "" : scriptContent, params);
} else {
String newScriptContent = scriptContent == null ? script.getIdOrCode() : scriptContent;
ScriptType newScriptType = type == null ? script.getType() : type;
String newScriptLang = lang == null ? script.getLang() : lang;
Map<String, Object> newScriptParams = params == null ? script.getParams() : params;
script = new Script(newScriptType, newScriptLang, newScriptContent, newScriptParams);
}
script(script);
}
/**
* The script to execute. Note, make sure not to send different script each
* times and instead use script params if possible with the same
* (automatically compiled) script.
*
* @deprecated Use {@link #script(Script)} instead
*/
@Deprecated
public UpdateRequest script(String script, ScriptType scriptType, @Nullable Map<String, Object> scriptParams) {
this.script = new Script(scriptType, Script.DEFAULT_SCRIPT_LANG, script, scriptParams);
return this;
}
/**
* The script to execute. Note, make sure not to send different script each
* times and instead use script params if possible with the same
* (automatically compiled) script.
*
* @param script
* The script to execute
* @param scriptLang
* The script language
* @param scriptType
* The script type
* @param scriptParams
* The script parameters
*
* @deprecated Use {@link #script(Script)} instead
*/
@Deprecated
public UpdateRequest script(String script, @Nullable String scriptLang, ScriptType scriptType,
@Nullable Map<String, Object> scriptParams) {
this.script = new Script(scriptType, scriptLang, script, scriptParams);
return this;
}
/**
* Explicitly specify the fields that will be returned. By default, nothing is returned.
* @deprecated Use {@link UpdateRequest#fetchSource(String[], String[])} instead
*/
@Deprecated
public UpdateRequest fields(String... fields) {
this.fields = fields;
return this;
}
/**
* Indicate that _source should be returned with every hit, with an
* "include" and/or "exclude" set which can include simple wildcard
* elements.
*
* @param include
* An optional include (optionally wildcarded) pattern to filter
* the returned _source
* @param exclude
* An optional exclude (optionally wildcarded) pattern to filter
* the returned _source
*/
public UpdateRequest fetchSource(@Nullable String include, @Nullable String exclude) {
FetchSourceContext context = this.fetchSourceContext == null ? FetchSourceContext.FETCH_SOURCE : this.fetchSourceContext;
this.fetchSourceContext = new FetchSourceContext(context.fetchSource(), new String[] {include}, new String[]{exclude});
return this;
}
/**
* Indicate that _source should be returned, with an
* "include" and/or "exclude" set which can include simple wildcard
* elements.
*
* @param includes
* An optional list of include (optionally wildcarded) pattern to
* filter the returned _source
* @param excludes
* An optional list of exclude (optionally wildcarded) pattern to
* filter the returned _source
*/
public UpdateRequest fetchSource(@Nullable String[] includes, @Nullable String[] excludes) {
FetchSourceContext context = this.fetchSourceContext == null ? FetchSourceContext.FETCH_SOURCE : this.fetchSourceContext;
this.fetchSourceContext = new FetchSourceContext(context.fetchSource(), includes, excludes);
return this;
}
/**
* Indicates whether the response should contain the updated _source.
*/
public UpdateRequest fetchSource(boolean fetchSource) {
FetchSourceContext context = this.fetchSourceContext == null ? FetchSourceContext.FETCH_SOURCE : this.fetchSourceContext;
this.fetchSourceContext = new FetchSourceContext(fetchSource, context.includes(), context.excludes());
return this;
}
/**
* Explicitely set the fetch source context for this request
*/
public UpdateRequest fetchSource(FetchSourceContext context) {
this.fetchSourceContext = context;
return this;
}
/**
* Get the fields to be returned.
* @deprecated Use {@link UpdateRequest#fetchSource()} instead
*/
@Deprecated
public String[] fields() {
return fields;
}
/**
* Gets the {@link FetchSourceContext} which defines how the _source should
* be fetched.
*/
public FetchSourceContext fetchSource() {
return fetchSourceContext;
}
/**
* Sets the number of retries of a version conflict occurs because the document was updated between
* getting it and updating it. Defaults to 0.
*/
public UpdateRequest retryOnConflict(int retryOnConflict) {
this.retryOnConflict = retryOnConflict;
return this;
}
public int retryOnConflict() {
return this.retryOnConflict;
}
@Override
public UpdateRequest version(long version) {
this.version = version;
return this;
}
@Override
public long version() {
return this.version;
}
@Override
public UpdateRequest versionType(VersionType versionType) {
this.versionType = versionType;
return this;
}
@Override
public VersionType versionType() {
return this.versionType;
}
@Override
public OpType opType() {
return OpType.UPDATE;
}
@Override
public UpdateRequest setRefreshPolicy(RefreshPolicy refreshPolicy) {
this.refreshPolicy = refreshPolicy;
return this;
}
@Override
public RefreshPolicy getRefreshPolicy() {
return refreshPolicy;
}
public ActiveShardCount waitForActiveShards() {
return this.waitForActiveShards;
}
/**
* Sets the number of shard copies that must be active before proceeding with the write.
* See {@link ReplicationRequest#waitForActiveShards(ActiveShardCount)} for details.
*/
public UpdateRequest waitForActiveShards(ActiveShardCount waitForActiveShards) {
this.waitForActiveShards = waitForActiveShards;
return this;
}
/**
* A shortcut for {@link #waitForActiveShards(ActiveShardCount)} where the numerical
* shard count is passed in, instead of having to first call {@link ActiveShardCount#from(int)}
* to get the ActiveShardCount.
*/
public UpdateRequest waitForActiveShards(final int waitForActiveShards) {
return waitForActiveShards(ActiveShardCount.from(waitForActiveShards));
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(IndexRequest doc) {
this.doc = doc;
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(XContentBuilder source) {
safeDoc().source(source);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(Map source) {
safeDoc().source(source);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(Map source, XContentType contentType) {
safeDoc().source(source, contentType);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(String source) {
safeDoc().source(source);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(byte[] source) {
safeDoc().source(source);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(byte[] source, int offset, int length) {
safeDoc().source(source, offset, length);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified, the doc provided
* is a field and value pairs.
*/
public UpdateRequest doc(Object... source) {
safeDoc().source(source);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(String field, Object value) {
safeDoc().source(field, value);
return this;
}
public IndexRequest doc() {
return this.doc;
}
private IndexRequest safeDoc() {
if (doc == null) {
doc = new IndexRequest();
}
return doc;
}
/**
* Sets the index request to be used if the document does not exists. Otherwise, a {@link org.elasticsearch.index.engine.DocumentMissingException}
* is thrown.
*/
public UpdateRequest upsert(IndexRequest upsertRequest) {
this.upsertRequest = upsertRequest;
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists.
*/
public UpdateRequest upsert(XContentBuilder source) {
safeUpsertRequest().source(source);
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists.
*/
public UpdateRequest upsert(Map source) {
safeUpsertRequest().source(source);
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists.
*/
public UpdateRequest upsert(Map source, XContentType contentType) {
safeUpsertRequest().source(source, contentType);
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists.
*/
public UpdateRequest upsert(String source) {
safeUpsertRequest().source(source);
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists.
*/
public UpdateRequest upsert(byte[] source) {
safeUpsertRequest().source(source);
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists.
*/
public UpdateRequest upsert(byte[] source, int offset, int length) {
safeUpsertRequest().source(source, offset, length);
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists. The doc
* includes field and value pairs.
*/
public UpdateRequest upsert(Object... source) {
safeUpsertRequest().source(source);
return this;
}
public IndexRequest upsertRequest() {
return this.upsertRequest;
}
private IndexRequest safeUpsertRequest() {
if (upsertRequest == null) {
upsertRequest = new IndexRequest();
}
return upsertRequest;
}
public UpdateRequest fromXContent(XContentBuilder source) throws Exception {
return fromXContent(source.bytes());
}
public UpdateRequest fromXContent(byte[] source) throws Exception {
return fromXContent(source, 0, source.length);
}
public UpdateRequest fromXContent(byte[] source, int offset, int length) throws Exception {
return fromXContent(new BytesArray(source, offset, length));
}
/**
* Should this update attempt to detect if it is a noop? Defaults to true.
* @return this for chaining
*/
public UpdateRequest detectNoop(boolean detectNoop) {
this.detectNoop = detectNoop;
return this;
}
/**
* Should this update attempt to detect if it is a noop? Defaults to true.
*/
public boolean detectNoop() {
return detectNoop;
}
public UpdateRequest fromXContent(BytesReference source) throws IOException {
Script script = null;
try (XContentParser parser = XContentFactory.xContent(source).createParser(source)) {
XContentParser.Token token = parser.nextToken();
if (token == null) {
return this;
}
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if ("script".equals(currentFieldName)) {
script = Script.parse(parser, ParseFieldMatcher.EMPTY);
} else if ("scripted_upsert".equals(currentFieldName)) {
scriptedUpsert = parser.booleanValue();
} else if ("upsert".equals(currentFieldName)) {
XContentType xContentType = XContentFactory.xContentType(source);
XContentBuilder builder = XContentFactory.contentBuilder(xContentType);
builder.copyCurrentStructure(parser);
safeUpsertRequest().source(builder);
} else if ("doc".equals(currentFieldName)) {
XContentType xContentType = XContentFactory.xContentType(source);
XContentBuilder docBuilder = XContentFactory.contentBuilder(xContentType);
docBuilder.copyCurrentStructure(parser);
safeDoc().source(docBuilder);
} else if ("doc_as_upsert".equals(currentFieldName)) {
docAsUpsert(parser.booleanValue());
} else if ("detect_noop".equals(currentFieldName)) {
detectNoop(parser.booleanValue());
} else if ("fields".equals(currentFieldName)) {
List<Object> fields = null;
if (token == XContentParser.Token.START_ARRAY) {
fields = (List) parser.list();
} else if (token.isValue()) {
fields = Collections.singletonList(parser.text());
}
if (fields != null) {
fields(fields.toArray(new String[fields.size()]));
}
} else if ("_source".equals(currentFieldName)) {
fetchSourceContext = FetchSourceContext.parse(parser);
}
}
if (script != null) {
this.script = script;
}
}
return this;
}
public boolean docAsUpsert() {
return this.docAsUpsert;
}
public UpdateRequest docAsUpsert(boolean shouldUpsertDoc) {
this.docAsUpsert = shouldUpsertDoc;
return this;
}
public boolean scriptedUpsert(){
return this.scriptedUpsert;
}
public UpdateRequest scriptedUpsert(boolean scriptedUpsert) {
this.scriptedUpsert = scriptedUpsert;
return this;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
waitForActiveShards = ActiveShardCount.readFrom(in);
type = in.readString();
id = in.readString();
routing = in.readOptionalString();
parent = in.readOptionalString();
if (in.readBoolean()) {
script = new Script(in);
}
retryOnConflict = in.readVInt();
refreshPolicy = RefreshPolicy.readFrom(in);
if (in.readBoolean()) {
doc = new IndexRequest();
doc.readFrom(in);
}
fields = in.readOptionalStringArray();
fetchSourceContext = in.readOptionalWriteable(FetchSourceContext::new);
if (in.readBoolean()) {
upsertRequest = new IndexRequest();
upsertRequest.readFrom(in);
}
docAsUpsert = in.readBoolean();
version = in.readLong();
versionType = VersionType.fromValue(in.readByte());
detectNoop = in.readBoolean();
scriptedUpsert = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
waitForActiveShards.writeTo(out);
out.writeString(type);
out.writeString(id);
out.writeOptionalString(routing);
out.writeOptionalString(parent);
boolean hasScript = script != null;
out.writeBoolean(hasScript);
if (hasScript) {
script.writeTo(out);
}
out.writeVInt(retryOnConflict);
refreshPolicy.writeTo(out);
if (doc == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
// make sure the basics are set
doc.index(index);
doc.type(type);
doc.id(id);
doc.writeTo(out);
}
out.writeOptionalStringArray(fields);
out.writeOptionalWriteable(fetchSourceContext);
if (upsertRequest == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
// make sure the basics are set
upsertRequest.index(index);
upsertRequest.type(type);
upsertRequest.id(id);
upsertRequest.writeTo(out);
}
out.writeBoolean(docAsUpsert);
out.writeLong(version);
out.writeByte(versionType.getValue());
out.writeBoolean(detectNoop);
out.writeBoolean(scriptedUpsert);
}
}
| |
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.vfs;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.util.StringCanonicalizer;
import java.io.File;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* This class represents an immutable UNIX filesystem path, which may be absolute or relative. The
* path is maintained as a simple ordered list of path segment strings.
*
* <p>This class is independent from other VFS classes, especially anything requiring native code.
* It is safe to use in places that need simple segmented string path functionality.
*
* <p>There is some limited support for Windows-style paths. Most importantly, drive identifiers
* in front of a path (c:/abc) are supported and such paths are correctly recognized as absolute.
* However, Windows-style backslash separators (C:\\foo\\bar) are explicitly not supported, same
* with advanced features like \\\\network\\paths and \\\\?\\unc\\paths.
*/
@Immutable @ThreadSafe
public final class PathFragment implements Comparable<PathFragment>, Serializable {
public static final int INVALID_SEGMENT = -1;
public static final char SEPARATOR_CHAR = '/';
public static final char EXTRA_SEPARATOR_CHAR =
(OS.getCurrent() == OS.WINDOWS) ? '\\' : '/';
public static final String ROOT_DIR = "/";
/** An empty path fragment. */
public static final PathFragment EMPTY_FRAGMENT = new PathFragment("");
public static final Function<String, PathFragment> TO_PATH_FRAGMENT =
new Function<String, PathFragment>() {
@Override
public PathFragment apply(String str) {
return new PathFragment(str);
}
};
public static final Predicate<PathFragment> IS_ABSOLUTE =
new Predicate<PathFragment>() {
@Override
public boolean apply(PathFragment input) {
return input.isAbsolute();
}
};
private static final Function<PathFragment, String> TO_SAFE_PATH_STRING =
new Function<PathFragment, String>() {
@Override
public String apply(PathFragment path) {
return path.getSafePathString();
}
};
/** Lower-level API. Create a PathFragment, interning segments. */
public static PathFragment create(char driveLetter, boolean isAbsolute, String[] segments) {
String[] internedSegments = new String[segments.length];
for (int i = 0; i < segments.length; i++) {
internedSegments[i] = StringCanonicalizer.intern(segments[i]);
}
return new PathFragment(driveLetter, isAbsolute, internedSegments);
}
/** Same as {@link #create(char, boolean, String[])}, except for {@link List}s of segments. */
public static PathFragment create(char driveLetter, boolean isAbsolute, List<String> segments) {
String[] internedSegments = new String[segments.size()];
for (int i = 0; i < segments.size(); i++) {
internedSegments[i] = StringCanonicalizer.intern(segments.get(i));
}
return new PathFragment(driveLetter, isAbsolute, internedSegments);
}
// We have 3 word-sized fields (segments, hashCode and path), and 2
// byte-sized ones, which fits in 16 bytes. Object sizes are rounded
// to 16 bytes. Medium sized builds can easily hold millions of
// live PathFragments, so do not add further fields on a whim.
// The individual path components.
// Does *not* include the Windows drive letter.
private final String[] segments;
// True both for UNIX-style absolute paths ("/foo") and Windows-style ("C:/foo").
// False for a Windows-style volume label ("C:") which is actually a relative path.
private final boolean isAbsolute;
// Upper case Windows drive letter, or '\0' if none or unknown.
private final char driveLetter;
// hashCode and path are lazily initialized but semantically immutable.
private int hashCode;
private String path;
/**
* Construct a PathFragment from a string, which is an absolute or relative UNIX or Windows path.
*/
public PathFragment(String path) {
this.driveLetter =
(OS.getCurrent() == OS.WINDOWS
&& path.length() >= 2
&& path.charAt(1) == ':'
&& Character.isLetter(path.charAt(0)))
? Character.toUpperCase(path.charAt(0))
: '\0';
if (driveLetter != '\0') {
path = path.substring(2);
// TODO(bazel-team): Decide what to do about non-absolute paths with a volume name, e.g. C:x.
}
this.isAbsolute = path.length() > 0 && isSeparator(path.charAt(0));
this.segments = segment(path, isAbsolute ? 1 : 0);
}
private static boolean isSeparator(char c) {
return c == SEPARATOR_CHAR || c == EXTRA_SEPARATOR_CHAR;
}
/**
* Construct a PathFragment from a java.io.File, which is an absolute or
* relative UNIX path. Does not support Windows-style Files.
*/
public PathFragment(File path) {
this(path.getPath());
}
/**
* Constructs a PathFragment, taking ownership of segments. Package-private,
* because it does not perform a defensive clone of the segments array. Used
* here in PathFragment, and by Path.asFragment() and Path.relativeTo().
*/
PathFragment(char driveLetter, boolean isAbsolute, String[] segments) {
driveLetter = Character.toUpperCase(driveLetter);
if (OS.getCurrent() == OS.WINDOWS
&& segments.length > 0
&& segments[0].length() == 2
&& Character.toUpperCase(segments[0].charAt(0)) == driveLetter
&& segments[0].charAt(1) == ':') {
throw new IllegalStateException(
String.format(
"the drive letter should not be a path segment; drive='%c', segments=[%s]",
driveLetter, Joiner.on(", ").join(segments)));
}
this.driveLetter = driveLetter;
this.isAbsolute = isAbsolute;
this.segments = segments;
}
/**
* Construct a PathFragment from a sequence of other PathFragments. The new
* fragment will be absolute iff the first fragment was absolute.
*/
public PathFragment(PathFragment first, PathFragment second, PathFragment... more) {
// TODO(bazel-team): The handling of absolute path fragments in this constructor is unexpected.
this.segments = new String[sumLengths(first, second, more)];
int offset = 0;
offset += addSegments(offset, first);
offset += addSegments(offset, second);
for (PathFragment fragment : more) {
offset += addSegments(offset, fragment);
}
this.isAbsolute = first.isAbsolute;
this.driveLetter = first.driveLetter;
}
private int addSegments(int offset, PathFragment fragment) {
int count = fragment.segmentCount();
System.arraycopy(fragment.segments, 0, this.segments, offset, count);
return count;
}
private static int sumLengths(PathFragment first, PathFragment second, PathFragment[] more) {
int total = first.segmentCount() + second.segmentCount();
for (PathFragment fragment : more) {
total += fragment.segmentCount();
}
return total;
}
/**
* Segments the string passed in as argument and returns an array of strings.
* The split is performed along occurrences of (sequences of) the slash
* character.
*
* @param toSegment the string to segment
* @param offset how many characters from the start of the string to ignore.
*/
private static String[] segment(String toSegment, int offset) {
int length = toSegment.length();
// Handle "/" and "" quickly.
if (length == offset) {
return new String[0];
}
// We make two passes through the array of characters: count & alloc,
// because simply using ArrayList was a bottleneck showing up during profiling.
int seg = 0;
int start = offset;
for (int i = offset; i < length; i++) {
if (isSeparator(toSegment.charAt(i))) {
if (i > start) { // to skip repeated separators
seg++;
}
start = i + 1;
}
}
if (start < length) {
seg++;
}
String[] result = new String[seg];
seg = 0;
start = offset;
for (int i = offset; i < length; i++) {
if (isSeparator(toSegment.charAt(i))) {
if (i > start) { // to skip repeated separators
result[seg] = StringCanonicalizer.intern(toSegment.substring(start, i));
seg++;
}
start = i + 1;
}
}
if (start < length) {
result[seg] = StringCanonicalizer.intern(toSegment.substring(start, length));
}
return result;
}
private Object writeReplace() {
return new PathFragmentSerializationProxy(toString());
}
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Serialization is allowed only by proxy");
}
/**
* Returns the path string using '/' as the name-separator character. Returns "" if the path
* is both relative and empty.
*/
public String getPathString() {
// Double-checked locking works, even without volatile, because path is a String, according to:
// http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
if (path == null) {
synchronized (this) {
if (path == null) {
path = StringCanonicalizer.intern(joinSegments(SEPARATOR_CHAR));
}
}
}
return path;
}
/**
* Returns "." if the path fragment is both relative and empty, or {@link
* #getPathString} otherwise.
*/
// TODO(bazel-team): Change getPathString to do this - this behavior makes more sense.
public String getSafePathString() {
return (!isAbsolute && (segmentCount() == 0)) ? "." : getPathString();
}
/**
* Returns the path string using '/' as the name-separator character, but do so in a way
* unambiguously recognizable as path. In other words, return "." for relative and empty paths,
* and prefix relative paths with one segment by "./".
*
* <p>In this way, a shell will always interpret such a string as path (absolute or relative to
* the working directory) and not as command to be searched for in the search path.
*/
public String getCallablePathString() {
if (isAbsolute) {
return getPathString();
} else if (segmentCount() == 0) {
return ".";
} else if (segmentCount() == 1) {
return "." + SEPARATOR_CHAR + getPathString();
} else {
return getPathString();
}
}
/**
* Returns a sequence consisting of the {@link #getSafePathString()} return of each item in
* {@code fragments}.
*/
public static Iterable<String> safePathStrings(Iterable<PathFragment> fragments) {
return Iterables.transform(fragments, TO_SAFE_PATH_STRING);
}
/** Returns the subset of {@code paths} that start with {@code startingWithPath}. */
public static ImmutableSet<PathFragment> filterPathsStartingWith(Set<PathFragment> paths,
PathFragment startingWithPath) {
return ImmutableSet.copyOf(Iterables.filter(paths, startsWithPredicate(startingWithPath)));
}
public static Predicate<PathFragment> startsWithPredicate(final PathFragment prefix) {
return new Predicate<PathFragment>() {
@Override
public boolean apply(PathFragment pathFragment) {
return pathFragment.startsWith(prefix);
}
};
}
/**
* Throws {@link IllegalArgumentException} if {@code paths} contains any paths that
* are equal to {@code startingWithPath} or that are not beneath {@code startingWithPath}.
*/
public static void checkAllPathsAreUnder(Iterable<PathFragment> paths,
PathFragment startingWithPath) {
for (PathFragment path : paths) {
Preconditions.checkArgument(
!path.equals(startingWithPath) && path.startsWith(startingWithPath),
"%s is not beneath %s", path, startingWithPath);
}
}
private String joinSegments(char separatorChar) {
if (segments.length == 0 && isAbsolute) {
return windowsVolume() + ROOT_DIR;
}
// Profile driven optimization:
// Preallocate a size determined by the number of segments, so that
// we do not have to expand the capacity of the StringBuilder.
// Heuristically, this estimate is right for about 99% of the time.
int estimateSize =
((driveLetter != '\0') ? 2 : 0)
+ ((segments.length == 0) ? 0 : (segments.length + 1) * 20);
StringBuilder result = new StringBuilder(estimateSize);
if (isAbsolute) {
// Only print the Windows volume label if the PathFragment is absolute. Do not print relative
// Windows paths like "C:foo/bar", it would break all kinds of things, e.g. glob().
result.append(windowsVolume());
}
boolean initialSegment = true;
for (String segment : segments) {
if (!initialSegment || isAbsolute) {
result.append(separatorChar);
}
initialSegment = false;
result.append(segment);
}
return result.toString();
}
/**
* Return true iff none of the segments are either "." or "..".
*/
public boolean isNormalized() {
for (String segment : segments) {
if (segment.equals(".") || segment.equals("..")) {
return false;
}
}
return true;
}
/**
* Normalizes the path fragment: removes "." and ".." segments if possible
* (if there are too many ".." segments, the resulting PathFragment will still
* start with "..").
*/
public PathFragment normalize() {
String[] scratchSegments = new String[segments.length];
int segmentCount = 0;
for (String segment : segments) {
switch (segment) {
case ".":
// Just discard it
break;
case "..":
if (segmentCount > 0 && !scratchSegments[segmentCount - 1].equals("..")) {
// Remove the last segment, if there is one and it is not "..". This
// means that the resulting PathFragment can still contain ".."
// segments at the beginning.
segmentCount--;
} else {
scratchSegments[segmentCount++] = segment;
}
break;
default:
scratchSegments[segmentCount++] = segment;
}
}
if (segmentCount == segments.length) {
// Optimization, no new PathFragment needs to be created.
return this;
}
return new PathFragment(driveLetter, isAbsolute,
subarray(scratchSegments, 0, segmentCount));
}
/**
* Returns the path formed by appending the relative or absolute path fragment
* {@code otherFragment} to this path.
*
* <p>If {@code otherFragment} is absolute, the current path will be ignored;
* otherwise, they will be concatenated. This is a purely syntactic operation,
* with no path normalization or I/O performed.
*/
public PathFragment getRelative(PathFragment otherFragment) {
if (otherFragment == EMPTY_FRAGMENT) {
return this;
}
if (otherFragment.isAbsolute()) {
return this.driveLetter == '\0' || otherFragment.driveLetter != '\0'
? otherFragment
: new PathFragment(this.driveLetter, true, otherFragment.segments);
} else {
return new PathFragment(this, otherFragment);
}
}
/**
* Returns the path formed by appending the relative or absolute string
* {@code path} to this path.
*
* <p>If the given path string is absolute, the current path will be ignored;
* otherwise, they will be concatenated. This is a purely syntactic operation,
* with no path normalization or I/O performed.
*/
public PathFragment getRelative(String path) {
return getRelative(new PathFragment(path));
}
/**
* Returns the path formed by appending the single non-special segment
* "baseName" to this path.
*
* <p>You should almost always use {@link #getRelative} instead, which has
* the same performance characteristics if the given name is a valid base
* name, and which also works for '.', '..', and strings containing '/'.
*
* @throws IllegalArgumentException if {@code baseName} is not a valid base
* name according to {@link FileSystemUtils#checkBaseName}
*/
public PathFragment getChild(String baseName) {
FileSystemUtils.checkBaseName(baseName);
baseName = StringCanonicalizer.intern(baseName);
String[] newSegments = Arrays.copyOf(segments, segments.length + 1);
newSegments[newSegments.length - 1] = baseName;
return new PathFragment(driveLetter, isAbsolute, newSegments);
}
/**
* Returns the last segment of this path, or "" for the empty fragment.
*/
public String getBaseName() {
return (segments.length == 0) ? "" : segments[segments.length - 1];
}
/**
* Returns the file extension of this path, excluding the period, or "" if there is no extension.
*/
public String getFileExtension() {
String baseName = getBaseName();
int lastIndex = baseName.lastIndexOf('.');
if (lastIndex != -1) {
return baseName.substring(lastIndex + 1);
}
return "";
}
/**
* Returns a relative path fragment to this path, relative to
* {@code ancestorDirectory}.
* <p>
* <code>x.relativeTo(z) == y</code> implies
* <code>z.getRelative(y) == x</code>.
* <p>
* For example, <code>"foo/bar/wiz".relativeTo("foo")</code>
* returns <code>"bar/wiz"</code>.
*/
public PathFragment relativeTo(PathFragment ancestorDirectory) {
String[] ancestorSegments = ancestorDirectory.segments();
int ancestorLength = ancestorSegments.length;
if (isAbsolute != ancestorDirectory.isAbsolute()
|| segments.length < ancestorLength) {
throw new IllegalArgumentException("PathFragment " + this
+ " is not beneath " + ancestorDirectory);
}
for (int index = 0; index < ancestorLength; index++) {
if (!segments[index].equals(ancestorSegments[index])) {
throw new IllegalArgumentException("PathFragment " + this
+ " is not beneath " + ancestorDirectory);
}
}
int length = segments.length - ancestorLength;
String[] resultSegments = subarray(segments, ancestorLength, length);
return new PathFragment('\0', false, resultSegments);
}
/**
* Returns a relative path fragment to this path, relative to {@code path}.
*/
public PathFragment relativeTo(String path) {
return relativeTo(new PathFragment(path));
}
/**
* Returns a new PathFragment formed by appending {@code newName} to the
* parent directory. Null is returned iff this method is called on a
* PathFragment with zero segments. If {@code newName} designates an absolute path,
* the value of {@code this} will be ignored and a PathFragment corresponding to
* {@code newName} will be returned. This behavior is consistent with the behavior of
* {@link #getRelative(String)}.
*/
public PathFragment replaceName(String newName) {
return segments.length == 0 ? null : getParentDirectory().getRelative(newName);
}
/**
* Returns a path representing the parent directory of this path,
* or null iff this Path represents the root of the filesystem.
*
* <p>Note: This method DOES NOT normalize ".." and "." path segments.
*/
public PathFragment getParentDirectory() {
return segments.length == 0 ? null : subFragment(0, segments.length - 1);
}
/**
* Returns true iff {@code prefix}, considered as a list of path segments, is
* a prefix of {@code this}, and that they are both relative or both
* absolute.
*
* <p>This is a reflexive, transitive, anti-symmetric relation (i.e. a partial
* order)
*/
public boolean startsWith(PathFragment prefix) {
if (this.isAbsolute != prefix.isAbsolute
|| this.segments.length < prefix.segments.length
|| (isAbsolute && this.driveLetter != prefix.driveLetter)) {
return false;
}
for (int i = 0, len = prefix.segments.length; i < len; i++) {
if (!this.segments[i].equals(prefix.segments[i])) {
return false;
}
}
return true;
}
/**
* Returns true iff {@code suffix}, considered as a list of path segments, is
* relative and a suffix of {@code this}, or both are absolute and equal.
*
* <p>This is a reflexive, transitive, anti-symmetric relation (i.e. a partial
* order)
*/
public boolean endsWith(PathFragment suffix) {
if ((suffix.isAbsolute && !suffix.equals(this)) ||
this.segments.length < suffix.segments.length) {
return false;
}
int offset = this.segments.length - suffix.segments.length;
for (int i = 0; i < suffix.segments.length; i++) {
if (!this.segments[offset + i].equals(suffix.segments[i])) {
return false;
}
}
return true;
}
private static String[] subarray(String[] array, int start, int length) {
String[] subarray = new String[length];
System.arraycopy(array, start, subarray, 0, length);
return subarray;
}
/**
* Returns a new path fragment that is a sub fragment of this one.
* The sub fragment begins at the specified <code>beginIndex</code> segment
* and ends at the segment at index <code>endIndex - 1</code>. Thus the number
* of segments in the new PathFragment is <code>endIndex - beginIndex</code>.
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified sub fragment, never null.
* @exception IndexOutOfBoundsException if the
* <code>beginIndex</code> is negative, or
* <code>endIndex</code> is larger than the length of
* this <code>String</code> object, or
* <code>beginIndex</code> is larger than
* <code>endIndex</code>.
*/
public PathFragment subFragment(int beginIndex, int endIndex) {
int count = segments.length;
if ((beginIndex < 0) || (beginIndex > endIndex) || (endIndex > count)) {
throw new IndexOutOfBoundsException(String.format("path: %s, beginIndex: %d endIndex: %d",
toString(), beginIndex, endIndex));
}
boolean isAbsolute = (beginIndex == 0) && this.isAbsolute;
return ((beginIndex == 0) && (endIndex == count)) ? this :
new PathFragment(driveLetter, isAbsolute,
subarray(segments, beginIndex, endIndex - beginIndex));
}
/**
* Returns true iff the path represented by this object is absolute.
*/
public boolean isAbsolute() {
return isAbsolute;
}
/**
* Returns the segments of this path fragment. This array should not be
* modified.
*/
String[] segments() {
return segments;
}
public ImmutableList<String> getSegments() {
return ImmutableList.copyOf(segments);
}
public String windowsVolume() {
return (driveLetter != '\0') ? driveLetter + ":" : "";
}
/** Return the drive letter or '\0' if not applicable. */
public char getDriveLetter() {
return driveLetter;
}
/**
* Returns the number of segments in this path.
*/
public int segmentCount() {
return segments.length;
}
/**
* Returns the specified segment of this path; index must be positive and
* less than numSegments().
*/
public String getSegment(int index) {
return segments[index];
}
/**
* Returns the index of the first segment which equals one of the input values
* or {@link PathFragment#INVALID_SEGMENT} if none of the segments match.
*/
public int getFirstSegment(Set<String> values) {
for (int i = 0; i < segments.length; i++) {
if (values.contains(segments[i])) {
return i;
}
}
return INVALID_SEGMENT;
}
/**
* Returns true iff this path contains uplevel references "..".
*/
public boolean containsUplevelReferences() {
for (String segment : segments) {
if (segment.equals("..")) {
return true;
}
}
return false;
}
/**
* Returns a relative PathFragment created from this absolute PathFragment using the
* same segments and drive letter.
*/
public PathFragment toRelative() {
Preconditions.checkArgument(isAbsolute);
return new PathFragment(driveLetter, false, segments);
}
private boolean isEmpty() {
return !isAbsolute && segments.length == 0;
}
@Override
public int hashCode() {
// We use the hash code caching strategy employed by java.lang.String. There are three subtle
// things going on here:
//
// (1) We use a value of 0 to indicate that the hash code hasn't been computed and cached yet.
// Yes, this means that if the hash code is really 0 then we will "recompute" it each time. But
// this isn't a problem in practice since a hash code of 0 is rare.
//
// (2) Since we have no synchronization, multiple threads can race here thinking they are the
// first one to compute and cache the hash code.
//
// (3) Moreover, since 'hashCode' is non-volatile, the cached hash code value written from one
// thread may not be visible by another.
//
// All three of these issues are benign from a correctness perspective; in the end we have no
// overhead from synchronization, at the cost of potentially computing the hash code more than
// once.
int h = hashCode;
if (h == 0) {
h = Boolean.hashCode(isAbsolute);
for (String segment : segments) {
h = h * 31 + segment.hashCode();
}
if (!isEmpty()) {
h = h * 31 + Character.hashCode(driveLetter);
}
hashCode = h;
}
return h;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof PathFragment)) {
return false;
}
PathFragment otherPath = (PathFragment) other;
if (isEmpty() && otherPath.isEmpty()) {
return true;
} else {
return isAbsolute == otherPath.isAbsolute
&& driveLetter == otherPath.driveLetter
&& Arrays.equals(otherPath.segments, segments);
}
}
/**
* Compares two PathFragments using the lexicographical order.
*/
@Override
public int compareTo(PathFragment p2) {
if (isAbsolute != p2.isAbsolute) {
return isAbsolute ? -1 : 1;
}
PathFragment p1 = this;
String[] segments1 = p1.segments;
String[] segments2 = p2.segments;
int len1 = segments1.length;
int len2 = segments2.length;
int n = Math.min(len1, len2);
for (int i = 0; i < n; i++) {
String segment1 = segments1[i];
String segment2 = segments2[i];
if (!segment1.equals(segment2)) {
return segment1.compareTo(segment2);
}
}
return len1 - len2;
}
@Override
public String toString() {
return getPathString();
}
}
| |
package org.mondo.collaboration.security.query;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Logger;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.incquery.runtime.api.IMatchProcessor;
import org.eclipse.incquery.runtime.api.IQuerySpecification;
import org.eclipse.incquery.runtime.api.IncQueryEngine;
import org.eclipse.incquery.runtime.api.impl.BaseMatcher;
import org.eclipse.incquery.runtime.exception.IncQueryException;
import org.eclipse.incquery.runtime.matchers.tuple.Tuple;
import org.eclipse.incquery.runtime.util.IncQueryLoggingUtil;
import org.mondo.collaboration.security.query.LockOp3HelperMatch;
import org.mondo.collaboration.security.query.util.LockOp3HelperQuerySpecification;
import wt.Control;
import wt.Signal;
/**
* Generated pattern matcher API of the org.mondo.collaboration.security.query.lockOp3Helper pattern,
* providing pattern-specific query methods.
*
* <p>Use the pattern matcher on a given model via {@link #on(IncQueryEngine)},
* e.g. in conjunction with {@link IncQueryEngine#on(Notifier)}.
*
* <p>Matches of the pattern will be represented as {@link LockOp3HelperMatch}.
*
* <p>Original source:
* <code><pre>
* pattern lockOp3Helper(signal :Signal, cycle, value, ctrl :Control) {
* Control.cycle(ctrl, cycle);
* Control.provides(ctrl, signal);
* Signal.frequency(signal, value);
* }
* </pre></code>
*
* @see LockOp3HelperMatch
* @see LockOp3HelperProcessor
* @see LockOp3HelperQuerySpecification
*
*/
@SuppressWarnings("all")
public class LockOp3HelperMatcher extends BaseMatcher<LockOp3HelperMatch> {
/**
* Initializes the pattern matcher within an existing EMF-IncQuery engine.
* If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
* The match set will be incrementally refreshed upon updates.
* @param engine the existing EMF-IncQuery engine in which this matcher will be created.
* @throws IncQueryException if an error occurs during pattern matcher creation
*
*/
public static LockOp3HelperMatcher on(final IncQueryEngine engine) throws IncQueryException {
// check if matcher already exists
LockOp3HelperMatcher matcher = engine.getExistingMatcher(querySpecification());
if (matcher == null) {
matcher = new LockOp3HelperMatcher(engine);
// do not have to "put" it into engine.matchers, reportMatcherInitialized() will take care of it
}
return matcher;
}
private final static int POSITION_SIGNAL = 0;
private final static int POSITION_CYCLE = 1;
private final static int POSITION_VALUE = 2;
private final static int POSITION_CTRL = 3;
private final static Logger LOGGER = IncQueryLoggingUtil.getLogger(LockOp3HelperMatcher.class);
/**
* Initializes the pattern matcher over a given EMF model root (recommended: Resource or ResourceSet).
* If a pattern matcher is already constructed with the same root, only a light-weight reference is returned.
* The scope of pattern matching will be the given EMF model root and below (see FAQ for more precise definition).
* The match set will be incrementally refreshed upon updates from this scope.
* <p>The matcher will be created within the managed {@link IncQueryEngine} belonging to the EMF model root, so
* multiple matchers will reuse the same engine and benefit from increased performance and reduced memory footprint.
* @param emfRoot the root of the EMF containment hierarchy where the pattern matcher will operate. Recommended: Resource or ResourceSet.
* @throws IncQueryException if an error occurs during pattern matcher creation
* @deprecated use {@link #on(IncQueryEngine)} instead, e.g. in conjunction with {@link IncQueryEngine#on(Notifier)}
*
*/
@Deprecated
public LockOp3HelperMatcher(final Notifier emfRoot) throws IncQueryException {
this(IncQueryEngine.on(emfRoot));
}
/**
* Initializes the pattern matcher within an existing EMF-IncQuery engine.
* If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
* The match set will be incrementally refreshed upon updates.
* @param engine the existing EMF-IncQuery engine in which this matcher will be created.
* @throws IncQueryException if an error occurs during pattern matcher creation
* @deprecated use {@link #on(IncQueryEngine)} instead
*
*/
@Deprecated
public LockOp3HelperMatcher(final IncQueryEngine engine) throws IncQueryException {
super(engine, querySpecification());
}
/**
* Returns the set of all matches of the pattern that conform to the given fixed values of some parameters.
* @param pSignal the fixed value of pattern parameter signal, or null if not bound.
* @param pCycle the fixed value of pattern parameter cycle, or null if not bound.
* @param pValue the fixed value of pattern parameter value, or null if not bound.
* @param pCtrl the fixed value of pattern parameter ctrl, or null if not bound.
* @return matches represented as a LockOp3HelperMatch object.
*
*/
public Collection<LockOp3HelperMatch> getAllMatches(final Signal pSignal, final String pCycle, final Integer pValue, final Control pCtrl) {
return rawGetAllMatches(new Object[]{pSignal, pCycle, pValue, pCtrl});
}
/**
* Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
* Neither determinism nor randomness of selection is guaranteed.
* @param pSignal the fixed value of pattern parameter signal, or null if not bound.
* @param pCycle the fixed value of pattern parameter cycle, or null if not bound.
* @param pValue the fixed value of pattern parameter value, or null if not bound.
* @param pCtrl the fixed value of pattern parameter ctrl, or null if not bound.
* @return a match represented as a LockOp3HelperMatch object, or null if no match is found.
*
*/
public LockOp3HelperMatch getOneArbitraryMatch(final Signal pSignal, final String pCycle, final Integer pValue, final Control pCtrl) {
return rawGetOneArbitraryMatch(new Object[]{pSignal, pCycle, pValue, pCtrl});
}
/**
* Indicates whether the given combination of specified pattern parameters constitute a valid pattern match,
* under any possible substitution of the unspecified parameters (if any).
* @param pSignal the fixed value of pattern parameter signal, or null if not bound.
* @param pCycle the fixed value of pattern parameter cycle, or null if not bound.
* @param pValue the fixed value of pattern parameter value, or null if not bound.
* @param pCtrl the fixed value of pattern parameter ctrl, or null if not bound.
* @return true if the input is a valid (partial) match of the pattern.
*
*/
public boolean hasMatch(final Signal pSignal, final String pCycle, final Integer pValue, final Control pCtrl) {
return rawHasMatch(new Object[]{pSignal, pCycle, pValue, pCtrl});
}
/**
* Returns the number of all matches of the pattern that conform to the given fixed values of some parameters.
* @param pSignal the fixed value of pattern parameter signal, or null if not bound.
* @param pCycle the fixed value of pattern parameter cycle, or null if not bound.
* @param pValue the fixed value of pattern parameter value, or null if not bound.
* @param pCtrl the fixed value of pattern parameter ctrl, or null if not bound.
* @return the number of pattern matches found.
*
*/
public int countMatches(final Signal pSignal, final String pCycle, final Integer pValue, final Control pCtrl) {
return rawCountMatches(new Object[]{pSignal, pCycle, pValue, pCtrl});
}
/**
* Executes the given processor on each match of the pattern that conforms to the given fixed values of some parameters.
* @param pSignal the fixed value of pattern parameter signal, or null if not bound.
* @param pCycle the fixed value of pattern parameter cycle, or null if not bound.
* @param pValue the fixed value of pattern parameter value, or null if not bound.
* @param pCtrl the fixed value of pattern parameter ctrl, or null if not bound.
* @param processor the action that will process each pattern match.
*
*/
public void forEachMatch(final Signal pSignal, final String pCycle, final Integer pValue, final Control pCtrl, final IMatchProcessor<? super LockOp3HelperMatch> processor) {
rawForEachMatch(new Object[]{pSignal, pCycle, pValue, pCtrl}, processor);
}
/**
* Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
* Neither determinism nor randomness of selection is guaranteed.
* @param pSignal the fixed value of pattern parameter signal, or null if not bound.
* @param pCycle the fixed value of pattern parameter cycle, or null if not bound.
* @param pValue the fixed value of pattern parameter value, or null if not bound.
* @param pCtrl the fixed value of pattern parameter ctrl, or null if not bound.
* @param processor the action that will process the selected match.
* @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked
*
*/
public boolean forOneArbitraryMatch(final Signal pSignal, final String pCycle, final Integer pValue, final Control pCtrl, final IMatchProcessor<? super LockOp3HelperMatch> processor) {
return rawForOneArbitraryMatch(new Object[]{pSignal, pCycle, pValue, pCtrl}, processor);
}
/**
* Returns a new (partial) match.
* This can be used e.g. to call the matcher with a partial match.
* <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
* @param pSignal the fixed value of pattern parameter signal, or null if not bound.
* @param pCycle the fixed value of pattern parameter cycle, or null if not bound.
* @param pValue the fixed value of pattern parameter value, or null if not bound.
* @param pCtrl the fixed value of pattern parameter ctrl, or null if not bound.
* @return the (partial) match object.
*
*/
public LockOp3HelperMatch newMatch(final Signal pSignal, final String pCycle, final Integer pValue, final Control pCtrl) {
return LockOp3HelperMatch.newMatch(pSignal, pCycle, pValue, pCtrl);
}
/**
* Retrieve the set of values that occur in matches for signal.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
protected Set<Signal> rawAccumulateAllValuesOfsignal(final Object[] parameters) {
Set<Signal> results = new HashSet<Signal>();
rawAccumulateAllValues(POSITION_SIGNAL, parameters, results);
return results;
}
/**
* Retrieve the set of values that occur in matches for signal.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
public Set<Signal> getAllValuesOfsignal() {
return rawAccumulateAllValuesOfsignal(emptyArray());
}
/**
* Retrieve the set of values that occur in matches for signal.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
public Set<Signal> getAllValuesOfsignal(final LockOp3HelperMatch partialMatch) {
return rawAccumulateAllValuesOfsignal(partialMatch.toArray());
}
/**
* Retrieve the set of values that occur in matches for signal.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
public Set<Signal> getAllValuesOfsignal(final String pCycle, final Integer pValue, final Control pCtrl) {
return rawAccumulateAllValuesOfsignal(new Object[]{
null,
pCycle,
pValue,
pCtrl
});
}
/**
* Retrieve the set of values that occur in matches for cycle.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
protected Set<String> rawAccumulateAllValuesOfcycle(final Object[] parameters) {
Set<String> results = new HashSet<String>();
rawAccumulateAllValues(POSITION_CYCLE, parameters, results);
return results;
}
/**
* Retrieve the set of values that occur in matches for cycle.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
public Set<String> getAllValuesOfcycle() {
return rawAccumulateAllValuesOfcycle(emptyArray());
}
/**
* Retrieve the set of values that occur in matches for cycle.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
public Set<String> getAllValuesOfcycle(final LockOp3HelperMatch partialMatch) {
return rawAccumulateAllValuesOfcycle(partialMatch.toArray());
}
/**
* Retrieve the set of values that occur in matches for cycle.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
public Set<String> getAllValuesOfcycle(final Signal pSignal, final Integer pValue, final Control pCtrl) {
return rawAccumulateAllValuesOfcycle(new Object[]{
pSignal,
null,
pValue,
pCtrl
});
}
/**
* Retrieve the set of values that occur in matches for value.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
protected Set<Integer> rawAccumulateAllValuesOfvalue(final Object[] parameters) {
Set<Integer> results = new HashSet<Integer>();
rawAccumulateAllValues(POSITION_VALUE, parameters, results);
return results;
}
/**
* Retrieve the set of values that occur in matches for value.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
public Set<Integer> getAllValuesOfvalue() {
return rawAccumulateAllValuesOfvalue(emptyArray());
}
/**
* Retrieve the set of values that occur in matches for value.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
public Set<Integer> getAllValuesOfvalue(final LockOp3HelperMatch partialMatch) {
return rawAccumulateAllValuesOfvalue(partialMatch.toArray());
}
/**
* Retrieve the set of values that occur in matches for value.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
public Set<Integer> getAllValuesOfvalue(final Signal pSignal, final String pCycle, final Control pCtrl) {
return rawAccumulateAllValuesOfvalue(new Object[]{
pSignal,
pCycle,
null,
pCtrl
});
}
/**
* Retrieve the set of values that occur in matches for ctrl.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
protected Set<Control> rawAccumulateAllValuesOfctrl(final Object[] parameters) {
Set<Control> results = new HashSet<Control>();
rawAccumulateAllValues(POSITION_CTRL, parameters, results);
return results;
}
/**
* Retrieve the set of values that occur in matches for ctrl.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
public Set<Control> getAllValuesOfctrl() {
return rawAccumulateAllValuesOfctrl(emptyArray());
}
/**
* Retrieve the set of values that occur in matches for ctrl.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
public Set<Control> getAllValuesOfctrl(final LockOp3HelperMatch partialMatch) {
return rawAccumulateAllValuesOfctrl(partialMatch.toArray());
}
/**
* Retrieve the set of values that occur in matches for ctrl.
* @return the Set of all values, null if no parameter with the given name exists, empty set if there are no matches
*
*/
public Set<Control> getAllValuesOfctrl(final Signal pSignal, final String pCycle, final Integer pValue) {
return rawAccumulateAllValuesOfctrl(new Object[]{
pSignal,
pCycle,
pValue,
null
});
}
@Override
protected LockOp3HelperMatch tupleToMatch(final Tuple t) {
try {
return LockOp3HelperMatch.newMatch((wt.Signal) t.get(POSITION_SIGNAL), (java.lang.String) t.get(POSITION_CYCLE), (java.lang.Integer) t.get(POSITION_VALUE), (wt.Control) t.get(POSITION_CTRL));
} catch(ClassCastException e) {
LOGGER.error("Element(s) in tuple not properly typed!",e);
return null;
}
}
@Override
protected LockOp3HelperMatch arrayToMatch(final Object[] match) {
try {
return LockOp3HelperMatch.newMatch((wt.Signal) match[POSITION_SIGNAL], (java.lang.String) match[POSITION_CYCLE], (java.lang.Integer) match[POSITION_VALUE], (wt.Control) match[POSITION_CTRL]);
} catch(ClassCastException e) {
LOGGER.error("Element(s) in array not properly typed!",e);
return null;
}
}
@Override
protected LockOp3HelperMatch arrayToMatchMutable(final Object[] match) {
try {
return LockOp3HelperMatch.newMutableMatch((wt.Signal) match[POSITION_SIGNAL], (java.lang.String) match[POSITION_CYCLE], (java.lang.Integer) match[POSITION_VALUE], (wt.Control) match[POSITION_CTRL]);
} catch(ClassCastException e) {
LOGGER.error("Element(s) in array not properly typed!",e);
return null;
}
}
/**
* @return the singleton instance of the query specification of this pattern
* @throws IncQueryException if the pattern definition could not be loaded
*
*/
public static IQuerySpecification<LockOp3HelperMatcher> querySpecification() throws IncQueryException {
return LockOp3HelperQuerySpecification.instance();
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.iotanalytics.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Where data in a data store is stored.. You can choose <code>serviceManagedS3</code> storage,
* <code>customerManagedS3</code> storage, or <code>iotSiteWiseMultiLayerStorage</code> storage. The default is
* <code>serviceManagedS3</code>. You can't change the choice of Amazon S3 storage after your data store is created.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotanalytics-2017-11-27/DatastoreStorage" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DatastoreStorage implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* Used to store data in an Amazon S3 bucket managed by IoT Analytics. You can't change the choice of Amazon S3
* storage after your data store is created.
* </p>
*/
private ServiceManagedDatastoreS3Storage serviceManagedS3;
/**
* <p>
* S3-customer-managed; When you choose customer-managed storage, the <code>retentionPeriod</code> parameter is
* ignored. You can't change the choice of Amazon S3 storage after your data store is created.
* </p>
*/
private CustomerManagedDatastoreS3Storage customerManagedS3;
/**
* <p>
* Used to store data used by IoT SiteWise in an Amazon S3 bucket that you manage. You can't change the choice of
* Amazon S3 storage after your data store is created.
* </p>
*/
private DatastoreIotSiteWiseMultiLayerStorage iotSiteWiseMultiLayerStorage;
/**
* <p>
* Used to store data in an Amazon S3 bucket managed by IoT Analytics. You can't change the choice of Amazon S3
* storage after your data store is created.
* </p>
*
* @param serviceManagedS3
* Used to store data in an Amazon S3 bucket managed by IoT Analytics. You can't change the choice of Amazon
* S3 storage after your data store is created.
*/
public void setServiceManagedS3(ServiceManagedDatastoreS3Storage serviceManagedS3) {
this.serviceManagedS3 = serviceManagedS3;
}
/**
* <p>
* Used to store data in an Amazon S3 bucket managed by IoT Analytics. You can't change the choice of Amazon S3
* storage after your data store is created.
* </p>
*
* @return Used to store data in an Amazon S3 bucket managed by IoT Analytics. You can't change the choice of Amazon
* S3 storage after your data store is created.
*/
public ServiceManagedDatastoreS3Storage getServiceManagedS3() {
return this.serviceManagedS3;
}
/**
* <p>
* Used to store data in an Amazon S3 bucket managed by IoT Analytics. You can't change the choice of Amazon S3
* storage after your data store is created.
* </p>
*
* @param serviceManagedS3
* Used to store data in an Amazon S3 bucket managed by IoT Analytics. You can't change the choice of Amazon
* S3 storage after your data store is created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DatastoreStorage withServiceManagedS3(ServiceManagedDatastoreS3Storage serviceManagedS3) {
setServiceManagedS3(serviceManagedS3);
return this;
}
/**
* <p>
* S3-customer-managed; When you choose customer-managed storage, the <code>retentionPeriod</code> parameter is
* ignored. You can't change the choice of Amazon S3 storage after your data store is created.
* </p>
*
* @param customerManagedS3
* S3-customer-managed; When you choose customer-managed storage, the <code>retentionPeriod</code> parameter
* is ignored. You can't change the choice of Amazon S3 storage after your data store is created.
*/
public void setCustomerManagedS3(CustomerManagedDatastoreS3Storage customerManagedS3) {
this.customerManagedS3 = customerManagedS3;
}
/**
* <p>
* S3-customer-managed; When you choose customer-managed storage, the <code>retentionPeriod</code> parameter is
* ignored. You can't change the choice of Amazon S3 storage after your data store is created.
* </p>
*
* @return S3-customer-managed; When you choose customer-managed storage, the <code>retentionPeriod</code> parameter
* is ignored. You can't change the choice of Amazon S3 storage after your data store is created.
*/
public CustomerManagedDatastoreS3Storage getCustomerManagedS3() {
return this.customerManagedS3;
}
/**
* <p>
* S3-customer-managed; When you choose customer-managed storage, the <code>retentionPeriod</code> parameter is
* ignored. You can't change the choice of Amazon S3 storage after your data store is created.
* </p>
*
* @param customerManagedS3
* S3-customer-managed; When you choose customer-managed storage, the <code>retentionPeriod</code> parameter
* is ignored. You can't change the choice of Amazon S3 storage after your data store is created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DatastoreStorage withCustomerManagedS3(CustomerManagedDatastoreS3Storage customerManagedS3) {
setCustomerManagedS3(customerManagedS3);
return this;
}
/**
* <p>
* Used to store data used by IoT SiteWise in an Amazon S3 bucket that you manage. You can't change the choice of
* Amazon S3 storage after your data store is created.
* </p>
*
* @param iotSiteWiseMultiLayerStorage
* Used to store data used by IoT SiteWise in an Amazon S3 bucket that you manage. You can't change the
* choice of Amazon S3 storage after your data store is created.
*/
public void setIotSiteWiseMultiLayerStorage(DatastoreIotSiteWiseMultiLayerStorage iotSiteWiseMultiLayerStorage) {
this.iotSiteWiseMultiLayerStorage = iotSiteWiseMultiLayerStorage;
}
/**
* <p>
* Used to store data used by IoT SiteWise in an Amazon S3 bucket that you manage. You can't change the choice of
* Amazon S3 storage after your data store is created.
* </p>
*
* @return Used to store data used by IoT SiteWise in an Amazon S3 bucket that you manage. You can't change the
* choice of Amazon S3 storage after your data store is created.
*/
public DatastoreIotSiteWiseMultiLayerStorage getIotSiteWiseMultiLayerStorage() {
return this.iotSiteWiseMultiLayerStorage;
}
/**
* <p>
* Used to store data used by IoT SiteWise in an Amazon S3 bucket that you manage. You can't change the choice of
* Amazon S3 storage after your data store is created.
* </p>
*
* @param iotSiteWiseMultiLayerStorage
* Used to store data used by IoT SiteWise in an Amazon S3 bucket that you manage. You can't change the
* choice of Amazon S3 storage after your data store is created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DatastoreStorage withIotSiteWiseMultiLayerStorage(DatastoreIotSiteWiseMultiLayerStorage iotSiteWiseMultiLayerStorage) {
setIotSiteWiseMultiLayerStorage(iotSiteWiseMultiLayerStorage);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getServiceManagedS3() != null)
sb.append("ServiceManagedS3: ").append(getServiceManagedS3()).append(",");
if (getCustomerManagedS3() != null)
sb.append("CustomerManagedS3: ").append(getCustomerManagedS3()).append(",");
if (getIotSiteWiseMultiLayerStorage() != null)
sb.append("IotSiteWiseMultiLayerStorage: ").append(getIotSiteWiseMultiLayerStorage());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DatastoreStorage == false)
return false;
DatastoreStorage other = (DatastoreStorage) obj;
if (other.getServiceManagedS3() == null ^ this.getServiceManagedS3() == null)
return false;
if (other.getServiceManagedS3() != null && other.getServiceManagedS3().equals(this.getServiceManagedS3()) == false)
return false;
if (other.getCustomerManagedS3() == null ^ this.getCustomerManagedS3() == null)
return false;
if (other.getCustomerManagedS3() != null && other.getCustomerManagedS3().equals(this.getCustomerManagedS3()) == false)
return false;
if (other.getIotSiteWiseMultiLayerStorage() == null ^ this.getIotSiteWiseMultiLayerStorage() == null)
return false;
if (other.getIotSiteWiseMultiLayerStorage() != null && other.getIotSiteWiseMultiLayerStorage().equals(this.getIotSiteWiseMultiLayerStorage()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getServiceManagedS3() == null) ? 0 : getServiceManagedS3().hashCode());
hashCode = prime * hashCode + ((getCustomerManagedS3() == null) ? 0 : getCustomerManagedS3().hashCode());
hashCode = prime * hashCode + ((getIotSiteWiseMultiLayerStorage() == null) ? 0 : getIotSiteWiseMultiLayerStorage().hashCode());
return hashCode;
}
@Override
public DatastoreStorage clone() {
try {
return (DatastoreStorage) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.iotanalytics.model.transform.DatastoreStorageMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
/* Copyright (c) 2015-2016 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Gabriel Roldan (Boundless) - initial implementation
*/
package org.locationtech.geogig.geotools.geopkg;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static org.locationtech.geogig.geotools.geopkg.GeopkgGeogigMetadata.AUDIT_OP_DELETE;
import static org.locationtech.geogig.geotools.geopkg.GeopkgGeogigMetadata.AUDIT_OP_INSERT;
import static org.locationtech.geogig.geotools.geopkg.GeopkgGeogigMetadata.AUDIT_OP_UPDATE;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import javax.sql.DataSource;
import org.eclipse.jdt.annotation.Nullable;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.geopkg.FeatureEntry;
import org.geotools.geopkg.GeoPackage;
import org.geotools.geopkg.geom.GeoPkgGeomReader;
import org.locationtech.geogig.model.Node;
import org.locationtech.geogig.model.NodeRef;
import org.locationtech.geogig.model.ObjectId;
import org.locationtech.geogig.model.RevCommit;
import org.locationtech.geogig.model.RevFeature;
import org.locationtech.geogig.model.RevFeatureType;
import org.locationtech.geogig.model.RevObject.TYPE;
import org.locationtech.geogig.model.RevTree;
import org.locationtech.geogig.model.impl.CanonicalTreeBuilder;
import org.locationtech.geogig.model.impl.CommitBuilder;
import org.locationtech.geogig.model.impl.RevFeatureBuilder;
import org.locationtech.geogig.model.impl.RevTreeBuilder;
import org.locationtech.geogig.plumbing.FindTreeChild;
import org.locationtech.geogig.plumbing.RevObjectParse;
import org.locationtech.geogig.porcelain.ConfigGet;
import org.locationtech.geogig.porcelain.MergeConflictsException;
import org.locationtech.geogig.porcelain.MergeOp;
import org.locationtech.geogig.porcelain.MergeOp.MergeReport;
import org.locationtech.geogig.repository.Context;
import org.locationtech.geogig.repository.DefaultProgressListener;
import org.locationtech.geogig.repository.DiffEntry.ChangeType;
import org.locationtech.geogig.repository.ProgressListener;
import org.locationtech.geogig.repository.impl.SpatialOps;
import org.locationtech.geogig.storage.ObjectStore;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.feature.type.GeometryDescriptor;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.base.Throwables;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* Class for augmenting a geopackage with additional tables to enable smooth import/export
* functionality with GeoGig. Extra tables keep track of which commit an export came from as well as
* which features have been modified since the export so that they can be properly merged on import.
*/
public class InterchangeFormat {
private Context context;
private ProgressListener progressListener = DefaultProgressListener.NULL;
private File geopackageDbFile;
public InterchangeFormat(final File geopackageDbFile, final Context context) {
checkNotNull(geopackageDbFile);
checkNotNull(context);
this.geopackageDbFile = geopackageDbFile;
this.context = context;
}
public InterchangeFormat setProgressListener(ProgressListener progressListener) {
checkNotNull(progressListener);
this.progressListener = progressListener;
return this;
}
private void info(String msgFormat, Object... args) {
progressListener.setDescription(format(msgFormat, args));
}
public void createFIDMappingTable(ConcurrentMap<String, String> fidMappings,
String targetTableName) throws IOException {
final GeoPackage geopackage = new GeoPackage(geopackageDbFile);
try {
final DataSource dataSource = geopackage.getDataSource();
try (Connection connection = dataSource.getConnection()) {
try (GeopkgGeogigMetadata metadata = new GeopkgGeogigMetadata(connection)) {
metadata.createFidMappingTable(targetTableName, fidMappings);
}
} catch (SQLException e) {
throw Throwables.propagate(e);
}
} finally {
geopackage.close();
}
}
/**
* Creates an audit table for a table in the geopackage. This function requires that the
* features have already been exported to the geopackage.
*
* @param sourcePathspec path from which features have been exported (supports format
* {@code <[<commit-ish>:]<treePath>>}. e.g. {@code buildings}, {@code HEAD~2:buildings},
* {@code abc123fg:buildings}, {@code origin/master:buildings} ). {@code buildings}
* resolves to {@code HEAD:buildings}.
* @param targetTableName name of table where features from {@code sourceCommitIsh} have been
* exported
*/
public void export(final String sourcePathspec, final String targetTableName)
throws IOException {
final String refspec;
final String headCommitish;
final String featureTreePath;
final ObjectId commitId;
{
if (sourcePathspec.contains(":")) {
refspec = sourcePathspec;
} else {
refspec = "HEAD:" + sourcePathspec;
}
checkArgument(!refspec.endsWith(":"), "No path specified.");
String[] split = refspec.split(":");
headCommitish = split[0];
featureTreePath = split[1];
Optional<RevCommit> commit = context.command(RevObjectParse.class)
.setRefSpec(headCommitish).call(RevCommit.class);
checkArgument(commit.isPresent(),
"Couldn't resolve '" + refspec + "' to a commitish object");
commitId = commit.get().getId();
}
info("Exporting repository metadata from '%s' (commit %s)...", refspec, commitId);
final GeoPackage geopackage = new GeoPackage(geopackageDbFile);
try {
FeatureEntry featureEntry = geopackage.feature(targetTableName);
checkState(featureEntry != null, "Table '%s' does not exist", targetTableName);
try {
createAuditLog(geopackage, featureTreePath, featureEntry, commitId);
} catch (SQLException e) {
throw Throwables.propagate(e);
}
} finally {
geopackage.close();
}
}
/**
* Create the audit tables for the specified feature type.
*
* @param geopackage the geopackage to add the tables to
* @param mappedPath the feature tree path
* @param fe the feature entry to add audit logs too
* @param commitId the commit that the exported features came from
* @throws SQLException
*/
private void createAuditLog(final GeoPackage geopackage, final String mappedPath,
final FeatureEntry fe, final ObjectId commitId) throws SQLException {
info("Creating audit metadata for table '%s'", fe.getIdentifier());
final DataSource dataSource = geopackage.getDataSource();
try (Connection connection = dataSource.getConnection();
GeopkgGeogigMetadata metadata = new GeopkgGeogigMetadata(connection)) {
URI repoURI = context.repository().getLocation();
metadata.init(repoURI);
final String auditedTable = fe.getIdentifier();
metadata.createAudit(auditedTable, mappedPath, commitId);
}
}
public void createChangeLog(final String targetTableName, Map<String, ChangeType> changedNodes)
throws IOException, SQLException {
final GeoPackage geopackage = new GeoPackage(geopackageDbFile);
final DataSource dataSource = geopackage.getDataSource();
try (Connection connection = dataSource.getConnection();
GeopkgGeogigMetadata metadata = new GeopkgGeogigMetadata(connection)) {
metadata.createChangeLog(targetTableName);
metadata.populateChangeLog(targetTableName, changedNodes);
} finally {
geopackage.close();
}
}
/**
* Imports the features from the geopackage based on the existing audit table onto the current
* branch. If the head commit of the current branch is different from the commit that the
* features were exported from, the features will be merged into the current branch. The calling
* function should anticipate the possibility of merge conflicts.
*
* @param commitMessage commit message for the imported features
* @param authorName author name to use for the commit
* @param authorEmail author email to use for the commit
* @param tableNames a list of tables to import from the geopackage, if none are specified, all
* tables will be imported
* @return the commit with the imported features, or the merge commit if it was not a
* fast-forward merge
*/
public GeopkgImportResult importAuditLog(@Nullable String commitMessage,
@Nullable String authorName, @Nullable String authorEmail,
@Nullable String... tableNames) {
final Set<String> importTables = tableNames == null ? ImmutableSet.of()
: Sets.newHashSet(tableNames);
List<AuditReport> reports = new ArrayList<>();
GeoPackage geopackage;
try {
geopackage = new GeoPackage(geopackageDbFile);
} catch (IOException e) {
throw Throwables.propagate(e);
}
final DataSource dataSource = geopackage.getDataSource();
RevCommit importCommit = null;
GeopkgImportResult importResult = null;
try (Connection connection = dataSource.getConnection();
GeopkgGeogigMetadata metadata = new GeopkgGeogigMetadata(connection)) {
final Map<String, AuditTable> tables = Maps.filterKeys(
Maps.uniqueIndex(metadata.getAuditTables(), t -> t.getTableName()),
k -> importTables.isEmpty() || importTables.contains(k));
checkState(tables.size() > 0, "No table to import.");
Iterator<AuditTable> iter = tables.values().iterator();
ObjectId commitId = iter.next().getCommitId();
while (iter.hasNext()) {
checkState(commitId.equals(iter.next().getCommitId()),
"Unable to simultaneously import tables with different source commit ids.");
}
RevCommit commit = context.objectDatabase().getCommit(commitId);
RevTree baseTree = context.objectDatabase().getTree(commit.getTreeId());
RevTreeBuilder newTreeBuilder = CanonicalTreeBuilder.create(context.objectDatabase(),
baseTree);
Map<String, String> fidMappings = null;
for (AuditTable t : tables.values()) {
fidMappings = metadata.getFidMappings(t.getTableName());
AuditReport report = importAuditLog(geopackage, t, baseTree, newTreeBuilder,
fidMappings);
reports.add(report);
}
RevTree newTree = newTreeBuilder.build();
context.objectDatabase().put(newTree);
if (authorName == null) {
authorName = context.command(ConfigGet.class).setName("user.name").call().orNull();
}
if (authorEmail == null) {
authorEmail = context.command(ConfigGet.class).setName("user.email").call()
.orNull();
}
CommitBuilder builder = new CommitBuilder();
long timestamp = context.platform().currentTimeMillis();
builder.setParentIds(Arrays.asList(commitId));
builder.setTreeId(newTree.getId());
builder.setCommitterTimestamp(timestamp);
builder.setCommitter(authorName);
builder.setCommitterEmail(authorEmail);
builder.setAuthorTimestamp(timestamp);
builder.setAuthor(authorName);
builder.setAuthorEmail(authorEmail);
if (commitMessage != null) {
builder.setMessage(commitMessage);
} else {
builder.setMessage("Imported features from geopackage.");
}
importCommit = builder.build();
importResult = new GeopkgImportResult(importCommit);
for (AuditReport auditReport : reports) {
if (auditReport.newMappings != null) {
importResult.newMappings.put(auditReport.table.getFeatureTreePath(),
auditReport.newMappings);
}
}
context.objectDatabase().put(importCommit);
MergeOp merge = context.command(MergeOp.class).setAuthor(authorName, authorEmail)
.addCommit(importCommit.getId());
if (commitMessage != null) {
merge.setMessage("Merge: " + commitMessage);
}
MergeReport report = merge.call();
RevCommit newCommit = report.getMergeCommit();
importResult.newCommit = newCommit;
} catch (MergeConflictsException e) {
throw new GeopkgMergeConflictsException(e, importResult);
} catch (Exception e) {
throw Throwables.propagate(e);
} finally {
geopackage.close();
}
return importResult;
}
/**
* Import the specified table and update the tree builder with the updated features.
*
* @param geopackage the geopackage to import from
* @param auditTable the audit table for the feature type
* @param baseTree the tree that the features were originally exported from
* @param newTreeBuilder the tree builder for the updated features
* @return the audit report for the table
* @throws SQLException
*/
private AuditReport importAuditLog(GeoPackage geopackage, AuditTable auditTable,
RevTree baseTree, RevTreeBuilder newTreeBuilder, Map<String, String> fidMappings)
throws SQLException {
info("Importing changes to table %s onto feature tree %s...", auditTable.getTableName(),
auditTable.getFeatureTreePath());
AuditReport tableReport = new AuditReport(auditTable);
try (Connection cx = geopackage.getDataSource().getConnection()) {
final String sql = format("SELECT * FROM %s", auditTable.getAuditTable());
try (Statement st = cx.createStatement()) {
try (ResultSet rs = st.executeQuery(sql)) {
final Optional<NodeRef> currentTreeRef = context.command(FindTreeChild.class)
.setParent(baseTree).setChildPath(auditTable.getFeatureTreePath())
.call();
Preconditions.checkState(currentTreeRef.isPresent(),
baseTree.toString() + auditTable.getFeatureTreePath());
final ObjectStore store = context.objectDatabase();
final NodeRef featureTreeRef = currentTreeRef.get();
final RevTree currentFeatureTree = store.getTree(featureTreeRef.getObjectId());
final RevFeatureType featureType = store
.getFeatureType(featureTreeRef.getMetadataId());
final Iterator<Change> changes = asChanges(rs, featureType, tableReport);
final RevTree newFeatureTree = importAuditLog(store, currentFeatureTree,
changes, fidMappings, tableReport);
Node featureTreeNode = Node.create(featureTreeRef.name(),
newFeatureTree.getId(), featureTreeRef.getMetadataId(), TYPE.TREE,
SpatialOps.boundsOf(newFeatureTree));
newTreeBuilder.put(featureTreeNode);
}
}
}
return tableReport;
}
/**
* Builds a new feature type tree based on the changes in the audit logs.
*
* @param store the object store
* @param currentFeatureTree the original feature tree
* @param changes all of the changes from the audit log
* @return the newly built tree
* @throws SQLException
*/
private RevTree importAuditLog(ObjectStore store, RevTree currentFeatureTree,
Iterator<Change> changes, Map<String, String> fidMappings, AuditReport report)
throws SQLException {
CanonicalTreeBuilder builder = CanonicalTreeBuilder.create(store, currentFeatureTree);
progressListener.setProgress(0);
Function<Change, RevFeature> function = new Function<InterchangeFormat.Change, RevFeature>() {
private int count = 0;
@Override
public RevFeature apply(Change change) {
progressListener.setProgress(++count);
@Nullable
RevFeature feature = change.getFeature();
String featureId = null;
if (fidMappings.containsKey(change.getFeautreId())) {
featureId = fidMappings.get(change.getFeautreId());
} else {
featureId = newFeatureId();
report.addMapping(change.getFeautreId(), featureId);
}
ChangeType type = change.getType();
switch (type) {
case REMOVED:
builder.remove(featureId);
break;
case ADDED:
case MODIFIED:
Node node = Node.create(featureId, feature.getId(), ObjectId.NULL, TYPE.FEATURE,
SpatialOps.boundsOf(feature));
builder.put(node);
return feature;
default:
throw new IllegalStateException();
}
return feature;
}
};
Iterator<RevFeature> feautres = Iterators.filter(Iterators.transform(changes, function),
Predicates.notNull());
store.putAll(feautres);
RevTree newTree = builder.build();
store.put(newTree);
return newTree;
}
/**
* Converts the audit log into an iterator for all of the changes and updates an audit report
* with a summary of the changes.
*
* @param rs the rows from the audit log
* @param featureType the feature type for the features in the table
* @param report the audit report to update
* @return
*/
private Iterator<Change> asChanges(final ResultSet rs, RevFeatureType featureType,
AuditReport report) {
return new AbstractIterator<InterchangeFormat.Change>() {
private final RecordToFeature recordToFeature = new RecordToFeature(
(SimpleFeatureType) featureType.type());
@Override
protected Change computeNext() {
try {
if (rs.next()) {
final String featureId = rs.getString("fid");
// final long auditTimestamp = rs.getLong("audit_timestamp");
// System.err.println(new Timestamp(auditTimestamp));
final int auditOp = rs.getInt("audit_op");
final ChangeType changeType = toChangeType(auditOp);
RevFeature revFeature = null;
if (ChangeType.REMOVED.equals(changeType)) {
report.removed.incrementAndGet();
} else {
revFeature = recordToFeature.apply(rs);
if (ChangeType.ADDED.equals(changeType)) {
report.added.incrementAndGet();
} else {
report.changed.incrementAndGet();
}
}
Change change = new Change(featureId, changeType, revFeature);
return change;
}
} catch (SQLException e) {
throw Throwables.propagate(e);
}
return endOfData();
}
private ChangeType toChangeType(int auditOp) {
switch (auditOp) {
case AUDIT_OP_INSERT:
return ChangeType.ADDED;
case AUDIT_OP_UPDATE:
return ChangeType.MODIFIED;
case AUDIT_OP_DELETE:
return ChangeType.REMOVED;
default:
throw new IllegalArgumentException(String.format(
"Geopackage audit log record contains an invalid audit op code: %d. Expected one if %d(INSERT), %d(UPDATE), %d(DELETE)",
auditOp, AUDIT_OP_INSERT, AUDIT_OP_UPDATE, AUDIT_OP_DELETE));
}
}
};
}
private String newFeatureId() {
return SimpleFeatureBuilder.createDefaultFeatureId();
}
/**
* Helper function to convert a row from an audit log into a feature.
*/
private static class RecordToFeature implements Function<ResultSet, RevFeature> {
private SimpleFeatureBuilder builder;
private final List<String> attNames;
private final String geometryAttribute;
RecordToFeature(SimpleFeatureType type) {
this.builder = new SimpleFeatureBuilder(type);
this.builder.setValidating(false);
List<AttributeDescriptor> descriptors = type.getAttributeDescriptors();
this.attNames = Lists.transform(descriptors, at -> at.getLocalName());
GeometryDescriptor geometryDescriptor = type.getGeometryDescriptor();
this.geometryAttribute = geometryDescriptor == null ? null
: geometryDescriptor.getLocalName();
}
@Override
public RevFeature apply(ResultSet rs) {
builder.reset();
try {
for (String attName : attNames) {
Object value = rs.getObject(attName);
if (attName.equals(geometryAttribute) && value != null) {
byte[] bytes = (byte[]) value;
value = new GeoPkgGeomReader(bytes).get();
}
builder.set(attName, value);
}
SimpleFeature feature = builder.buildFeature("fakeId");
return RevFeatureBuilder.build(feature);
} catch (SQLException | IOException e) {
throw Throwables.propagate(e);
}
}
}
/**
* Helper class for a change from an audit log.
*/
private static class Change {
private final String featureId;
private final ChangeType changeType;
private final @Nullable RevFeature feature;
public Change(final String featureId, final ChangeType changeType,
final @Nullable RevFeature feature) {
this.featureId = featureId;
this.changeType = changeType;
this.feature = feature;
}
public ChangeType getType() {
return changeType;
}
public @Nullable RevFeature getFeature() {
return feature;
}
public String getFeautreId() {
return featureId;
}
}
}
| |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.source.hls.playlist;
import android.net.Uri;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.source.hls.playlist.HlsMediaPlaylist.Segment;
import com.google.android.exoplayer2.upstream.ParsingLoadable;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.Util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* HLS playlists parsing logic.
*/
public final class HlsPlaylistParser implements ParsingLoadable.Parser<HlsPlaylist> {
private static final String TAG_VERSION = "#EXT-X-VERSION";
private static final String TAG_STREAM_INF = "#EXT-X-STREAM-INF";
private static final String TAG_MEDIA = "#EXT-X-MEDIA";
private static final String TAG_DISCONTINUITY = "#EXT-X-DISCONTINUITY";
private static final String TAG_DISCONTINUITY_SEQUENCE = "#EXT-X-DISCONTINUITY-SEQUENCE";
private static final String TAG_PROGRAM_DATE_TIME = "#EXT-X-PROGRAM-DATE-TIME";
private static final String TAG_INIT_SEGMENT = "#EXT-X-MAP";
private static final String TAG_MEDIA_DURATION = "#EXTINF";
private static final String TAG_MEDIA_SEQUENCE = "#EXT-X-MEDIA-SEQUENCE";
private static final String TAG_TARGET_DURATION = "#EXT-X-TARGETDURATION";
private static final String TAG_ENDLIST = "#EXT-X-ENDLIST";
private static final String TAG_KEY = "#EXT-X-KEY";
private static final String TAG_BYTERANGE = "#EXT-X-BYTERANGE";
private static final String TYPE_AUDIO = "AUDIO";
private static final String TYPE_VIDEO = "VIDEO";
private static final String TYPE_SUBTITLES = "SUBTITLES";
private static final String TYPE_CLOSED_CAPTIONS = "CLOSED-CAPTIONS";
private static final String METHOD_NONE = "NONE";
private static final String METHOD_AES128 = "AES-128";
private static final String BOOLEAN_TRUE = "YES";
private static final String BOOLEAN_FALSE = "NO";
private static final Pattern REGEX_BANDWIDTH = Pattern.compile("BANDWIDTH=(\\d+)\\b");
private static final Pattern REGEX_CODECS = Pattern.compile("CODECS=\"(.+?)\"");
private static final Pattern REGEX_RESOLUTION = Pattern.compile("RESOLUTION=(\\d+x\\d+)");
private static final Pattern REGEX_TARGET_DURATION = Pattern.compile(TAG_TARGET_DURATION
+ ":(\\d+)\\b");
private static final Pattern REGEX_VERSION = Pattern.compile(TAG_VERSION + ":(\\d+)\\b");
private static final Pattern REGEX_MEDIA_SEQUENCE = Pattern.compile(TAG_MEDIA_SEQUENCE
+ ":(\\d+)\\b");
private static final Pattern REGEX_MEDIA_DURATION = Pattern.compile(TAG_MEDIA_DURATION
+ ":([\\d\\.]+)\\b");
private static final Pattern REGEX_BYTERANGE = Pattern.compile(TAG_BYTERANGE
+ ":(\\d+(?:@\\d+)?)\\b");
private static final Pattern REGEX_ATTR_BYTERANGE =
Pattern.compile("BYTERANGE=\"(\\d+(?:@\\d+)?)\\b\"");
private static final Pattern REGEX_METHOD = Pattern.compile("METHOD=(" + METHOD_NONE + "|"
+ METHOD_AES128 + ")");
private static final Pattern REGEX_URI = Pattern.compile("URI=\"(.+?)\"");
private static final Pattern REGEX_IV = Pattern.compile("IV=([^,.*]+)");
private static final Pattern REGEX_TYPE = Pattern.compile("TYPE=(" + TYPE_AUDIO + "|" + TYPE_VIDEO
+ "|" + TYPE_SUBTITLES + "|" + TYPE_CLOSED_CAPTIONS + ")");
private static final Pattern REGEX_LANGUAGE = Pattern.compile("LANGUAGE=\"(.+?)\"");
private static final Pattern REGEX_NAME = Pattern.compile("NAME=\"(.+?)\"");
private static final Pattern REGEX_INSTREAM_ID = Pattern.compile("INSTREAM-ID=\"(.+?)\"");
private static final Pattern REGEX_AUTOSELECT = compileBooleanAttrPattern("AUTOSELECT");
private static final Pattern REGEX_DEFAULT = compileBooleanAttrPattern("DEFAULT");
private static final Pattern REGEX_FORCED = compileBooleanAttrPattern("FORCED");
@Override
public HlsPlaylist parse(Uri uri, InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
Queue<String> extraLines = new LinkedList<>();
String line;
try {
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
// Do nothing.
} else if (line.startsWith(TAG_STREAM_INF)) {
extraLines.add(line);
return parseMasterPlaylist(new LineIterator(extraLines, reader), uri.toString());
} else if (line.startsWith(TAG_TARGET_DURATION)
|| line.startsWith(TAG_MEDIA_SEQUENCE)
|| line.startsWith(TAG_MEDIA_DURATION)
|| line.startsWith(TAG_KEY)
|| line.startsWith(TAG_BYTERANGE)
|| line.equals(TAG_DISCONTINUITY)
|| line.equals(TAG_DISCONTINUITY_SEQUENCE)
|| line.equals(TAG_ENDLIST)) {
extraLines.add(line);
return parseMediaPlaylist(new LineIterator(extraLines, reader), uri.toString());
} else {
extraLines.add(line);
}
}
} finally {
reader.close();
}
throw new ParserException("Failed to parse the playlist, could not identify any tags.");
}
private static HlsMasterPlaylist parseMasterPlaylist(LineIterator iterator, String baseUri)
throws IOException {
ArrayList<HlsMasterPlaylist.HlsUrl> variants = new ArrayList<>();
ArrayList<HlsMasterPlaylist.HlsUrl> audios = new ArrayList<>();
ArrayList<HlsMasterPlaylist.HlsUrl> subtitles = new ArrayList<>();
Format muxedAudioFormat = null;
Format muxedCaptionFormat = null;
String line;
while (iterator.hasNext()) {
line = iterator.next();
if (line.startsWith(TAG_MEDIA)) {
@C.SelectionFlags int selectionFlags = parseSelectionFlags(line);
String uri = parseOptionalStringAttr(line, REGEX_URI);
String name = parseStringAttr(line, REGEX_NAME);
String language = parseOptionalStringAttr(line, REGEX_LANGUAGE);
Format format;
switch (parseStringAttr(line, REGEX_TYPE)) {
case TYPE_AUDIO:
format = Format.createAudioContainerFormat(name, MimeTypes.APPLICATION_M3U8,
null, null, Format.NO_VALUE, Format.NO_VALUE, Format.NO_VALUE, null, selectionFlags,
language);
if (uri == null) {
muxedAudioFormat = format;
} else {
audios.add(new HlsMasterPlaylist.HlsUrl(name, uri, format, null, format, null));
}
break;
case TYPE_SUBTITLES:
format = Format.createTextContainerFormat(name, MimeTypes.APPLICATION_M3U8,
MimeTypes.TEXT_VTT, null, Format.NO_VALUE, selectionFlags, language);
subtitles.add(new HlsMasterPlaylist.HlsUrl(name, uri, format, null, format, null));
break;
case TYPE_CLOSED_CAPTIONS:
if ("CC1".equals(parseOptionalStringAttr(line, REGEX_INSTREAM_ID))) {
muxedCaptionFormat = Format.createTextContainerFormat(name,
MimeTypes.APPLICATION_M3U8, MimeTypes.APPLICATION_CEA608, null, Format.NO_VALUE,
selectionFlags, language);
}
break;
default:
// Do nothing.
break;
}
} else if (line.startsWith(TAG_STREAM_INF)) {
int bitrate = parseIntAttr(line, REGEX_BANDWIDTH);
String codecs = parseOptionalStringAttr(line, REGEX_CODECS);
String resolutionString = parseOptionalStringAttr(line, REGEX_RESOLUTION);
int width;
int height;
if (resolutionString != null) {
String[] widthAndHeight = resolutionString.split("x");
width = Integer.parseInt(widthAndHeight[0]);
height = Integer.parseInt(widthAndHeight[1]);
if (width <= 0 || height <= 0) {
// Resolution string is invalid.
width = Format.NO_VALUE;
height = Format.NO_VALUE;
}
} else {
width = Format.NO_VALUE;
height = Format.NO_VALUE;
}
line = iterator.next();
String name = Integer.toString(variants.size());
Format format = Format.createVideoContainerFormat(name, MimeTypes.APPLICATION_M3U8, null,
codecs, bitrate, width, height, Format.NO_VALUE, null);
variants.add(new HlsMasterPlaylist.HlsUrl(name, line, format, null, null, null));
}
}
return new HlsMasterPlaylist(baseUri, variants, audios, subtitles, muxedAudioFormat,
muxedCaptionFormat);
}
@C.SelectionFlags
private static int parseSelectionFlags(String line) {
return (parseBooleanAttribute(line, REGEX_DEFAULT, false) ? C.SELECTION_FLAG_DEFAULT : 0)
| (parseBooleanAttribute(line, REGEX_FORCED, false) ? C.SELECTION_FLAG_FORCED : 0)
| (parseBooleanAttribute(line, REGEX_AUTOSELECT, false) ? C.SELECTION_FLAG_AUTOSELECT : 0);
}
private static HlsMediaPlaylist parseMediaPlaylist(LineIterator iterator, String baseUri)
throws IOException {
int mediaSequence = 0;
int version = 1; // Default version == 1.
long targetDurationUs = C.TIME_UNSET;
boolean hasEndTag = false;
Segment initializationSegment = null;
List<Segment> segments = new ArrayList<>();
long segmentDurationUs = 0;
int discontinuitySequenceNumber = 0;
long playlistStartTimeUs = 0;
long segmentStartTimeUs = 0;
long segmentByteRangeOffset = 0;
long segmentByteRangeLength = C.LENGTH_UNSET;
int segmentMediaSequence = 0;
boolean isEncrypted = false;
String encryptionKeyUri = null;
String encryptionIV = null;
String line;
while (iterator.hasNext()) {
line = iterator.next();
if (line.startsWith(TAG_INIT_SEGMENT)) {
String uri = parseStringAttr(line, REGEX_URI);
String byteRange = parseOptionalStringAttr(line, REGEX_ATTR_BYTERANGE);
if (byteRange != null) {
String[] splitByteRange = byteRange.split("@");
segmentByteRangeLength = Long.parseLong(splitByteRange[0]);
if (splitByteRange.length > 1) {
segmentByteRangeOffset = Long.parseLong(splitByteRange[1]);
}
}
initializationSegment = new Segment(uri, segmentByteRangeOffset, segmentByteRangeLength);
segmentByteRangeOffset = 0;
segmentByteRangeLength = C.LENGTH_UNSET;
} else if (line.startsWith(TAG_TARGET_DURATION)) {
targetDurationUs = parseIntAttr(line, REGEX_TARGET_DURATION) * C.MICROS_PER_SECOND;
} else if (line.startsWith(TAG_MEDIA_SEQUENCE)) {
mediaSequence = parseIntAttr(line, REGEX_MEDIA_SEQUENCE);
segmentMediaSequence = mediaSequence;
} else if (line.startsWith(TAG_VERSION)) {
version = parseIntAttr(line, REGEX_VERSION);
} else if (line.startsWith(TAG_MEDIA_DURATION)) {
segmentDurationUs =
(long) (parseDoubleAttr(line, REGEX_MEDIA_DURATION) * C.MICROS_PER_SECOND);
} else if (line.startsWith(TAG_KEY)) {
String method = parseStringAttr(line, REGEX_METHOD);
isEncrypted = METHOD_AES128.equals(method);
if (isEncrypted) {
encryptionKeyUri = parseStringAttr(line, REGEX_URI);
encryptionIV = parseOptionalStringAttr(line, REGEX_IV);
} else {
encryptionKeyUri = null;
encryptionIV = null;
}
} else if (line.startsWith(TAG_BYTERANGE)) {
String byteRange = parseStringAttr(line, REGEX_BYTERANGE);
String[] splitByteRange = byteRange.split("@");
segmentByteRangeLength = Long.parseLong(splitByteRange[0]);
if (splitByteRange.length > 1) {
segmentByteRangeOffset = Long.parseLong(splitByteRange[1]);
}
} else if (line.startsWith(TAG_DISCONTINUITY_SEQUENCE)) {
discontinuitySequenceNumber = Integer.parseInt(line.substring(line.indexOf(':') + 1));
} else if (line.equals(TAG_DISCONTINUITY)) {
discontinuitySequenceNumber++;
} else if (line.startsWith(TAG_PROGRAM_DATE_TIME)) {
if (playlistStartTimeUs == 0) {
long programDatetimeUs =
C.msToUs(Util.parseXsDateTime(line.substring(line.indexOf(':') + 1)));
playlistStartTimeUs = programDatetimeUs - segmentStartTimeUs;
}
} else if (!line.startsWith("#")) {
String segmentEncryptionIV;
if (!isEncrypted) {
segmentEncryptionIV = null;
} else if (encryptionIV != null) {
segmentEncryptionIV = encryptionIV;
} else {
segmentEncryptionIV = Integer.toHexString(segmentMediaSequence);
}
segmentMediaSequence++;
if (segmentByteRangeLength == C.LENGTH_UNSET) {
segmentByteRangeOffset = 0;
}
segments.add(new Segment(line, segmentDurationUs, discontinuitySequenceNumber,
segmentStartTimeUs, isEncrypted, encryptionKeyUri, segmentEncryptionIV,
segmentByteRangeOffset, segmentByteRangeLength));
segmentStartTimeUs += segmentDurationUs;
segmentDurationUs = 0;
if (segmentByteRangeLength != C.LENGTH_UNSET) {
segmentByteRangeOffset += segmentByteRangeLength;
}
segmentByteRangeLength = C.LENGTH_UNSET;
} else if (line.equals(TAG_ENDLIST)) {
hasEndTag = true;
}
}
return new HlsMediaPlaylist(baseUri, playlistStartTimeUs, mediaSequence, version,
targetDurationUs, hasEndTag, playlistStartTimeUs != 0, initializationSegment, segments);
}
private static String parseStringAttr(String line, Pattern pattern) throws ParserException {
Matcher matcher = pattern.matcher(line);
if (matcher.find() && matcher.groupCount() == 1) {
return matcher.group(1);
}
throw new ParserException("Couldn't match " + pattern.pattern() + " in " + line);
}
private static int parseIntAttr(String line, Pattern pattern) throws ParserException {
return Integer.parseInt(parseStringAttr(line, pattern));
}
private static double parseDoubleAttr(String line, Pattern pattern) throws ParserException {
return Double.parseDouble(parseStringAttr(line, pattern));
}
private static String parseOptionalStringAttr(String line, Pattern pattern) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
private static boolean parseBooleanAttribute(String line, Pattern pattern, boolean defaultValue) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
return matcher.group(1).equals(BOOLEAN_TRUE);
}
return defaultValue;
}
private static Pattern compileBooleanAttrPattern(String attribute) {
return Pattern.compile(attribute + "=(" + BOOLEAN_FALSE + "|" + BOOLEAN_TRUE + ")");
}
private static class LineIterator {
private final BufferedReader reader;
private final Queue<String> extraLines;
private String next;
public LineIterator(Queue<String> extraLines, BufferedReader reader) {
this.extraLines = extraLines;
this.reader = reader;
}
public boolean hasNext() throws IOException {
if (next != null) {
return true;
}
if (!extraLines.isEmpty()) {
next = extraLines.poll();
return true;
}
while ((next = reader.readLine()) != null) {
next = next.trim();
if (!next.isEmpty()) {
return true;
}
}
return false;
}
public String next() throws IOException {
String result = null;
if (hasNext()) {
result = next;
next = null;
}
return result;
}
}
}
| |
/*
* Created on Jun 14, 2004
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2004 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2012:02/01 Changed getHostPort() to return proper port number even if it
// is not explicitly specified in URI
// ZAP: 2011/08/04 Changed to support Logging
// ZAP: 2011/10/29 Log errors
// ZAP: 2011/11/03 Changed isImage() to prevent a NullPointerException when the path doesn't exist
// ZAP: 2011/12/09 Changed HttpRequestHeader(String method, URI uri, String version) to add
// the Cache-Control header field when the HTTP version is 1.1 and changed a if condition to
// validate the variable version instead of the variable method.
// ZAP: 2012/03/15 Changed to use the class StringBuilder instead of StringBuffer. Reworked some
// methods.
// ZAP: 2012/04/23 Added @Override annotation to all appropriate methods.
// ZAP: 2012/06/24 Added method to add Cookies of type java.net.HttpCookie to request header
// ZAP: 2012/06/24 Added new method of getting cookies from the request header.
// ZAP: 2012/10/08 Issue 361: getHostPort on HttpRequestHeader for HTTPS CONNECT
// requests returns the wrong port
// ZAP: 2013/01/23 Clean up of exception handling/logging.
// ZAP: 2013/03/08 Improved parse error reporting
// ZAP: 2013/04/14 Issue 596: Rename the method HttpRequestHeader.getSecure to isSecure
// ZAP: 2013/05/02 Re-arranged all modifiers into Java coding standard order
// ZAP: 2013/12/09 Set Content-type only in case of POST or PUT HTTP methods
// ZAP: 2015/08/07 Issue 1768: Update to use a more recent default user agent
// ZAP: 2016/06/17 Remove redundant initialisations of instance variables
// ZAP: 2016/09/26 JavaDoc tweaks
// ZAP: 2017/02/23 Issue 3227: Limit API access to permitted IP addresses
// ZAP: 2017/04/24 Added more HTTP methods
// ZAP: 2017/10/19 Skip parsing of empty Cookie headers.
// ZAP: 2017/11/22 Address a NPE in isImage().
// ZAP: 2018/01/10 Tweak how cookie header is reconstructed from HtmlParameter(s).
// ZAP: 2018/02/06 Make the upper case changes locale independent (Issue 4327).
// ZAP: 2018/08/10 Allow to set the user agent used by default request headers (Issue 4846).
// ZAP: 2018/11/16 Add Accept header.
// ZAP: 2019/01/25 Add Origin header.
// ZAP: 2019/03/06 Log or include the malformed data in the exception message.
// ZAP: 2019/03/19 Changed the parse method to only parse the authority on CONNECT requests
// ZAP: 2019/06/01 Normalise line endings.
// ZAP: 2019/06/05 Normalise format/style.
// ZAP: 2019/12/09 Address deprecation of getHeaders(String) Vector method.
// ZAP: 2020/11/10 Add convenience method isCss(), refactor isImage() to use new private method
// isSpecificType(Pattern).
// ZAP: 2020/11/26 Use Log4j 2 classes for logging.
package org.parosproxy.paros.network;
import java.io.UnsupportedEncodingException;
import java.net.HttpCookie;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class HttpRequestHeader extends HttpHeader {
/**
* The {@code Accept} request header.
*
* @since 2.8.0
*/
public static final String ACCEPT = "Accept";
/**
* The {@code Origin} request header.
*
* @since 2.8.0
*/
public static final String ORIGIN = "Origin";
private static final long serialVersionUID = 4156598327921777493L;
private static final Logger log = LogManager.getLogger(HttpRequestHeader.class);
// method list
public static final String CONNECT = "CONNECT";
public static final String DELETE = "DELETE";
public static final String GET = "GET";
public static final String HEAD = "HEAD";
public static final String OPTIONS = "OPTIONS";
public static final String PATCH = "PATCH";
public static final String POST = "POST";
public static final String PUT = "PUT";
public static final String TRACE = "TRACE";
public static final String TRACK = "TRACK";
// ZAP: Added method array
public static final String[] METHODS = {
CONNECT, DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, TRACE, TRACK
};
public static final String HOST = "Host";
private static final Pattern patternRequestLine =
Pattern.compile(p_METHOD + p_SP + p_URI + p_SP + p_VERSION, Pattern.CASE_INSENSITIVE);
// private static final Pattern patternHostHeader
// = Pattern.compile("([^:]+)\\s*?:?\\s*?(\\d*?)");
private static final Pattern patternImage =
Pattern.compile("\\.(bmp|ico|jpg|jpeg|gif|tiff|tif|png)\\z", Pattern.CASE_INSENSITIVE);
private static final Pattern patternPartialRequestLine =
Pattern.compile(
"\\A *(OPTIONS|GET|HEAD|POST|PUT|DELETE|TRACE|CONNECT)\\b",
Pattern.CASE_INSENSITIVE);
private static final Pattern PATTERN_CSS =
Pattern.compile("\\.css\\z", Pattern.CASE_INSENSITIVE);
/**
* The user agent used by {@link #HttpRequestHeader(String, URI, String) default request
* header}.
*/
private static String defaultUserAgent;
private String mMethod;
private URI mUri;
private String mHostName;
private InetAddress senderAddress;
/**
* The host port number of this request message, a non-negative integer.
*
* <p>Default is {@code 80}.
*
* <p><strong>Note:</strong> All the modifications to the instance variable {@code mHostPort}
* must be done through the method {@code setHostPort(int)}, so a valid and correct value is set
* when no port number is defined (which is represented with the negative integer -1).
*
* @see #getHostPort()
* @see #setHostPort(int)
* @see URI#getPort()
*/
private int mHostPort;
private boolean mIsSecure;
/** Constructor for an empty header. */
public HttpRequestHeader() {
super();
mMethod = "";
mHostName = "";
mHostPort = 80;
}
/**
* Constructor of a request header with the string.
*
* @param data the request header
* @param isSecure {@code true} if the request should be secure, {@code false} otherwise
* @throws HttpMalformedHeaderException if the request being set is malformed
* @see #setSecure(boolean)
*/
public HttpRequestHeader(String data, boolean isSecure) throws HttpMalformedHeaderException {
setMessage(data, isSecure);
}
/**
* Constructor of a request header with the string. Whether this is a secure header depends on
* the URL given.
*
* @param data the request header
* @throws HttpMalformedHeaderException if the request being set is malformed
*/
public HttpRequestHeader(String data) throws HttpMalformedHeaderException {
setMessage(data);
}
@Override
public void clear() {
super.clear();
mMethod = "";
mUri = null;
mHostName = "";
setHostPort(-1);
}
/**
* Constructs a {@code HttpRequestHeader} with the given method, URI, and version.
*
* <p>The following headers are automatically added:
*
* <ul>
* <li>{@code Host}, with the domain and port from the given URI.
* <li>{@code User-Agent}, using the {@link #getDefaultUserAgent()}.
* <li>{@code Pragma: no-cache}
* <li>{@code Cache-Control: no-cache}, if version is HTTP/1.1
* <li>{@code Content-Type: application/x-www-form-urlencoded}, if the method is POST or PUT.
* </ul>
*
* @param method the request method.
* @param uri the request target.
* @param version the version, for example, {@code HTTP/1.1}.
* @throws HttpMalformedHeaderException if the resulting HTTP header is malformed.
*/
public HttpRequestHeader(String method, URI uri, String version)
throws HttpMalformedHeaderException {
this(method + " " + uri.toString() + " " + version.toUpperCase(Locale.ROOT) + CRLF + CRLF);
try {
setHeader(
HOST,
uri.getHost()
+ (uri.getPort() > 0 ? ":" + Integer.toString(uri.getPort()) : ""));
} catch (URIException e) {
log.error(e.getMessage(), e);
}
setHeader(USER_AGENT, defaultUserAgent);
setHeader(PRAGMA, "no-cache");
// ZAP: added the Cache-Control header field to comply with HTTP/1.1
if (version.equalsIgnoreCase(HTTP11)) {
setHeader(CACHE_CONTROL, "no-cache");
}
// ZAP: set content type x-www-urlencoded only if it's a POST or a PUT
if (method.equalsIgnoreCase(POST) || method.equalsIgnoreCase(PUT)) {
setHeader(CONTENT_TYPE, "application/x-www-form-urlencoded");
}
setHeader(ACCEPT_ENCODING, null);
// ZAP: changed from method to version
if (version.equalsIgnoreCase(HTTP11)) {
setContentLength(0);
}
}
/**
* Constructs a {@code HttpRequestHeader} with the given method, URI, and version.
*
* <p>The following headers are automatically added:
*
* <ul>
* <li>{@code Host}, with the domain and port from the given URI.
* <li>{@code User-Agent}, using the {@link #getDefaultUserAgent()}.
* <li>{@code Pragma: no-cache}
* <li>{@code Cache-Control: no-cache}, if version is HTTP/1.1
* <li>{@code Content-Type: application/x-www-form-urlencoded}, if the method is POST or PUT.
* </ul>
*
* @param method the request method.
* @param uri the request target.
* @param version the version, for example, {@code HTTP/1.1}.
* @param params unused.
* @throws HttpMalformedHeaderException if the resulting HTTP header is malformed.
* @deprecated (2.8.0) Use {@link #HttpRequestHeader(String, URI, String)} instead.
* @since 2.4.2
*/
@Deprecated
public HttpRequestHeader(String method, URI uri, String version, ConnectionParam params)
throws HttpMalformedHeaderException {
this(method, uri, version);
}
/**
* Set this request header with the given message.
*
* @param data the request header
* @param isSecure {@code true} if the request should be secure, {@code false} otherwise
* @throws HttpMalformedHeaderException if the request being set is malformed
* @see #setSecure(boolean)
*/
public void setMessage(String data, boolean isSecure) throws HttpMalformedHeaderException {
super.setMessage(data);
try {
parse(isSecure);
} catch (HttpMalformedHeaderException e) {
mMalformedHeader = true;
if (log.isDebugEnabled()) {
log.debug("Malformed header: " + data, e);
}
throw e;
} catch (Exception e) {
log.error("Failed to parse:\n" + data, e);
mMalformedHeader = true;
throw new HttpMalformedHeaderException(e.getMessage());
}
}
/**
* Set this request header with the given message. Whether this is a secure header depends on
* the URL given.
*/
@Override
public void setMessage(String data) throws HttpMalformedHeaderException {
this.setMessage(data, false);
}
/**
* Get the HTTP method (GET, POST, ..., etc.).
*
* @return the request method
*/
public String getMethod() {
return mMethod;
}
/**
* Set the HTTP method of this request header.
*
* @param method the new method, must not be {@code null}.
*/
public void setMethod(String method) {
mMethod = method.toUpperCase(Locale.ROOT);
}
/**
* Get the URI of this request header.
*
* @return the request URI
*/
public URI getURI() {
return mUri;
}
/**
* Sets the URI of this request header.
*
* @param uri the new request URI
* @throws URIException if an error occurred while setting the request URI
*/
public void setURI(URI uri) throws URIException {
if (uri.getScheme() == null || uri.getScheme().equals("")) {
mUri = new URI(HTTP + "://" + getHeader(HOST) + "/" + mUri.toString(), true);
} else {
mUri = uri;
}
if (uri.getScheme().equalsIgnoreCase(HTTPS)) {
mIsSecure = true;
} else {
mIsSecure = false;
}
setHostPort(mUri.getPort());
}
/**
* Get if this request header is under secure connection.
*
* @return {@code true} if the request is secure, {@code false} otherwise
* @deprecated Replaced by {@link #isSecure()}. It will be removed in a future release.
*/
@Deprecated
public boolean getSecure() {
return mIsSecure;
}
/**
* Tells whether the request is secure, or not. A request is considered secure if it's using the
* HTTPS protocol.
*
* @return {@code true} if the request is secure, {@code false} otherwise.
*/
public boolean isSecure() {
return mIsSecure;
}
/**
* Sets whether or not the request is done using a secure scheme, HTTPS.
*
* @param isSecure {@code true} if the request should be secure, {@code false} otherwise
* @throws URIException if an error occurred while rebuilding the request URI
*/
public void setSecure(boolean isSecure) throws URIException {
mIsSecure = isSecure;
if (mUri == null) {
// mUri not yet set
return;
}
URI newUri = mUri;
// check if URI consistent
if (isSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) {
newUri = new URI(mUri.toString().replaceFirst(HTTP, HTTPS), true);
} else if (!isSecure() && mUri.getScheme().equalsIgnoreCase(HTTPS)) {
newUri = new URI(mUri.toString().replaceFirst(HTTPS, HTTP), true);
}
if (newUri != mUri) {
mUri = newUri;
setHostPort(mUri.getPort());
}
}
/** Set the HTTP version of this request header. */
@Override
public void setVersion(String version) {
mVersion = version.toUpperCase(Locale.ROOT);
}
/**
* Get the content length in this request header. If the content length is undetermined, 0 will
* be returned.
*/
@Override
public int getContentLength() {
if (mContentLength == -1) {
return 0;
}
return mContentLength;
}
/**
* Parse this request header.
*
* @param isSecure {@code true} if the request is secure, {@code false} otherwise
* @throws URIException if failed to parse the URI
* @throws HttpMalformedHeaderException if the request being parsed is malformed
*/
private void parse(boolean isSecure) throws URIException, HttpMalformedHeaderException {
mIsSecure = isSecure;
Matcher matcher = patternRequestLine.matcher(mStartLine);
if (!matcher.find()) {
mMalformedHeader = true;
throw new HttpMalformedHeaderException(
"Failed to find pattern " + patternRequestLine + " in: " + mStartLine);
}
mMethod = matcher.group(1);
String sUri = matcher.group(2);
mVersion = matcher.group(3);
if (!mVersion.equalsIgnoreCase(HTTP09)
&& !mVersion.equalsIgnoreCase(HTTP10)
&& !mVersion.equalsIgnoreCase(HTTP11)) {
mMalformedHeader = true;
throw new HttpMalformedHeaderException("Unexpected version: " + mVersion);
}
if (mMethod.equalsIgnoreCase(CONNECT)) {
parseHostName(sUri);
mUri = parseURI(mHostName);
} else {
mUri = parseURI(sUri);
if (mUri.getScheme() == null || mUri.getScheme().equals("")) {
mUri = new URI(HTTP + "://" + getHeader(HOST) + mUri.toString(), true);
}
if (isSecure() && mUri.getScheme().equalsIgnoreCase(HTTP)) {
mUri = new URI(mUri.toString().replaceFirst(HTTP, HTTPS), true);
}
if (mUri.getScheme().equalsIgnoreCase(HTTPS)) {
setSecure(true);
}
mHostName = mUri.getHost();
setHostPort(mUri.getPort());
}
}
private void parseHostName(String hostHeader) {
// no host header given but a valid host name already exist.
if (hostHeader == null) {
return;
}
int port = -1;
int pos;
if ((pos = hostHeader.indexOf(':', 2)) > -1) {
mHostName = hostHeader.substring(0, pos).trim();
try {
port = Integer.parseInt(hostHeader.substring(pos + 1));
} catch (NumberFormatException e) {
}
} else {
mHostName = hostHeader.trim();
}
setHostPort(port);
}
/**
* Get the host name in this request header.
*
* @return Host name.
*/
public String getHostName() {
String hostName = mHostName;
try {
// ZAP: fixed cases, where host name is null
hostName = ((mUri.getHost() != null) ? mUri.getHost() : mHostName);
} catch (URIException e) {
if (log.isDebugEnabled()) {
log.warn(e);
}
}
return hostName;
}
/**
* Gets the host port number of this request message, a non-negative integer.
*
* <p>If no port is defined the default port for the used scheme will be returned, either 80 for
* HTTP or 443 for HTTPS.
*
* @return the host port number, a non-negative integer
*/
public int getHostPort() {
return mHostPort;
}
/**
* Sets the host port number of this request message.
*
* <p>If the given {@code port} number is negative (usually -1 to represent that no port number
* is defined), the port number set will be the default port number for the used scheme known
* using the method {@code isSecure()}, either 80 for HTTP or 443 for HTTPS.
*
* @param port the new port number
* @see #mHostPort
* @see #isSecure()
* @see URI#getPort()
*/
private void setHostPort(int port) {
if (port > -1) {
mHostPort = port;
} else if (this.isSecure()) {
mHostPort = 443;
} else {
mHostPort = 80;
}
}
/** Return if this request header is a image request basing on the path suffix. */
@Override
public boolean isImage() {
return isSpecificType(patternImage);
}
public boolean isCss() {
return isSpecificType(PATTERN_CSS);
}
private boolean isSpecificType(Pattern pattern) {
if (getURI() == null) {
return false;
}
try {
// ZAP: prevents a NullPointerException when no path exists
final String path = getURI().getPath();
if (path != null) {
return (pattern.matcher(path).find());
}
} catch (URIException e) {
log.error(e.getMessage(), e);
}
return false;
}
/**
* Return if the data given is a request header basing on the first start line.
*
* @param data the data to be checked
* @return {@code true} if the data contains a request line, {@code false} otherwise.
*/
public static boolean isRequestLine(String data) {
return patternPartialRequestLine.matcher(data).find();
}
/** Return the prime header (first line). */
@Override
public String getPrimeHeader() {
return getMethod() + " " + getURI().toString() + " " + getVersion();
}
/*
* private static final char[] DELIM_UNWISE_CHAR = { '<', '>', '#', '"', '
* ', '{', '}', '|', '\\', '^', '[', ']', '`' };
*/
private static final String DELIM = "<>#\"";
private static final String UNWISE = "{}|\\^[]`";
private static final String DELIM_UNWISE = DELIM + UNWISE;
public static URI parseURI(String sUri) throws URIException {
URI uri;
int len = sUri.length();
StringBuilder sb = new StringBuilder(len);
char[] charray = new char[1];
String s;
for (int i = 0; i < len; i++) {
char ch = sUri.charAt(i);
// String ch = sUri.substring(i, i+1);
if (DELIM_UNWISE.indexOf(ch) >= 0) {
// check if unwise or delim in RFC. If so, encode it.
charray[0] = ch;
s = new String(charray);
try {
s = URLEncoder.encode(s, "UTF8");
} catch (UnsupportedEncodingException e1) {
}
sb.append(s);
} else if (ch == '%') {
// % is exception - no encoding to be done because some server may not handle
// correctly when % is invalid.
//
// sb.append(ch);
// if % followed by hex, no encode.
try {
String hex = sUri.substring(i + 1, i + 3);
Integer.parseInt(hex, 16);
sb.append(ch);
} catch (Exception e) {
charray[0] = ch;
s = new String(charray);
try {
s = URLEncoder.encode(s, "UTF8");
} catch (UnsupportedEncodingException e1) {
}
sb.append(s);
}
} else if (ch == ' ') {
// if URLencode, '+' will be appended.
sb.append("%20");
} else {
sb.append(ch);
}
}
uri = new URI(sb.toString(), true);
return uri;
}
// Construct new GET url of request
// Based on getParams
public void setGetParams(TreeSet<HtmlParameter> getParams) {
if (mUri == null) {
return;
}
if (getParams.isEmpty()) {
try {
mUri.setQuery("");
} catch (URIException e) {
log.error(e.getMessage(), e);
}
return;
}
StringBuilder sbQuery = new StringBuilder();
for (HtmlParameter parameter : getParams) {
if (parameter.getType() != HtmlParameter.Type.url) {
continue;
}
sbQuery.append(parameter.getName());
sbQuery.append('=');
sbQuery.append(parameter.getValue());
sbQuery.append('&');
}
if (sbQuery.length() <= 2) {
try {
mUri.setQuery("");
} catch (URIException e) {
log.error(e.getMessage(), e);
}
return;
}
String query = sbQuery.substring(0, sbQuery.length() - 1);
try {
// The previous behaviour was escaping the query,
// so it is maintained with the use of setQuery.
mUri.setQuery(query);
} catch (URIException e) {
log.error(e.getMessage(), e);
}
}
/**
* Construct new "Cookie:" line in request header based on HttpCookies.
*
* @param cookies the new cookies
*/
public void setCookies(List<HttpCookie> cookies) {
if (cookies.isEmpty()) {
setHeader(HttpHeader.COOKIE, null);
}
StringBuilder sbData = new StringBuilder();
for (HttpCookie c : cookies) {
sbData.append(c.getName());
sbData.append('=');
sbData.append(c.getValue());
sbData.append("; ");
}
if (sbData.length() <= 3) {
setHeader(HttpHeader.COOKIE, null);
return;
}
final String data = sbData.substring(0, sbData.length() - 2);
setHeader(HttpHeader.COOKIE, data);
}
// Construct new "Cookie:" line in request header,
// based on cookieParams
public void setCookieParams(TreeSet<HtmlParameter> cookieParams) {
if (cookieParams.isEmpty()) {
setHeader(HttpHeader.COOKIE, null);
}
StringBuilder sbData = new StringBuilder();
for (HtmlParameter parameter : cookieParams) {
if (parameter.getType() != HtmlParameter.Type.cookie) {
continue;
}
String cookieName = parameter.getName();
if (!cookieName.isEmpty()) {
sbData.append(cookieName);
sbData.append('=');
}
sbData.append(parameter.getValue());
sbData.append("; ");
}
if (sbData.length() <= 2) {
setHeader(HttpHeader.COOKIE, null);
return;
}
final String data = sbData.substring(0, sbData.length() - 2);
setHeader(HttpHeader.COOKIE, data);
}
public TreeSet<HtmlParameter> getCookieParams() {
TreeSet<HtmlParameter> set = new TreeSet<>();
for (String cookieLine : getHeaderValues(HttpHeader.COOKIE)) {
// watch out for the scenario where the first cookie name starts with "cookie"
// (uppercase or lowercase)
if (cookieLine.toUpperCase().startsWith(HttpHeader.COOKIE.toUpperCase() + ":")) {
// HttpCookie wont parse lines starting with "Cookie:"
cookieLine = cookieLine.substring(HttpHeader.COOKIE.length() + 1);
}
if (cookieLine.isEmpty()) {
// Nothing to parse.
continue;
}
// These can be comma separated type=value
String[] cookieArray = cookieLine.split(";");
for (String cookie : cookieArray) {
set.add(new HtmlParameter(cookie));
}
}
return set;
}
// ZAP: Added method for working directly with HttpCookie
/**
* Gets a list of the http cookies from this request Header.
*
* @return the http cookies
* @throws IllegalArgumentException if a problem is encountered while processing the "Cookie: "
* header line.
*/
public List<HttpCookie> getHttpCookies() {
List<HttpCookie> cookies = new LinkedList<>();
// Use getCookieParams to reduce the places we parse cookies
TreeSet<HtmlParameter> ts = getCookieParams();
Iterator<HtmlParameter> it = ts.iterator();
while (it.hasNext()) {
HtmlParameter htmlParameter = it.next();
if (!htmlParameter.getName().isEmpty()) {
try {
cookies.add(new HttpCookie(htmlParameter.getName(), htmlParameter.getValue()));
} catch (IllegalArgumentException e) {
// Occurs while scanning ;)
log.debug(e.getMessage() + " " + htmlParameter.getName());
}
}
}
return cookies;
}
/**
* Sets the senders IP address. Note that this is not persisted.
*
* @param inetAddress the senders IP address
* @since 2.6.0
*/
public void setSenderAddress(InetAddress inetAddress) {
this.senderAddress = inetAddress;
}
/**
* Gets the senders IP address
*
* @return the senders IP address
* @since 2.6.0
*/
public InetAddress getSenderAddress() {
return senderAddress;
}
/**
* Sets the user agent used by {@link #HttpRequestHeader(String, URI, String) default request
* header}.
*
* <p>This is expected to be called only by core code, when the corresponding option is changed.
*
* @param defaultUserAgent the default user agent.
* @since 2.8.0
*/
public static void setDefaultUserAgent(String defaultUserAgent) {
HttpRequestHeader.defaultUserAgent = defaultUserAgent;
}
/**
* Gets the user agent used by {@link #HttpRequestHeader(String, URI, String) default request
* header}.
*
* @return the default user agent.
* @since 2.8.0
*/
public static String getDefaultUserAgent() {
return defaultUserAgent;
}
}
| |
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.identitymanagement.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Contains the response to a successful <a>ListUserPolicies</a> request.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUserPolicies" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListUserPoliciesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* A list of policy names.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> policyNames;
/**
* <p>
* A flag that indicates whether there are more items to return. If your results were truncated, you can make a
* subsequent pagination request using the <code>Marker</code> request parameter to retrieve more items. Note that
* IAM might return fewer than the <code>MaxItems</code> number of results even when there are more results
* available. We recommend that you check <code>IsTruncated</code> after every call to ensure that you receive all
* of your results.
* </p>
*/
private Boolean isTruncated;
/**
* <p>
* When <code>IsTruncated</code> is <code>true</code>, this element is present and contains the value to use for the
* <code>Marker</code> parameter in a subsequent pagination request.
* </p>
*/
private String marker;
/**
* <p>
* A list of policy names.
* </p>
*
* @return A list of policy names.
*/
public java.util.List<String> getPolicyNames() {
if (policyNames == null) {
policyNames = new com.amazonaws.internal.SdkInternalList<String>();
}
return policyNames;
}
/**
* <p>
* A list of policy names.
* </p>
*
* @param policyNames
* A list of policy names.
*/
public void setPolicyNames(java.util.Collection<String> policyNames) {
if (policyNames == null) {
this.policyNames = null;
return;
}
this.policyNames = new com.amazonaws.internal.SdkInternalList<String>(policyNames);
}
/**
* <p>
* A list of policy names.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setPolicyNames(java.util.Collection)} or {@link #withPolicyNames(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param policyNames
* A list of policy names.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListUserPoliciesResult withPolicyNames(String... policyNames) {
if (this.policyNames == null) {
setPolicyNames(new com.amazonaws.internal.SdkInternalList<String>(policyNames.length));
}
for (String ele : policyNames) {
this.policyNames.add(ele);
}
return this;
}
/**
* <p>
* A list of policy names.
* </p>
*
* @param policyNames
* A list of policy names.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListUserPoliciesResult withPolicyNames(java.util.Collection<String> policyNames) {
setPolicyNames(policyNames);
return this;
}
/**
* <p>
* A flag that indicates whether there are more items to return. If your results were truncated, you can make a
* subsequent pagination request using the <code>Marker</code> request parameter to retrieve more items. Note that
* IAM might return fewer than the <code>MaxItems</code> number of results even when there are more results
* available. We recommend that you check <code>IsTruncated</code> after every call to ensure that you receive all
* of your results.
* </p>
*
* @param isTruncated
* A flag that indicates whether there are more items to return. If your results were truncated, you can make
* a subsequent pagination request using the <code>Marker</code> request parameter to retrieve more items.
* Note that IAM might return fewer than the <code>MaxItems</code> number of results even when there are more
* results available. We recommend that you check <code>IsTruncated</code> after every call to ensure that
* you receive all of your results.
*/
public void setIsTruncated(Boolean isTruncated) {
this.isTruncated = isTruncated;
}
/**
* <p>
* A flag that indicates whether there are more items to return. If your results were truncated, you can make a
* subsequent pagination request using the <code>Marker</code> request parameter to retrieve more items. Note that
* IAM might return fewer than the <code>MaxItems</code> number of results even when there are more results
* available. We recommend that you check <code>IsTruncated</code> after every call to ensure that you receive all
* of your results.
* </p>
*
* @return A flag that indicates whether there are more items to return. If your results were truncated, you can
* make a subsequent pagination request using the <code>Marker</code> request parameter to retrieve more
* items. Note that IAM might return fewer than the <code>MaxItems</code> number of results even when there
* are more results available. We recommend that you check <code>IsTruncated</code> after every call to
* ensure that you receive all of your results.
*/
public Boolean getIsTruncated() {
return this.isTruncated;
}
/**
* <p>
* A flag that indicates whether there are more items to return. If your results were truncated, you can make a
* subsequent pagination request using the <code>Marker</code> request parameter to retrieve more items. Note that
* IAM might return fewer than the <code>MaxItems</code> number of results even when there are more results
* available. We recommend that you check <code>IsTruncated</code> after every call to ensure that you receive all
* of your results.
* </p>
*
* @param isTruncated
* A flag that indicates whether there are more items to return. If your results were truncated, you can make
* a subsequent pagination request using the <code>Marker</code> request parameter to retrieve more items.
* Note that IAM might return fewer than the <code>MaxItems</code> number of results even when there are more
* results available. We recommend that you check <code>IsTruncated</code> after every call to ensure that
* you receive all of your results.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListUserPoliciesResult withIsTruncated(Boolean isTruncated) {
setIsTruncated(isTruncated);
return this;
}
/**
* <p>
* A flag that indicates whether there are more items to return. If your results were truncated, you can make a
* subsequent pagination request using the <code>Marker</code> request parameter to retrieve more items. Note that
* IAM might return fewer than the <code>MaxItems</code> number of results even when there are more results
* available. We recommend that you check <code>IsTruncated</code> after every call to ensure that you receive all
* of your results.
* </p>
*
* @return A flag that indicates whether there are more items to return. If your results were truncated, you can
* make a subsequent pagination request using the <code>Marker</code> request parameter to retrieve more
* items. Note that IAM might return fewer than the <code>MaxItems</code> number of results even when there
* are more results available. We recommend that you check <code>IsTruncated</code> after every call to
* ensure that you receive all of your results.
*/
public Boolean isTruncated() {
return this.isTruncated;
}
/**
* <p>
* When <code>IsTruncated</code> is <code>true</code>, this element is present and contains the value to use for the
* <code>Marker</code> parameter in a subsequent pagination request.
* </p>
*
* @param marker
* When <code>IsTruncated</code> is <code>true</code>, this element is present and contains the value to use
* for the <code>Marker</code> parameter in a subsequent pagination request.
*/
public void setMarker(String marker) {
this.marker = marker;
}
/**
* <p>
* When <code>IsTruncated</code> is <code>true</code>, this element is present and contains the value to use for the
* <code>Marker</code> parameter in a subsequent pagination request.
* </p>
*
* @return When <code>IsTruncated</code> is <code>true</code>, this element is present and contains the value to use
* for the <code>Marker</code> parameter in a subsequent pagination request.
*/
public String getMarker() {
return this.marker;
}
/**
* <p>
* When <code>IsTruncated</code> is <code>true</code>, this element is present and contains the value to use for the
* <code>Marker</code> parameter in a subsequent pagination request.
* </p>
*
* @param marker
* When <code>IsTruncated</code> is <code>true</code>, this element is present and contains the value to use
* for the <code>Marker</code> parameter in a subsequent pagination request.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListUserPoliciesResult withMarker(String marker) {
setMarker(marker);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getPolicyNames() != null)
sb.append("PolicyNames: ").append(getPolicyNames()).append(",");
if (getIsTruncated() != null)
sb.append("IsTruncated: ").append(getIsTruncated()).append(",");
if (getMarker() != null)
sb.append("Marker: ").append(getMarker());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListUserPoliciesResult == false)
return false;
ListUserPoliciesResult other = (ListUserPoliciesResult) obj;
if (other.getPolicyNames() == null ^ this.getPolicyNames() == null)
return false;
if (other.getPolicyNames() != null && other.getPolicyNames().equals(this.getPolicyNames()) == false)
return false;
if (other.getIsTruncated() == null ^ this.getIsTruncated() == null)
return false;
if (other.getIsTruncated() != null && other.getIsTruncated().equals(this.getIsTruncated()) == false)
return false;
if (other.getMarker() == null ^ this.getMarker() == null)
return false;
if (other.getMarker() != null && other.getMarker().equals(this.getMarker()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getPolicyNames() == null) ? 0 : getPolicyNames().hashCode());
hashCode = prime * hashCode + ((getIsTruncated() == null) ? 0 : getIsTruncated().hashCode());
hashCode = prime * hashCode + ((getMarker() == null) ? 0 : getMarker().hashCode());
return hashCode;
}
@Override
public ListUserPoliciesResult clone() {
try {
return (ListUserPoliciesResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.irc;
import junit.framework.*;
import net.java.sip.communicator.impl.protocol.irc.exception.*;
import org.easymock.*;
public class CommandFactoryTest
extends TestCase
{
public void testCommandsAvailable()
{
Assert.assertNotNull(CommandFactory.getCommands());
}
public void testRegisterNullCommand()
{
try
{
CommandFactory.registerCommand(null, Test.class);
Assert.fail();
}
catch (IllegalArgumentException e)
{
}
}
public void testRegisterNullType()
{
try
{
CommandFactory.registerCommand("test", null);
Assert.fail();
}
catch (IllegalArgumentException e)
{
}
}
public void testRegisterCorrectCommand()
{
CommandFactory.registerCommand("test", Test.class);
Assert.assertEquals(1, CommandFactory.getCommands().size());
Assert.assertEquals(Test.class, CommandFactory.getCommands()
.get("test"));
CommandFactory.unregisterCommand(Test.class, "test");
Assert.assertEquals(0, CommandFactory.getCommands().size());
}
public void testRegisterMultipleCommandsForType()
{
CommandFactory.registerCommand("test", Test.class);
CommandFactory.registerCommand("bla", Test.class);
Assert.assertEquals(Test.class, CommandFactory.getCommands()
.get("test"));
Assert.assertEquals(Test.class, CommandFactory.getCommands()
.get("bla"));
Assert.assertEquals(2, CommandFactory.getCommands().size());
CommandFactory.unregisterCommand(Test.class, null);
Assert.assertEquals(0, CommandFactory.getCommands().size());
}
public void testUnregisterMultipleAmongOtherTypes()
{
Command anotherType = new Command() {
@Override
public void execute(String source, String line)
{
}
@Override
public String help()
{
return null;
}};
CommandFactory.registerCommand("test", Test.class);
CommandFactory.registerCommand("foo", anotherType.getClass());
CommandFactory.registerCommand("bla", Test.class);
Assert.assertEquals(Test.class, CommandFactory.getCommands()
.get("test"));
Assert.assertEquals(Test.class, CommandFactory.getCommands()
.get("bla"));
Assert.assertNotNull(CommandFactory.getCommands().get("foo"));
Assert.assertEquals(3, CommandFactory.getCommands().size());
CommandFactory.unregisterCommand(Test.class, null);
Assert.assertEquals(1, CommandFactory.getCommands().size());
Assert.assertNotSame(Test.class, CommandFactory.getCommands().get("foo"));
CommandFactory.unregisterCommand(anotherType.getClass(), null);
}
public void testUnregisterOneAmongMultipleSameType()
{
CommandFactory.registerCommand("test", Test.class);
CommandFactory.registerCommand("bla", Test.class);
Assert.assertEquals(Test.class, CommandFactory.getCommands()
.get("test"));
Assert.assertEquals(Test.class, CommandFactory.getCommands()
.get("bla"));
Assert.assertEquals(2, CommandFactory.getCommands().size());
CommandFactory.unregisterCommand(Test.class, "test");
Assert.assertEquals(1, CommandFactory.getCommands().size());
Assert.assertEquals(Test.class, CommandFactory.getCommands().get("bla"));
CommandFactory.unregisterCommand(Test.class, null);
}
public static class Test implements Command
{
public Test(ProtocolProviderServiceIrcImpl provider,
IrcConnection connection)
{
}
@Override
public void execute(String source, String line)
{
}
@Override
public String help()
{
return null;
}
}
public void testConstructionNullProvider()
{
IrcConnection connection = EasyMock.createMock(IrcConnection.class);
EasyMock.replay(connection);
try
{
new CommandFactory(null, connection);
Assert.fail();
}
catch (IllegalArgumentException e)
{
}
}
public void testConstructionNullConnection()
{
ProtocolProviderServiceIrcImpl provider = EasyMock.createMock(ProtocolProviderServiceIrcImpl.class);
EasyMock.replay(provider);
try
{
new CommandFactory(provider, null);
Assert.fail();
}
catch (IllegalArgumentException e)
{
}
}
public void testConstruction()
{
ProtocolProviderServiceIrcImpl provider = EasyMock.createMock(ProtocolProviderServiceIrcImpl.class);
IrcConnection connection = EasyMock.createMock(IrcConnection.class);
EasyMock.replay(provider, connection);
new CommandFactory(provider, connection);
}
public void testNonExistingCommand() throws BadCommandException
{
ProtocolProviderServiceIrcImpl provider = EasyMock.createMock(ProtocolProviderServiceIrcImpl.class);
IrcConnection connection = EasyMock.createMock(IrcConnection.class);
EasyMock.replay(provider, connection);
try
{
CommandFactory factory = new CommandFactory(provider, connection);
factory.createCommand("test");
Assert.fail();
}
catch (UnsupportedCommandException e)
{
}
}
public void testCreateNullCommandName() throws UnsupportedCommandException, BadCommandException
{
ProtocolProviderServiceIrcImpl provider = EasyMock.createMock(ProtocolProviderServiceIrcImpl.class);
IrcConnection connection = EasyMock.createMock(IrcConnection.class);
EasyMock.replay(provider, connection);
CommandFactory.registerCommand("test", Test.class);
try
{
CommandFactory factory = new CommandFactory(provider, connection);
factory.createCommand(null);
Assert.fail();
}
catch (IllegalArgumentException e)
{
}
CommandFactory.unregisterCommand(Test.class, null);
}
public void testCreateEmptyCommandName() throws UnsupportedCommandException, BadCommandException
{
ProtocolProviderServiceIrcImpl provider = EasyMock.createMock(ProtocolProviderServiceIrcImpl.class);
IrcConnection connection = EasyMock.createMock(IrcConnection.class);
EasyMock.replay(provider, connection);
CommandFactory.registerCommand("test", Unreachable.class);
try
{
CommandFactory factory = new CommandFactory(provider, connection);
factory.createCommand("");
Assert.fail();
}
catch (IllegalArgumentException e)
{
}
finally
{
CommandFactory.unregisterCommand(Test.class, null);
}
}
public void testExistingCommand() throws UnsupportedCommandException, BadCommandException
{
ProtocolProviderServiceIrcImpl provider = EasyMock.createMock(ProtocolProviderServiceIrcImpl.class);
IrcConnection connection = EasyMock.createMock(IrcConnection.class);
EasyMock.replay(provider, connection);
CommandFactory.registerCommand("test", Test.class);
try
{
CommandFactory factory = new CommandFactory(provider, connection);
Command cmd = factory.createCommand("test");
Assert.assertNotNull(cmd);
Assert.assertTrue(cmd instanceof Test);
}
finally
{
CommandFactory.unregisterCommand(Test.class, null);
}
}
public void testUnreachableCommand() throws UnsupportedCommandException
{
ProtocolProviderServiceIrcImpl provider = EasyMock.createMock(ProtocolProviderServiceIrcImpl.class);
IrcConnection connection = EasyMock.createMock(IrcConnection.class);
EasyMock.replay(provider, connection);
CommandFactory.registerCommand("test", Unreachable.class);
try
{
CommandFactory factory = new CommandFactory(provider, connection);
factory.createCommand("test");
Assert.fail();
}
catch (BadCommandException e)
{
}
finally
{
CommandFactory.unregisterCommand(Unreachable.class, null);
}
}
public void testBadCommand() throws UnsupportedCommandException
{
ProtocolProviderServiceIrcImpl provider = EasyMock.createMock(ProtocolProviderServiceIrcImpl.class);
IrcConnection connection = EasyMock.createMock(IrcConnection.class);
EasyMock.replay(provider, connection);
CommandFactory.registerCommand("test", BadImplementation.class);
try
{
CommandFactory factory = new CommandFactory(provider, connection);
factory.createCommand("test");
Assert.fail();
}
catch (BadCommandException e)
{
}
finally
{
CommandFactory.unregisterCommand(BadImplementation.class, null);
}
}
private static final class Unreachable implements Command
{
private Unreachable(ProtocolProviderServiceIrcImpl provider,
IrcConnection connection)
{
}
@Override
public void execute(String source, String line)
{
}
@Override
public String help()
{
return null;
}
}
public abstract static class BadImplementation implements Command
{
public BadImplementation(ProtocolProviderServiceIrcImpl provider,
IrcConnection connection)
{
}
}
}
| |
package butterknife;
import com.google.common.base.Joiner;
import com.google.testing.compile.JavaFileObjects;
import org.junit.Test;
import javax.tools.JavaFileObject;
import butterknife.compiler.ButterKnifeProcessor;
import static com.google.common.truth.Truth.assertAbout;
import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
import static com.google.testing.compile.JavaSourcesSubjectFactory.javaSources;
import static java.util.Arrays.asList;
public class UnbinderTest {
@Test public void multipleBindings() {
JavaFileObject source = JavaFileObjects.forSourceString("test.Test", ""
+ "package test;\n"
+ "import android.support.v4.app.Fragment;\n"
+ "import android.view.View;\n"
+ "import butterknife.BindView;\n"
+ "import butterknife.ButterKnife;\n"
+ "import butterknife.OnClick;\n"
+ "import butterknife.OnLongClick;\n"
+ "import butterknife.Unbinder;\n"
+ "public class Test extends Fragment {\n"
+ " @BindView(B.id.one) View view;\n"
+ " @BindView(B.id.two) View view2;\n"
+ " @OnClick(B.id.one) void doStuff() {}\n"
+ " @OnLongClick(B.id.one) boolean doMoreStuff() { return false; }\n"
+ "}"
);
JavaFileObject expectedSource = JavaFileObjects.forSourceString("test/Test$$ViewBinder", ""
+ "package test;\n"
+ "import android.view.View;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.DebouncingOnClickListener;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.ViewBinder;\n"
+ "import java.lang.IllegalStateException;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "public class Test$$ViewBinder<T extends Test> implements ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " return new InnerUnbinder(target, finder, source);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends Test> implements Unbinder {\n"
+ " protected T target;\n"
+ " private View testRidone;\n"
+ " protected InnerUnbinder(final T target, Finder finder, Object source) {\n"
+ " this.target = target;\n"
+ " View view;\n"
+ " view = finder.findRequiredView(source, test.R.id.one, \"field 'view', method 'doStuff', and method 'doMoreStuff'\");\n"
+ " target.view = view;\n"
+ " testRidone = view;\n"
+ " view.setOnClickListener(new DebouncingOnClickListener() {\n"
+ " @Override\n"
+ " public void doClick(View p0) {\n"
+ " target.doStuff();\n"
+ " }\n"
+ " });\n"
+ " view.setOnLongClickListener(new View.OnLongClickListener() {\n"
+ " @Override\n"
+ " public boolean onLongClick(View p0) {\n"
+ " return target.doMoreStuff();\n"
+ " }\n"
+ " });\n"
+ " target.view2 = finder.findRequiredView(source, test.R.id.two, \"field 'view2'\");\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " T target = this.target;\n"
+ " if (target == null) throw new IllegalStateException(\"Bindings already cleared.\");\n"
+ " target.view = null;\n"
+ " target.view2 = null;\n"
+ " testRidone.setOnClickListener(null);\n"
+ " testRidone.setOnLongClickListener(null);\n"
+ " testRidone = null;\n"
+ " this.target = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
assertAbout(javaSource()).that(source)
.processedWith(new ButterKnifeProcessor())
.compilesWithoutError()
.and()
.generatesSources(expectedSource);
}
@Test public void unbinderRespectsNullable() {
JavaFileObject source = JavaFileObjects.forSourceString("test.Test", ""
+ "package test;\n"
+ "import android.support.v4.app.Fragment;\n"
+ "import butterknife.ButterKnife;\n"
+ "import butterknife.OnClick;\n"
+ "import butterknife.Optional;\n"
+ "import butterknife.Unbinder;\n"
+ "public class Test extends Fragment {\n"
+ " @Optional @OnClick(B.id.one) void doStuff() {}\n"
+ "}"
);
JavaFileObject expectedSource = JavaFileObjects.forSourceString("test/Test$$ViewBinder", ""
+ "package test;\n"
+ "import android.view.View;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.DebouncingOnClickListener;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.ViewBinder;\n"
+ "import java.lang.IllegalStateException;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "public class Test$$ViewBinder<T extends Test> implements ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " return new InnerUnbinder(target, finder, source);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends Test> implements Unbinder {\n"
+ " protected T target;\n"
+ " private View testRidone;\n"
+ " protected InnerUnbinder(final T target, Finder finder, Object source) {\n"
+ " this.target = target;\n"
+ " View view;\n"
+ " view = finder.findOptionalView(source, test.R.id.one);\n"
+ " if (view != null) {\n"
+ " testRidone = view;\n"
+ " view.setOnClickListener(new DebouncingOnClickListener() {\n"
+ " @Override\n"
+ " public void doClick(View p0) {\n"
+ " target.doStuff();\n"
+ " }\n"
+ " });\n"
+ " }\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " if (this.target == null) throw new IllegalStateException(\"Bindings already cleared.\");\n"
+ " if (testRidone != null) {\n"
+ " testRidone.setOnClickListener(null);\n"
+ " testRidone = null;\n"
+ " }\n"
+ " this.target = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
assertAbout(javaSource()).that(source)
.processedWith(new ButterKnifeProcessor())
.compilesWithoutError()
.and()
.generatesSources(expectedSource);
}
@Test public void childBindsSecondUnbinder() {
JavaFileObject source = JavaFileObjects.forSourceString("test.Test", ""
+ "package test;\n"
+ "import android.support.v4.app.Fragment;\n"
+ "import butterknife.ButterKnife;\n"
+ "import butterknife.OnClick;\n"
+ "import butterknife.Unbinder;\n"
+ "public class Test extends Fragment {\n"
+ " @OnClick(B.id.one) void doStuff1() {}\n"
+ "}\n"
+ "class TestOne extends Test {\n"
+ " @OnClick(B.id.one) void doStuff2() {}\n"
+ "}\n"
+ "class TestTwo extends Test {}"
);
JavaFileObject expectedSource1 = JavaFileObjects.forSourceString("test/Test$$ViewBinder", ""
+ "package test;\n"
+ "import android.view.View;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.DebouncingOnClickListener;\n"
+ "import butterknife.internal.Finder;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "public class TestOne$$ViewBinder<T extends TestOne> extends Test$$ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " return new InnerUnbinder(target, finder, source);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends TestOne> extends Test$$ViewBinder.InnerUnbinder<T> {\n"
+ " private View testRidone;\n"
+ " protected InnerUnbinder(final T target, Finder finder, Object source) {\n"
+ " super(target, finder, source);\n"
+ " View view;\n"
+ " view = finder.findRequiredView(source, test.R.id.one, \"method 'doStuff2'\");\n"
+ " testRidone = view;\n"
+ " view.setOnClickListener(new DebouncingOnClickListener() {\n"
+ " @Override\n"
+ " public void doClick(View p0) {\n"
+ " target.doStuff2();\n"
+ " }\n"
+ " });\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " super.unbind();\n"
+ " testRidone.setOnClickListener(null);\n"
+ " testRidone = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
JavaFileObject expectedSource2 = JavaFileObjects.forSourceString("test/TestOne$$ViewBinder", ""
+ "package test;\n"
+ "import android.view.View;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.DebouncingOnClickListener;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.ViewBinder;\n"
+ "import java.lang.IllegalStateException;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "public class Test$$ViewBinder<T extends Test> implements ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " return new InnerUnbinder(target, finder, source);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends Test> implements Unbinder {\n"
+ " protected T target;\n"
+ " private View testRidone;\n"
+ " protected InnerUnbinder(final T target, Finder finder, Object source) {\n"
+ " this.target = target;\n"
+ " View view;\n"
+ " view = finder.findRequiredView(source, test.R.id.one, \"method 'doStuff1'\");\n"
+ " testRidone = view;\n"
+ " view.setOnClickListener(new DebouncingOnClickListener() {\n"
+ " @Override\n"
+ " public void doClick(View p0) {\n"
+ " target.doStuff1();\n"
+ " }\n"
+ " });\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " if (this.target == null) throw new IllegalStateException(\"Bindings already cleared.\");\n"
+ " testRidone.setOnClickListener(null);\n"
+ " testRidone = null;\n"
+ " this.target = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
assertAbout(javaSource()).that(source)
.processedWith(new ButterKnifeProcessor())
.compilesWithoutError()
.and()
.generatesSources(expectedSource1, expectedSource2);
}
@Test public void childUsesOwnUnbinder() {
JavaFileObject source = JavaFileObjects.forSourceString("test.Test",
Joiner.on('\n')
.join(
"package test;",
"import android.support.v4.app.Fragment;",
"import butterknife.ButterKnife;",
"import butterknife.OnClick;",
"import butterknife.Unbinder;",
"public class Test extends Fragment {",
" @OnClick(B.id.one) void doStuff1() { }",
"}",
"class TestOne extends Test {",
" @OnClick(B.id.one) void doStuff2() { }",
"}"
));
JavaFileObject expectedSource1 = JavaFileObjects.forSourceString("test/Test$$ViewBinder", ""
+ "package test;\n"
+ "import android.view.View;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.DebouncingOnClickListener;\n"
+ "import butterknife.internal.Finder;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "public class TestOne$$ViewBinder<T extends TestOne> extends Test$$ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " return new InnerUnbinder(target, finder, source);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends TestOne> extends Test$$ViewBinder.InnerUnbinder<T> {\n"
+ " private View testRidone;\n"
+ " protected InnerUnbinder(final T target, Finder finder, Object source) {\n"
+ " super(target, finder, source);\n"
+ " View view;\n"
+ " view = finder.findRequiredView(source, test.R.id.one, \"method 'doStuff2'\");\n"
+ " testRidone = view;\n"
+ " view.setOnClickListener(new DebouncingOnClickListener() {\n"
+ " @Override\n"
+ " public void doClick(View p0) {\n"
+ " target.doStuff2();\n"
+ " }\n"
+ " });\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " super.unbind();\n"
+ " testRidone.setOnClickListener(null);\n"
+ " testRidone = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
JavaFileObject expectedSource2 = JavaFileObjects.forSourceString("test/TestOne$$ViewBinder", ""
+ "package test;\n"
+ "import android.view.View;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.DebouncingOnClickListener;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.ViewBinder;\n"
+ "import java.lang.IllegalStateException;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "public class Test$$ViewBinder<T extends Test> implements ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " return new InnerUnbinder(target, finder, source);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends Test> implements Unbinder {\n"
+ " protected T target;\n"
+ " private View testRidone;\n"
+ " protected InnerUnbinder(final T target, Finder finder, Object source) {\n"
+ " this.target = target;\n"
+ " View view;\n"
+ " view = finder.findRequiredView(source, test.R.id.one, \"method 'doStuff1'\");\n"
+ " testRidone = view;\n"
+ " view.setOnClickListener(new DebouncingOnClickListener() {\n"
+ " @Override\n"
+ " public void doClick(View p0) {\n"
+ " target.doStuff1();\n"
+ " }\n"
+ " });\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " if (this.target == null) throw new IllegalStateException(\"Bindings already cleared.\");\n"
+ " testRidone.setOnClickListener(null);\n"
+ " testRidone = null;\n"
+ " this.target = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
assertAbout(javaSource()).that(source)
.processedWith(new ButterKnifeProcessor())
.compilesWithoutError()
.and()
.generatesSources(expectedSource1, expectedSource2);
}
@Test public void childInDifferentPackage() {
JavaFileObject source1 = JavaFileObjects.forSourceString("test.Test",
Joiner.on('\n')
.join(
"package test;",
"import android.support.v4.app.Fragment;",
"import butterknife.ButterKnife;",
"import butterknife.OnClick;",
"import butterknife.Unbinder;",
"public class Test extends Fragment {",
" @OnClick(B.id.one) void doStuff1() { }",
"}"
));
JavaFileObject source2 = JavaFileObjects.forSourceString("test.one.TestOne",
Joiner.on('\n')
.join(
"package test.one;",
"import test.Test;",
"import butterknife.OnClick;",
"class TestOne extends Test {",
" @OnClick(test.B.id.two) void doStuff2() { }",
"}"
));
JavaFileObject expectedSource1 = JavaFileObjects.forSourceString("test/Test$$ViewBinder", ""
+ "package test;\n"
+ "import android.view.View;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.DebouncingOnClickListener;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.ViewBinder;\n"
+ "import java.lang.IllegalStateException;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "public class Test$$ViewBinder<T extends Test> implements ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " return new InnerUnbinder(target, finder, source);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends Test> implements Unbinder {\n"
+ " protected T target;\n"
+ " private View testRidone;\n"
+ " protected InnerUnbinder(final T target, Finder finder, Object source) {\n"
+ " this.target = target;\n"
+ " View view;\n"
+ " view = finder.findRequiredView(source, test.R.id.one, \"method 'doStuff1'\");\n"
+ " testRidone = view;\n"
+ " view.setOnClickListener(new DebouncingOnClickListener() {\n"
+ " @Override\n"
+ " public void doClick(View p0) {\n"
+ " target.doStuff1();\n"
+ " }\n"
+ " });\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " if (this.target == null) throw new IllegalStateException(\"Bindings already cleared.\");\n"
+ " testRidone.setOnClickListener(null);\n"
+ " testRidone = null;\n"
+ " this.target = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
JavaFileObject expectedSource2 = JavaFileObjects.forSourceString("test/one/TestOne$$ViewBinder", ""
+ "package test.one;\n"
+ "import android.view.View;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.DebouncingOnClickListener;\n"
+ "import butterknife.internal.Finder;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "import test.Test$$ViewBinder;\n"
+ "public class TestOne$$ViewBinder<T extends TestOne> extends Test$$ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " return new InnerUnbinder(target, finder, source);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends TestOne> extends Test$$ViewBinder.InnerUnbinder<T> {\n"
+ " private View testRidtwo;\n"
+ " protected InnerUnbinder(final T target, Finder finder, Object source) {\n"
+ " super(target, finder, source);\n"
+ " View view;\n"
+ " view = finder.findRequiredView(source, test.R.id.two, \"method 'doStuff2'\");\n"
+ " testRidtwo = view;\n"
+ " view.setOnClickListener(new DebouncingOnClickListener() {\n"
+ " @Override\n"
+ " public void doClick(View p0) {\n"
+ " target.doStuff2();\n"
+ " }\n"
+ " });\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " super.unbind();\n"
+ " testRidtwo.setOnClickListener(null);\n"
+ " testRidtwo = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
assertAbout(javaSources()).that(asList(source1, source2))
.processedWith(new ButterKnifeProcessor())
.compilesWithoutError()
.and()
.generatesSources(expectedSource1, expectedSource2);
}
@Test public void unbindingThroughAbstractChild() {
JavaFileObject source = JavaFileObjects.forSourceString("test.Test",
Joiner.on('\n')
.join(
"package test;",
"import android.support.v4.app.Fragment;",
"import butterknife.ButterKnife;",
"import butterknife.OnClick;",
"import butterknife.Unbinder;",
"public class Test extends Fragment {",
" @OnClick(B.id.one) void doStuff1() { }",
"}",
"class TestOne extends Test {",
"}",
"class TestTwo extends TestOne {",
" @OnClick(B.id.one) void doStuff2() { }",
"}"
));
JavaFileObject expectedSource1 = JavaFileObjects.forSourceString("test/Test$$ViewBinder", ""
+ "package test;\n"
+ "import android.view.View;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.DebouncingOnClickListener;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.ViewBinder;\n"
+ "import java.lang.IllegalStateException;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "public class Test$$ViewBinder<T extends Test> implements ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " return new InnerUnbinder(target, finder, source);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends Test> implements Unbinder {\n"
+ " protected T target;\n"
+ " private View testRidone;\n"
+ " protected InnerUnbinder(final T target, Finder finder, Object source) {\n"
+ " this.target = target;\n"
+ " View view;\n"
+ " view = finder.findRequiredView(source, test.R.id.one, \"method 'doStuff1'\");\n"
+ " testRidone = view;\n"
+ " view.setOnClickListener(new DebouncingOnClickListener() {\n"
+ " @Override\n"
+ " public void doClick(View p0) {\n"
+ " target.doStuff1();\n"
+ " }\n"
+ " });\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " if (this.target == null) throw new IllegalStateException(\"Bindings already cleared.\");\n"
+ " testRidone.setOnClickListener(null);\n"
+ " testRidone = null;\n"
+ " this.target = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
JavaFileObject expectedSource2 = JavaFileObjects.forSourceString("test/TestTwo$$ViewBinder", ""
+ "package test;\n"
+ "import android.view.View;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.DebouncingOnClickListener;\n"
+ "import butterknife.internal.Finder;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "public class TestTwo$$ViewBinder<T extends TestTwo> extends Test$$ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " return new InnerUnbinder(target, finder, source);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends TestTwo> extends Test$$ViewBinder.InnerUnbinder<T> {\n"
+ " private View testRidone;\n"
+ " protected InnerUnbinder(final T target, Finder finder, Object source) {\n"
+ " super(target, finder, source);\n"
+ " View view;\n"
+ " view = finder.findRequiredView(source, test.R.id.one, \"method 'doStuff2'\");\n"
+ " testRidone = view;\n"
+ " view.setOnClickListener(new DebouncingOnClickListener() {\n"
+ " @Override\n"
+ " public void doClick(View p0) {\n"
+ " target.doStuff2();\n"
+ " }\n"
+ " });\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " super.unbind();\n"
+ " testRidone.setOnClickListener(null);\n"
+ " testRidone = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
assertAbout(javaSource()).that(source)
.processedWith(new ButterKnifeProcessor())
.compilesWithoutError()
.and()
.generatesSources(expectedSource1, expectedSource2);
}
@Test public void fullIntegration() {
JavaFileObject sourceA = JavaFileObjects.forSourceString("test.A", ""
+ "package test;\n"
+ "import android.support.annotation.ColorInt;\n"
+ "import android.view.View;\n"
+ "import butterknife.BindColor;\n"
+ "import butterknife.ButterKnife;\n"
+ "public class A {\n"
+ " @BindColor(\"android.R.color.black\") @ColorInt int blackColor;\n"
+ " public A(View view) {\n"
+ " ButterKnife.bind(this, view);\n"
+ " }\n"
+ "}\n");
JavaFileObject sourceB = JavaFileObjects.forSourceString("test.B", ""
+ "package test;\n"
+ "import android.support.annotation.ColorInt;\n"
+ "import android.view.View;\n"
+ "import butterknife.BindColor;\n"
+ "import butterknife.ButterKnife;\n"
+ "public class B extends A {\n"
+ " @BindColor(\"android.R.color.white\") @ColorInt int whiteColor;\n"
+ " public B(View view) {\n"
+ " super(view);\n"
+ " ButterKnife.bind(this, view);\n"
+ " }\n"
+ "}\n");
JavaFileObject sourceC = JavaFileObjects.forSourceString("test.C", ""
+ "package test;\n"
+ "import android.support.annotation.ColorInt;\n"
+ "import android.view.View;\n"
+ "import butterknife.BindView;\n"
+ "import butterknife.BindColor;\n"
+ "import butterknife.ButterKnife;\n"
+ "public class C extends B {\n"
+ " @BindColor(\"android.R.color.transparent\") @ColorInt int transparentColor;\n"
+ " @BindView(\"android.R.id.button1\") View button1;\n"
+ " public C(View view) {\n"
+ " super(view);\n"
+ " ButterKnife.bind(this, view);\n"
+ " }\n"
+ "}\n");
JavaFileObject sourceD = JavaFileObjects.forSourceString("test.D", ""
+ "package test;\n"
+ "import android.support.annotation.ColorInt;\n"
+ "import android.view.View;\n"
+ "import butterknife.BindColor;\n"
+ "import butterknife.ButterKnife;\n"
+ "public class D extends C {\n"
+ " @BindColor(\"android.R.color.darker_gray\") @ColorInt int grayColor;\n"
+ " public D(View view) {\n"
+ " super(view);\n"
+ " ButterKnife.bind(this, view);\n"
+ " }\n"
+ "}\n");
JavaFileObject sourceE = JavaFileObjects.forSourceString("test.E", ""
+ "package test;\n"
+ "import android.support.annotation.ColorInt;\n"
+ "import android.view.View;\n"
+ "import butterknife.BindColor;\n"
+ "import butterknife.ButterKnife;\n"
+ "public class E extends C {\n"
+ " @BindColor(\"android.R.color.background_dark\") @ColorInt int backgroundDarkColor;\n"
+ " public E(View view) {\n"
+ " super(view);\n"
+ " ButterKnife.bind(this, view);\n"
+ " }\n"
+ "}\n");
JavaFileObject sourceF = JavaFileObjects.forSourceString("test.F", ""
+ "package test;\n"
+ "import android.support.annotation.ColorInt;\n"
+ "import android.view.View;\n"
+ "import butterknife.BindColor;\n"
+ "import butterknife.ButterKnife;\n"
+ "public class F extends D {\n"
+ " @BindColor(\"android.R.color.background_light\") @ColorInt int backgroundLightColor;\n"
+ " public F(View view) {\n"
+ " super(view);\n"
+ " ButterKnife.bind(this, view);\n"
+ " }\n"
+ "}\n");
JavaFileObject sourceG = JavaFileObjects.forSourceString("test.G", ""
+ "package test;\n"
+ "import android.support.annotation.ColorInt;\n"
+ "import android.view.View;\n"
+ "import butterknife.BindView;\n"
+ "import butterknife.BindColor;\n"
+ "import butterknife.ButterKnife;\n"
+ "import butterknife.OnClick;\n"
+ "public class G extends E {\n"
+ " @BindColor(\"android.R.color.darker_gray\") @ColorInt int grayColor;\n"
+ " @BindView(\"android.R.id.button2\") View button2;\n"
+ " public G(View view) {\n"
+ " super(view);\n"
+ " ButterKnife.bind(this, view);\n"
+ " }\n"
+ " @OnClick(\"android.R.id.content\") public void onClick() {\n"
+ " }\n"
+ "}\n");
JavaFileObject sourceH = JavaFileObjects.forSourceString("test.H", ""
+ "package test;\n"
+ "import android.support.annotation.ColorInt;\n"
+ "import android.view.View;\n"
+ "import butterknife.BindView;\n"
+ "import butterknife.BindColor;\n"
+ "import butterknife.ButterKnife;\n"
+ "public class H extends G {\n"
+ " @BindColor(\"android.R.color.primary_text_dark\") @ColorInt int grayColor;\n"
+ " @BindView(\"android.R.id.button3\") View button3;\n"
+ " public H(View view) {\n"
+ " super(view);\n"
+ " ButterKnife.bind(this, view);\n"
+ " }\n"
+ "}\n");
JavaFileObject expectedSourceA = JavaFileObjects.forSourceString("test/A$$ViewBinder", ""
+ "package test;\n"
+ "import android.content.Context;\n"
+ "import android.content.res.Resources;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.Utils;\n"
+ "import butterknife.internal.ViewBinder;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "import java.lang.SuppressWarnings;\n"
+ "public class A$$ViewBinder<T extends A> implements ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " Context context = finder.getContext(source);\n"
+ " Resources res = context.getResources();\n"
+ " Resources.Theme theme = context.getTheme();\n"
+ " bindToTarget(target, res, theme);\n"
+ " return Unbinder.EMPTY;\n"
+ " }\n"
+ " @SuppressWarnings(\"ResourceType\")\n"
+ " protected static void bindToTarget(A target, Resources res, Resources.Theme theme) {\n"
+ " target.blackColor = Utils.getColor(res, theme, android.R.color.black);\n"
+ " }\n"
+ "}"
);
JavaFileObject expectedSourceB = JavaFileObjects.forSourceString("test/B$$ViewBinder", ""
+ "package test;\n"
+ "import android.content.Context;\n"
+ "import android.content.res.Resources;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.Utils;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "import java.lang.SuppressWarnings;\n"
+ "public class B$$ViewBinder<T extends B> extends A$$ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " Context context = finder.getContext(source);\n"
+ " Resources res = context.getResources();\n"
+ " Resources.Theme theme = context.getTheme();\n"
+ " bindToTarget(target, res, theme);\n"
+ " return Unbinder.EMPTY;\n"
+ " }\n"
+ " @SuppressWarnings(\"ResourceType\")\n"
+ " protected static void bindToTarget(B target, Resources res, Resources.Theme theme) {\n"
+ " A$$ViewBinder.bindToTarget(target, res, theme);\n"
+ " target.whiteColor = Utils.getColor(res, theme, android.R.color.white);\n"
+ " }\n"
+ "}"
);
JavaFileObject expectedSourceC = JavaFileObjects.forSourceString("test/C$$ViewBinder", ""
+ "package test;\n"
+ "import android.content.Context;\n"
+ "import android.content.res.Resources;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.Utils;\n"
+ "import java.lang.IllegalStateException;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "import java.lang.SuppressWarnings;\n"
+ "public class C$$ViewBinder<T extends C> extends B$$ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " Context context = finder.getContext(source);\n"
+ " Resources res = context.getResources();\n"
+ " Resources.Theme theme = context.getTheme();\n"
+ " return new InnerUnbinder(target, finder, source, res, theme);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends C> implements Unbinder {\n"
+ " protected T target;\n"
+ " @SuppressWarnings(\"ResourceType\")\n"
+ " protected InnerUnbinder(T target, Finder finder, Object source, Resources res, Resources.Theme theme) {\n"
+ " this.target = target;\n"
+ " B$$ViewBinder.bindToTarget(target, res, theme);\n"
+ " target.button1 = finder.findRequiredView(source, android.R.id.button1, \"field 'button1'\");\n"
+ " target.transparentColor = Utils.getColor(res, theme, android.R.color.transparent);\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " T target = this.target;\n"
+ " if (target == null) throw new IllegalStateException(\"Bindings already cleared.\");\n"
+ " target.button1 = null;\n"
+ " this.target = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
JavaFileObject expectedSourceD = JavaFileObjects.forSourceString("test/D$$ViewBinder", ""
+ "package test;\n"
+ "import android.content.Context;\n"
+ "import android.content.res.Resources;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.Utils;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "import java.lang.SuppressWarnings;\n"
+ "public class D$$ViewBinder<T extends D> extends C$$ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " Context context = finder.getContext(source);\n"
+ " Resources res = context.getResources();\n"
+ " Resources.Theme theme = context.getTheme();\n"
+ " return new InnerUnbinder(target, finder, source, res, theme);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends D> extends C$$ViewBinder.InnerUnbinder<T> {\n"
+ " @SuppressWarnings(\"ResourceType\")\n"
+ " protected InnerUnbinder(T target, Finder finder, Object source, Resources res, Resources.Theme theme) {\n"
+ " super(target, finder, source, res, theme);\n"
+ " target.grayColor = Utils.getColor(res, theme, android.R.color.darker_gray);\n"
+ " }\n"
+ " }\n"
+ "}"
);
JavaFileObject expectedSourceE = JavaFileObjects.forSourceString("test/E$$ViewBinder", ""
+ "package test;\n"
+ "import android.content.Context;\n"
+ "import android.content.res.Resources;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.Utils;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "import java.lang.SuppressWarnings;\n"
+ "public class E$$ViewBinder<T extends E> extends C$$ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " Context context = finder.getContext(source);\n"
+ " Resources res = context.getResources();\n"
+ " Resources.Theme theme = context.getTheme();\n"
+ " return new InnerUnbinder(target, finder, source, res, theme);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends E> extends C$$ViewBinder.InnerUnbinder<T> {\n"
+ " @SuppressWarnings(\"ResourceType\")\n"
+ " protected InnerUnbinder(T target, Finder finder, Object source, Resources res, Resources.Theme theme) {\n"
+ " super(target, finder, source, res, theme);\n"
+ " target.backgroundDarkColor = Utils.getColor(res, theme, android.R.color.background_dark);\n"
+ " }\n"
+ " }\n"
+ "}"
);
JavaFileObject expectedSourceF = JavaFileObjects.forSourceString("test/F$$ViewBinder", ""
+ "package test;\n"
+ "import android.content.Context;\n"
+ "import android.content.res.Resources;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.Utils;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "import java.lang.SuppressWarnings;\n"
+ "public class F$$ViewBinder<T extends F> extends D$$ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " Context context = finder.getContext(source);\n"
+ " Resources res = context.getResources();\n"
+ " Resources.Theme theme = context.getTheme();\n"
+ " return new InnerUnbinder(target, finder, source, res, theme);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends F> extends D$$ViewBinder.InnerUnbinder<T> {\n"
+ " @SuppressWarnings(\"ResourceType\")\n"
+ " protected InnerUnbinder(T target, Finder finder, Object source, Resources res, Resources.Theme theme) {\n"
+ " super(target, finder, source, res, theme);\n"
+ " target.backgroundLightColor = Utils.getColor(res, theme, android.R.color.background_light);\n"
+ " }\n"
+ " }\n"
+ "}"
);
JavaFileObject expectedSourceG = JavaFileObjects.forSourceString("test/G$$ViewBinder", ""
+ "package test;\n"
+ "import android.content.Context;\n"
+ "import android.content.res.Resources;\n"
+ "import android.view.View;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.DebouncingOnClickListener;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.Utils;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "import java.lang.SuppressWarnings;\n"
+ "public class G$$ViewBinder<T extends G> extends E$$ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " Context context = finder.getContext(source);\n"
+ " Resources res = context.getResources();\n"
+ " Resources.Theme theme = context.getTheme();\n"
+ " return new InnerUnbinder(target, finder, source, res, theme);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends G> extends E$$ViewBinder.InnerUnbinder<T> {\n"
+ " private View androidRidcontent;\n"
+ " @SuppressWarnings(\"ResourceType\")\n"
+ " protected InnerUnbinder(final T target, Finder finder, Object source, Resources res, Resources.Theme theme) {\n"
+ " super(target, finder, source, res, theme);\n"
+ " View view;\n"
+ " target.button2 = finder.findRequiredView(source, android.R.id.button2, \"field 'button2'\");\n"
+ " view = finder.findRequiredView(source, android.R.id.content, \"method 'onClick'\");\n"
+ " androidRidcontent = view;\n"
+ " view.setOnClickListener(new DebouncingOnClickListener() {\n"
+ " @Override\n"
+ " public void doClick(View p0) {\n"
+ " target.onClick();\n"
+ " }\n"
+ " });\n"
+ " target.grayColor = Utils.getColor(res, theme, android.R.color.darker_gray);\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " T target = this.target;\n"
+ " super.unbind();\n"
+ " target.button2 = null;\n"
+ " androidRidcontent.setOnClickListener(null);\n"
+ " androidRidcontent = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
JavaFileObject expectedSourceH = JavaFileObjects.forSourceString("test/H$$ViewBinder", ""
+ "package test;\n"
+ "import android.content.Context;\n"
+ "import android.content.res.Resources;\n"
+ "import butterknife.Unbinder;\n"
+ "import butterknife.internal.Finder;\n"
+ "import butterknife.internal.Utils;\n"
+ "import java.lang.Object;\n"
+ "import java.lang.Override;\n"
+ "import java.lang.SuppressWarnings;\n"
+ "public class H$$ViewBinder<T extends H> extends G$$ViewBinder<T> {\n"
+ " @Override\n"
+ " public Unbinder bind(Finder finder, T target, Object source) {\n"
+ " Context context = finder.getContext(source);\n"
+ " Resources res = context.getResources();\n"
+ " Resources.Theme theme = context.getTheme();\n"
+ " return new InnerUnbinder(target, finder, source, res, theme);\n"
+ " }\n"
+ " protected static class InnerUnbinder<T extends H> extends G$$ViewBinder.InnerUnbinder<T> {\n"
+ " @SuppressWarnings(\"ResourceType\")\n"
+ " protected InnerUnbinder(T target, Finder finder, Object source, Resources res, Resources.Theme theme) {\n"
+ " super(target, finder, source, res, theme);\n"
+ " target.button3 = finder.findRequiredView(source, android.R.id.button3, \"field 'button3'\");\n"
+ " target.grayColor = Utils.getColor(res, theme, android.R.color.primary_text_dark);\n"
+ " }\n"
+ " @Override\n"
+ " public void unbind() {\n"
+ " T target = this.target;\n"
+ " super.unbind();\n"
+ " target.button3 = null;\n"
+ " }\n"
+ " }\n"
+ "}"
);
assertAbout(javaSources())
.that(asList(sourceA,
sourceB,
sourceC,
sourceD,
sourceE,
sourceF,
sourceG,
sourceH))
.processedWith(new ButterKnifeProcessor())
.compilesWithoutError()
.and()
.generatesSources(expectedSourceA,
expectedSourceB,
expectedSourceC,
expectedSourceD,
expectedSourceE,
expectedSourceF,
expectedSourceG,
expectedSourceH);
}
}
| |
/*
* Copyright 2014 Open Networking Laboratory
*
* 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.onosproject.net.networkports.impl;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.onosproject.net.NetworkId.networkId;
import static org.onosproject.net.OvsPortId.portId;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.Collections;
import java.util.concurrent.ConcurrentMap;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onosproject.event.EventDeliveryService;
import org.onosproject.net.DefaultOvsPort;
import org.onosproject.net.OvsPort;
import org.onosproject.net.OvsPortId;
import org.onosproject.net.ovsports.OvsPortEvent;
import org.onosproject.net.ovsports.OvsPortService;
import org.onosproject.net.ovsports.OvsPortStore;
import org.onosproject.net.ovsports.OvsPortStoreDelegate;
import org.onosproject.net.provider.ProviderId;
import org.slf4j.Logger;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Maps;
/**
* Provides implementation of the OvsPort NB APIs.
*/
@Component(immediate = true)
@Service
public class OvsPortManager implements OvsPortService {
private static final String OVSPORT_ID_NULL = "OvsPort ID cannot be null";
private static final String CREATE_PORT = "create port";
private static final String UPDATE_PORT = "update port";
public static final ProviderId PID = new ProviderId("of", "foo");
private final Logger log = getLogger(getClass());
private final OvsPortStoreDelegate delegate = new InternalStoreDelegate();
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected OvsPortStore store;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected EventDeliveryService eventDispatcher;
@Activate
public void activate() {
store.setDelegate(delegate);
log.info("Started");
}
@Deactivate
public void deactivate() {
store.unsetDelegate(delegate);
log.info("Stopped");
}
// Posts the specified event to the local event dispatcher.
private void post(OvsPortEvent event) {
if (event != null && eventDispatcher != null) {
eventDispatcher.post(event);
}
}
// Store delegate to re-post events emitted from the store.
private class InternalStoreDelegate
implements OvsPortStoreDelegate {
@Override
public void notify(OvsPortEvent event) {
post(event);
}
}
@Override
public int getPortCount() {
return store.getPortCount();
}
@Override
public Iterable<OvsPort> getPorts() {
return store.getPorts();
}
@Override
public OvsPort getPort(OvsPortId ovsportId) {
checkNotNull(ovsportId, OVSPORT_ID_NULL);
return store.getPort(ovsportId);
}
@Override
public boolean portExists(OvsPortId ovsportId) {
checkNotNull(ovsportId, OVSPORT_ID_NULL);
return store.portExists(ovsportId);
}
@Override
public boolean removePort(OvsPortId ovsportId) {
checkNotNull(ovsportId, OVSPORT_ID_NULL);
return store.removePort(ovsportId);
}
@Override
public boolean createPort(JsonNode cfg) {
log.info("Handling STEP NO.1 ---------------OvsportManager-------------------");
JsonNode nodes = null;
Iterable<OvsPort> ovsports = null;
if (cfg.get("port") != null) {
nodes = cfg.get("port");
if (nodes.isArray()) {
ovsports = changeJson2objs(nodes);
} else {
ovsports = changeJson2obj(CREATE_PORT, null, nodes);
}
} else if (cfg.get("ports") != null) {
nodes = cfg.get("ports");
ovsports = changeJson2objs(nodes);
}
log.info("Handling STEP NO.2 ---------------OvsportManagerEnd-------------------");
return store.createPort(ovsports);
}
@Override
public boolean updatePort(OvsPortId ovsportId, JsonNode cfg) {
JsonNode nodes = null;
Iterable<OvsPort> ovsports = null;
if (cfg.get("port") != null) {
nodes = cfg.get("port");
ovsports = changeJson2obj(UPDATE_PORT, ovsportId, nodes);
} else if (cfg.get("ports") != null) {
nodes = cfg.get("ports");
ovsports = changeJson2obj(UPDATE_PORT, ovsportId, nodes);
}
return store.updatePort(ovsportId, ovsports);
}
/**
* Returns a collection of the currently known infrastructure ovsport.
* @param JsonNode node the ovsport json
* @return collection of ovsport
*/
public Iterable<OvsPort> changeJson2objs(JsonNode nodes) {
OvsPort ovsport = null;
ConcurrentMap<OvsPortId, OvsPort> portsMap = Maps.newConcurrentMap();
if (nodes != null) {
for (JsonNode node : nodes) {
String id = node.get("id").asText();
String networkid = node.get("network_id").asText();
String name = node.get("name").asText();
Boolean adminStateUp = node.get("admin_state_up").asBoolean();
String status = node.get("status").asText();
String macaddress = node.get("mac_address").asText();
String tenantID = node.get("tenant_id").asText();
String deviceID = node.get("device_id").asText();
String deviceOwner = node.get("device_owner").asText();
JsonNode allowedAPnodes = node.get("allowed_address_pairs");
// JsonNode extralDHCPOptions = node.get("extra_dhcp_opts");
JsonNode fixedIPs = node.get("fixed_ips");
String bindingHostId = node.get("binding:host_id").asText();
String bindingVnicType = node.get("binding:vnic_type").asText();
String bindingVifType = node.get("binding:vif_type").asText();
JsonNode bindingvifDetails = node.get("binding:vif_details");
JsonNode securityGroups = node.get("security_groups");
ConcurrentMap<String, String> strMap = Maps.newConcurrentMap();
strMap.putIfAbsent("name", name);
strMap.putIfAbsent("adminStateUp", adminStateUp.toString());
strMap.putIfAbsent("status", status);
strMap.putIfAbsent("macaddress", macaddress);
strMap.putIfAbsent("tenantID", tenantID);
strMap.putIfAbsent("deviceID", deviceID);
strMap.putIfAbsent("deviceOwner", deviceOwner);
ovsport = new DefaultOvsPort(PID, portId(id), networkId(networkid), strMap,
allowedAPnodes,
// extralDHCPOptions,
fixedIPs, bindingHostId, bindingVnicType, bindingVifType,
bindingvifDetails, securityGroups);
portsMap.putIfAbsent(portId(id), ovsport);
}
}
return Collections.unmodifiableCollection(portsMap.values());
}
/**
* Returns a Object of the currently known infrastructure ovsport.
* @param ovsportId ovsport identifier
* @param JsonNode node the ovsport json
* @return Object of ovsport
*/
public Iterable<OvsPort> changeJson2obj(String flag, OvsPortId ovsportId, JsonNode node) {
OvsPort ovsport = null;
ConcurrentMap<OvsPortId, OvsPort> portsMap = Maps.newConcurrentMap();
if (node != null) {
String networkid = node.get("network_id").asText();
String name = node.get("name").asText();
Boolean adminStateUp = node.get("admin_state_up").asBoolean();
String status = node.get("status").asText();
String macaddress = node.get("mac_address").asText();
String tenantID = node.get("tenant_id").asText();
String deviceID = node.get("device_id").asText();
String deviceOwner = node.get("device_owner").asText();
JsonNode allowedAPnodes = node.get("allowed_address_pairs");
// JsonNode extralDHCPOptions = node.get("extra_dhcp_opts");
JsonNode fixedIPs = node.get("fixed_ips");
String bindingHostId = node.get("binding:host_id").asText();
String bindingVnicType = node.get("binding:vnic_type").asText();
String bindingVifType = node.get("binding:vif_type").asText();
JsonNode bindingvifDetails = node.get("binding:vif_details");
JsonNode securityGroups = node.get("security_groups");
ConcurrentMap<String, String> strMap = Maps.newConcurrentMap();
strMap.putIfAbsent("name", name);
strMap.putIfAbsent("adminStateUp", adminStateUp.toString());
strMap.putIfAbsent("status", status);
strMap.putIfAbsent("macaddress", macaddress);
strMap.putIfAbsent("tenantID", tenantID);
strMap.putIfAbsent("deviceID", deviceID);
strMap.putIfAbsent("deviceOwner", deviceOwner);
OvsPortId id = null;
if (flag == CREATE_PORT) {
id = portId(node.get("id").asText());
} else if (flag == UPDATE_PORT) {
id = ovsportId;
}
ovsport = new DefaultOvsPort(PID, id, networkId(networkid), strMap,
allowedAPnodes,
// extralDHCPOptions,
fixedIPs, bindingHostId, bindingVnicType, bindingVifType,
bindingvifDetails, securityGroups);
portsMap.putIfAbsent(id, ovsport);
}
return Collections.unmodifiableCollection(portsMap.values());
}
}
| |
/**
* Copyright (C) 2012-2013 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* 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.dasein.cloud.flexiant.ci;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.ResourceStatus;
import org.dasein.cloud.ci.AbstractTopologySupport;
import org.dasein.cloud.ci.Topology;
import org.dasein.cloud.ci.Topology.VLANDevice;
import org.dasein.cloud.ci.Topology.VMDevice;
import org.dasein.cloud.ci.TopologyFilterOptions;
import org.dasein.cloud.ci.TopologyState;
import org.dasein.cloud.compute.Architecture;
import org.dasein.cloud.compute.Platform;
import org.dasein.cloud.flexiant.FCOProvider;
import org.dasein.cloud.flexiant.FCOProviderUtils;
import org.dasein.cloud.identity.ServiceAction;
import org.dasein.util.uom.storage.Storage;
import com.extl.jade.user.DeploymentTemplate;
import com.extl.jade.user.ExtilityException;
import com.extl.jade.user.ListResult;
import com.extl.jade.user.Network;
import com.extl.jade.user.ResourceState;
import com.extl.jade.user.ResourceType;
import com.extl.jade.user.SearchFilter;
import com.extl.jade.user.Server;
import com.extl.jade.user.UserService;
/**
* The AbstractTopologySupport implementation for the Dasein FCO implementation
*
* @version 2013.12 initial version
* @since 2013.12
*/
public class FCOTopologySupport extends AbstractTopologySupport<FCOProvider> {
private UserService userService;
public FCOTopologySupport(FCOProvider provider) {
super(provider);
userService = FCOProviderUtils.getUserServiceFromContext(provider.getContext());
}
@Override
public String getProviderTermForTopology(Locale locale) {
return "DeploymentTemplate";
}
@Override
public boolean isSubscribed() throws CloudException, InternalException {
return true;
}
@Override
public Iterable<Topology> listTopologies(TopologyFilterOptions options) throws CloudException, InternalException {
List<Topology> list = new ArrayList<Topology>();
SearchFilter filter = new SearchFilter();
try{
ListResult result = FCOProviderUtils.listAllResources(userService, filter, ResourceType.DEPLOYMENT_TEMPLATE);
if(result == null || result.getList() == null){
return list;
}
for(Object obj : result.getList()){
DeploymentTemplate template = (DeploymentTemplate) obj;
list.add(createTopologyFromDeploymentTemplate(template, getContext().getRegionId()));
}
}catch (ExtilityException e){
throw new CloudException(e);
}
return list;
}
@Override
@Nullable
public Topology getTopology(@Nonnull String topologyId) throws CloudException, InternalException {
try{
return createTopologyFromDeploymentTemplate((DeploymentTemplate) FCOProviderUtils.getResource(userService, topologyId, ResourceType.DEPLOYMENT_TEMPLATE, true), getContext().getRegionId());
}catch (ExtilityException e){
throw new CloudException(e);
}
}
@Override
@Nonnull
public Iterable<ResourceStatus> listTopologyStatus() throws InternalException, CloudException {
ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>();
try{
ListResult result = FCOProviderUtils.listWithChildren(userService, null, ResourceType.DEPLOYMENT_TEMPLATE);
if(result == null || result.getList() == null){
return list;
}
for(Object obj : result.getList()){
DeploymentTemplate deploymentTemplate = (DeploymentTemplate) obj;
list.add(new ResourceStatus(deploymentTemplate.getResourceUUID(), getTopologyStateFromResourceState(deploymentTemplate.getResourceState())));
}
}catch (ExtilityException e){
throw new CloudException(e);
}
return list;
}
@Override
@Nonnull
public String[] mapServiceAction(@Nonnull ServiceAction action) {
return new String[0];
}
@Override
@Nonnull
public Iterable<Topology> searchPublicTopologies(@Nullable TopologyFilterOptions options) throws CloudException, InternalException {
ArrayList<Topology> list = new ArrayList<Topology>();
try{
ListResult result = FCOProviderUtils.listWithChildren(userService, null, ResourceType.DEPLOYMENT_TEMPLATE);
if(result == null || result.getList() == null){
return list;
}
for(Object obj : result.getList()){
Topology topology = createTopologyFromDeploymentTemplate((DeploymentTemplate) obj, getContext().getRegionId());
if(options.matches(topology)){
list.add(topology);
}
}
}catch (ExtilityException e){
throw new CloudException(e);
}
return list;
}
@Override
public boolean supportsPublicLibrary() throws CloudException, InternalException {
return true;
}
// ----------- Helper Methods --------- //
private static Topology createTopologyFromDeploymentTemplate(DeploymentTemplate deploymentTemplate, String currentRegion) {
if(deploymentTemplate == null){
return null;
}
String regionId = deploymentTemplate.getClusterUUID();
if(!FCOProviderUtils.isSet(regionId)){
regionId = currentRegion;
}
Topology topology = Topology.getInstance(deploymentTemplate.getCustomerUUID(), regionId, deploymentTemplate.getResourceUUID(), getTopologyStateFromResourceState(deploymentTemplate.getResourceState()), deploymentTemplate.getResourceName(), deploymentTemplate.getResourceName());
if(deploymentTemplate.getResourceCreateDate() != null){
topology.createdAt(deploymentTemplate.getResourceCreateDate().toGregorianCalendar().getTimeInMillis());
}
for(Server server : deploymentTemplate.getServer()){
topology.withVirtualMachines(createVMDeviceFromServer(server));
}
for(Network network : deploymentTemplate.getNetwork()){
topology.withVLANs(createVLANDeviceFromNetwork(network));
}
return topology;
}
private static TopologyState getTopologyStateFromResourceState(ResourceState resourceState) {
switch(resourceState){
case ACTIVE:
return TopologyState.ACTIVE;
case DELETED:
case TO_BE_DELETED:
return TopologyState.DELETED;
case CREATING:
return TopologyState.PENDING;
case HIDDEN:
case LOCKED:
default:
return TopologyState.OFFLINE;
}
}
private static VMDevice createVMDeviceFromServer(Server server){
return VMDevice.getInstance(server.getResourceUUID(), server.getDisks().size(), server.getResourceName(), server.getCpu(), Storage.valueOf(server.getRam(),"mb"), Architecture.I32, Platform.guess(server.getImageName()));
}
private static VLANDevice createVLANDeviceFromNetwork(Network network){
return VLANDevice.getInstance(network.getResourceUUID(), network.getResourceName());
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.qldb.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/qldb-2019-01-02/GetRevision" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetRevisionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name of the ledger.
* </p>
*/
private String name;
/**
* <p>
* The block location of the document revision to be verified. An address is an Amazon Ion structure that has two
* fields: <code>strandId</code> and <code>sequenceNo</code>.
* </p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:14}</code>.
* </p>
*/
private ValueHolder blockAddress;
/**
* <p>
* The UUID (represented in Base62-encoded text) of the document to be verified.
* </p>
*/
private String documentId;
/**
* <p>
* The latest block location covered by the digest for which to request a proof. An address is an Amazon Ion
* structure that has two fields: <code>strandId</code> and <code>sequenceNo</code>.
* </p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:49}</code>.
* </p>
*/
private ValueHolder digestTipAddress;
/**
* <p>
* The name of the ledger.
* </p>
*
* @param name
* The name of the ledger.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the ledger.
* </p>
*
* @return The name of the ledger.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the ledger.
* </p>
*
* @param name
* The name of the ledger.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetRevisionRequest withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The block location of the document revision to be verified. An address is an Amazon Ion structure that has two
* fields: <code>strandId</code> and <code>sequenceNo</code>.
* </p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:14}</code>.
* </p>
*
* @param blockAddress
* The block location of the document revision to be verified. An address is an Amazon Ion structure that has
* two fields: <code>strandId</code> and <code>sequenceNo</code>.</p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:14}</code>.
*/
public void setBlockAddress(ValueHolder blockAddress) {
this.blockAddress = blockAddress;
}
/**
* <p>
* The block location of the document revision to be verified. An address is an Amazon Ion structure that has two
* fields: <code>strandId</code> and <code>sequenceNo</code>.
* </p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:14}</code>.
* </p>
*
* @return The block location of the document revision to be verified. An address is an Amazon Ion structure that
* has two fields: <code>strandId</code> and <code>sequenceNo</code>.</p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:14}</code>.
*/
public ValueHolder getBlockAddress() {
return this.blockAddress;
}
/**
* <p>
* The block location of the document revision to be verified. An address is an Amazon Ion structure that has two
* fields: <code>strandId</code> and <code>sequenceNo</code>.
* </p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:14}</code>.
* </p>
*
* @param blockAddress
* The block location of the document revision to be verified. An address is an Amazon Ion structure that has
* two fields: <code>strandId</code> and <code>sequenceNo</code>.</p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:14}</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetRevisionRequest withBlockAddress(ValueHolder blockAddress) {
setBlockAddress(blockAddress);
return this;
}
/**
* <p>
* The UUID (represented in Base62-encoded text) of the document to be verified.
* </p>
*
* @param documentId
* The UUID (represented in Base62-encoded text) of the document to be verified.
*/
public void setDocumentId(String documentId) {
this.documentId = documentId;
}
/**
* <p>
* The UUID (represented in Base62-encoded text) of the document to be verified.
* </p>
*
* @return The UUID (represented in Base62-encoded text) of the document to be verified.
*/
public String getDocumentId() {
return this.documentId;
}
/**
* <p>
* The UUID (represented in Base62-encoded text) of the document to be verified.
* </p>
*
* @param documentId
* The UUID (represented in Base62-encoded text) of the document to be verified.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetRevisionRequest withDocumentId(String documentId) {
setDocumentId(documentId);
return this;
}
/**
* <p>
* The latest block location covered by the digest for which to request a proof. An address is an Amazon Ion
* structure that has two fields: <code>strandId</code> and <code>sequenceNo</code>.
* </p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:49}</code>.
* </p>
*
* @param digestTipAddress
* The latest block location covered by the digest for which to request a proof. An address is an Amazon Ion
* structure that has two fields: <code>strandId</code> and <code>sequenceNo</code>.</p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:49}</code>.
*/
public void setDigestTipAddress(ValueHolder digestTipAddress) {
this.digestTipAddress = digestTipAddress;
}
/**
* <p>
* The latest block location covered by the digest for which to request a proof. An address is an Amazon Ion
* structure that has two fields: <code>strandId</code> and <code>sequenceNo</code>.
* </p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:49}</code>.
* </p>
*
* @return The latest block location covered by the digest for which to request a proof. An address is an Amazon Ion
* structure that has two fields: <code>strandId</code> and <code>sequenceNo</code>.</p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:49}</code>.
*/
public ValueHolder getDigestTipAddress() {
return this.digestTipAddress;
}
/**
* <p>
* The latest block location covered by the digest for which to request a proof. An address is an Amazon Ion
* structure that has two fields: <code>strandId</code> and <code>sequenceNo</code>.
* </p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:49}</code>.
* </p>
*
* @param digestTipAddress
* The latest block location covered by the digest for which to request a proof. An address is an Amazon Ion
* structure that has two fields: <code>strandId</code> and <code>sequenceNo</code>.</p>
* <p>
* For example: <code>{strandId:"BlFTjlSXze9BIh1KOszcE3",sequenceNo:49}</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetRevisionRequest withDigestTipAddress(ValueHolder digestTipAddress) {
setDigestTipAddress(digestTipAddress);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getBlockAddress() != null)
sb.append("BlockAddress: ").append("***Sensitive Data Redacted***").append(",");
if (getDocumentId() != null)
sb.append("DocumentId: ").append(getDocumentId()).append(",");
if (getDigestTipAddress() != null)
sb.append("DigestTipAddress: ").append("***Sensitive Data Redacted***");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetRevisionRequest == false)
return false;
GetRevisionRequest other = (GetRevisionRequest) obj;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getBlockAddress() == null ^ this.getBlockAddress() == null)
return false;
if (other.getBlockAddress() != null && other.getBlockAddress().equals(this.getBlockAddress()) == false)
return false;
if (other.getDocumentId() == null ^ this.getDocumentId() == null)
return false;
if (other.getDocumentId() != null && other.getDocumentId().equals(this.getDocumentId()) == false)
return false;
if (other.getDigestTipAddress() == null ^ this.getDigestTipAddress() == null)
return false;
if (other.getDigestTipAddress() != null && other.getDigestTipAddress().equals(this.getDigestTipAddress()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getBlockAddress() == null) ? 0 : getBlockAddress().hashCode());
hashCode = prime * hashCode + ((getDocumentId() == null) ? 0 : getDocumentId().hashCode());
hashCode = prime * hashCode + ((getDigestTipAddress() == null) ? 0 : getDigestTipAddress().hashCode());
return hashCode;
}
@Override
public GetRevisionRequest clone() {
return (GetRevisionRequest) super.clone();
}
}
| |
/*
* 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.intellij.openapi.wm.impl;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.UiActivity;
import com.intellij.ide.UiActivityMonitor;
import com.intellij.internal.focus.FocusTracesAction;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationActivationListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.components.impl.ServiceManagerImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.*;
import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy;
import com.intellij.openapi.wm.ex.LayoutFocusTraversalPolicyExt;
import com.intellij.reference.SoftReference;
import com.intellij.ui.FocusTrackback;
import com.intellij.util.containers.WeakValueHashMap;
import com.intellij.util.ui.UIUtil;
import gnu.trove.TIntIntHashMap;
import gnu.trove.TIntIntProcedure;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
public class FocusManagerImpl extends IdeFocusManager implements Disposable {
private static final Logger LOG = Logger.getInstance(FocusManagerImpl.class);
private static final UiActivity FOCUS = new UiActivity.Focus("awtFocusRequest");
private static final UiActivity TYPEAHEAD = new UiActivity.Focus("typeahead");
private final Application myApp;
private FocusCommand myRequestFocusCmd;
private final List<FocusCommand> myFocusRequests = new ArrayList<FocusCommand>();
private final List<KeyEvent> myToDispatchOnDone = new ArrayList<KeyEvent>();
private Reference<FocusCommand> myLastForcedRequest;
private FocusCommand myFocusCommandOnAppActivation;
private ActionCallback myCallbackOnActivation;
private final boolean isInternalMode = ApplicationManagerEx.getApplicationEx().isInternal();
private final LinkedList<FocusRequestInfo> myRequests = new LinkedList<FocusRequestInfo>();
private final IdeEventQueue myQueue;
private final KeyProcessorContext myKeyProcessorContext = new KeyProcessorContext();
private long myCmdTimestamp;
private long myForcedCmdTimestamp;
private final EdtAlarm myFocusedComponentAlarm;
private final EdtAlarm myForcedFocusRequestsAlarm;
private final SimpleTimer myTimer = SimpleTimer.newInstance("FocusManager timer");
private final EdtAlarm myIdleAlarm;
private final Set<Runnable> myIdleRequests = new LinkedHashSet<Runnable>();
private boolean myFlushWasDelayedToFixFocus;
private ExpirableRunnable myFocusRevalidator;
private final Set<FurtherRequestor> myValidFurtherRequestors = new HashSet<FurtherRequestor>();
private final Set<ActionCallback> myTypeAheadRequestors = new HashSet<ActionCallback>();
private final UiActivityMonitor myActivityMonitor;
private boolean myTypeaheadEnabled = true;
private int myModalityStateForLastForcedRequest;
private class IdleRunnable extends EdtRunnable {
@Override
public void runEdt() {
if (canFlushIdleRequests()) {
flushIdleRequests();
}
else {
if (processFocusRevalidation()) {
if (isFocusTransferReady()) {
flushIdleRequests();
}
}
restartIdleAlarm();
}
}
}
private boolean canFlushIdleRequests() {
Component focusOwner = getFocusOwner();
return isFocusTransferReady()
&& !isIdleQueueEmpty()
&& !IdeEventQueue.getInstance().isDispatchingFocusEvent()
&& !(focusOwner == null && (!myValidFurtherRequestors.isEmpty() || myFocusRevalidator != null && !myFocusRevalidator.isExpired()));
}
private final Map<IdeFrame, Component> myLastFocused = new WeakValueHashMap<IdeFrame, Component>();
private final Map<IdeFrame, Component> myLastFocusedAtDeactivation = new WeakValueHashMap<IdeFrame, Component>();
private DataContext myRunContext;
private final TIntIntHashMap myModalityCount2FlushCount = new TIntIntHashMap();
private IdeFrame myLastFocusedFrame;
@SuppressWarnings("UnusedParameters") // the dependencies are needed to ensure correct loading order
public FocusManagerImpl(ServiceManagerImpl serviceManager, WindowManager wm, UiActivityMonitor monitor) {
myApp = ApplicationManager.getApplication();
myQueue = IdeEventQueue.getInstance();
myActivityMonitor = monitor;
myFocusedComponentAlarm = new EdtAlarm();
myForcedFocusRequestsAlarm = new EdtAlarm();
myIdleAlarm = new EdtAlarm();
final AppListener myAppListener = new AppListener();
myApp.getMessageBus().connect().subscribe(ApplicationActivationListener.TOPIC, myAppListener);
IdeEventQueue.getInstance().addDispatcher(new IdeEventQueue.EventDispatcher() {
@Override
public boolean dispatch(AWTEvent e) {
if (e instanceof FocusEvent) {
final FocusEvent fe = (FocusEvent)e;
final Component c = fe.getComponent();
if (c instanceof Window || c == null) return false;
Component parent = SwingUtilities.getWindowAncestor(c);
if (parent instanceof IdeFrame) {
myLastFocused.put((IdeFrame)parent, c);
}
}
else if (e instanceof WindowEvent) {
Window wnd = ((WindowEvent)e).getWindow();
if (e.getID() == WindowEvent.WINDOW_CLOSED) {
if (wnd instanceof IdeFrame) {
myLastFocused.remove(wnd);
myLastFocusedAtDeactivation.remove(wnd);
}
}
}
return false;
}
}, this);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusedWindow", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() instanceof IdeFrame) {
myLastFocusedFrame = (IdeFrame)evt.getNewValue();
}
}
});
}
@Override
public IdeFrame getLastFocusedFrame() {
return myLastFocusedFrame;
}
@Override
@NotNull
public ActionCallback requestFocus(@NotNull final Component c, final boolean forced) {
return requestFocus(new FocusCommand.ByComponent(c, new Exception()), forced);
}
@Override
@NotNull
public ActionCallback requestFocus(@NotNull final FocusCommand command, final boolean forced) {
assertDispatchThread();
if (isInternalMode) {
recordCommand(command, new Throwable(), forced);
}
final ActionCallback result = new ActionCallback();
myActivityMonitor.addActivity(FOCUS, ModalityState.any());
if (!forced) {
UIUtil.invokeAndWaitIfNeeded(new Runnable() {
@Override
public void run() {
if (!myFocusRequests.contains(command)) {
myFocusRequests.add(command);
}
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
resetUnforcedCommand(command);
_requestFocus(command, forced, result);
}
});
}
else {
_requestFocus(command, forced, result);
}
result.doWhenProcessed(new Runnable() {
@Override
public void run() {
restartIdleAlarm();
}
});
return result;
}
@NotNull
public List<FocusRequestInfo> getRequests() {
return myRequests;
}
public void recordFocusRequest(Component c, boolean forced) {
myRequests.add(new FocusRequestInfo(c, new Throwable(), forced));
if (myRequests.size() > 200) {
myRequests.removeFirst();
}
}
private void recordCommand(@NotNull FocusCommand command, @NotNull Throwable trace, boolean forced) {
if (FocusTracesAction.isActive()) {
recordFocusRequest(command.getDominationComponent(), forced);
}
}
private void _requestFocus(@NotNull final FocusCommand command, final boolean forced, @NotNull final ActionCallback result) {
result.doWhenProcessed(new Runnable() {
@Override
public void run() {
maybeRemoveFocusActivity();
}
});
if (checkForRejectOrByPass(command, forced, result)) return;
setCommand(command);
command.setCallback(result);
if (forced) {
myForcedFocusRequestsAlarm.cancelAllRequests();
setLastEffectiveForcedRequest(command);
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (checkForRejectOrByPass(command, forced, result)) return;
if (myRequestFocusCmd == command) {
final TimedOutCallback focusTimeout =
new TimedOutCallback(Registry.intValue("actionSystem.commandProcessingTimeout"),
"Focus command timed out, cmd=" + command, command.getAllocation(), true) {
@Override
protected void onTimeout() {
forceFinishFocusSettleDown(command, result);
}
};
if (command.invalidatesRequestors()) {
myCmdTimestamp++;
}
revalidateFurtherRequestors();
if (forced) {
if (command.invalidatesRequestors()) {
myForcedCmdTimestamp++;
}
revalidateFurtherRequestors();
}
command.setForced(forced);
command.run().doWhenDone(new Runnable() {
@Override
public void run() {
UIUtil.invokeLaterIfNeeded(new Runnable() {
@Override
public void run() {
resetCommand(command, false);
result.setDone();
}
});
}
}).doWhenRejected(new Runnable() {
@Override
public void run() {
result.setRejected();
resetCommand(command, true);
}
}).doWhenProcessed(new Runnable() {
@Override
public void run() {
if (forced) {
myForcedFocusRequestsAlarm.addRequest(new SetLastEffectiveRunnable(), 250);
}
}
}).notify(focusTimeout);
}
else {
rejectCommand(command, result);
}
}
});
}
private void maybeRemoveFocusActivity() {
if (isFocusTransferReady()) {
myActivityMonitor.removeActivity(FOCUS);
}
}
private boolean checkForRejectOrByPass(@NotNull FocusCommand cmd, final boolean forced, @NotNull ActionCallback result) {
if (cmd.isExpired()) {
rejectCommand(cmd, result);
return true;
}
final FocusCommand lastRequest = getLastEffectiveForcedRequest();
if (!forced && !isUnforcedRequestAllowed()) {
if (cmd.equals(lastRequest)) {
resetCommand(cmd, false);
result.setDone();
}
else {
rejectCommand(cmd, result);
}
return true;
}
if (lastRequest != null && lastRequest.dominatesOver(cmd)) {
rejectCommand(cmd, result);
return true;
}
if (!Registry.is("focus.fix.lost.cursor")) {
boolean doNotExecuteBecauseAppIsInactive =
!myApp.isActive() && !canExecuteOnInactiveApplication(cmd) && Registry.is("actionSystem.suspendFocusTransferIfApplicationInactive");
if (doNotExecuteBecauseAppIsInactive) {
if (myCallbackOnActivation != null) {
myCallbackOnActivation.setRejected();
if (myFocusCommandOnAppActivation != null) {
resetCommand(myFocusCommandOnAppActivation, true);
}
}
myFocusCommandOnAppActivation = cmd;
myCallbackOnActivation = result;
return true;
}
}
return false;
}
private void setCommand(@NotNull final FocusCommand command) {
myRequestFocusCmd = command;
UIUtil.invokeAndWaitIfNeeded(new Runnable() {
@Override
public void run() {
if (!myFocusRequests.contains(command)) {
myFocusRequests.add(command);
}
}
});
}
private void resetCommand(@NotNull final FocusCommand cmd, boolean reject) {
assertDispatchThread();
if (cmd == myRequestFocusCmd) {
myRequestFocusCmd = null;
}
final KeyEventProcessor processor = cmd.getProcessor();
if (processor != null) {
processor.finish(myKeyProcessorContext);
}
UIUtil.invokeAndWaitIfNeeded(new Runnable() {
@Override
public void run() {
myFocusRequests.remove(cmd);
}
});
if (reject) {
ActionCallback cb = cmd.getCallback();
if (cb != null && !cb.isProcessed()) {
cmd.getCallback().setRejected();
}
}
}
private void resetUnforcedCommand(@NotNull final FocusCommand cmd) {
UIUtil.invokeAndWaitIfNeeded(new Runnable() {
@Override
public void run() {
myFocusRequests.remove(cmd);
}
});
}
private static boolean canExecuteOnInactiveApplication(@NotNull FocusCommand cmd) {
return cmd.canExecuteOnInactiveApp();
}
private void setLastEffectiveForcedRequest(@Nullable FocusCommand command) {
myLastForcedRequest = command == null ? null : new WeakReference<FocusCommand>(command);
myModalityStateForLastForcedRequest = getCurrentModalityCount();
}
@Nullable
private FocusCommand getLastEffectiveForcedRequest() {
final FocusCommand request = SoftReference.dereference(myLastForcedRequest);
return request != null && !request.isExpired() ? request : null;
}
boolean isUnforcedRequestAllowed() {
if (getLastEffectiveForcedRequest() == null) return true;
return myModalityStateForLastForcedRequest != getCurrentModalityCount();
}
public static FocusManagerImpl getInstance() {
return (FocusManagerImpl)ApplicationManager.getApplication().getComponent(IdeFocusManager.class);
}
@Override
public void dispose() {
myForcedFocusRequestsAlarm.cancelAllRequests();
myFocusedComponentAlarm.cancelAllRequests();
}
private class KeyProcessorContext implements KeyEventProcessor.Context {
@Override
@NotNull
public List<KeyEvent> getQueue() {
return myToDispatchOnDone;
}
@Override
public void dispatch(@NotNull final List<KeyEvent> events) {
doWhenFocusSettlesDown(new Runnable() {
@Override
public void run() {
myToDispatchOnDone.addAll(events);
restartIdleAlarm();
}
});
}
}
@Override
public void doWhenFocusSettlesDown(@NotNull ExpirableRunnable runnable) {
doWhenFocusSettlesDown((Runnable)runnable);
}
@Override
public void doWhenFocusSettlesDown(@NotNull final Runnable runnable) {
UIUtil.invokeLaterIfNeeded(new Runnable() {
@Override
public void run() {
if (isFlushingIdleRequests()) {
myIdleRequests.add(runnable);
return;
}
if (myRunContext != null) {
flushRequest(runnable);
return;
}
final boolean needsRestart = isIdleQueueEmpty();
if (myIdleRequests.contains(runnable)) {
myIdleRequests.remove(runnable);
myIdleRequests.add(runnable);
} else {
myIdleRequests.add(runnable);
}
if (canFlushIdleRequests()) {
flushIdleRequests();
}
else {
if (needsRestart) {
restartIdleAlarm();
}
}
}
});
}
private void restartIdleAlarm() {
if (!ApplicationManager.getApplication().isActive()) return;
myIdleAlarm.cancelAllRequests();
myIdleAlarm.addRequest(new IdleRunnable(), Registry.intValue("actionSystem.focusIdleTimeout"));
}
private void flushIdleRequests() {
int currentModalityCount = getCurrentModalityCount();
try {
incFlushingRequests(1, currentModalityCount);
if (!isTypeaheadEnabled()) {
myToDispatchOnDone.clear();
myTypeAheadRequestors.clear();
}
if (!myToDispatchOnDone.isEmpty() && myTypeAheadRequestors.isEmpty()) {
final KeyEvent[] events = myToDispatchOnDone.toArray(new KeyEvent[myToDispatchOnDone.size()]);
IdeEventQueue.getInstance().getKeyEventDispatcher().resetState();
for (int eachIndex = 0; eachIndex < events.length; eachIndex++) {
if (!isFocusTransferReady()) {
break;
}
KeyEvent each = events[eachIndex];
Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (owner == null) {
owner = JOptionPane.getRootFrame();
}
boolean metaKey =
each.getKeyCode() == KeyEvent.VK_ALT ||
each.getKeyCode() == KeyEvent.VK_CONTROL ||
each.getKeyCode() == KeyEvent.VK_SHIFT ||
each.getKeyCode() == KeyEvent.VK_META;
boolean toDispatch = false;
if (!metaKey && (each.getID() == KeyEvent.KEY_RELEASED || each.getID() == KeyEvent.KEY_TYPED)) {
for (int i = 0; i < eachIndex; i++) {
final KeyEvent prev = events[i];
if (prev == null) continue;
if (prev.getID() == KeyEvent.KEY_PRESSED) {
if (prev.getKeyCode() == each.getKeyCode() || prev.getKeyChar() == each.getKeyChar()) {
toDispatch = true;
events[i] = null;
break;
}
}
}
}
else {
toDispatch = true;
}
myToDispatchOnDone.remove(each);
if (!toDispatch) {
continue;
}
KeyEvent keyEvent = new KeyEvent(owner, each.getID(), each.getWhen(), each.getModifiersEx(), each.getKeyCode(), each.getKeyChar(),
each.getKeyLocation());
if (owner != null && SwingUtilities.getWindowAncestor(owner) != null) {
IdeEventQueue.getInstance().dispatchEvent(keyEvent);
}
else {
myQueue._dispatchEvent(keyEvent, true);
}
}
if (myToDispatchOnDone.isEmpty() && myTypeAheadRequestors.isEmpty()) {
myActivityMonitor.removeActivity(TYPEAHEAD);
}
}
if (!isFocusBeingTransferred()) {
boolean focusOk = getFocusOwner() != null;
if (!focusOk && !myFlushWasDelayedToFixFocus) {
IdeEventQueue.getInstance().fixStickyFocusedComponents(null);
myFlushWasDelayedToFixFocus = true;
}
else if (!focusOk) {
myFlushWasDelayedToFixFocus = false;
}
if (canFlushIdleRequests() && getFlushingIdleRequests() <= 1 && (focusOk || !myFlushWasDelayedToFixFocus)) {
myFlushWasDelayedToFixFocus = false;
flushNow();
}
}
}
finally {
incFlushingRequests(-1, currentModalityCount);
if (!isIdleQueueEmpty()) {
restartIdleAlarm();
}
maybeRemoveFocusActivity();
}
}
private boolean processFocusRevalidation() {
ExpirableRunnable revalidator = myFocusRevalidator;
myFocusRevalidator = null;
if (revalidator != null && !revalidator.isExpired()) {
revalidator.run();
return true;
}
return false;
}
private void flushNow() {
final Runnable[] all = myIdleRequests.toArray(new Runnable[myIdleRequests.size()]);
myIdleRequests.clear();
for (int i = 0; i < all.length; i++) {
flushRequest(all[i]);
if (isFocusBeingTransferred()) {
for (int j = i + 1; j < all.length; j++) {
myIdleRequests.add(all[j]);
}
break;
}
}
maybeRemoveFocusActivity();
}
private static void flushRequest(Runnable each) {
if (each == null) return;
if (each instanceof Expirable) {
if (!((Expirable)each).isExpired()) {
each.run();
}
} else {
each.run();
}
}
public boolean isFocusTransferReady() {
assertDispatchThread();
if (myRunContext != null) return true;
invalidateFocusRequestsQueue();
if (!myFocusRequests.isEmpty()) return false;
if (myQueue == null) return true;
return !myQueue.isSuspendMode() && !myQueue.hasFocusEventsPending();
}
private void invalidateFocusRequestsQueue() {
assertDispatchThread();
UIUtil.invokeAndWaitIfNeeded(new Runnable() {
@Override
public void run() {
if (myFocusRequests.isEmpty()) return;
FocusCommand[] requests = myFocusRequests.toArray(new FocusCommand[myFocusRequests.size()]);
boolean wasChanged = false;
for (FocusCommand each : requests) {
if (each.isExpired()) {
resetCommand(each, true);
wasChanged = true;
}
}
if (wasChanged && myFocusRequests.isEmpty()) {
restartIdleAlarm();
}
}
});
}
private boolean isIdleQueueEmpty() {
return isPendingKeyEventsRedispatched() && myIdleRequests.isEmpty();
}
private boolean isPendingKeyEventsRedispatched() {
return myToDispatchOnDone.isEmpty();
}
@Override
public boolean dispatch(@NotNull KeyEvent e) {
if (!isTypeaheadEnabled()) return false;
if (isFlushingIdleRequests()) return false;
assertDispatchThread();
if (!isFocusTransferReady() || !isPendingKeyEventsRedispatched() || !myTypeAheadRequestors.isEmpty()) {
for (FocusCommand each : myFocusRequests) {
final KeyEventProcessor processor = each.getProcessor();
if (processor != null) {
final Boolean result = processor.dispatch(e, myKeyProcessorContext);
if (result != null) {
if (result.booleanValue()) {
myActivityMonitor.addActivity(TYPEAHEAD, ModalityState.any());
return true;
}
return false;
}
}
}
myToDispatchOnDone.add(e);
myActivityMonitor.addActivity(TYPEAHEAD, ModalityState.any());
restartIdleAlarm();
return true;
}
return false;
}
@Override
public void setTypeaheadEnabled(boolean enabled) {
myTypeaheadEnabled = enabled;
}
private boolean isTypeaheadEnabled() {
return Registry.is("actionSystem.fixLostTyping") && myTypeaheadEnabled;
}
@Override
public void typeAheadUntil(@NotNull ActionCallback callback) {
if (!isTypeaheadEnabled()) return;
final long currentTime = System.currentTimeMillis();
final ActionCallback done;
if (!Registry.is("type.ahead.logging.enabled")) {
done = callback;
}
else {
final String id = new Exception().getStackTrace()[2].getClassName();
//LOG.setLevel(Level.ALL);
final SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:ss:SSS", Locale.US);
LOG.info(dateFormat.format(System.currentTimeMillis()) + "\tStarted: " + id);
done = new ActionCallback();
callback.doWhenDone(new Runnable() {
@Override
public void run() {
done.setDone();
LOG.info(dateFormat.format(System.currentTimeMillis()) + "\tDone: " + id);
}
});
callback.doWhenRejected(new Runnable() {
@Override
public void run() {
done.setRejected();
LOG.info(dateFormat.format(System.currentTimeMillis()) + "\tRejected: " + id);
}
});
}
assertDispatchThread();
myTypeAheadRequestors.add(done);
done.notify(new TimedOutCallback(Registry.intValue("actionSystem.commandProcessingTimeout"),
"Typeahead request blocked",
new Exception() {
@Override
public String getMessage() {
return "Time: " + (System.currentTimeMillis() - currentTime);
}
},
true).doWhenProcessed(new Runnable() {
@Override
public void run() {
if (myTypeAheadRequestors.remove(done)) {
restartIdleAlarm();
}
}
}));
}
private boolean isFlushingIdleRequests() {
return getFlushingIdleRequests() > 0;
}
private int getFlushingIdleRequests() {
int currentModalityCount = getCurrentModalityCount();
return myModalityCount2FlushCount.get(currentModalityCount);
}
private void incFlushingRequests(int delta, final int currentModalityCount) {
if (myModalityCount2FlushCount.containsKey(currentModalityCount)) {
myModalityCount2FlushCount.adjustValue(currentModalityCount, delta);
}
else {
myModalityCount2FlushCount.put(currentModalityCount, delta);
}
}
private int getCurrentModalityCount() {
int modalityCount = 0;
Window[] windows = Window.getWindows();
for (Window each : windows) {
if (!each.isShowing()) continue;
if (each instanceof Dialog) {
Dialog eachDialog = (Dialog)each;
if (eachDialog.isModal()) {
modalityCount++;
}
else if (each instanceof JDialog) {
if (isModalContextPopup(((JDialog)each).getRootPane())) {
modalityCount++;
}
}
}
else if (each instanceof JWindow) {
JRootPane rootPane = ((JWindow)each).getRootPane();
if (isModalContextPopup(rootPane)) {
modalityCount++;
}
}
}
final int finalModalityCount = modalityCount;
myModalityCount2FlushCount.retainEntries(new TIntIntProcedure() {
@Override
public boolean execute(int eachModalityCount, int flushCount) {
return eachModalityCount <= finalModalityCount;
}
});
return modalityCount;
}
private static boolean isModalContextPopup(@NotNull JRootPane rootPane) {
final JBPopup popup = (JBPopup)rootPane.getClientProperty(JBPopup.KEY);
return popup != null && popup.isModalContext();
}
@NotNull
@Override
public Expirable getTimestamp(final boolean trackOnlyForcedCommands) {
assertDispatchThread();
return new Expirable() {
long myOwnStamp = trackOnlyForcedCommands ? myForcedCmdTimestamp : myCmdTimestamp;
@Override
public boolean isExpired() {
return myOwnStamp < (trackOnlyForcedCommands ? myForcedCmdTimestamp : myCmdTimestamp);
}
};
}
@NotNull
@Override
public FocusRequestor getFurtherRequestor() {
assertDispatchThread();
FurtherRequestor requestor = new FurtherRequestor(this, getTimestamp(true));
myValidFurtherRequestors.add(requestor);
revalidateFurtherRequestors();
return requestor;
}
private void revalidateFurtherRequestors() {
Iterator<FurtherRequestor> requestorIterator = myValidFurtherRequestors.iterator();
while (requestorIterator.hasNext()) {
FurtherRequestor each = requestorIterator.next();
if (each.isExpired()) {
requestorIterator.remove();
Disposer.dispose(each);
}
}
}
@Override
public void revalidateFocus(@NotNull final ExpirableRunnable runnable) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myFocusRevalidator = runnable;
restartIdleAlarm();
}
});
}
@Override
public Component getFocusOwner() {
assertDispatchThread();
Component result = null;
if (!ApplicationManager.getApplication().isActive()) {
result = myLastFocusedAtDeactivation.get(getLastFocusedFrame());
}
else if (myRunContext != null) {
result = (Component)myRunContext.getData(PlatformDataKeys.CONTEXT_COMPONENT.getName());
}
if (result == null) {
result = isFocusBeingTransferred() ? null : KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
}
final boolean meaninglessOwner = UIUtil.isMeaninglessFocusOwner(result);
if (result == null && !isFocusBeingTransferred() || meaninglessOwner) {
final Component permOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
if (permOwner != null) {
result = permOwner;
}
if (UIUtil.isMeaninglessFocusOwner(result)) {
result = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
}
}
return result;
}
@Override
public void runOnOwnContext(@NotNull DataContext context, @NotNull Runnable runnable) {
assertDispatchThread();
myRunContext = context;
try {
runnable.run();
}
finally {
myRunContext = null;
}
}
@Override
public Component getLastFocusedFor(IdeFrame frame) {
assertDispatchThread();
return myLastFocused.get(frame);
}
public void setLastFocusedAtDeactivation(@NotNull IdeFrame frame, @NotNull Component c) {
myLastFocusedAtDeactivation.put(frame, c);
}
@Override
public void toFront(JComponent c) {
assertDispatchThread();
if (c == null) return;
final Window window = UIUtil.getParentOfType(Window.class, c);
if (window != null && window.isShowing()) {
doWhenFocusSettlesDown(new Runnable() {
@Override
public void run() {
if (ApplicationManager.getApplication().isActive()) {
window.toFront();
}
}
});
}
}
private static class FurtherRequestor implements FocusRequestor {
private final IdeFocusManager myManager;
private final Expirable myExpirable;
private Throwable myAllocation;
private boolean myDisposed;
private FurtherRequestor(@NotNull IdeFocusManager manager, @NotNull Expirable expirable) {
myManager = manager;
myExpirable = expirable;
if (Registry.is("ide.debugMode")) {
myAllocation = new Exception();
}
}
@NotNull
@Override
public ActionCallback requestFocus(@NotNull Component c, boolean forced) {
final ActionCallback result = isExpired() ? new ActionCallback.Rejected() : myManager.requestFocus(c, forced);
result.doWhenProcessed(new Runnable() {
@Override
public void run() {
Disposer.dispose(FurtherRequestor.this);
}
});
return result;
}
private boolean isExpired() {
return myExpirable.isExpired() || myDisposed;
}
@NotNull
@Override
public ActionCallback requestFocus(@NotNull FocusCommand command, boolean forced) {
return isExpired() ? new ActionCallback.Rejected() : myManager.requestFocus(command, forced);
}
@Override
public void dispose() {
myDisposed = true;
}
}
class EdtAlarm {
private final Set<EdtRunnable> myRequests = new HashSet<EdtRunnable>();
public void cancelAllRequests() {
for (EdtRunnable each : myRequests) {
each.expire();
}
myRequests.clear();
}
public void addRequest(@NotNull EdtRunnable runnable, int delay) {
myRequests.add(runnable);
myTimer.setUp(runnable, delay);
}
}
private void forceFinishFocusSettleDown(@NotNull FocusCommand cmd, @NotNull ActionCallback cmdCallback) {
rejectCommand(cmd, cmdCallback);
}
private void rejectCommand(@NotNull FocusCommand cmd, @NotNull ActionCallback callback) {
resetCommand(cmd, true);
resetUnforcedCommand(cmd);
callback.setRejected();
}
private class AppListener implements ApplicationActivationListener {
@Override
public void applicationDeactivated(IdeFrame ideFrame) {
final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
Component parent = UIUtil.findUltimateParent(owner);
if (parent == ideFrame) {
myLastFocusedAtDeactivation.put(ideFrame, owner);
}
}
@Override
public void applicationActivated(final IdeFrame ideFrame) {
final FocusCommand cmd = myFocusCommandOnAppActivation;
ActionCallback callback = myCallbackOnActivation;
myFocusCommandOnAppActivation = null;
myCallbackOnActivation = null;
if (cmd != null) {
requestFocus(cmd, true).notify(callback);
} else {
focusLastFocusedComponent(ideFrame);
}
}
private void focusLastFocusedComponent(IdeFrame ideFrame) {
final KeyboardFocusManager mgr = KeyboardFocusManager.getCurrentKeyboardFocusManager();
if (mgr.getFocusOwner() == null) {
Component c = getComponent(myLastFocusedAtDeactivation, ideFrame);
if (c == null || !c.isShowing()) {
c = getComponent(myLastFocused, ideFrame);
}
final boolean mouseEventAhead = IdeEventQueue.isMouseEventAhead(null);
if (c != null && c.isShowing() && !mouseEventAhead) {
final LayoutFocusTraversalPolicyExt policy = LayoutFocusTraversalPolicyExt.findWindowPolicy(c);
if (policy != null) {
policy.setNoDefaultComponent(true, FocusManagerImpl.this);
}
requestFocus(c, false).doWhenProcessed(new Runnable() {
@Override
public void run() {
if (policy != null) {
policy.setNoDefaultComponent(false, FocusManagerImpl.this);
}
}
});
}
}
myLastFocusedAtDeactivation.remove(ideFrame);
}
}
@Nullable
private static Component getComponent(@NotNull Map<IdeFrame, Component> map, IdeFrame frame) {
return map.get(frame);
}
@Override
public JComponent getFocusTargetFor(@NotNull JComponent comp) {
return IdeFocusTraversalPolicy.getPreferredFocusedComponent(comp);
}
@Override
public Component getFocusedDescendantFor(Component comp) {
final Component focused = getFocusOwner();
if (focused == null) return null;
if (focused == comp || SwingUtilities.isDescendingFrom(focused, comp)) return focused;
List<JBPopup> popups = FocusTrackback.getChildPopups(comp);
for (JBPopup each : popups) {
if (each.isFocused()) return focused;
}
return null;
}
@Override
public boolean isFocusBeingTransferred() {
return !isFocusTransferReady();
}
@NotNull
@Override
public ActionCallback requestDefaultFocus(boolean forced) {
Component toFocus = null;
if (myLastFocusedFrame != null) {
toFocus = myLastFocused.get(myLastFocusedFrame);
if (toFocus == null || !toFocus.isShowing()) {
toFocus = getFocusTargetFor(myLastFocusedFrame.getComponent());
}
}
else {
Window[] windows = Window.getWindows();
for (Window each : windows) {
if (each.isActive()) {
if (each instanceof JFrame) {
toFocus = getFocusTargetFor(((JFrame)each).getRootPane());
break;
} else if (each instanceof JDialog) {
toFocus = getFocusTargetFor(((JDialog)each).getRootPane());
break;
} else if (each instanceof JWindow) {
toFocus = getFocusTargetFor(((JWindow)each).getRootPane());
break;
}
}
}
}
if (toFocus != null) {
return requestFocus(new FocusCommand.ByComponent(toFocus, new Exception()).setToInvalidateRequestors(false), forced);
}
return new ActionCallback.Done();
}
@Override
public boolean isFocusTransferEnabled() {
if (Registry.is("focus.fix.lost.cursor")) return true;
return myApp.isActive() || !Registry.is("actionSystem.suspendFocusTransferIfApplicationInactive");
}
private static void assertDispatchThread() {
if (Registry.is("actionSystem.assertFocusAccessFromEdt")) {
ApplicationManager.getApplication().assertIsDispatchThread();
}
}
private class SetLastEffectiveRunnable extends EdtRunnable {
@Override
public void runEdt() {
setLastEffectiveForcedRequest(null);
}
}
}
| |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.remote.ui;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.ExecutionException;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.remote.CredentialsType;
import com.intellij.remote.RemoteSdkAdditionalData;
import com.intellij.remote.RemoteSdkCredentials;
import com.intellij.remote.RemoteSdkException;
import com.intellij.remote.ext.*;
import com.intellij.ui.ComponentUtil;
import com.intellij.ui.ContextHelpLabel;
import com.intellij.ui.StatusPanel;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBRadioButton;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.List;
import java.util.*;
abstract public class CreateRemoteSdkForm<T extends RemoteSdkAdditionalData> extends JPanel implements RemoteSdkEditorForm, Disposable {
private JPanel myMainPanel;
private JBLabel myInterpreterPathLabel;
protected TextFieldWithBrowseButton myInterpreterPathField;
protected TextFieldWithBrowseButton myHelpersPathField;
private JTextField myNameField;
private JBLabel myNameLabel;
private JBLabel myHelpersPathLabel;
private JPanel myStatusPanelHolder;
private final StatusPanel myStatusPanel;
private JPanel myRadioPanel;
private JPanel myTypesPanel;
private JPanel myRunAsRootViaSudoPanel;
private JBCheckBox myRunAsRootViaSudoJBCheckBox;
private JPanel myRunAsRootViaSudoHelpPanel;
private ButtonGroup myTypeButtonGroup;
private boolean myNameVisible;
private final Project myProject;
@NotNull
private final RemoteSdkEditorContainer myParentContainer;
private final Runnable myValidator;
@NotNull
private final BundleAccessor myBundleAccessor;
private boolean myTempFilesPathVisible;
private CredentialsType myConnectionType;
private final Map<CredentialsType, TypeHandler> myCredentialsType2Handler;
private final Set<CredentialsType> myUnsupportedConnectionTypes = new HashSet<>();
@NotNull
private final SdkScopeController mySdkScopeController;
public CreateRemoteSdkForm(@Nullable Project project,
@NotNull RemoteSdkEditorContainer parentContainer,
@Nullable Runnable validator,
@NotNull final BundleAccessor bundleAccessor) {
this(project, parentContainer, ApplicationOnlySdkScopeController.INSTANCE, validator, bundleAccessor);
}
public CreateRemoteSdkForm(@Nullable Project project,
@NotNull RemoteSdkEditorContainer parentContainer,
@NotNull SdkScopeController sdkScopeController,
@Nullable Runnable validator,
@NotNull final BundleAccessor bundleAccessor) {
super(new BorderLayout());
myProject = project;
myParentContainer = parentContainer;
Disposer.register(parentContainer.getDisposable(), this);
mySdkScopeController = sdkScopeController;
myBundleAccessor = bundleAccessor;
myValidator = validator;
add(myMainPanel, BorderLayout.CENTER);
myStatusPanel = new StatusPanel();
myStatusPanelHolder.setLayout(new BorderLayout());
myStatusPanelHolder.add(myStatusPanel, BorderLayout.CENTER);
setNameVisible(false);
setTempFilesPathVisible(false);
myInterpreterPathLabel.setLabelFor(myInterpreterPathField.getTextField());
myInterpreterPathLabel.setText(myBundleAccessor.message("remote.interpreter.configure.path.label"));
myHelpersPathLabel.setText(myBundleAccessor.message("remote.interpreter.configure.temp.files.path.label"));
myInterpreterPathField.addActionListener(e -> {
showBrowsePathsDialog(myInterpreterPathField, myBundleAccessor.message("remote.interpreter.configure.path.title"));
});
myHelpersPathField.addActionListener(e -> {
showBrowsePathsDialog(myHelpersPathField, myBundleAccessor.message("remote.interpreter.configure.temp.files.path.title"));
});
myTypesPanel.setLayout(new ResizingCardLayout());
myCredentialsType2Handler = new HashMap<>();
installExtendedTypes(project);
installRadioListeners(myCredentialsType2Handler.values());
if (isSshSudoSupported()) {
myRunAsRootViaSudoJBCheckBox.setText(
bundleAccessor.message("remote.interpreter.configure.ssh.run_as_root_via_sudo.checkbox"));
myRunAsRootViaSudoHelpPanel.add(ContextHelpLabel.create(
bundleAccessor.message("remote.interpreter.configure.ssh.run_as_root_via_sudo.help")),
BorderLayout.WEST);
}
else {
myRunAsRootViaSudoPanel.setVisible(false);
}
// select the first credentials type for the start
Iterator<TypeHandler> iterator = myCredentialsType2Handler.values().iterator();
if (iterator.hasNext()) {
iterator.next().getRadioButton().setSelected(true);
}
radioSelected(true);
}
public void showBrowsePathsDialog(@NotNull TextFieldWithBrowseButton textFieldWithBrowseButton, @NotNull String dialogTitle) {
if (myConnectionType instanceof PathsBrowserDialogProvider) {
((PathsBrowserDialogProvider)myConnectionType).showPathsBrowserDialog(
myProject, textFieldWithBrowseButton.getTextField(),
dialogTitle,
() -> createSdkDataInner()
);
}
}
protected void disableChangeTypePanel() {
myRadioPanel.setVisible(false);
}
private void installRadioListeners(@NotNull final Collection<TypeHandler> values) {
ActionListener l = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
radioSelected(true);
}
};
for (TypeHandler typeHandler : values) {
typeHandler.getRadioButton().addActionListener(l);
}
}
private void installExtendedTypes(@Nullable Project project) {
for (final CredentialsType type : CredentialsManager.getInstance().getAllTypes()) {
CredentialsEditorProvider editorProvider = ObjectUtils.tryCast(type, CredentialsEditorProvider.class);
if (editorProvider != null) {
final List<CredentialsLanguageContribution> contributions = getContributions();
if (!contributions.isEmpty()) {
for (CredentialsLanguageContribution contribution : contributions) {
if (contribution.getType() == type && editorProvider.isAvailable(contribution)) {
final CredentialsEditor<?> editor = editorProvider.createEditor(project, contribution, this);
trackEditorLabelsColumn(editor);
JBRadioButton typeButton = new JBRadioButton(editor.getName());
myTypeButtonGroup.add(typeButton);
myRadioPanel.add(typeButton);
final JPanel editorMainPanel = editor.getMainPanel();
myTypesPanel.add(editorMainPanel, type.getName());
myCredentialsType2Handler.put(type,
new TypeHandlerEx(typeButton,
editorMainPanel,
editorProvider.getDefaultInterpreterPath(myBundleAccessor),
type,
editor));
// set initial connection type
if (myConnectionType == null) {
myConnectionType = type;
}
}
}
}
}
}
}
@NotNull
protected List<CredentialsLanguageContribution> getContributions() {
return Collections.emptyList();
}
@NotNull
@Override
public final SdkScopeController getSdkScopeController() {
return mySdkScopeController;
}
private void radioSelected(boolean propagateEvent) {
CredentialsType selectedType = getSelectedType();
CardLayout layout = (CardLayout)myTypesPanel.getLayout();
layout.show(myTypesPanel, selectedType.getName());
changeWindowHeightToPreferred();
setBrowseButtonsVisible(myCredentialsType2Handler.get(selectedType).isBrowsingAvailable());
if (propagateEvent) {
myStatusPanel.resetState();
// store interpreter path entered for previously selected type
String interpreterPath = myInterpreterPathField.getText();
if (StringUtil.isNotEmpty(interpreterPath)) {
myCredentialsType2Handler.get(myConnectionType).setInterpreterPath(interpreterPath);
}
myConnectionType = selectedType;
TypeHandler typeHandler = myCredentialsType2Handler.get(myConnectionType);
myInterpreterPathField.setText(typeHandler.getInterpreterPath());
typeHandler.onSelected();
}
else {
myCredentialsType2Handler.get(selectedType).onInit();
}
}
private void changeWindowHeightToPreferred() {
final Window window = ComponentUtil.getWindow(myMainPanel);
if (window != null) {
ApplicationManager.getApplication().invokeLater(() -> {
Dimension currentSize = window.getSize();
Dimension preferredSize = window.getPreferredSize();
window.setSize(currentSize.width, preferredSize.height);
}, ModalityState.stateForComponent(window));
}
}
private CredentialsType getSelectedType() {
for (Map.Entry<CredentialsType, TypeHandler> type2handler : myCredentialsType2Handler.entrySet()) {
if (type2handler.getValue().getRadioButton().isSelected()) {
return type2handler.getKey();
}
}
throw new IllegalStateException();
}
private void setBrowseButtonsVisible(boolean visible) {
myInterpreterPathField.getButton().setVisible(visible);
myHelpersPathField.getButton().setVisible(visible);
}
// TODO: (next) may propose to start DockerMachine - somewhere
@NotNull
public final RemoteSdkCredentials computeSdkCredentials() throws ExecutionException, InterruptedException {
final T sdkData = createSdkDataInner();
return sdkData.getRemoteSdkCredentials(myProject, true);
}
@Nullable
public JComponent getPreferredFocusedComponent() {
if (myNameVisible) {
return myNameField;
}
else {
final CredentialsType selectedType = getSelectedType();
final TypeHandler typeHandler = myCredentialsType2Handler.get(selectedType);
if (typeHandler != null) {
JComponent preferredFocusedComponent = UIUtil.getPreferredFocusedComponent(typeHandler.getContentComponent());
if (preferredFocusedComponent != null) return preferredFocusedComponent;
}
return myTypesPanel;
}
}
public T createSdkData() throws RemoteSdkException {
return createSdkDataInner();
}
protected T createSdkDataInner() {
final T sdkData = doCreateSdkData(getInterpreterPath());//todo ???
//if (!myCredentialsType2Handler.containsKey(sdkData.getRemoteConnectionType())) return sdkData;
//if () {
// ArrayUtil.mergeArrays(cases, exCases.toArray(new CredentialsCase[exCases.size()]))
//}
myConnectionType.saveCredentials(
sdkData,
new CaseCollector() {
@Override
protected void processEx(CredentialsEditor editor, Object credentials) {
editor.saveCredentials(credentials);
}
}.collectCases());
sdkData.setRunAsRootViaSudo(myRunAsRootViaSudoJBCheckBox.isSelected());
sdkData.setHelpersPath(getTempFilesPath());
return sdkData;
}
@NotNull
abstract protected T doCreateSdkData(@NotNull String interpreterPath);
private void setNameVisible(boolean visible) {
myNameField.setVisible(visible);
myNameLabel.setVisible(visible);
myNameVisible = visible;
}
public void setSdkName(String name) {
if (name != null) {
setNameVisible(true);
myNameField.setText(name);
}
}
public void init(final @NotNull T data) {
myConnectionType = data.connectionCredentials().getRemoteConnectionType();
TypeHandler typeHandler = myCredentialsType2Handler.get(myConnectionType);
if (typeHandler == null) {
typeHandler = new UnsupportedCredentialsTypeHandler(myConnectionType.getName());
myUnsupportedConnectionTypes.add(myConnectionType);
myCredentialsType2Handler.put(myConnectionType, typeHandler);
myTypeButtonGroup.add(typeHandler.getRadioButton());
myRadioPanel.add(typeHandler.getRadioButton());
myTypesPanel.add(typeHandler.getContentComponent(), myConnectionType.getName());
}
typeHandler.getRadioButton().setSelected(true);
boolean connectionTypeIsSupported = !myUnsupportedConnectionTypes.contains(myConnectionType);
myRadioPanel.setVisible(connectionTypeIsSupported);
data.switchOnConnectionType(
new CaseCollector() {
@Override
protected void processEx(CredentialsEditor editor, Object credentials) {
editor.init(credentials);
}
}.collectCases());
radioSelected(false);
String interpreterPath = data.getInterpreterPath();
myInterpreterPathField.setText(interpreterPath);
typeHandler.setInterpreterPath(interpreterPath);
setTempFilesPath(data);
if (isSshSudoSupported()) {
myRunAsRootViaSudoJBCheckBox.setSelected(data.isRunAsRootViaSudo());
}
}
private void setTempFilesPath(RemoteSdkAdditionalData data) {
myHelpersPathField.setText(data.getHelpersPath());
if (!StringUtil.isEmpty(data.getHelpersPath())) {
setTempFilesPathVisible(true);
}
}
protected void setTempFilesPathVisible(boolean visible) {
myHelpersPathField.setVisible(visible);
myHelpersPathLabel.setVisible(visible);
myTempFilesPathVisible = visible;
}
protected void setInterpreterPathVisible(boolean visible) {
myInterpreterPathField.setVisible(visible);
myInterpreterPathLabel.setVisible(visible);
}
public String getInterpreterPath() {
return myInterpreterPathField.getText().trim();
}
public String getTempFilesPath() {
return myHelpersPathField.getText();
}
@Nullable
public ValidationInfo validateRemoteInterpreter() {
TypeHandler typeHandler = myCredentialsType2Handler.get(getSelectedType());
if (StringUtil.isEmpty(getInterpreterPath())) {
return new ValidationInfo(
myBundleAccessor.message("remote.interpreter.unspecified.interpreter.path"),
myInterpreterPathField);
}
if (myTempFilesPathVisible) {
if (StringUtil.isEmpty(getTempFilesPath())) {
return new ValidationInfo(myBundleAccessor.message("remote.interpreter.unspecified.temp.files.path"), myHelpersPathField);
}
}
return typeHandler.validate();
}
@Nullable
public String getSdkName() {
if (myNameVisible) {
return myNameField.getText().trim();
}
else {
return null;
}
}
public void updateModifiedValues(RemoteSdkCredentials data) {
myHelpersPathField.setText(data.getHelpersPath());
}
public void updateHelpersPath(String helpersPath) {
myHelpersPathField.setText(helpersPath);
}
@Override
public boolean isSdkInConsistentState(@NotNull CredentialsType<?> connectionType) {
return myCredentialsType2Handler.get(connectionType).getRadioButton().isSelected(); // TODO: may encapsutate
}
public String getValidationError() {
return myStatusPanel.getError();
}
@Nullable
public String validateFinal() {
return myCredentialsType2Handler.get(myConnectionType).validateFinal();
}
@Override
public void dispose() {
// Disposable is the marker interface for CreateRemoteSdkForm
}
@NotNull
@Override
public final Disposable getDisposable() {
return this;
}
@NotNull
@Override
public final BundleAccessor getBundleAccessor() {
return myBundleAccessor;
}
private interface TypeHandler {
@NotNull JPanel getContentComponent();
@NotNull JBRadioButton getRadioButton();
void onInit();
void onSelected();
@Nullable String getInterpreterPath();
void setInterpreterPath(@Nullable String interpreterPath);
@Nullable ValidationInfo validate();
@Nullable String validateFinal();
boolean isBrowsingAvailable();
}
private static class UnsupportedCredentialsTypeHandler implements TypeHandler {
@NotNull private final JBRadioButton myTypeButton;
@NotNull private final JPanel myPanel;
private UnsupportedCredentialsTypeHandler(@Nullable String credentialsTypeName) {
myTypeButton = new JBRadioButton(credentialsTypeName);
myPanel = new JPanel(new BorderLayout());
String errorMessage = ExecutionBundle.message("remote.interpreter.cannot.load.interpreter.message", credentialsTypeName);
JBLabel errorLabel = new JBLabel(errorMessage);
errorLabel.setIcon(AllIcons.General.BalloonError);
myPanel.add(errorLabel, BorderLayout.CENTER);
}
@Override
public @NotNull JPanel getContentComponent() {
return myPanel;
}
@Override
public @NotNull JBRadioButton getRadioButton() {
return myTypeButton;
}
@Override
public @Nullable String getInterpreterPath() {
return null;
}
@Override
public void setInterpreterPath(@Nullable String interpreterPath) {
}
@Override
public void onInit() {
}
@Override
public void onSelected() {
}
@Nullable
@Override
public ValidationInfo validate() {
return null;
}
@Nullable
@Override
public String validateFinal() {
return null;
}
@Override
public boolean isBrowsingAvailable() {
return false;
}
}
private class TypeHandlerEx implements TypeHandler {
@NotNull private final JBRadioButton myRadioButton;
@NotNull private final JPanel myPanel;
private @Nullable String myInterpreterPath;
@NotNull private final CredentialsType<?> myType;
@NotNull private final CredentialsEditor<?> myEditor;
TypeHandlerEx(@NotNull JBRadioButton radioButton,
@NotNull JPanel panel,
@Nullable String defaultInterpreterPath,
@NotNull CredentialsType<?> type,
@NotNull CredentialsEditor editor) {
myRadioButton = radioButton;
myPanel = panel;
myInterpreterPath = defaultInterpreterPath;
myType = type;
myEditor = editor;
}
@NotNull
public CredentialsEditor getEditor() {
return myEditor;
}
@Override
public void onInit() {
}
@Override
public void onSelected() {
myConnectionType = myType;
myEditor.onSelected();
}
@Override
@NotNull
public JPanel getContentComponent() {
return myPanel;
}
@Override
@NotNull
public JBRadioButton getRadioButton() {
return myRadioButton;
}
@Override
public void setInterpreterPath(@Nullable String interpreterPath) {
myInterpreterPath = interpreterPath;
}
@Override
@Nullable
public String getInterpreterPath() {
return myInterpreterPath;
}
@Nullable
@Override
public ValidationInfo validate() {
return myEditor.validate();
}
@Nullable
@Override
public String validateFinal() {
return myEditor.validateFinal(() -> createSdkDataInner(), helpersPath -> updateHelpersPath(helpersPath));
}
@NotNull
public CredentialsType<?> getType() {
return myType;
}
@Override
public boolean isBrowsingAvailable() {
return myType instanceof PathsBrowserDialogProvider;
}
}
private abstract class CaseCollector {
public CredentialsCase[] collectCases(CredentialsCase... cases) {
List<CredentialsCase> exCases = new ArrayList<>();
for (TypeHandler typeHandler : myCredentialsType2Handler.values()) {
final TypeHandlerEx handlerEx = ObjectUtils.tryCast(typeHandler, TypeHandlerEx.class);
if (handlerEx != null) {
exCases.add(new CredentialsCase() {
@Override
public CredentialsType getType() {
return handlerEx.getType();
}
@Override
public void process(Object credentials) {
processEx(handlerEx.getEditor(), credentials);
}
});
}
}
return ArrayUtil.mergeArrays(cases, exCases.toArray(new CredentialsCase[0]));
}
protected abstract void processEx(CredentialsEditor editor, Object credentials);
}
@Nullable
public Project getProject() {
return myProject;
}
@NotNull
@Override
public final RemoteSdkEditorContainer getParentContainer() {
return myParentContainer;
}
@NotNull
@Override
public StatusPanel getStatusPanel() {
return myStatusPanel;
}
@Nullable
@Override
public Runnable getValidator() {
return myValidator;
}
/**
* Returns whether running SSH interpreter as root via sudo is
* supported or not.
*/
public boolean isSshSudoSupported() {
return false;
}
/**
* Returns whether editing of SDK with specified {@link CredentialsType} is
* supported or not.
* <p>
* Certain remote interpreters (e.g. PHP, Python, Ruby, etc.) may or may not
* support SDK with certain credentials type (e.g. Docker, Docker Compose,
* WSL, etc.).
*
* @param type credentials type to check
* @return whether editing of SDK is supported or not
*/
public boolean isConnectionTypeSupported(@NotNull CredentialsType type) {
return myCredentialsType2Handler.containsKey(type) && !myUnsupportedConnectionTypes.contains(type);
}
/**
* {@link ResizingCardLayout#preferredLayoutSize(Container)} and {@link ResizingCardLayout#minimumLayoutSize(Container)} methods are the
* same as in {@link CardLayout} but they take into account only visible components.
*/
private static final class ResizingCardLayout extends CardLayout {
@Override
public Dimension preferredLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int w = 0;
int h = 0;
for (int i = 0; i < ncomponents; i++) {
Component comp = parent.getComponent(i);
if (comp.isVisible()) {
Dimension d = comp.getPreferredSize();
if (d.width > w) {
w = d.width;
}
if (d.height > h) {
h = d.height;
}
}
}
return new Dimension(insets.left + insets.right + w + getHgap() * 2,
insets.top + insets.bottom + h + getVgap() * 2);
}
}
@Override
public Dimension minimumLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int w = 0;
int h = 0;
for (int i = 0; i < ncomponents; i++) {
Component comp = parent.getComponent(i);
if (comp.isVisible()) {
Dimension d = comp.getMinimumSize();
if (d.width > w) {
w = d.width;
}
if (d.height > h) {
h = d.height;
}
}
}
return new Dimension(insets.left + insets.right + w + getHgap() * 2,
insets.top + insets.bottom + h + getVgap() * 2);
}
}
}
@TestOnly
public void selectType(CredentialsType credentialsType) {
for (Map.Entry<CredentialsType, TypeHandler> type2handler : myCredentialsType2Handler.entrySet()) {
if (type2handler.getKey() == credentialsType) {
type2handler.getValue().getRadioButton().setSelected(true);
break;
}
}
radioSelected(true);
}
private void trackEditorLabelsColumn(@NotNull CredentialsEditor<?> editor) {
if (editor instanceof FormWithAlignableLabelsColumn) {
for (JBLabel label : ((FormWithAlignableLabelsColumn)editor).getLabelsColumn()) {
label.addAncestorListener(myLabelsColumnTracker);
label.addComponentListener(myLabelsColumnTracker);
}
}
}
@NotNull
private final CredentialsEditorLabelsColumnTracker myLabelsColumnTracker = new CredentialsEditorLabelsColumnTracker();
private class CredentialsEditorLabelsColumnTracker implements ComponentListener, AncestorListener {
@NotNull
private final Set<JBLabel> myVisibleLabelsColumn = new HashSet<>();
@Nullable
private JBLabel myAnchoredLabel;
@Override
public void componentResized(ComponentEvent e) { /* do nothing */ }
@Override
public void componentMoved(ComponentEvent e) { /* do nothing */ }
@Override
public void componentShown(ComponentEvent e) { onEvent(e.getComponent()); }
@Override
public void componentHidden(ComponentEvent e) { onEvent(e.getComponent()); }
@Override
public void ancestorAdded(AncestorEvent event) { onEvent(event.getComponent()); }
@Override
public void ancestorRemoved(AncestorEvent event) { onEvent(event.getComponent()); }
@Override
public void ancestorMoved(AncestorEvent event) { onEvent(event.getComponent()); }
private void onEvent(@Nullable Component component) {
if (component == null) return;
if (component instanceof JBLabel) {
if (component.isShowing()) {
onLabelShowing((JBLabel)component);
}
else {
onLabelHidden((JBLabel)component);
}
}
}
private void onLabelShowing(@NotNull JBLabel component) {
if (myVisibleLabelsColumn.add(component)) {
alignForm();
}
}
protected void onLabelHidden(@NotNull JBLabel component) {
if (myVisibleLabelsColumn.remove(component)) {
alignForm();
}
}
private void alignForm() {
myInterpreterPathLabel.setAnchor(null);
if (myAnchoredLabel != null) {
myAnchoredLabel.setAnchor(null);
myAnchoredLabel = null;
}
if (!myVisibleLabelsColumn.isEmpty()) {
JBLabel labelWithMaxWidth = Collections.max(myVisibleLabelsColumn, Comparator.comparingInt(o -> o.getPreferredSize().width));
if (myInterpreterPathLabel.getPreferredSize().width < labelWithMaxWidth.getPreferredSize().getWidth()) {
myInterpreterPathLabel.setAnchor(labelWithMaxWidth);
}
else {
for (JBLabel label : myVisibleLabelsColumn) {
label.setAnchor(myInterpreterPathLabel);
label.revalidate();
}
myAnchoredLabel = labelWithMaxWidth;
}
}
}
}
}
| |
/*
* Copyright 2006-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.consol.citrus.validation;
import com.consol.citrus.exceptions.CitrusRuntimeException;
import com.consol.citrus.message.DefaultMessage;
import com.consol.citrus.message.MessageType;
import com.consol.citrus.validation.context.DefaultValidationContext;
import com.consol.citrus.validation.context.ValidationContext;
import com.consol.citrus.validation.json.*;
import com.consol.citrus.validation.script.*;
import com.consol.citrus.validation.text.PlainTextMessageValidator;
import com.consol.citrus.validation.xml.*;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
/**
* @author Christoph Deppisch
* @since 2.0
*/
public class MessageValidatorRegistryTest {
@Test
public void testFindMessageValidators() throws Exception {
MessageValidatorRegistry messageValidatorRegistry = new MessageValidatorRegistry();
List<MessageValidator<? extends ValidationContext>> messageValidators = new ArrayList<>();
messageValidators.add(new PlainTextMessageValidator());
messageValidatorRegistry.setMessageValidators(messageValidators);
messageValidatorRegistry.afterPropertiesSet();
List<MessageValidator<? extends ValidationContext>> matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.PLAINTEXT.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 1L);
Assert.assertEquals(matchingValidators.get(0).getClass(), PlainTextMessageValidator.class);
try {
messageValidatorRegistry.findMessageValidators(MessageType.JSON.name(), new DefaultMessage(""));
Assert.fail("Missing exception due to no matching validator implementation");
} catch (CitrusRuntimeException e) {
Assert.assertTrue(e.getMessage().startsWith("Could not find proper message validator for message type"));
}
messageValidatorRegistry.getMessageValidators().add(new DomXmlMessageValidator());
messageValidatorRegistry.getMessageValidators().add(new GroovyScriptMessageValidator());
List<ValidationContext> validationContexts = new ArrayList<>();
validationContexts.add(new DefaultValidationContext());
validationContexts.add(new XmlMessageValidationContext());
validationContexts.add(new JsonMessageValidationContext());
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.PLAINTEXT.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 2L);
Assert.assertEquals(matchingValidators.get(0).getClass(), PlainTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), GroovyScriptMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
validationContexts.add(new ScriptValidationContext(MessageType.PLAINTEXT.name()));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.PLAINTEXT.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 2L);
Assert.assertEquals(matchingValidators.get(0).getClass(), PlainTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), GroovyScriptMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
validationContexts = new ArrayList<>();
validationContexts.add(new DefaultValidationContext());
validationContexts.add(new XmlMessageValidationContext());
validationContexts.add(new JsonMessageValidationContext());
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.XML.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 1L);
Assert.assertEquals(matchingValidators.get(0).getClass(), DomXmlMessageValidator.class);
}
@Test
public void testMessageValidatorRegistryXmlConfig() throws Exception {
MessageValidatorRegistry messageValidatorRegistry = new MessageValidatorConfig().getMessageValidatorRegistry();
messageValidatorRegistry.afterPropertiesSet();
//non XML message type
List<MessageValidator<? extends ValidationContext>> matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.PLAINTEXT.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 3L);
Assert.assertEquals(matchingValidators.get(0).getClass(), PlainTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyScriptMessageValidator.class);
List<ValidationContext> validationContexts = new ArrayList<>();
validationContexts.add(new DefaultValidationContext());
validationContexts.add(new XmlMessageValidationContext());
validationContexts.add(new JsonMessageValidationContext());
//XML message type and empty payload
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.XML.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), DomXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), XpathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
//XML message type and non empty payload
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.XML.name(), new DefaultMessage("<id>12345</id>"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), DomXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), XpathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
//script XML validation context
validationContexts.add(new ScriptValidationContext(MessageType.XML.name()));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.XML.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), DomXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), XpathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.XML.name(), new DefaultMessage("<id>12345</id>"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), DomXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), XpathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
//xpath message validation context
validationContexts = new ArrayList<>();
validationContexts.add(new DefaultValidationContext());
validationContexts.add(new XmlMessageValidationContext());
validationContexts.add(new JsonMessageValidationContext());
validationContexts.add(new XpathMessageValidationContext());
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.XML.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), DomXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), XpathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.XML.name(), new DefaultMessage("<id>12345</id>"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), DomXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), XpathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
}
@Test
public void testMessageValidatorRegistryJsonConfig() throws Exception {
MessageValidatorRegistry messageValidatorRegistry = new MessageValidatorConfig().getMessageValidatorRegistry();
messageValidatorRegistry.afterPropertiesSet();
List<ValidationContext> validationContexts = new ArrayList<>();
validationContexts.add(new DefaultValidationContext());
validationContexts.add(new XmlMessageValidationContext());
validationContexts.add(new JsonMessageValidationContext());
//JSON message type and empty payload
List<MessageValidator<? extends ValidationContext>> matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.JSON.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), JsonTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), JsonPathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), GroovyJsonMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
//JSON message type and non empty payload
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.JSON.name(), new DefaultMessage("{ \"id\": 12345 }"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), JsonTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), JsonPathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), GroovyJsonMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
//script JSON validation context
validationContexts.add(new ScriptValidationContext(MessageType.JSON.name()));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.JSON.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), JsonTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), JsonPathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), GroovyJsonMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.JSON.name(), new DefaultMessage("{ \"id\": 12345 }"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), JsonTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), JsonPathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), GroovyJsonMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
//json path message validation context
validationContexts = new ArrayList<>();
validationContexts.add(new DefaultValidationContext());
validationContexts.add(new XmlMessageValidationContext());
validationContexts.add(new JsonMessageValidationContext());
validationContexts.add(new JsonPathMessageValidationContext());
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.JSON.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), JsonTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), JsonPathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), GroovyJsonMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.JSON.name(), new DefaultMessage("{ \"id\": 12345 }"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), JsonTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), JsonPathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), GroovyJsonMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
}
@Test
public void testMessageValidatorRegistryPlaintextConfig() throws Exception {
MessageValidatorRegistry messageValidatorRegistry = new MessageValidatorConfig().getMessageValidatorRegistry();
messageValidatorRegistry.afterPropertiesSet();
List<ValidationContext> validationContexts = new ArrayList<>();
validationContexts.add(new DefaultValidationContext());
validationContexts.add(new XmlMessageValidationContext());
validationContexts.add(new JsonMessageValidationContext());
//Plaintext message type and empty payload
List<MessageValidator<? extends ValidationContext>> matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.PLAINTEXT.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 3L);
Assert.assertEquals(matchingValidators.get(0).getClass(), PlainTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyScriptMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
//Plaintext message type and non empty payload
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.PLAINTEXT.name(), new DefaultMessage("id=12345"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 3L);
Assert.assertEquals(matchingValidators.get(0).getClass(), PlainTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyScriptMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
//script plaintext validation context
validationContexts.add(new ScriptValidationContext(MessageType.PLAINTEXT.name()));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.PLAINTEXT.name(), new DefaultMessage(""));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 3L);
Assert.assertEquals(matchingValidators.get(0).getClass(), PlainTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyScriptMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.PLAINTEXT.name(), new DefaultMessage("id=12345"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 3L);
Assert.assertEquals(matchingValidators.get(0).getClass(), PlainTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyScriptMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
}
@Test
public void testMessageValidatorRegistryFallback() throws Exception {
MessageValidatorRegistry messageValidatorRegistry = new MessageValidatorConfig().getMessageValidatorRegistry();
messageValidatorRegistry.afterPropertiesSet();
List<ValidationContext> validationContexts = new ArrayList<>();
validationContexts.add(new DefaultValidationContext());
validationContexts.add(new XmlMessageValidationContext());
validationContexts.add(new JsonMessageValidationContext());
List<MessageValidator<? extends ValidationContext>> matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.XML.name(), new DefaultMessage("{ \"id\": 12345 }"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), JsonTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), JsonPathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), GroovyJsonMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.JSON.name(), new DefaultMessage("<id>12345</id>"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 4L);
Assert.assertEquals(matchingValidators.get(0).getClass(), DomXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), XpathMessageValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyXmlMessageValidator.class);
Assert.assertEquals(matchingValidators.get(3).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(3)).findValidationContext(validationContexts));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.PLAINTEXT.name(), new DefaultMessage("<id>12345</id>"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 3L);
Assert.assertEquals(matchingValidators.get(0).getClass(), PlainTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyScriptMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.PLAINTEXT.name(), new DefaultMessage("{ \"id\": 12345 }"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 3L);
Assert.assertEquals(matchingValidators.get(0).getClass(), PlainTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyScriptMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.XML.name(), new DefaultMessage("id=12345"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 3L);
Assert.assertEquals(matchingValidators.get(0).getClass(), PlainTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyScriptMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
matchingValidators = messageValidatorRegistry.findMessageValidators(MessageType.JSON.name(), new DefaultMessage("id=12345"));
Assert.assertNotNull(matchingValidators);
Assert.assertEquals(matchingValidators.size(), 3L);
Assert.assertEquals(matchingValidators.get(0).getClass(), PlainTextMessageValidator.class);
Assert.assertEquals(matchingValidators.get(1).getClass(), DefaultMessageHeaderValidator.class);
Assert.assertEquals(matchingValidators.get(2).getClass(), GroovyScriptMessageValidator.class);
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(0)).findValidationContext(validationContexts));
Assert.assertNotNull(((AbstractMessageValidator)matchingValidators.get(1)).findValidationContext(validationContexts));
Assert.assertNull(((AbstractMessageValidator)matchingValidators.get(2)).findValidationContext(validationContexts));
}
@Test(expectedExceptions = CitrusRuntimeException.class)
public void testEmptyListOfMessageValidators() throws Exception {
MessageValidatorRegistry messageValidatorRegistry = new MessageValidatorRegistry();
messageValidatorRegistry.afterPropertiesSet();
}
}
| |
/*
* Copyright (C) 2011 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.math.RoundingMode.CEILING;
import static java.math.RoundingMode.FLOOR;
import static java.math.RoundingMode.HALF_EVEN;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
/**
* A class for arithmetic on values of type {@code BigInteger}.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code int} and for {@code long} can be found in
* {@link IntMath} and {@link LongMath} respectively.
*
* @author Louis Wasserman
* @since 11.0
*/
@GwtCompatible(emulated = true)
public final class BigIntegerMath {
/**
* Returns {@code true} if {@code x} represents a power of two.
*/
public static boolean isPowerOfTwo(BigInteger x) {
checkNotNull(x);
return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1;
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
// TODO(kevinb): remove after this warning is disabled globally
public static int log2(BigInteger x, RoundingMode mode) {
checkPositive("x", checkNotNull(x));
int logFloor = x.bitLength() - 1;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through
case DOWN:
case FLOOR:
return logFloor;
case UP:
case CEILING:
return isPowerOfTwo(x) ? logFloor : logFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) {
BigInteger halfPower = SQRT2_PRECOMPUTED_BITS.shiftRight(
SQRT2_PRECOMPUTE_THRESHOLD - logFloor);
if (x.compareTo(halfPower) <= 0) {
return logFloor;
} else {
return logFloor + 1;
}
}
/*
* Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
*
* To determine which side of logFloor.5 the logarithm is, we compare x^2 to 2^(2 *
* logFloor + 1).
*/
BigInteger x2 = x.pow(2);
int logX2Floor = x2.bitLength() - 1;
return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}
/*
* The maximum number of bits in a square root for which we'll precompute an explicit half power
* of two. This can be any value, but higher values incur more class load time and linearly
* increasing memory consumption.
*/
@VisibleForTesting static final int SQRT2_PRECOMPUTE_THRESHOLD = 256;
@VisibleForTesting static final BigInteger SQRT2_PRECOMPUTED_BITS =
new BigInteger("16a09e667f3bcc908b2fb1366ea957d3e3adec17512775099da2f590b0667322a", 16);
/**
* Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
@GwtIncompatible("TODO")
@SuppressWarnings("fallthrough")
public static int log10(BigInteger x, RoundingMode mode) {
checkPositive("x", x);
if (fitsInLong(x)) {
return LongMath.log10(x.longValue(), mode);
}
int approxLog10 = (int) (log2(x, FLOOR) * LN_2 / LN_10);
BigInteger approxPow = BigInteger.TEN.pow(approxLog10);
int approxCmp = approxPow.compareTo(x);
/*
* We adjust approxLog10 and approxPow until they're equal to floor(log10(x)) and
* 10^floor(log10(x)).
*/
if (approxCmp > 0) {
/*
* The code is written so that even completely incorrect approximations will still yield the
* correct answer eventually, but in practice this branch should almost never be entered,
* and even then the loop should not run more than once.
*/
do {
approxLog10--;
approxPow = approxPow.divide(BigInteger.TEN);
approxCmp = approxPow.compareTo(x);
} while (approxCmp > 0);
} else {
BigInteger nextPow = BigInteger.TEN.multiply(approxPow);
int nextCmp = nextPow.compareTo(x);
while (nextCmp <= 0) {
approxLog10++;
approxPow = nextPow;
approxCmp = nextCmp;
nextPow = BigInteger.TEN.multiply(approxPow);
nextCmp = nextPow.compareTo(x);
}
}
int floorLog = approxLog10;
BigInteger floorPow = approxPow;
int floorCmp = approxCmp;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(floorCmp == 0);
// fall through
case FLOOR:
case DOWN:
return floorLog;
case CEILING:
case UP:
return floorPow.equals(x) ? floorLog : floorLog + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(10) is irrational, log10(x) - floorLog can never be exactly 0.5
BigInteger x2 = x.pow(2);
BigInteger halfPowerSquared = floorPow.pow(2).multiply(BigInteger.TEN);
return (x2.compareTo(halfPowerSquared) <= 0) ? floorLog : floorLog + 1;
default:
throw new AssertionError();
}
}
private static final double LN_10 = Math.log(10);
private static final double LN_2 = Math.log(2);
/**
* Returns the square root of {@code x}, rounded with the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x < 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and
* {@code sqrt(x)} is not an integer
*/
@GwtIncompatible("TODO")
@SuppressWarnings("fallthrough")
public static BigInteger sqrt(BigInteger x, RoundingMode mode) {
checkNonNegative("x", x);
if (fitsInLong(x)) {
return BigInteger.valueOf(LongMath.sqrt(x.longValue(), mode));
}
BigInteger sqrtFloor = sqrtFloor(x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(sqrtFloor.pow(2).equals(x)); // fall through
case FLOOR:
case DOWN:
return sqrtFloor;
case CEILING:
case UP:
int sqrtFloorInt = sqrtFloor.intValue();
boolean sqrtFloorIsExact =
(sqrtFloorInt * sqrtFloorInt == x.intValue()) // fast check mod 2^32
&& sqrtFloor.pow(2).equals(x); // slow exact check
return sqrtFloorIsExact ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
BigInteger halfSquare = sqrtFloor.pow(2).add(sqrtFloor);
/*
* We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both
* x and halfSquare are integers, this is equivalent to testing whether or not x <=
* halfSquare.
*/
return (halfSquare.compareTo(x) >= 0) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
default:
throw new AssertionError();
}
}
@GwtIncompatible("TODO")
private static BigInteger sqrtFloor(BigInteger x) {
/*
* Adapted from Hacker's Delight, Figure 11-1.
*
* Using DoubleUtils.bigToDouble, getting a double approximation of x is extremely fast, and
* then we can get a double approximation of the square root. Then, we iteratively improve this
* guess with an application of Newton's method, which sets guess := (guess + (x / guess)) / 2.
* This iteration has the following two properties:
*
* a) every iteration (except potentially the first) has guess >= floor(sqrt(x)). This is
* because guess' is the arithmetic mean of guess and x / guess, sqrt(x) is the geometric mean,
* and the arithmetic mean is always higher than the geometric mean.
*
* b) this iteration converges to floor(sqrt(x)). In fact, the number of correct digits doubles
* with each iteration, so this algorithm takes O(log(digits)) iterations.
*
* We start out with a double-precision approximation, which may be higher or lower than the
* true value. Therefore, we perform at least one Newton iteration to get a guess that's
* definitely >= floor(sqrt(x)), and then continue the iteration until we reach a fixed point.
*/
BigInteger sqrt0;
int log2 = log2(x, FLOOR);
if (log2 < DoubleUtils.MAX_EXPONENT) {
sqrt0 = sqrtApproxWithDoubles(x);
} else {
int shift = (log2 - DoubleUtils.SIGNIFICAND_BITS) & ~1; // even!
/*
* We have that x / 2^shift < 2^54. Our initial approximation to sqrtFloor(x) will be
* 2^(shift/2) * sqrtApproxWithDoubles(x / 2^shift).
*/
sqrt0 = sqrtApproxWithDoubles(x.shiftRight(shift)).shiftLeft(shift >> 1);
}
BigInteger sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1);
if (sqrt0.equals(sqrt1)) {
return sqrt0;
}
do {
sqrt0 = sqrt1;
sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1);
} while (sqrt1.compareTo(sqrt0) < 0);
return sqrt0;
}
@GwtIncompatible("TODO")
private static BigInteger sqrtApproxWithDoubles(BigInteger x) {
return DoubleMath.roundToBigInteger(Math.sqrt(DoubleUtils.bigToDouble(x)), HALF_EVEN);
}
/**
* Returns the result of dividing {@code p} by {@code q}, rounding using the specified
* {@code RoundingMode}.
*
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
@GwtIncompatible("TODO")
public static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode) {
BigDecimal pDec = new BigDecimal(p);
BigDecimal qDec = new BigDecimal(q);
return pDec.divide(qDec, 0, mode).toBigIntegerExact();
}
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, or {@code 1} if {@code n == 0}.
*
* <p><b>Warning</b>: the result takes <i>O(n log n)</i> space, so use cautiously.
*
* <p>This uses an efficient binary recursive algorithm to compute the factorial
* with balanced multiplies. It also removes all the 2s from the intermediate
* products (shifting them back in at the end).
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static BigInteger factorial(int n) {
checkNonNegative("n", n);
// If the factorial is small enough, just use LongMath to do it.
if (n < LongMath.factorials.length) {
return BigInteger.valueOf(LongMath.factorials[n]);
}
// Pre-allocate space for our list of intermediate BigIntegers.
int approxSize = IntMath.divide(n * IntMath.log2(n, CEILING), Long.SIZE, CEILING);
ArrayList<BigInteger> bignums = new ArrayList<BigInteger>(approxSize);
// Start from the pre-computed maximum long factorial.
int startingNumber = LongMath.factorials.length;
long product = LongMath.factorials[startingNumber - 1];
// Strip off 2s from this value.
int shift = Long.numberOfTrailingZeros(product);
product >>= shift;
// Use floor(log2(num)) + 1 to prevent overflow of multiplication.
int productBits = LongMath.log2(product, FLOOR) + 1;
int bits = LongMath.log2(startingNumber, FLOOR) + 1;
// Check for the next power of two boundary, to save us a CLZ operation.
int nextPowerOfTwo = 1 << (bits - 1);
// Iteratively multiply the longs as big as they can go.
for (long num = startingNumber; num <= n; num++) {
// Check to see if the floor(log2(num)) + 1 has changed.
if ((num & nextPowerOfTwo) != 0) {
nextPowerOfTwo <<= 1;
bits++;
}
// Get rid of the 2s in num.
int tz = Long.numberOfTrailingZeros(num);
long normalizedNum = num >> tz;
shift += tz;
// Adjust floor(log2(num)) + 1.
int normalizedBits = bits - tz;
// If it won't fit in a long, then we store off the intermediate product.
if (normalizedBits + productBits >= Long.SIZE) {
bignums.add(BigInteger.valueOf(product));
product = 1;
productBits = 0;
}
product *= normalizedNum;
productBits = LongMath.log2(product, FLOOR) + 1;
}
// Check for leftovers.
if (product > 1) {
bignums.add(BigInteger.valueOf(product));
}
// Efficiently multiply all the intermediate products together.
return listProduct(bignums).shiftLeft(shift);
}
static BigInteger listProduct(List<BigInteger> nums) {
return listProduct(nums, 0, nums.size());
}
static BigInteger listProduct(List<BigInteger> nums, int start, int end) {
switch (end - start) {
case 0:
return BigInteger.ONE;
case 1:
return nums.get(start);
case 2:
return nums.get(start).multiply(nums.get(start + 1));
case 3:
return nums.get(start).multiply(nums.get(start + 1)).multiply(nums.get(start + 2));
default:
// Otherwise, split the list in half and recursively do this.
int m = (end + start) >>> 1;
return listProduct(nums, start, m).multiply(listProduct(nums, m, end));
}
}
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, that is, {@code n! / (k! (n - k)!)}.
*
* <p><b>Warning</b>: the result can take as much as <i>O(k log n)</i> space.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
*/
public static BigInteger binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
if (k < LongMath.biggestBinomials.length && n <= LongMath.biggestBinomials[k]) {
return BigInteger.valueOf(LongMath.binomial(n, k));
}
BigInteger accum = BigInteger.ONE;
long numeratorAccum = n;
long denominatorAccum = 1;
int bits = LongMath.log2(n, RoundingMode.CEILING);
int numeratorBits = bits;
for (int i = 1; i < k; i++) {
int p = n - i;
int q = i + 1;
// log2(p) >= bits - 1, because p >= n/2
if (numeratorBits + bits >= Long.SIZE - 1) {
// The numerator is as big as it can get without risking overflow.
// Multiply numeratorAccum / denominatorAccum into accum.
accum = accum
.multiply(BigInteger.valueOf(numeratorAccum))
.divide(BigInteger.valueOf(denominatorAccum));
numeratorAccum = p;
denominatorAccum = q;
numeratorBits = bits;
} else {
// We can definitely multiply into the long accumulators without overflowing them.
numeratorAccum *= p;
denominatorAccum *= q;
numeratorBits += bits;
}
}
return accum
.multiply(BigInteger.valueOf(numeratorAccum))
.divide(BigInteger.valueOf(denominatorAccum));
}
// Returns true if BigInteger.valueOf(x.longValue()).equals(x).
@GwtIncompatible("TODO")
static boolean fitsInLong(BigInteger x) {
return x.bitLength() <= Long.SIZE - 1;
}
private BigIntegerMath() {}
}
| |
/*
* 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.processing.surrogatekeysgenerator.csvbased;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.carbondata.common.logging.LogService;
import org.apache.carbondata.common.logging.LogServiceFactory;
import org.apache.carbondata.core.cache.Cache;
import org.apache.carbondata.core.cache.CacheProvider;
import org.apache.carbondata.core.cache.CacheType;
import org.apache.carbondata.core.cache.dictionary.Dictionary;
import org.apache.carbondata.core.cache.dictionary.DictionaryColumnUniqueIdentifier;
import org.apache.carbondata.core.carbon.CarbonTableIdentifier;
import org.apache.carbondata.core.carbon.ColumnIdentifier;
import org.apache.carbondata.core.carbon.metadata.CarbonMetadata;
import org.apache.carbondata.core.carbon.metadata.schema.table.CarbonTable;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.datastorage.store.filesystem.CarbonFile;
import org.apache.carbondata.core.keygenerator.KeyGenException;
import org.apache.carbondata.core.keygenerator.KeyGenerator;
import org.apache.carbondata.core.util.CarbonProperties;
import org.apache.carbondata.core.util.CarbonTimeStatisticsFactory;
import org.apache.carbondata.core.util.CarbonUtilException;
import org.apache.carbondata.core.writer.ByteArrayHolder;
import org.apache.carbondata.core.writer.HierarchyValueWriterForCSV;
import org.apache.carbondata.processing.datatypes.GenericDataType;
import org.apache.carbondata.processing.mdkeygen.file.FileData;
import org.apache.carbondata.processing.mdkeygen.file.FileManager;
import org.apache.carbondata.processing.mdkeygen.file.IFileManagerComposite;
import org.apache.carbondata.processing.schema.metadata.ColumnSchemaDetails;
import org.apache.carbondata.processing.schema.metadata.ColumnSchemaDetailsWrapper;
import org.apache.carbondata.processing.schema.metadata.ColumnsInfo;
import org.apache.carbondata.processing.util.CarbonDataProcessorUtil;
import org.pentaho.di.core.exception.KettleException;
public class FileStoreSurrogateKeyGenForCSV extends CarbonCSVBasedDimSurrogateKeyGen {
/**
* LOGGER
*/
private static final LogService LOGGER =
LogServiceFactory.getLogService(FileStoreSurrogateKeyGenForCSV.class.getName());
/**
* hierValueWriter
*/
private Map<String, HierarchyValueWriterForCSV> hierValueWriter;
/**
* keyGenerator
*/
private Map<String, KeyGenerator> keyGenerator;
/**
* baseStorePath
*/
private String baseStorePath;
/**
* LOAD_FOLDER
*/
private String loadFolderName;
/**
* folderList
*/
private List<CarbonFile> folderList = new ArrayList<CarbonFile>(5);
/**
* primaryKeyStringArray
*/
private String[] primaryKeyStringArray;
/**
* partitionID
*/
private String partitionID;
/**
* load Id
*/
private int segmentId;
/**
* task id, each spark task has a unique id
*/
private String taskNo;
/**
* @param columnsInfo
* @throws KettleException
*/
public FileStoreSurrogateKeyGenForCSV(ColumnsInfo columnsInfo, String partitionID, int segmentId,
String taskNo) throws KettleException {
super(columnsInfo);
populatePrimaryKeyarray(dimInsertFileNames, columnsInfo.getPrimaryKeyMap());
this.partitionID = partitionID;
this.segmentId = segmentId;
this.taskNo = taskNo;
keyGenerator = new HashMap<String, KeyGenerator>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE);
baseStorePath = columnsInfo.getBaseStoreLocation();
setStoreFolderWithLoadNumber(
checkAndCreateLoadFolderNumber(columnsInfo.getDatabaseName(),
columnsInfo.getTableName()));
fileManager = new FileManager();
fileManager.setName(loadFolderName + CarbonCommonConstants.FILE_INPROGRESS_STATUS);
hierValueWriter = new HashMap<String, HierarchyValueWriterForCSV>(
CarbonCommonConstants.DEFAULT_COLLECTION_SIZE);
for (Entry<String, String> entry : hierInsertFileNames.entrySet()) {
String hierFileName = entry.getValue().trim();
hierValueWriter.put(entry.getKey(),
new HierarchyValueWriterForCSV(hierFileName, getStoreFolderWithLoadNumber()));
Map<String, KeyGenerator> keyGenerators = columnsInfo.getKeyGenerators();
keyGenerator.put(entry.getKey(), keyGenerators.get(entry.getKey()));
FileData fileData = new FileData(hierFileName, getStoreFolderWithLoadNumber());
fileData.setHierarchyValueWriter(hierValueWriter.get(entry.getKey()));
fileManager.add(fileData);
}
populateCache();
//Update the primary key surroagate key map
updatePrimaryKeyMaxSurrogateMap();
}
private void populatePrimaryKeyarray(String[] dimInsertFileNames, Map<String, Boolean> map) {
List<String> primaryKeyList = new ArrayList<String>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
for (String columnName : dimInsertFileNames) {
if (null != map.get(columnName)) {
map.put(columnName, false);
}
}
Set<Entry<String, Boolean>> entrySet = map.entrySet();
for (Entry<String, Boolean> entry : entrySet) {
if (entry.getValue()) {
primaryKeyList.add(entry.getKey().trim());
}
}
primaryKeyStringArray = primaryKeyList.toArray(new String[primaryKeyList.size()]);
}
/**
* update the
*/
private void updatePrimaryKeyMaxSurrogateMap() {
Map<String, Boolean> primaryKeyMap = columnsInfo.getPrimaryKeyMap();
for (Entry<String, Boolean> entry : primaryKeyMap.entrySet()) {
if (!primaryKeyMap.get(entry.getKey())) {
int repeatedPrimaryFromLevels =
getRepeatedPrimaryFromLevels(dimInsertFileNames, entry.getKey());
if (null == primaryKeysMaxSurroagetMap) {
primaryKeysMaxSurroagetMap =
new HashMap<String, Integer>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE);
}
primaryKeysMaxSurroagetMap.put(entry.getKey(), max[repeatedPrimaryFromLevels]);
}
}
}
private int getRepeatedPrimaryFromLevels(String[] columnNames, String primaryKey) {
for (int j = 0; j < columnNames.length; j++) {
if (primaryKey.equals(columnNames[j])) {
return j;
}
}
return -1;
}
private String checkAndCreateLoadFolderNumber(String databaseName,
String tableName) throws KettleException {
String carbonDataDirectoryPath = CarbonDataProcessorUtil
.getLocalDataFolderLocation(databaseName, tableName, taskNo, partitionID, segmentId + "",
false);
boolean isDirCreated = new File(carbonDataDirectoryPath).mkdirs();
if (!isDirCreated) {
throw new KettleException("Unable to create data load directory" + carbonDataDirectoryPath);
}
return carbonDataDirectoryPath;
}
/**
* This method will update the maxkey information.
* @param tabColumnName
* @param maxKey max cardinality of a column
*/
private void updateMaxKeyInfo(String tabColumnName, int maxKey) {
checkAndUpdateMap(maxKey, tabColumnName);
}
/**
* This method will generate cache for all the global dictionaries during data loading.
*/
private void populateCache() throws KettleException {
String carbonStorePath =
CarbonProperties.getInstance().getProperty(CarbonCommonConstants.STORE_LOCATION_HDFS);
String[] dimColumnNames = columnsInfo.getDimColNames();
String[] dimColumnIds = columnsInfo.getDimensionColumnIds();
String databaseName = columnsInfo.getDatabaseName();
String tableName = columnsInfo.getTableName();
CarbonTable carbonTable = CarbonMetadata.getInstance()
.getCarbonTable(databaseName + CarbonCommonConstants.UNDERSCORE + tableName);
CarbonTableIdentifier carbonTableIdentifier = carbonTable.getCarbonTableIdentifier();
CacheProvider cacheProvider = CacheProvider.getInstance();
Cache reverseDictionaryCache =
cacheProvider.createCache(CacheType.REVERSE_DICTIONARY, carbonStorePath);
List<String> dictionaryKeys = new ArrayList<>(dimColumnNames.length);
List<DictionaryColumnUniqueIdentifier> dictionaryColumnUniqueIdentifiers =
new ArrayList<>(dimColumnNames.length);
ColumnSchemaDetailsWrapper columnSchemaDetailsWrapper =
columnsInfo.getColumnSchemaDetailsWrapper();
// update the member cache for dimension
for (int i = 0; i < dimColumnNames.length; i++) {
String dimColName = dimColumnNames[i].substring(tableName.length() + 1);
ColumnSchemaDetails details = columnSchemaDetailsWrapper.get(dimColumnIds[i]);
if (details.isDirectDictionary()) {
continue;
}
GenericDataType complexType = columnsInfo.getComplexTypesMap().get(dimColName);
if (complexType != null) {
List<GenericDataType> primitiveChild = new ArrayList<GenericDataType>();
complexType.getAllPrimitiveChildren(primitiveChild);
for (GenericDataType eachPrimitive : primitiveChild) {
details = columnSchemaDetailsWrapper.get(eachPrimitive.getColumnId());
if (details.isDirectDictionary()) {
continue;
}
ColumnIdentifier columnIdentifier = new ColumnIdentifier(eachPrimitive.getColumnId(),
columnsInfo.getColumnProperties(eachPrimitive.getName()), details.getColumnType());
String dimColumnName =
tableName + CarbonCommonConstants.UNDERSCORE + eachPrimitive.getName();
DictionaryColumnUniqueIdentifier dictionaryColumnUniqueIdentifier =
new DictionaryColumnUniqueIdentifier(carbonTableIdentifier, columnIdentifier);
dictionaryColumnUniqueIdentifiers.add(dictionaryColumnUniqueIdentifier);
dictionaryKeys.add(dimColumnName);
}
} else {
ColumnIdentifier columnIdentifier =
new ColumnIdentifier(dimColumnIds[i], columnsInfo.getColumnProperties(dimColName),
details.getColumnType());
DictionaryColumnUniqueIdentifier dictionaryColumnUniqueIdentifier =
new DictionaryColumnUniqueIdentifier(carbonTableIdentifier, columnIdentifier);
dictionaryColumnUniqueIdentifiers.add(dictionaryColumnUniqueIdentifier);
dictionaryKeys.add(dimColumnNames[i]);
}
}
initDictionaryCacheInfo(dictionaryKeys, dictionaryColumnUniqueIdentifiers,
reverseDictionaryCache, carbonStorePath);
}
/**
* This method will initial the needed information for a dictionary of one column.
*
* @param dictionaryKeys
* @param dictionaryColumnUniqueIdentifiers
* @param reverseDictionaryCache
* @param carbonStorePath
* @throws KettleException
*/
private void initDictionaryCacheInfo(List<String> dictionaryKeys,
List<DictionaryColumnUniqueIdentifier> dictionaryColumnUniqueIdentifiers,
Cache reverseDictionaryCache, String carbonStorePath) throws KettleException {
long lruCacheStartTime = System.currentTimeMillis();
try {
List reverseDictionaries = reverseDictionaryCache.getAll(dictionaryColumnUniqueIdentifiers);
for (int i = 0; i < reverseDictionaries.size(); i++) {
Dictionary reverseDictionary = (Dictionary) reverseDictionaries.get(i);
getDictionaryCaches().put(dictionaryKeys.get(i), reverseDictionary);
updateMaxKeyInfo(dictionaryKeys.get(i), reverseDictionary.getDictionaryChunks().getSize());
}
CarbonTimeStatisticsFactory.getLoadStatisticsInstance().recordLruCacheLoadTime(
(System.currentTimeMillis() - lruCacheStartTime)/1000.0);
} catch (CarbonUtilException e) {
throw new KettleException(e.getMessage());
}
}
@Override protected byte[] getHierFromStore(int[] val, String hier, int primaryKey)
throws KettleException {
byte[] bytes;
try {
bytes = columnsInfo.getKeyGenerators().get(hier).generateKey(val);
hierValueWriter.get(hier).getByteArrayList().add(new ByteArrayHolder(bytes, primaryKey));
} catch (KeyGenException e) {
throw new KettleException(e);
}
return bytes;
}
@Override protected int getSurrogateFromStore(String value, int index, Object[] properties)
throws KettleException {
max[index]++;
int key = max[index];
return key;
}
@Override
protected int updateSurrogateToStore(String tuple, String columnName, int index, int key,
Object[] properties) throws KettleException {
Map<String, Integer> cache = getTimeDimCache().get(columnName);
if (cache == null) {
return key;
}
return key;
}
private void checkAndUpdateMap(int maxKey, String dimInsertFileNames) {
String[] dimsFiles2 = getDimsFiles();
for (int i = 0; i < dimsFiles2.length; i++) {
if (dimInsertFileNames.equalsIgnoreCase(dimsFiles2[i])) {
if (max[i] < maxKey) {
max[i] = maxKey;
break;
}
}
}
}
@Override public boolean isCacheFilled(String[] columns) {
for (String column : columns) {
Dictionary dicCache = getDictionaryCaches().get(column);
if (null == dicCache) {
return true;
}
}
return false;
}
public IFileManagerComposite getFileManager() {
return fileManager;
}
@Override protected byte[] getNormalizedHierFromStore(int[] val, String hier, int primaryKey,
HierarchyValueWriterForCSV hierWriter) throws KettleException {
byte[] bytes;
try {
bytes = columnsInfo.getKeyGenerators().get(hier).generateKey(val);
hierWriter.getByteArrayList().add(new ByteArrayHolder(bytes, primaryKey));
} catch (KeyGenException e) {
throw new KettleException(e);
}
return bytes;
}
@Override public int getSurrogateForMeasure(String tuple, String columnName)
throws KettleException {
Integer measureSurrogate = null;
Map<String, Dictionary> dictionaryCaches = getDictionaryCaches();
Dictionary dicCache = dictionaryCaches.get(columnName);
measureSurrogate = dicCache.getSurrogateKey(tuple);
return measureSurrogate;
}
@Override public void writeDataToFileAndCloseStreams() throws KettleException, KeyGenException {
// For closing stream inside hierarchy writer
for (Entry<String, String> entry : hierInsertFileNames.entrySet()) {
String hierFileName = hierValueWriter.get(entry.getKey()).getHierarchyName();
int size = fileManager.size();
for (int j = 0; j < size; j++) {
FileData fileData = (FileData) fileManager.get(j);
String fileName = fileData.getFileName();
if (hierFileName.equals(fileName)) {
HierarchyValueWriterForCSV hierarchyValueWriter = fileData.getHierarchyValueWriter();
hierarchyValueWriter.performRequiredOperation();
break;
}
}
}
}
}
| |
/*
* *********************************************************************
* Copyright (c) 2010 Pedro Gomes and Universidade do Minho.
* 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.
*
* ********************************************************************
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.uminho.gsd.benchmarks.generic.entities;
import org.uminho.gsd.benchmarks.interfaces.Entity;
import java.sql.Date;
import java.util.TreeMap;
/**
* I_ID
* I_TITLE
* I_A_ID
* I_PUB_DATE X
* I_PUBLISHER
* I_SUBJECT
* I_DESC
* I_RELATED[1 -5]
* I_THUMBNAIL X
* I_IMAGE X
* I_SRP X
* I_COST
* I_AVAIL
* I_STOCK
* I_ISBN
* I_PAGE
* I_BACKING
* I_DIMENSION
*/
public class Item implements Entity {
int i_id; //ID
String I_TITLE;
Date pubDate;
int I_AUTHOR;
String I_PUBLISHER;
String I_DESC;
String I_SUBJECT;
String thumbnail;
String image;
double I_COST;
int I_STOCK;
String isbn;//international id
double srp;//Suggested Retail Price
int I_RELATED1;
int I_RELATED2;
int I_RELATED3;
int I_RELATED4;
int I_RELATED5;
int I_PAGE;
Date avail; //Data when available
String I_BACKING;
String dimensions;
public Item(int i_id, String I_TITLE, Date pubDate, String I_PUBLISHER, String I_DESC, String I_SUBJECT, String thumbnail, String image, double I_COST, int I_STOCK, String isbn, double srp, int I_RELATED1, int I_RELATED2, int I_RELATED3, int I_RELATED4, int I_RELATED5, int I_PAGE, Date avail, String I_BACKING, String dimensions, int author) {
this.i_id = i_id;
this.I_TITLE = I_TITLE;
this.pubDate = pubDate;
this.I_AUTHOR = author;
this.I_PUBLISHER = I_PUBLISHER;
this.I_DESC = I_DESC;
this.I_SUBJECT = I_SUBJECT;
this.thumbnail = thumbnail;
this.image = image;
this.I_COST = I_COST;
this.I_STOCK = I_STOCK;
this.isbn = isbn;
this.srp = srp;
this.I_RELATED1 = I_RELATED1;
this.I_RELATED2 = I_RELATED2;
this.I_RELATED3 = I_RELATED3;
this.I_RELATED4 = I_RELATED4;
this.I_RELATED5 = I_RELATED5;
this.I_PAGE = I_PAGE;
this.avail = avail;
this.I_BACKING = I_BACKING;
this.dimensions = dimensions;
}
public int getI_AUTHOR() {
return I_AUTHOR;
}
public void setI_AUTHOR(int i_AUTHOR) {
I_AUTHOR = i_AUTHOR;
}
public String getI_BACKING() {
return I_BACKING;
}
public void setI_BACKING(String I_BACKING) {
this.I_BACKING = I_BACKING;
}
public double getI_COST() {
return I_COST;
}
public void setI_COST(double i_COST) {
I_COST = i_COST;
}
public String getI_DESC() {
return I_DESC;
}
public void setI_DESC(String I_DESC) {
this.I_DESC = I_DESC;
}
public int getI_PAGE() {
return I_PAGE;
}
public void setI_PAGE(int I_PAGE) {
this.I_PAGE = I_PAGE;
}
public String getI_PUBLISHER() {
return I_PUBLISHER;
}
public void setI_PUBLISHER(String I_PUBLISHER) {
this.I_PUBLISHER = I_PUBLISHER;
}
public int getI_STOCK() {
return I_STOCK;
}
public void setI_STOCK(int i_STOCK) {
I_STOCK = i_STOCK;
}
public String getI_SUBJECT() {
return I_SUBJECT;
}
public void setI_SUBJECT(String I_SUBJECT) {
this.I_SUBJECT = I_SUBJECT;
}
public String getI_TITLE() {
return I_TITLE;
}
public void setI_TITLE(String I_TITLE) {
this.I_TITLE = I_TITLE;
}
public Date getAvail() {
return avail;
}
public void setAvail(Date avail) {
this.avail = avail;
}
public String getDimensions() {
return dimensions;
}
public void setDimensions(String dimensions) {
this.dimensions = dimensions;
}
public int getI_id() {
return i_id;
}
public void setI_id(int i_id) {
this.i_id = i_id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Date getPubDate() {
return pubDate;
}
public void setPubDate(Date pubDate) {
this.pubDate = pubDate;
}
public double getSrp() {
return srp;
}
public void setSrp(double srp) {
this.srp = srp;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public TreeMap<String, Object> getValuesToInsert() {
//
//
// I_ID
//I_TITLE
//I_A_ID
//I_PUB_DATE
//I_PUBLISHER
//I_SUBJECT
//I_DESC
//I_RELATED[1-5]
//I_THUMBNAIL
//I_IMAGE
//I_SRP
//I_COST
//I_AVAIL
//I_STOCK
//I_ISBN
//I_PAGE
//I_BACKING
//I_DIMENSION
TreeMap<String, Object> values = new TreeMap<String, Object>();
values.put("I_TITLE", I_TITLE);
values.put("I_A_ID", I_AUTHOR);
values.put("I_PUB_DATE", pubDate);
values.put("I_PUBLISHER", I_PUBLISHER);
values.put("I_SUBJECT", I_SUBJECT);
values.put("I_DESC", I_DESC);
values.put("I_RELATED1", I_RELATED1);
values.put("I_RELATED2", I_RELATED2);
values.put("I_RELATED3", I_RELATED3);
values.put("I_RELATED4", I_RELATED4);
values.put("I_RELATED5", I_RELATED5);
values.put("I_THUMBNAIL", thumbnail);
values.put("I_IMAGE", image);
values.put("I_SRP", srp);
values.put("I_COST", I_COST);
values.put("I_AVAIL", avail);
values.put("I_STOCK", I_STOCK);
values.put("I_ISBN", isbn);
values.put("I_PAGE", I_PAGE);
values.put("I_BACKING", I_BACKING);
values.put("I_DIMENSION", dimensions);
return values;
}
public String getKeyName() {
return "I_ID";
}
}
| |
/*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.compiler.integrationtests;
import org.drools.compiler.Address;
import org.drools.compiler.CommonTestMethodBase;
import org.drools.compiler.Person;
import org.junit.Test;
import org.kie.internal.KnowledgeBase;
import org.kie.internal.runtime.StatefulKnowledgeSession;
public class NullSafeDereferencingTest extends CommonTestMethodBase {
@Test
public void testNullSafeBinding() {
String str = "import org.drools.compiler.*;\n" +
"rule R1 when\n" +
" Person( $streetName : address!.street ) \n" +
"then\n" +
"end";
KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
ksession.insert(new Person("Mario", 38));
Person mark = new Person("Mark", 37);
mark.setAddress(new Address("Main Street"));
ksession.insert(mark);
Person edson = new Person("Edson", 34);
edson.setAddress(new Address(null));
ksession.insert(edson);
assertEquals(2, ksession.fireAllRules());
ksession.dispose();
}
@Test
public void testNullSafeNullComparison() {
String str = "import org.drools.compiler.*;\n" +
"rule R1 when\n" +
" Person( address!.street == null ) \n" +
"then\n" +
"end";
KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
ksession.insert(new Person("Mario", 38));
Person mark = new Person("Mark", 37);
mark.setAddress(new Address("Main Street"));
ksession.insert(mark);
Person edson = new Person("Edson", 34);
edson.setAddress(new Address(null));
ksession.insert(edson);
assertEquals(1, ksession.fireAllRules());
ksession.dispose();
}
@Test
public void testNullSafeNullComparison2() {
String str = "import org.drools.compiler.*;\n" +
"rule R1 when\n" +
" $street : String()\n"+
" Person( address!.street == $street ) \n" +
"then\n" +
"end";
KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
ksession.insert(new Person("Mario", 38));
ksession.insert("Main Street");
Person mark = new Person("Mark", 37);
mark.setAddress(new Address("Main Street"));
ksession.insert(mark);
Person edson = new Person("Edson", 34);
edson.setAddress(new Address(null));
ksession.insert(edson);
assertEquals(1, ksession.fireAllRules());
ksession.dispose();
}
@Test
public void testNullSafeNullComparisonReverse() {
// DROOLS-82
String str =
"import org.drools.compiler.*;\n" +
"rule R1 when\n" +
" Person( \"Main Street\".equalsIgnoreCase(address!.street) )\n" +
"then\n" +
"end";
KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
ksession.insert(new Person("Mario", 38));
Person mark = new Person("Mark", 37);
mark.setAddress(new Address("Main Street"));
ksession.insert(mark);
Person edson = new Person("Edson", 34);
edson.setAddress(new Address(null));
ksession.insert(edson);
assertEquals(1, ksession.fireAllRules());
ksession.dispose();
}
@Test
public void testNullSafeNullComparisonReverseComplex() {
// DROOLS-82
String str =
"import org.drools.compiler.*;\n" +
"rule R1 when\n" +
" Person( \"Main\".equalsIgnoreCase(address!.street!.substring(0, address!.street!.indexOf(' '))) )\n" +
"then\n" +
"end";
KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
ksession.insert(new Person("Mario", 38));
Person mark = new Person("Mark", 37);
mark.setAddress(new Address("Main Street"));
ksession.insert(mark);
Person edson = new Person("Edson", 34);
edson.setAddress(new Address(null));
ksession.insert(edson);
assertEquals(1, ksession.fireAllRules());
ksession.dispose();
}
@Test
public void testDoubleNullSafe() {
String str = "import org.drools.compiler.*;\n" +
"rule R1 when\n" +
" Person( address!.street!.length > 15 ) \n" +
"then\n" +
"end";
KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
ksession.insert(new Person("Mario", 38));
Person mark = new Person("Mark", 37);
mark.setAddress(new Address("Main Street"));
ksession.insert(mark);
Person edson = new Person("Edson", 34);
edson.setAddress(new Address(null));
ksession.insert(edson);
Person alex = new Person("Alex", 34);
alex.setAddress(new Address("The Main Very Big Street"));
ksession.insert(alex);
assertEquals(1, ksession.fireAllRules());
ksession.dispose();
}
@Test
public void testMixedNullSafes() {
String str = "import org.drools.compiler.*;\n" +
"rule R1 when\n" +
" $p : Person( " +
" address!.street!.length > 0 && ( address!.street!.length < 15 || > 20 && < 30 ) " +
" && address!.zipCode!.length > 0 && address.zipCode == \"12345\" " +
" ) \n" +
"then\n" +
" System.out.println( $p ); \n" +
"end";
KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
ksession.insert(new Person("Mario", 38));
Person mark = new Person("Mark", 37);
mark.setAddress(new Address("Main Street",null,"12345"));
ksession.insert(mark);
Person edson = new Person("Edson", 34);
edson.setAddress(new Address(null));
ksession.insert(edson);
Person alex = new Person("Alex", 34);
alex.setAddress(new Address("The Main Verrry Long Street"));
ksession.insert(alex);
Person frank = new Person("Frank", 24);
frank.setAddress(new Address("Long Street number 21",null,"12345"));
ksession.insert(frank);
assertEquals(2, ksession.fireAllRules());
ksession.dispose();
}
@Test
public void testNullSafeMemberOf() {
// DROOLS-50
String str =
"declare A\n" +
" list : java.util.List\n" +
"end\n" +
"\n" +
"rule Init when\n" +
"then\n" +
" insert( new A( java.util.Arrays.asList( \"test\" ) ) );" +
" insert( \"test\" );" +
"end\n" +
"rule R when\n" +
" $a : A()\n" +
" $s : String( this memberOf $a!.list )\n" +
"then\n" +
"end";
KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
assertEquals(2, ksession.fireAllRules());
ksession.dispose();
}
@Test
public void testNullSafeInnerConstraint() {
String str =
"declare Content\n" +
" complexContent : Content\n" +
" extension : Content\n" +
"end\n" +
"\n" +
"declare Context\n" +
" ctx : Content\n" +
"end\n" +
"\n" +
"rule \"Complex Type Attribute\"\n" +
"when\n" +
" $con : Content()\n" +
" Context( ctx == $con || == $con!.complexContent!.extension )\n" +
"then\n" +
" System.out.println( $con ); \n" +
"end\n" +
"\n" +
"rule \"Init\"\n" +
"when\n" +
"then\n" +
" Content ext = new Content();\n" +
" Content complex = new Content( new Content( null, ext ), null );\n" +
" Content complex2 = new Content( null, null );\n" +
" Context ctx = new Context( ext );\n" +
" Context ctx2 = new Context( complex2 );\n" +
" insert( complex );\n" +
" insert( complex2 );\n" +
" insert( ctx );\n" +
" insert( ctx2 );\n" +
"end";
KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
assertEquals( 3, ksession.fireAllRules() );
ksession.dispose();
}
}
| |
/*
* Copyright (c) 2010-2017 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.web.page.admin.users;
import com.evolveum.midpoint.gui.api.ComponentConstants;
import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab;
import com.evolveum.midpoint.gui.api.component.tabs.PanelTab;
import com.evolveum.midpoint.gui.api.model.LoadableModel;
import com.evolveum.midpoint.gui.api.util.FocusTabVisibleBehavior;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils;
import com.evolveum.midpoint.model.api.ModelAuthorizationAction;
import com.evolveum.midpoint.prism.PrismContainerDefinition;
import com.evolveum.midpoint.prism.PrismReferenceValue;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.builder.QueryBuilder;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.web.component.assignment.AssignmentEditorDto;
import com.evolveum.midpoint.web.component.assignment.AssignmentTablePanel;
import com.evolveum.midpoint.web.component.assignment.DelegationEditorPanel;
import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem;
import com.evolveum.midpoint.web.component.objectdetails.UserDelegationsTabPanel;
import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails;
import com.evolveum.midpoint.web.page.admin.users.component.AssignmentsPreviewDto;
import com.evolveum.midpoint.web.page.admin.users.dto.UserDtoStatus;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.tabs.ITab;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.security.api.AuthorizationConstants;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.application.AuthorizationAction;
import com.evolveum.midpoint.web.application.PageDescriptor;
import com.evolveum.midpoint.web.component.FocusSummaryPanel;
import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel;
import com.evolveum.midpoint.web.component.objectdetails.FocusMainPanel;
import com.evolveum.midpoint.web.page.admin.PageAdminFocus;
import com.evolveum.midpoint.web.page.admin.users.component.UserSummaryPanel;
import com.evolveum.midpoint.web.util.OnePageParameterEncoder;
import java.util.*;
/**
* @author lazyman
* @author semancik
*/
@PageDescriptor(url = "/admin/user", encoder = OnePageParameterEncoder.class, action = {
@AuthorizationAction(actionUri = PageAdminUsers.AUTH_USERS_ALL,
label = PageAdminUsers.AUTH_USERS_ALL_LABEL,
description = PageAdminUsers.AUTH_USERS_ALL_DESCRIPTION),
@AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_USER_URL,
label = "PageUser.auth.user.label",
description = "PageUser.auth.user.description")})
public class PageUser extends PageAdminFocus<UserType> {
private static final String DOT_CLASS = PageUser.class.getName() + ".";
private static final String OPERATION_LOAD_DELEGATED_BY_ME_ASSIGNMENTS = DOT_CLASS + "loadDelegatedByMeAssignments";
private static final String OPERATION_LOAD_ASSIGNMENT_PEVIEW_DTO_LIST = DOT_CLASS + "createAssignmentPreviewDtoList";
private static final String ID_TASK_TABLE = "taskTable";
private static final String ID_TASKS = "tasks";
private LoadableModel<List<AssignmentEditorDto>> delegationsModel;
private LoadableModel<List<AssignmentsPreviewDto>> privilegesListModel;
private UserDelegationsTabPanel userDelegationsTabPanel = null;
private static final Trace LOGGER = TraceManager.getTrace(PageUser.class);
public PageUser() {
initialize(null);
}
public PageUser(PageParameters parameters) {
getPageParameters().overwriteWith(parameters);
initialize(null);
}
public PageUser(final PrismObject<UserType> userToEdit) {
initialize(userToEdit);
}
@Override
protected void initializeModel(final PrismObject<UserType> objectToEdit) {
super.initializeModel(objectToEdit);
delegationsModel = new LoadableModel<List<AssignmentEditorDto>>(false) {
@Override
protected List<AssignmentEditorDto> load() {
if (StringUtils.isNotEmpty(getObjectWrapper().getOid())) {
return loadDelegatedByMeAssignments();
} else {
return new ArrayList<>();
}
}
};
privilegesListModel = new LoadableModel<List<AssignmentsPreviewDto>>(false) {
@Override
protected List<AssignmentsPreviewDto> load() {
return getUserPrivilegesList();
}
};
}
@Override
protected FocusSummaryPanel<UserType> createSummaryPanel() {
return new UserSummaryPanel(ID_SUMMARY_PANEL, getObjectModel(), this);
}
protected void cancelPerformed(AjaxRequestTarget target) {
// uncoment later -> check for changes to not allow leave the page when
// some changes were made
// try{
// if (userModel.getObject().getOldDelta() != null &&
// !userModel.getObject().getOldDelta().isEmpty() ||
// userModel.getObject().getFocusPrimaryDelta() != null &&
// !userModel.getObject().getFocusPrimaryDelta().isEmpty()){
// showModalWindow(MODAL_ID_CONFIRM_CANCEL, target);
// } else{
redirectBack();
// }
// }catch(Exception ex){
// LoggingUtils.logUnexpectedException(LOGGER, "Could not return to user list",
// ex);
// }
}
@Override
protected UserType createNewObject() {
return new UserType();
}
@Override
protected Class getRestartResponsePage() {
return PageUsers.class;
}
@Override
public Class getCompileTimeClass() {
return UserType.class;
}
@Override
protected AbstractObjectMainPanel<UserType> createMainPanel(String id) {
return new FocusMainPanel<UserType>(id, getObjectModel(), getAssignmentsModel(), getPolicyRulesModel(), getProjectionModel(), this) {
@Override
protected void addSpecificTabs(final PageAdminObjectDetails<UserType> parentPage, List<ITab> tabs) {
FocusTabVisibleBehavior authorization;
if (WebComponentUtil.isAuthorized(ModelAuthorizationAction.AUDIT_READ.getUrl())){
authorization = new FocusTabVisibleBehavior(unwrapModel(), ComponentConstants.UI_FOCUS_TAB_OBJECT_HISTORY_URL);
tabs.add(
new PanelTab(parentPage.createStringResource("pageAdminFocus.objectHistory"), authorization) {
private static final long serialVersionUID = 1L;
@Override
public WebMarkupContainer createPanel(String panelId) {
return createObjectHistoryTabPanel(panelId, parentPage);
}
});
}
authorization = new FocusTabVisibleBehavior(unwrapModel(),
ComponentConstants.UI_FOCUS_TAB_DELEGATIONS_URL);
tabs.add(new CountablePanelTab(parentPage.createStringResource("FocusType.delegations"), authorization)
{
private static final long serialVersionUID = 1L;
@Override
public WebMarkupContainer createPanel(String panelId) {
userDelegationsTabPanel = new UserDelegationsTabPanel<>(panelId, getMainForm(), getObjectModel(),
delegationsModel, privilegesListModel, PageUser.this);
return userDelegationsTabPanel;
}
@Override
public String getCount() {
return Integer.toString(delegationsModel.getObject() == null ? 0 : delegationsModel.getObject().size());
}
});
authorization = new FocusTabVisibleBehavior(unwrapModel(),
ComponentConstants.UI_FOCUS_TAB_DELEGATED_TO_ME_URL);
tabs.add(new CountablePanelTab(parentPage.createStringResource("FocusType.delegatedToMe"), authorization)
{
private static final long serialVersionUID = 1L;
@Override
public WebMarkupContainer createPanel(String panelId) {
return new AssignmentTablePanel<UserType>(panelId, parentPage.createStringResource("FocusType.delegatedToMe"),
getDelegatedToMeModel(), PageUser.this) {
private static final long serialVersionUID = 1L;
@Override
public void populateAssignmentDetailsPanel(ListItem<AssignmentEditorDto> item) {
DelegationEditorPanel editor = new DelegationEditorPanel(ID_ROW, item.getModel(), true,
privilegesListModel, PageUser.this);
item.add(editor);
}
@Override
public String getExcludeOid() {
return getObject().getOid();
}
@Override
protected List<InlineMenuItem> createAssignmentMenu() {
return new ArrayList<>();
}
};
}
@Override
public String getCount() {
return Integer.toString(getDelegatedToMeModel().getObject() == null ?
0 : getDelegatedToMeModel().getObject().size());
}
});
}
@Override
protected boolean getOptionsPanelVisibility() {
if (isSelfProfile()){
return false;
} else {
return super.getOptionsPanelVisibility();
}
}
@Override
protected boolean areSavePreviewButtonsEnabled(){
return super.areSavePreviewButtonsEnabled() ||
(userDelegationsTabPanel != null ? userDelegationsTabPanel.isDelegationsModelChanged() : false);
}
};
}
protected boolean isSelfProfile(){
return false;
}
private List<AssignmentEditorDto> loadDelegatedByMeAssignments() {
OperationResult result = new OperationResult(OPERATION_LOAD_DELEGATED_BY_ME_ASSIGNMENTS);
List<AssignmentEditorDto> list = new ArrayList<>();
try{
Task task = createSimpleTask(OPERATION_LOAD_DELEGATED_BY_ME_ASSIGNMENTS);
PrismReferenceValue referenceValue = new PrismReferenceValue(getObjectWrapper().getOid(),
UserType.COMPLEX_TYPE);
referenceValue.setRelation(SchemaConstants.ORG_DEPUTY);
ObjectFilter refFilter = QueryBuilder.queryFor(UserType.class, getPrismContext())
.item(UserType.F_ASSIGNMENT, AssignmentType.F_TARGET_REF).ref(referenceValue)
.buildFilter();
ObjectQuery query = new ObjectQuery();
query.setFilter(refFilter);
List<PrismObject<UserType>> usersList = getModelService().searchObjects(UserType.class, query, null, task, result);
List<String> processedUsersOid = new ArrayList<>();
if (usersList != null && usersList.size() > 0){
for (PrismObject<UserType> user : usersList) {
if (processedUsersOid.contains(user.getOid())){
continue;
}
List<AssignmentType> assignments = user.asObjectable().getAssignment();
for (AssignmentType assignment : assignments) {
if (assignment.getTargetRef() != null &&
StringUtils.isNotEmpty(assignment.getTargetRef().getOid()) &&
assignment.getTargetRef().getOid().equals(getObjectWrapper().getOid())) {
AssignmentEditorDto dto = new AssignmentEditorDto(UserDtoStatus.MODIFY, assignment, this,
user.asObjectable());
dto.setEditable(false);
list.add(dto);
}
}
processedUsersOid.add(user.getOid());
}
}
} catch (Exception ex){
result.recomputeStatus();
showResult(result);
}
Collections.sort(list);
return list;
}
private List<AssignmentsPreviewDto> getUserPrivilegesList(){
List<AssignmentsPreviewDto> list = new ArrayList<>();
OperationResult result = new OperationResult(OPERATION_LOAD_ASSIGNMENT_PEVIEW_DTO_LIST);
Task task = createSimpleTask(OPERATION_LOAD_ASSIGNMENT_PEVIEW_DTO_LIST);
for (AssignmentType assignment : getObjectWrapper().getObject().asObjectable().getAssignment()){
AssignmentsPreviewDto dto = createDelegableAssignmentsPreviewDto(assignment, task, result);
if (dto != null){
list.add(dto);
}
}
return list;
}
@Override
protected boolean processDeputyAssignments(boolean previewOnly) {
boolean isAnythingChanged = false;
if (!previewOnly) {
for (AssignmentEditorDto dto : delegationsModel.getObject()) {
if (!UserDtoStatus.MODIFY.equals(dto.getStatus())) {
UserType user = dto.getDelegationOwner();
List<AssignmentEditorDto> userAssignmentsDtos = new ArrayList<>();
userAssignmentsDtos.add(dto);
saveDelegationToUser(user, userAssignmentsDtos);
isAnythingChanged = true;
}
}
}
return isAnythingChanged;
}
private void saveDelegationToUser(UserType user, List<AssignmentEditorDto> assignmentEditorDtos) {
OperationResult result = new OperationResult(OPERATION_SAVE);
ObjectDelta<UserType> delta;
Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<ObjectDelta<? extends ObjectType>>();
try {
delta = user.asPrismObject().createModifyDelta();
deltas.add(delta);
PrismContainerDefinition def = user.asPrismObject().getDefinition().findContainerDefinition(UserType.F_ASSIGNMENT);
handleAssignmentDeltas(delta, assignmentEditorDtos, def, true);
getModelService().executeChanges(deltas, null, createSimpleTask(OPERATION_SAVE), result);
result.recordSuccess();
} catch (Exception e) {
LoggingUtils.logUnexpectedException(LOGGER, "Could not save assignments ", e);
error("Could not save assignments. Reason: " + e);
} finally {
result.recomputeStatus();
}
showResult(result);
}
public boolean isLoggedInUserPage(){
return getObjectWrapper() != null && getObjectWrapper().getObject() != null &&
StringUtils.isNotEmpty(getObjectWrapper().getObject().asObjectable().getOid()) &&
getObjectWrapper().getObject().asObjectable().getOid().equals(WebModelServiceUtils.getLoggedInUserOid());
}
}
| |
/**
* Copyright 2005 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.jbpm.workflow.instance.node;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import org.drools.core.common.InternalKnowledgeRuntime;
import org.drools.core.util.MVELSafeHelper;
import org.jbpm.process.core.Context;
import org.jbpm.process.core.ContextContainer;
import org.jbpm.process.core.context.exception.ExceptionScope;
import org.jbpm.process.core.context.variable.VariableScope;
import org.jbpm.process.core.impl.DataTransformerRegistry;
import org.jbpm.process.instance.ContextInstance;
import org.jbpm.process.instance.ContextInstanceContainer;
import org.jbpm.process.instance.ProcessInstance;
import org.jbpm.process.instance.StartProcessHelper;
import org.jbpm.process.instance.context.exception.ExceptionScopeInstance;
import org.jbpm.process.instance.context.variable.VariableScopeInstance;
import org.jbpm.process.instance.impl.ContextInstanceFactory;
import org.jbpm.process.instance.impl.ContextInstanceFactoryRegistry;
import org.jbpm.process.instance.impl.ProcessInstanceImpl;
import org.jbpm.process.instance.impl.util.VariableUtil;
import org.jbpm.workflow.core.node.DataAssociation;
import org.jbpm.workflow.core.node.SubProcessNode;
import org.jbpm.workflow.core.node.Transformation;
import org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory;
import org.jbpm.workflow.instance.impl.VariableScopeResolverFactory;
import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl;
import org.kie.api.KieBase;
import org.kie.api.definition.process.Node;
import org.kie.api.definition.process.Process;
import org.kie.api.runtime.EnvironmentName;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.api.runtime.process.DataTransformer;
import org.kie.api.runtime.process.EventListener;
import org.kie.api.runtime.process.NodeInstance;
import org.kie.internal.KieInternalServices;
import org.kie.internal.process.CorrelationAwareProcessRuntime;
import org.kie.internal.process.CorrelationKey;
import org.kie.internal.process.CorrelationKeyFactory;
import org.kie.internal.runtime.KnowledgeRuntime;
import org.kie.internal.runtime.manager.context.CaseContext;
import org.kie.internal.runtime.manager.SessionNotFoundException;
import org.kie.internal.runtime.manager.context.ProcessInstanceIdContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Runtime counterpart of a SubFlow node.
*
*/
public class SubProcessNodeInstance extends StateBasedNodeInstance implements EventListener, ContextInstanceContainer {
private static final long serialVersionUID = 510l;
private static final Logger logger = LoggerFactory.getLogger(SubProcessNodeInstance.class);
// NOTE: ContetxInstances are not persisted as current functionality (exception scope) does not require it
private Map<String, ContextInstance> contextInstances = new HashMap<String, ContextInstance>();
private Map<String, List<ContextInstance>> subContextInstances = new HashMap<String, List<ContextInstance>>();
private long processInstanceId;
protected SubProcessNode getSubProcessNode() {
return (SubProcessNode) getNode();
}
public void internalTrigger(final NodeInstance from, String type) {
super.internalTrigger(from, type);
// if node instance was cancelled, abort
if (getNodeInstanceContainer().getNodeInstance(getId()) == null) {
return;
}
if (!org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE.equals(type)) {
throw new IllegalArgumentException(
"A SubProcess node only accepts default incoming connections!");
}
Map<String, Object> parameters = new HashMap<String, Object>();
for (Iterator<DataAssociation> iterator = getSubProcessNode().getInAssociations().iterator(); iterator.hasNext(); ) {
DataAssociation mapping = iterator.next();
Object parameterValue = null;
if (mapping.getTransformation() != null) {
Transformation transformation = mapping.getTransformation();
DataTransformer transformer = DataTransformerRegistry.get().find(transformation.getLanguage());
if (transformer != null) {
parameterValue = transformer.transform(transformation.getCompiledExpression(), getSourceParameters(mapping));
}
} else {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, mapping.getSources().get(0));
if (variableScopeInstance != null) {
parameterValue = variableScopeInstance.getVariable(mapping.getSources().get(0));
} else {
try {
parameterValue = MVELSafeHelper.getEvaluator().eval(mapping.getSources().get(0), new NodeInstanceResolverFactory(this));
} catch (Throwable t) {
parameterValue = VariableUtil.resolveVariable(mapping.getSources().get(0), this);
if (parameterValue != null && !parameterValue.equals(mapping.getSources().get(0))) {
parameters.put(mapping.getTarget(), parameterValue);
} else {
logger.error("Could not find variable scope for variable {}", mapping.getSources().get(0));
logger.error("when trying to execute SubProcess node {}", getSubProcessNode().getName());
logger.error("Continuing without setting parameter.");
}
}
}
}
if (parameterValue != null) {
parameters.put(mapping.getTarget(),parameterValue);
}
}
String processId = getSubProcessNode().getProcessId();
if (processId == null) {
// if process id is not given try with process name
processId = getSubProcessNode().getProcessName();
}
// resolve processId if necessary
Map<String, String> replacements = new HashMap<String, String>();
Matcher matcher = PARAMETER_MATCHER.matcher(processId);
while (matcher.find()) {
String paramName = matcher.group(1);
if (replacements.get(paramName) == null) {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, paramName);
if (variableScopeInstance != null) {
Object variableValue = variableScopeInstance.getVariable(paramName);
String variableValueString = variableValue == null ? "" : variableValue.toString();
replacements.put(paramName, variableValueString);
} else {
try {
Object variableValue = MVELSafeHelper.getEvaluator().eval(paramName, new NodeInstanceResolverFactory(this));
String variableValueString = variableValue == null ? "" : variableValue.toString();
replacements.put(paramName, variableValueString);
} catch (Throwable t) {
logger.error("Could not find variable scope for variable {}", paramName);
logger.error("when trying to replace variable in processId for sub process {}", getNodeName());
logger.error("Continuing without setting process id.");
}
}
}
}
for (Map.Entry<String, String> replacement: replacements.entrySet()) {
processId = processId.replace("#{" + replacement.getKey() + "}", replacement.getValue());
}
KieBase kbase = ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime().getKieBase();
// start process instance
Process process = kbase.getProcess(processId);
if (process == null) {
// try to find it by name
String latestProcessId = StartProcessHelper.findLatestProcessByName(kbase, processId);
if (latestProcessId != null) {
processId = latestProcessId;
process = kbase.getProcess(processId);
}
}
if (process == null) {
logger.error("Could not find process {}", processId);
logger.error("Aborting process");
((ProcessInstance) getProcessInstance()).setState(ProcessInstance.STATE_ABORTED);
throw new RuntimeException("Could not find process " + processId);
} else {
KnowledgeRuntime kruntime = ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime();
RuntimeManager manager = (RuntimeManager) kruntime.getEnvironment().get(EnvironmentName.RUNTIME_MANAGER);
if (manager != null) {
org.kie.api.runtime.manager.Context<?> context = ProcessInstanceIdContext.get();
String caseId = (String) kruntime.getEnvironment().get(EnvironmentName.CASE_ID);
if (caseId != null) {
context = CaseContext.get(caseId);
}
RuntimeEngine runtime = manager.getRuntimeEngine(context);
kruntime = (KnowledgeRuntime) runtime.getKieSession();
}
if (getSubProcessNode().getMetaData("MICollectionInput") != null) {
// remove foreach input variable to avoid problems when running in variable strict mode
parameters.remove(getSubProcessNode().getMetaData("MICollectionInput"));
}
ProcessInstance processInstance = null;
if (((WorkflowProcessInstanceImpl)getProcessInstance()).getCorrelationKey() != null) {
// in case there is correlation key on parent instance pass it along to child so it can be easily correlated
// since correlation key must be unique for active instances it appends processId and timestamp
List<String> businessKeys = new ArrayList<String>();
businessKeys.add(((WorkflowProcessInstanceImpl)getProcessInstance()).getCorrelationKey());
businessKeys.add(processId);
businessKeys.add(String.valueOf(System.currentTimeMillis()));
CorrelationKeyFactory correlationKeyFactory = KieInternalServices.Factory.get().newCorrelationKeyFactory();
CorrelationKey subProcessCorrelationKey = correlationKeyFactory.newCorrelationKey(businessKeys);
processInstance = (ProcessInstance) ((CorrelationAwareProcessRuntime)kruntime).createProcessInstance(processId, subProcessCorrelationKey, parameters);
} else {
processInstance = ( ProcessInstance ) kruntime.createProcessInstance(processId, parameters);
}
this.processInstanceId = processInstance.getId();
((ProcessInstanceImpl) processInstance).setMetaData("ParentProcessInstanceId", getProcessInstance().getId());
((ProcessInstanceImpl) processInstance).setMetaData("ParentNodeInstanceId", getUniqueId());
((ProcessInstanceImpl) processInstance).setMetaData("ParentNodeId", getSubProcessNode().getUniqueId());
((ProcessInstanceImpl) processInstance).setParentProcessInstanceId(getProcessInstance().getId());
((ProcessInstanceImpl) processInstance).setSignalCompletion(getSubProcessNode().isWaitForCompletion());
kruntime.startProcessInstance(processInstance.getId());
if (!getSubProcessNode().isWaitForCompletion()) {
triggerCompleted();
} else if (processInstance.getState() == ProcessInstance.STATE_COMPLETED
|| processInstance.getState() == ProcessInstance.STATE_ABORTED) {
processInstanceCompleted(processInstance);
} else {
addProcessListener();
}
}
}
public void cancel() {
super.cancel();
if (getSubProcessNode() == null || !getSubProcessNode().isIndependent()) {
ProcessInstance processInstance = null;
InternalKnowledgeRuntime kruntime = ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime();
RuntimeManager manager = (RuntimeManager) kruntime.getEnvironment().get(EnvironmentName.RUNTIME_MANAGER);
if (manager != null) {
try {
org.kie.api.runtime.manager.Context<?> context = ProcessInstanceIdContext.get(processInstanceId);
String caseId = (String) kruntime.getEnvironment().get(EnvironmentName.CASE_ID);
if (caseId != null) {
context = CaseContext.get(caseId);
}
RuntimeEngine runtime = manager.getRuntimeEngine(context);
KnowledgeRuntime managedkruntime = (KnowledgeRuntime) runtime.getKieSession();
processInstance = (ProcessInstance) managedkruntime.getProcessInstance(processInstanceId);
} catch (SessionNotFoundException e) {
// in case no session is found for parent process let's skip signal for process instance completion
}
} else {
processInstance = (ProcessInstance) kruntime.getProcessInstance(processInstanceId);
}
if (processInstance != null) {
processInstance.setState(ProcessInstance.STATE_ABORTED);
}
}
}
public long getProcessInstanceId() {
return processInstanceId;
}
public void internalSetProcessInstanceId(long processInstanceId) {
this.processInstanceId = processInstanceId;
}
public void addEventListeners() {
super.addEventListeners();
addProcessListener();
}
private void addProcessListener() {
getProcessInstance().addEventListener("processInstanceCompleted:" + processInstanceId, this, true);
}
public void removeEventListeners() {
super.removeEventListeners();
getProcessInstance().removeEventListener("processInstanceCompleted:" + processInstanceId, this, true);
}
@Override
public void signalEvent(String type, Object event) {
if (("processInstanceCompleted:" + processInstanceId).equals(type)) {
processInstanceCompleted((ProcessInstance) event);
} else {
super.signalEvent(type, event);
}
}
@Override
public String[] getEventTypes() {
return new String[] { "processInstanceCompleted:" + processInstanceId };
}
public void processInstanceCompleted(ProcessInstance processInstance) {
removeEventListeners();
handleOutMappings(processInstance);
if (processInstance.getState() == ProcessInstance.STATE_ABORTED) {
String faultName = processInstance.getOutcome()==null?"":processInstance.getOutcome();
// handle exception as sub process failed with error code
ExceptionScopeInstance exceptionScopeInstance = (ExceptionScopeInstance)
resolveContextInstance(ExceptionScope.EXCEPTION_SCOPE, faultName);
if (exceptionScopeInstance != null) {
exceptionScopeInstance.handleException(faultName, processInstance.getFaultData());
cancel();
return;
} else if (!getSubProcessNode().isIndependent()){
((ProcessInstance) getProcessInstance()).setState(ProcessInstance.STATE_ABORTED, faultName);
return;
}
}
// if there were no exception proceed normally
triggerCompleted();
}
private void handleOutMappings(ProcessInstance processInstance) {
VariableScopeInstance subProcessVariableScopeInstance = (VariableScopeInstance)
processInstance.getContextInstance(VariableScope.VARIABLE_SCOPE);
SubProcessNode subProcessNode = getSubProcessNode();
if (subProcessNode != null) {
for (Iterator<org.jbpm.workflow.core.node.DataAssociation> iterator= subProcessNode.getOutAssociations().iterator(); iterator.hasNext(); ) {
org.jbpm.workflow.core.node.DataAssociation mapping = iterator.next();
if (mapping.getTransformation() != null) {
Transformation transformation = mapping.getTransformation();
DataTransformer transformer = DataTransformerRegistry.get().find(transformation.getLanguage());
if (transformer != null) {
Object parameterValue = transformer.transform(transformation.getCompiledExpression(), subProcessVariableScopeInstance.getVariables());
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, mapping.getTarget());
if (variableScopeInstance != null && parameterValue != null) {
variableScopeInstance.setVariable(mapping.getTarget(), parameterValue);
} else {
logger.warn("Could not find variable scope for variable {}", mapping.getTarget());
logger.warn("Continuing without setting variable.");
}
}
} else {
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, mapping.getTarget());
if (variableScopeInstance != null) {
Object value = subProcessVariableScopeInstance.getVariable(mapping.getSources().get(0));
if (value == null) {
try {
value = MVELSafeHelper.getEvaluator().eval(mapping.getSources().get(0), new VariableScopeResolverFactory(subProcessVariableScopeInstance));
} catch (Throwable t) {
// do nothing
}
}
variableScopeInstance.setVariable(mapping.getTarget(), value);
} else {
logger.error("Could not find variable scope for variable {}", mapping.getTarget());
logger.error("when trying to complete SubProcess node {}", getSubProcessNode().getName());
logger.error("Continuing without setting variable.");
}
}
}
}
}
public String getNodeName() {
Node node = getNode();
if (node == null) {
return "[Dynamic] Sub Process";
}
return super.getNodeName();
}
@Override
public List<ContextInstance> getContextInstances(String contextId) {
return this.subContextInstances.get(contextId);
}
@Override
public void addContextInstance(String contextId, ContextInstance contextInstance) {
List<ContextInstance> list = this.subContextInstances.get(contextId);
if (list == null) {
list = new ArrayList<ContextInstance>();
this.subContextInstances.put(contextId, list);
}
list.add(contextInstance);
}
@Override
public void removeContextInstance(String contextId, ContextInstance contextInstance) {
List<ContextInstance> list = this.subContextInstances.get(contextId);
if (list != null) {
list.remove(contextInstance);
}
}
@Override
public ContextInstance getContextInstance(String contextId, long id) {
List<ContextInstance> contextInstances = subContextInstances.get(contextId);
if (contextInstances != null) {
for (ContextInstance contextInstance: contextInstances) {
if (contextInstance.getContextId() == id) {
return contextInstance;
}
}
}
return null;
}
@Override
public ContextInstance getContextInstance(Context context) {
ContextInstanceFactory conf = ContextInstanceFactoryRegistry.INSTANCE.getContextInstanceFactory(context);
if (conf == null) {
throw new IllegalArgumentException("Illegal context type (registry not found): " + context.getClass());
}
ContextInstance contextInstance = (ContextInstance) conf.getContextInstance(context, this, (ProcessInstance) getProcessInstance());
if (contextInstance == null) {
throw new IllegalArgumentException("Illegal context type (instance not found): " + context.getClass());
}
return contextInstance;
}
@Override
public ContextContainer getContextContainer() {
return getSubProcessNode();
}
protected Map<String, Object> getSourceParameters(DataAssociation association) {
Map<String, Object> parameters = new HashMap<String, Object>();
for (String sourceParam : association.getSources()) {
Object parameterValue = null;
VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
resolveContextInstance(VariableScope.VARIABLE_SCOPE, sourceParam);
if (variableScopeInstance != null) {
parameterValue = variableScopeInstance.getVariable(sourceParam);
} else {
try {
parameterValue = MVELSafeHelper.getEvaluator().eval(sourceParam, new NodeInstanceResolverFactory(this));
} catch (Throwable t) {
logger.warn("Could not find variable scope for variable {}", sourceParam);
}
}
if (parameterValue != null) {
parameters.put(association.getTarget(), parameterValue);
}
}
return parameters;
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.execution;
import com.facebook.presto.Session;
import com.facebook.presto.spi.ConnectorHandleResolver;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.FixedPageSource;
import com.facebook.presto.spi.Plugin;
import com.facebook.presto.spi.connector.Connector;
import com.facebook.presto.spi.connector.ConnectorContext;
import com.facebook.presto.spi.connector.ConnectorFactory;
import com.facebook.presto.spi.connector.ConnectorMetadata;
import com.facebook.presto.spi.connector.ConnectorPageSinkProvider;
import com.facebook.presto.spi.connector.ConnectorPageSourceProvider;
import com.facebook.presto.spi.connector.ConnectorSplitManager;
import com.facebook.presto.spi.connector.ConnectorTransactionHandle;
import com.facebook.presto.spi.transaction.IsolationLevel;
import com.facebook.presto.testing.QueryRunner;
import com.facebook.presto.testing.TestingHandleResolver;
import com.facebook.presto.testing.TestingMetadata;
import com.facebook.presto.testing.TestingPageSinkProvider;
import com.facebook.presto.testing.TestingSplitManager;
import com.facebook.presto.testing.TestingTransactionHandle;
import com.facebook.presto.tests.AbstractTestQueryFramework;
import com.facebook.presto.tests.DistributedQueryRunner;
import com.facebook.presto.tpch.TpchPlugin;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static com.facebook.presto.testing.TestingSession.testSessionBuilder;
import static java.util.Objects.requireNonNull;
import static org.testng.Assert.assertEquals;
@Test(singleThreaded = true)
public class TestBeginQuery
extends AbstractTestQueryFramework
{
private TestMetadata metadata;
protected TestBeginQuery()
{
super(TestBeginQuery::createQueryRunner);
}
private static QueryRunner createQueryRunner()
throws Exception
{
Session session = testSessionBuilder()
.setCatalog("test")
.setSchema("default")
.build();
return new DistributedQueryRunner(session, 1);
}
@BeforeClass
public void setUp()
{
metadata = new TestMetadata();
getQueryRunner().installPlugin(new TestPlugin(metadata));
getQueryRunner().installPlugin(new TpchPlugin());
getQueryRunner().createCatalog("test", "test", ImmutableMap.of());
getQueryRunner().createCatalog("tpch", "tpch", ImmutableMap.of());
}
@AfterMethod(alwaysRun = true)
public void afterMethod()
{
metadata.clear();
}
@AfterClass(alwaysRun = true)
public void tearDown()
{
metadata.clear();
metadata = null;
}
@Test
public void testCreateTableAsSelect()
{
assertNoBeginQuery("CREATE TABLE nation AS SELECT * FROM tpch.tiny.nation");
}
@Test
public void testCreateTableAsSelectSameConnector()
{
assertNoBeginQuery("CREATE TABLE nation AS SELECT * FROM tpch.tiny.nation");
assertBeginQuery("CREATE TABLE nation_copy AS SELECT * FROM nation");
}
@Test
public void testInsert()
{
assertNoBeginQuery("CREATE TABLE nation AS SELECT * FROM tpch.tiny.nation");
assertBeginQuery("INSERT INTO nation SELECT * FROM tpch.tiny.nation");
assertBeginQuery("INSERT INTO nation VALUES (12345, 'name', 54321, 'comment')");
}
@Test
public void testInsertSelectSameConnector()
{
assertNoBeginQuery("CREATE TABLE nation AS SELECT * FROM tpch.tiny.nation");
assertBeginQuery("INSERT INTO nation SELECT * FROM nation");
}
@Test
public void testSelect()
{
assertNoBeginQuery("CREATE TABLE nation AS SELECT * FROM tpch.tiny.nation");
assertBeginQuery("SELECT * FROM nation");
}
private void assertBeginQuery(String query)
{
metadata.resetCounters();
computeActual(query);
assertEquals(metadata.begin.get(), 1);
assertEquals(metadata.end.get(), 1);
metadata.resetCounters();
}
private void assertNoBeginQuery(String query)
{
metadata.resetCounters();
computeActual(query);
assertEquals(metadata.begin.get(), 0);
assertEquals(metadata.end.get(), 0);
metadata.resetCounters();
}
private static class TestPlugin
implements Plugin
{
private final TestMetadata metadata;
private TestPlugin(TestMetadata metadata)
{
this.metadata = requireNonNull(metadata, "metadata is null");
}
@Override
public Iterable<ConnectorFactory> getConnectorFactories()
{
return ImmutableList.of(new ConnectorFactory()
{
@Override
public String getName()
{
return "test";
}
@Override
public ConnectorHandleResolver getHandleResolver()
{
return new TestingHandleResolver();
}
@Override
public Connector create(String catalogName, Map<String, String> config, ConnectorContext context)
{
return new TestConnector(metadata);
}
});
}
}
private static class TestConnector
implements Connector
{
private final ConnectorMetadata metadata;
private TestConnector(ConnectorMetadata metadata)
{
this.metadata = requireNonNull(metadata, "metadata is null");
}
@Override
public ConnectorTransactionHandle beginTransaction(IsolationLevel isolationLevel, boolean readOnly)
{
return TestingTransactionHandle.create();
}
@Override
public ConnectorMetadata getMetadata(ConnectorTransactionHandle transactionHandle)
{
return metadata;
}
@Override
public ConnectorSplitManager getSplitManager()
{
return new TestingSplitManager(ImmutableList.of());
}
@Override
public ConnectorPageSourceProvider getPageSourceProvider()
{
return (transactionHandle, session, split, columns) -> new FixedPageSource(ImmutableList.of());
}
@Override
public ConnectorPageSinkProvider getPageSinkProvider()
{
return new TestingPageSinkProvider();
}
}
private static class TestMetadata
extends TestingMetadata
{
private final AtomicInteger begin = new AtomicInteger();
private final AtomicInteger end = new AtomicInteger();
@Override
public void beginQuery(ConnectorSession session)
{
begin.incrementAndGet();
}
@Override
public void cleanupQuery(ConnectorSession session)
{
end.incrementAndGet();
}
public void resetCounters()
{
begin.set(0);
end.set(0);
}
}
}
| |
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.cloudtrail.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* The settings for a trail.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/Trail" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Trail implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* Name of the trail set by calling <a>CreateTrail</a>. The maximum length is 128 characters.
* </p>
*/
private String name;
/**
* <p>
* Name of the Amazon S3 bucket into which CloudTrail delivers your trail files. See <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/create_trail_naming_policy.html">Amazon S3 Bucket
* Naming Requirements</a>.
* </p>
*/
private String s3BucketName;
/**
* <p>
* Specifies the Amazon S3 key prefix that comes after the name of the bucket you have designated for log file
* delivery. For more information, see <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-find-log-files.html">Finding Your
* CloudTrail Log Files</a>.The maximum length is 200 characters.
* </p>
*/
private String s3KeyPrefix;
/**
* <p>
* This field is deprecated. Use SnsTopicARN.
* </p>
*/
@Deprecated
private String snsTopicName;
/**
* <p>
* Specifies the ARN of the Amazon SNS topic that CloudTrail uses to send notifications when log files are
* delivered. The format of a topic ARN is:
* </p>
* <p>
* <code>arn:aws:sns:us-east-1:123456789012:MyTopic</code>
* </p>
*/
private String snsTopicARN;
/**
* <p>
* Set to <b>True</b> to include AWS API calls from AWS global services such as IAM. Otherwise, <b>False</b>.
* </p>
*/
private Boolean includeGlobalServiceEvents;
/**
* <p>
* Specifies whether the trail belongs only to one region or exists in all regions.
* </p>
*/
private Boolean isMultiRegionTrail;
/**
* <p>
* The region in which the trail was created.
* </p>
*/
private String homeRegion;
/**
* <p>
* Specifies the ARN of the trail. The format of a trail ARN is:
* </p>
* <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code>
* </p>
*/
private String trailARN;
/**
* <p>
* Specifies whether log file validation is enabled.
* </p>
*/
private Boolean logFileValidationEnabled;
/**
* <p>
* Specifies an Amazon Resource Name (ARN), a unique identifier that represents the log group to which CloudTrail
* logs will be delivered.
* </p>
*/
private String cloudWatchLogsLogGroupArn;
/**
* <p>
* Specifies the role for the CloudWatch Logs endpoint to assume to write to a user's log group.
* </p>
*/
private String cloudWatchLogsRoleArn;
/**
* <p>
* Specifies the KMS key ID that encrypts the logs delivered by CloudTrail. The value is a fully specified ARN to a
* KMS key in the format:
* </p>
* <p>
* <code>arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012</code>
* </p>
*/
private String kmsKeyId;
/**
* <p>
* Specifies if the trail has custom event selectors.
* </p>
*/
private Boolean hasCustomEventSelectors;
/**
* <p>
* Name of the trail set by calling <a>CreateTrail</a>. The maximum length is 128 characters.
* </p>
*
* @param name
* Name of the trail set by calling <a>CreateTrail</a>. The maximum length is 128 characters.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* Name of the trail set by calling <a>CreateTrail</a>. The maximum length is 128 characters.
* </p>
*
* @return Name of the trail set by calling <a>CreateTrail</a>. The maximum length is 128 characters.
*/
public String getName() {
return this.name;
}
/**
* <p>
* Name of the trail set by calling <a>CreateTrail</a>. The maximum length is 128 characters.
* </p>
*
* @param name
* Name of the trail set by calling <a>CreateTrail</a>. The maximum length is 128 characters.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withName(String name) {
setName(name);
return this;
}
/**
* <p>
* Name of the Amazon S3 bucket into which CloudTrail delivers your trail files. See <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/create_trail_naming_policy.html">Amazon S3 Bucket
* Naming Requirements</a>.
* </p>
*
* @param s3BucketName
* Name of the Amazon S3 bucket into which CloudTrail delivers your trail files. See <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/create_trail_naming_policy.html">Amazon S3
* Bucket Naming Requirements</a>.
*/
public void setS3BucketName(String s3BucketName) {
this.s3BucketName = s3BucketName;
}
/**
* <p>
* Name of the Amazon S3 bucket into which CloudTrail delivers your trail files. See <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/create_trail_naming_policy.html">Amazon S3 Bucket
* Naming Requirements</a>.
* </p>
*
* @return Name of the Amazon S3 bucket into which CloudTrail delivers your trail files. See <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/create_trail_naming_policy.html">Amazon
* S3 Bucket Naming Requirements</a>.
*/
public String getS3BucketName() {
return this.s3BucketName;
}
/**
* <p>
* Name of the Amazon S3 bucket into which CloudTrail delivers your trail files. See <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/create_trail_naming_policy.html">Amazon S3 Bucket
* Naming Requirements</a>.
* </p>
*
* @param s3BucketName
* Name of the Amazon S3 bucket into which CloudTrail delivers your trail files. See <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/create_trail_naming_policy.html">Amazon S3
* Bucket Naming Requirements</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withS3BucketName(String s3BucketName) {
setS3BucketName(s3BucketName);
return this;
}
/**
* <p>
* Specifies the Amazon S3 key prefix that comes after the name of the bucket you have designated for log file
* delivery. For more information, see <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-find-log-files.html">Finding Your
* CloudTrail Log Files</a>.The maximum length is 200 characters.
* </p>
*
* @param s3KeyPrefix
* Specifies the Amazon S3 key prefix that comes after the name of the bucket you have designated for log
* file delivery. For more information, see <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-find-log-files.html">Finding
* Your CloudTrail Log Files</a>.The maximum length is 200 characters.
*/
public void setS3KeyPrefix(String s3KeyPrefix) {
this.s3KeyPrefix = s3KeyPrefix;
}
/**
* <p>
* Specifies the Amazon S3 key prefix that comes after the name of the bucket you have designated for log file
* delivery. For more information, see <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-find-log-files.html">Finding Your
* CloudTrail Log Files</a>.The maximum length is 200 characters.
* </p>
*
* @return Specifies the Amazon S3 key prefix that comes after the name of the bucket you have designated for log
* file delivery. For more information, see <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-find-log-files.html">Finding
* Your CloudTrail Log Files</a>.The maximum length is 200 characters.
*/
public String getS3KeyPrefix() {
return this.s3KeyPrefix;
}
/**
* <p>
* Specifies the Amazon S3 key prefix that comes after the name of the bucket you have designated for log file
* delivery. For more information, see <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-find-log-files.html">Finding Your
* CloudTrail Log Files</a>.The maximum length is 200 characters.
* </p>
*
* @param s3KeyPrefix
* Specifies the Amazon S3 key prefix that comes after the name of the bucket you have designated for log
* file delivery. For more information, see <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-find-log-files.html">Finding
* Your CloudTrail Log Files</a>.The maximum length is 200 characters.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withS3KeyPrefix(String s3KeyPrefix) {
setS3KeyPrefix(s3KeyPrefix);
return this;
}
/**
* <p>
* This field is deprecated. Use SnsTopicARN.
* </p>
*
* @param snsTopicName
* This field is deprecated. Use SnsTopicARN.
*/
@Deprecated
public void setSnsTopicName(String snsTopicName) {
this.snsTopicName = snsTopicName;
}
/**
* <p>
* This field is deprecated. Use SnsTopicARN.
* </p>
*
* @return This field is deprecated. Use SnsTopicARN.
*/
@Deprecated
public String getSnsTopicName() {
return this.snsTopicName;
}
/**
* <p>
* This field is deprecated. Use SnsTopicARN.
* </p>
*
* @param snsTopicName
* This field is deprecated. Use SnsTopicARN.
* @return Returns a reference to this object so that method calls can be chained together.
*/
@Deprecated
public Trail withSnsTopicName(String snsTopicName) {
setSnsTopicName(snsTopicName);
return this;
}
/**
* <p>
* Specifies the ARN of the Amazon SNS topic that CloudTrail uses to send notifications when log files are
* delivered. The format of a topic ARN is:
* </p>
* <p>
* <code>arn:aws:sns:us-east-1:123456789012:MyTopic</code>
* </p>
*
* @param snsTopicARN
* Specifies the ARN of the Amazon SNS topic that CloudTrail uses to send notifications when log files are
* delivered. The format of a topic ARN is:</p>
* <p>
* <code>arn:aws:sns:us-east-1:123456789012:MyTopic</code>
*/
public void setSnsTopicARN(String snsTopicARN) {
this.snsTopicARN = snsTopicARN;
}
/**
* <p>
* Specifies the ARN of the Amazon SNS topic that CloudTrail uses to send notifications when log files are
* delivered. The format of a topic ARN is:
* </p>
* <p>
* <code>arn:aws:sns:us-east-1:123456789012:MyTopic</code>
* </p>
*
* @return Specifies the ARN of the Amazon SNS topic that CloudTrail uses to send notifications when log files are
* delivered. The format of a topic ARN is:</p>
* <p>
* <code>arn:aws:sns:us-east-1:123456789012:MyTopic</code>
*/
public String getSnsTopicARN() {
return this.snsTopicARN;
}
/**
* <p>
* Specifies the ARN of the Amazon SNS topic that CloudTrail uses to send notifications when log files are
* delivered. The format of a topic ARN is:
* </p>
* <p>
* <code>arn:aws:sns:us-east-1:123456789012:MyTopic</code>
* </p>
*
* @param snsTopicARN
* Specifies the ARN of the Amazon SNS topic that CloudTrail uses to send notifications when log files are
* delivered. The format of a topic ARN is:</p>
* <p>
* <code>arn:aws:sns:us-east-1:123456789012:MyTopic</code>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withSnsTopicARN(String snsTopicARN) {
setSnsTopicARN(snsTopicARN);
return this;
}
/**
* <p>
* Set to <b>True</b> to include AWS API calls from AWS global services such as IAM. Otherwise, <b>False</b>.
* </p>
*
* @param includeGlobalServiceEvents
* Set to <b>True</b> to include AWS API calls from AWS global services such as IAM. Otherwise, <b>False</b>.
*/
public void setIncludeGlobalServiceEvents(Boolean includeGlobalServiceEvents) {
this.includeGlobalServiceEvents = includeGlobalServiceEvents;
}
/**
* <p>
* Set to <b>True</b> to include AWS API calls from AWS global services such as IAM. Otherwise, <b>False</b>.
* </p>
*
* @return Set to <b>True</b> to include AWS API calls from AWS global services such as IAM. Otherwise,
* <b>False</b>.
*/
public Boolean getIncludeGlobalServiceEvents() {
return this.includeGlobalServiceEvents;
}
/**
* <p>
* Set to <b>True</b> to include AWS API calls from AWS global services such as IAM. Otherwise, <b>False</b>.
* </p>
*
* @param includeGlobalServiceEvents
* Set to <b>True</b> to include AWS API calls from AWS global services such as IAM. Otherwise, <b>False</b>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withIncludeGlobalServiceEvents(Boolean includeGlobalServiceEvents) {
setIncludeGlobalServiceEvents(includeGlobalServiceEvents);
return this;
}
/**
* <p>
* Set to <b>True</b> to include AWS API calls from AWS global services such as IAM. Otherwise, <b>False</b>.
* </p>
*
* @return Set to <b>True</b> to include AWS API calls from AWS global services such as IAM. Otherwise,
* <b>False</b>.
*/
public Boolean isIncludeGlobalServiceEvents() {
return this.includeGlobalServiceEvents;
}
/**
* <p>
* Specifies whether the trail belongs only to one region or exists in all regions.
* </p>
*
* @param isMultiRegionTrail
* Specifies whether the trail belongs only to one region or exists in all regions.
*/
public void setIsMultiRegionTrail(Boolean isMultiRegionTrail) {
this.isMultiRegionTrail = isMultiRegionTrail;
}
/**
* <p>
* Specifies whether the trail belongs only to one region or exists in all regions.
* </p>
*
* @return Specifies whether the trail belongs only to one region or exists in all regions.
*/
public Boolean getIsMultiRegionTrail() {
return this.isMultiRegionTrail;
}
/**
* <p>
* Specifies whether the trail belongs only to one region or exists in all regions.
* </p>
*
* @param isMultiRegionTrail
* Specifies whether the trail belongs only to one region or exists in all regions.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withIsMultiRegionTrail(Boolean isMultiRegionTrail) {
setIsMultiRegionTrail(isMultiRegionTrail);
return this;
}
/**
* <p>
* Specifies whether the trail belongs only to one region or exists in all regions.
* </p>
*
* @return Specifies whether the trail belongs only to one region or exists in all regions.
*/
public Boolean isMultiRegionTrail() {
return this.isMultiRegionTrail;
}
/**
* <p>
* The region in which the trail was created.
* </p>
*
* @param homeRegion
* The region in which the trail was created.
*/
public void setHomeRegion(String homeRegion) {
this.homeRegion = homeRegion;
}
/**
* <p>
* The region in which the trail was created.
* </p>
*
* @return The region in which the trail was created.
*/
public String getHomeRegion() {
return this.homeRegion;
}
/**
* <p>
* The region in which the trail was created.
* </p>
*
* @param homeRegion
* The region in which the trail was created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withHomeRegion(String homeRegion) {
setHomeRegion(homeRegion);
return this;
}
/**
* <p>
* Specifies the ARN of the trail. The format of a trail ARN is:
* </p>
* <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code>
* </p>
*
* @param trailARN
* Specifies the ARN of the trail. The format of a trail ARN is:</p>
* <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code>
*/
public void setTrailARN(String trailARN) {
this.trailARN = trailARN;
}
/**
* <p>
* Specifies the ARN of the trail. The format of a trail ARN is:
* </p>
* <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code>
* </p>
*
* @return Specifies the ARN of the trail. The format of a trail ARN is:</p>
* <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code>
*/
public String getTrailARN() {
return this.trailARN;
}
/**
* <p>
* Specifies the ARN of the trail. The format of a trail ARN is:
* </p>
* <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code>
* </p>
*
* @param trailARN
* Specifies the ARN of the trail. The format of a trail ARN is:</p>
* <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withTrailARN(String trailARN) {
setTrailARN(trailARN);
return this;
}
/**
* <p>
* Specifies whether log file validation is enabled.
* </p>
*
* @param logFileValidationEnabled
* Specifies whether log file validation is enabled.
*/
public void setLogFileValidationEnabled(Boolean logFileValidationEnabled) {
this.logFileValidationEnabled = logFileValidationEnabled;
}
/**
* <p>
* Specifies whether log file validation is enabled.
* </p>
*
* @return Specifies whether log file validation is enabled.
*/
public Boolean getLogFileValidationEnabled() {
return this.logFileValidationEnabled;
}
/**
* <p>
* Specifies whether log file validation is enabled.
* </p>
*
* @param logFileValidationEnabled
* Specifies whether log file validation is enabled.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withLogFileValidationEnabled(Boolean logFileValidationEnabled) {
setLogFileValidationEnabled(logFileValidationEnabled);
return this;
}
/**
* <p>
* Specifies whether log file validation is enabled.
* </p>
*
* @return Specifies whether log file validation is enabled.
*/
public Boolean isLogFileValidationEnabled() {
return this.logFileValidationEnabled;
}
/**
* <p>
* Specifies an Amazon Resource Name (ARN), a unique identifier that represents the log group to which CloudTrail
* logs will be delivered.
* </p>
*
* @param cloudWatchLogsLogGroupArn
* Specifies an Amazon Resource Name (ARN), a unique identifier that represents the log group to which
* CloudTrail logs will be delivered.
*/
public void setCloudWatchLogsLogGroupArn(String cloudWatchLogsLogGroupArn) {
this.cloudWatchLogsLogGroupArn = cloudWatchLogsLogGroupArn;
}
/**
* <p>
* Specifies an Amazon Resource Name (ARN), a unique identifier that represents the log group to which CloudTrail
* logs will be delivered.
* </p>
*
* @return Specifies an Amazon Resource Name (ARN), a unique identifier that represents the log group to which
* CloudTrail logs will be delivered.
*/
public String getCloudWatchLogsLogGroupArn() {
return this.cloudWatchLogsLogGroupArn;
}
/**
* <p>
* Specifies an Amazon Resource Name (ARN), a unique identifier that represents the log group to which CloudTrail
* logs will be delivered.
* </p>
*
* @param cloudWatchLogsLogGroupArn
* Specifies an Amazon Resource Name (ARN), a unique identifier that represents the log group to which
* CloudTrail logs will be delivered.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withCloudWatchLogsLogGroupArn(String cloudWatchLogsLogGroupArn) {
setCloudWatchLogsLogGroupArn(cloudWatchLogsLogGroupArn);
return this;
}
/**
* <p>
* Specifies the role for the CloudWatch Logs endpoint to assume to write to a user's log group.
* </p>
*
* @param cloudWatchLogsRoleArn
* Specifies the role for the CloudWatch Logs endpoint to assume to write to a user's log group.
*/
public void setCloudWatchLogsRoleArn(String cloudWatchLogsRoleArn) {
this.cloudWatchLogsRoleArn = cloudWatchLogsRoleArn;
}
/**
* <p>
* Specifies the role for the CloudWatch Logs endpoint to assume to write to a user's log group.
* </p>
*
* @return Specifies the role for the CloudWatch Logs endpoint to assume to write to a user's log group.
*/
public String getCloudWatchLogsRoleArn() {
return this.cloudWatchLogsRoleArn;
}
/**
* <p>
* Specifies the role for the CloudWatch Logs endpoint to assume to write to a user's log group.
* </p>
*
* @param cloudWatchLogsRoleArn
* Specifies the role for the CloudWatch Logs endpoint to assume to write to a user's log group.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withCloudWatchLogsRoleArn(String cloudWatchLogsRoleArn) {
setCloudWatchLogsRoleArn(cloudWatchLogsRoleArn);
return this;
}
/**
* <p>
* Specifies the KMS key ID that encrypts the logs delivered by CloudTrail. The value is a fully specified ARN to a
* KMS key in the format:
* </p>
* <p>
* <code>arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012</code>
* </p>
*
* @param kmsKeyId
* Specifies the KMS key ID that encrypts the logs delivered by CloudTrail. The value is a fully specified
* ARN to a KMS key in the format:</p>
* <p>
* <code>arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012</code>
*/
public void setKmsKeyId(String kmsKeyId) {
this.kmsKeyId = kmsKeyId;
}
/**
* <p>
* Specifies the KMS key ID that encrypts the logs delivered by CloudTrail. The value is a fully specified ARN to a
* KMS key in the format:
* </p>
* <p>
* <code>arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012</code>
* </p>
*
* @return Specifies the KMS key ID that encrypts the logs delivered by CloudTrail. The value is a fully specified
* ARN to a KMS key in the format:</p>
* <p>
* <code>arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012</code>
*/
public String getKmsKeyId() {
return this.kmsKeyId;
}
/**
* <p>
* Specifies the KMS key ID that encrypts the logs delivered by CloudTrail. The value is a fully specified ARN to a
* KMS key in the format:
* </p>
* <p>
* <code>arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012</code>
* </p>
*
* @param kmsKeyId
* Specifies the KMS key ID that encrypts the logs delivered by CloudTrail. The value is a fully specified
* ARN to a KMS key in the format:</p>
* <p>
* <code>arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012</code>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withKmsKeyId(String kmsKeyId) {
setKmsKeyId(kmsKeyId);
return this;
}
/**
* <p>
* Specifies if the trail has custom event selectors.
* </p>
*
* @param hasCustomEventSelectors
* Specifies if the trail has custom event selectors.
*/
public void setHasCustomEventSelectors(Boolean hasCustomEventSelectors) {
this.hasCustomEventSelectors = hasCustomEventSelectors;
}
/**
* <p>
* Specifies if the trail has custom event selectors.
* </p>
*
* @return Specifies if the trail has custom event selectors.
*/
public Boolean getHasCustomEventSelectors() {
return this.hasCustomEventSelectors;
}
/**
* <p>
* Specifies if the trail has custom event selectors.
* </p>
*
* @param hasCustomEventSelectors
* Specifies if the trail has custom event selectors.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Trail withHasCustomEventSelectors(Boolean hasCustomEventSelectors) {
setHasCustomEventSelectors(hasCustomEventSelectors);
return this;
}
/**
* <p>
* Specifies if the trail has custom event selectors.
* </p>
*
* @return Specifies if the trail has custom event selectors.
*/
public Boolean isHasCustomEventSelectors() {
return this.hasCustomEventSelectors;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getS3BucketName() != null)
sb.append("S3BucketName: ").append(getS3BucketName()).append(",");
if (getS3KeyPrefix() != null)
sb.append("S3KeyPrefix: ").append(getS3KeyPrefix()).append(",");
if (getSnsTopicName() != null)
sb.append("SnsTopicName: ").append(getSnsTopicName()).append(",");
if (getSnsTopicARN() != null)
sb.append("SnsTopicARN: ").append(getSnsTopicARN()).append(",");
if (getIncludeGlobalServiceEvents() != null)
sb.append("IncludeGlobalServiceEvents: ").append(getIncludeGlobalServiceEvents()).append(",");
if (getIsMultiRegionTrail() != null)
sb.append("IsMultiRegionTrail: ").append(getIsMultiRegionTrail()).append(",");
if (getHomeRegion() != null)
sb.append("HomeRegion: ").append(getHomeRegion()).append(",");
if (getTrailARN() != null)
sb.append("TrailARN: ").append(getTrailARN()).append(",");
if (getLogFileValidationEnabled() != null)
sb.append("LogFileValidationEnabled: ").append(getLogFileValidationEnabled()).append(",");
if (getCloudWatchLogsLogGroupArn() != null)
sb.append("CloudWatchLogsLogGroupArn: ").append(getCloudWatchLogsLogGroupArn()).append(",");
if (getCloudWatchLogsRoleArn() != null)
sb.append("CloudWatchLogsRoleArn: ").append(getCloudWatchLogsRoleArn()).append(",");
if (getKmsKeyId() != null)
sb.append("KmsKeyId: ").append(getKmsKeyId()).append(",");
if (getHasCustomEventSelectors() != null)
sb.append("HasCustomEventSelectors: ").append(getHasCustomEventSelectors());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Trail == false)
return false;
Trail other = (Trail) obj;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getS3BucketName() == null ^ this.getS3BucketName() == null)
return false;
if (other.getS3BucketName() != null && other.getS3BucketName().equals(this.getS3BucketName()) == false)
return false;
if (other.getS3KeyPrefix() == null ^ this.getS3KeyPrefix() == null)
return false;
if (other.getS3KeyPrefix() != null && other.getS3KeyPrefix().equals(this.getS3KeyPrefix()) == false)
return false;
if (other.getSnsTopicName() == null ^ this.getSnsTopicName() == null)
return false;
if (other.getSnsTopicName() != null && other.getSnsTopicName().equals(this.getSnsTopicName()) == false)
return false;
if (other.getSnsTopicARN() == null ^ this.getSnsTopicARN() == null)
return false;
if (other.getSnsTopicARN() != null && other.getSnsTopicARN().equals(this.getSnsTopicARN()) == false)
return false;
if (other.getIncludeGlobalServiceEvents() == null ^ this.getIncludeGlobalServiceEvents() == null)
return false;
if (other.getIncludeGlobalServiceEvents() != null && other.getIncludeGlobalServiceEvents().equals(this.getIncludeGlobalServiceEvents()) == false)
return false;
if (other.getIsMultiRegionTrail() == null ^ this.getIsMultiRegionTrail() == null)
return false;
if (other.getIsMultiRegionTrail() != null && other.getIsMultiRegionTrail().equals(this.getIsMultiRegionTrail()) == false)
return false;
if (other.getHomeRegion() == null ^ this.getHomeRegion() == null)
return false;
if (other.getHomeRegion() != null && other.getHomeRegion().equals(this.getHomeRegion()) == false)
return false;
if (other.getTrailARN() == null ^ this.getTrailARN() == null)
return false;
if (other.getTrailARN() != null && other.getTrailARN().equals(this.getTrailARN()) == false)
return false;
if (other.getLogFileValidationEnabled() == null ^ this.getLogFileValidationEnabled() == null)
return false;
if (other.getLogFileValidationEnabled() != null && other.getLogFileValidationEnabled().equals(this.getLogFileValidationEnabled()) == false)
return false;
if (other.getCloudWatchLogsLogGroupArn() == null ^ this.getCloudWatchLogsLogGroupArn() == null)
return false;
if (other.getCloudWatchLogsLogGroupArn() != null && other.getCloudWatchLogsLogGroupArn().equals(this.getCloudWatchLogsLogGroupArn()) == false)
return false;
if (other.getCloudWatchLogsRoleArn() == null ^ this.getCloudWatchLogsRoleArn() == null)
return false;
if (other.getCloudWatchLogsRoleArn() != null && other.getCloudWatchLogsRoleArn().equals(this.getCloudWatchLogsRoleArn()) == false)
return false;
if (other.getKmsKeyId() == null ^ this.getKmsKeyId() == null)
return false;
if (other.getKmsKeyId() != null && other.getKmsKeyId().equals(this.getKmsKeyId()) == false)
return false;
if (other.getHasCustomEventSelectors() == null ^ this.getHasCustomEventSelectors() == null)
return false;
if (other.getHasCustomEventSelectors() != null && other.getHasCustomEventSelectors().equals(this.getHasCustomEventSelectors()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getS3BucketName() == null) ? 0 : getS3BucketName().hashCode());
hashCode = prime * hashCode + ((getS3KeyPrefix() == null) ? 0 : getS3KeyPrefix().hashCode());
hashCode = prime * hashCode + ((getSnsTopicName() == null) ? 0 : getSnsTopicName().hashCode());
hashCode = prime * hashCode + ((getSnsTopicARN() == null) ? 0 : getSnsTopicARN().hashCode());
hashCode = prime * hashCode + ((getIncludeGlobalServiceEvents() == null) ? 0 : getIncludeGlobalServiceEvents().hashCode());
hashCode = prime * hashCode + ((getIsMultiRegionTrail() == null) ? 0 : getIsMultiRegionTrail().hashCode());
hashCode = prime * hashCode + ((getHomeRegion() == null) ? 0 : getHomeRegion().hashCode());
hashCode = prime * hashCode + ((getTrailARN() == null) ? 0 : getTrailARN().hashCode());
hashCode = prime * hashCode + ((getLogFileValidationEnabled() == null) ? 0 : getLogFileValidationEnabled().hashCode());
hashCode = prime * hashCode + ((getCloudWatchLogsLogGroupArn() == null) ? 0 : getCloudWatchLogsLogGroupArn().hashCode());
hashCode = prime * hashCode + ((getCloudWatchLogsRoleArn() == null) ? 0 : getCloudWatchLogsRoleArn().hashCode());
hashCode = prime * hashCode + ((getKmsKeyId() == null) ? 0 : getKmsKeyId().hashCode());
hashCode = prime * hashCode + ((getHasCustomEventSelectors() == null) ? 0 : getHasCustomEventSelectors().hashCode());
return hashCode;
}
@Override
public Trail clone() {
try {
return (Trail) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.cloudtrail.model.transform.TrailMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
/**
*============================================================================
* Copyright The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC, and
* Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
*============================================================================
**/
package org.cagrid.gaards.ui.dorian.federation;
import gov.nih.nci.cagrid.common.FaultHelper;
import gov.nih.nci.cagrid.common.FaultUtil;
import gov.nih.nci.cagrid.common.Runner;
import gov.nih.nci.cagrid.common.Utils;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.gaards.authentication.client.AuthenticationServiceClient;
import org.cagrid.gaards.dorian.client.GridAdministrationClient;
import org.cagrid.gaards.dorian.common.SAMLConstants;
import org.cagrid.gaards.dorian.federation.GridUserPolicy;
import org.cagrid.gaards.dorian.federation.SAMLAttributeDescriptor;
import org.cagrid.gaards.dorian.federation.SAMLAuthenticationMethod;
import org.cagrid.gaards.dorian.federation.TrustedIdP;
import org.cagrid.gaards.dorian.stubs.types.PermissionDeniedFault;
import org.cagrid.gaards.pki.CertUtil;
import org.cagrid.gaards.ui.common.CertificatePanel;
import org.cagrid.gaards.ui.common.ProgressPanel;
import org.cagrid.gaards.ui.common.TitlePanel;
import org.cagrid.gaards.ui.dorian.DorianLookAndFeel;
import org.cagrid.gaards.ui.dorian.DorianSession;
import org.cagrid.gaards.ui.dorian.DorianSessionProvider;
import org.cagrid.grape.ApplicationComponent;
import org.cagrid.grape.GridApplication;
import org.cagrid.grape.LookAndFeel;
import org.cagrid.grape.utils.ErrorDialog;
import org.globus.gsi.GlobusCredential;
import org.oasis.wsrf.faults.BaseFaultType;
/**
* @author <A HREF="MAILTO:langella@bmi.osu.edu">Stephen Langella </A>
* @author <A HREF="MAILTO:oster@bmi.osu.edu">Scott Oster </A>
* @author <A HREF="MAILTO:hastings@bmi.osu.edu">Shannon Langella </A>
*/
public class TrustedIdPWindow extends ApplicationComponent implements DorianSessionProvider {
private static Log log = LogFactory.getLog(TrustedIdPWindow.class);
private static final long serialVersionUID = 1L;
public static final String PUBLISH_YES = "Yes";
public static final String PUBLISH_NO = "No";
public static final String PASSWORD = SAMLAuthenticationMethod.value1.getValue();
public static final String KERBEROS = SAMLAuthenticationMethod.value2.getValue();
public static final String SRP = SAMLAuthenticationMethod.value3.getValue();
public static final String HARDWARE_TOKEN = SAMLAuthenticationMethod.value4.getValue();
public static final String TLS = SAMLAuthenticationMethod.value5.getValue();
public static final String PKI = SAMLAuthenticationMethod.value6.getValue();
public static final String PGP = SAMLAuthenticationMethod.value7.getValue();
public static final String SPKI = SAMLAuthenticationMethod.value8.getValue();
public static final String XKMS = SAMLAuthenticationMethod.value9.getValue();
public static final String XML_SIGNATURE = SAMLAuthenticationMethod.value10.getValue();
public static final String UNSPECIFIED = SAMLAuthenticationMethod.value11.getValue();
private final static String INFO_PANEL = "General";
private final static String AUTHENTICATION_SERVICE = "Authentication Service";
private final static String CERTIFICATE_PANEL = "Certificate";
private final static String ATTRIBUTES_PANEL = "Attributes";
private final static String AUDIT_PANEL = "Audit";
private final static String LOCKOUT_PANEL = "Lockouts";
private JPanel mainPanel = null;
private JPanel buttonPanel = null;
private JButton updateTrustedIdP = null;
private JTabbedPane jTabbedPane = null;
private JPanel infoPanel = null;
private TrustedIdP idp = null;
private JPanel certificatePanel = null;
private CertificatePanel credPanel = null;
private boolean newTrustedIdP;
private JLabel idLabel = null;
private JTextField idpId = null;
private JLabel nameLabel = null;
private JTextField idpName = null;
private JLabel statusLabel = null;
private TrustedIdPStatusComboBox status = null;
private List<GridUserPolicy> policies = null;
private JLabel policyLabel = null;
private JComboBox userPolicy = null;
private JPanel authPanel = null;
private JLabel passwordLabel = null;
private JCheckBox passwordMethod = null;
private JCheckBox kerberosMethod = null;
private JLabel kerberosLabel = null;
private JCheckBox srpMethod = null;
private JLabel srpLabel = null;
private JCheckBox hardwareTokenMethod = null;
private JLabel tokenLabel = null;
private JCheckBox tlsMethod = null;
private JLabel tlsLabel = null;
private JCheckBox pkiMethod = null;
private JLabel pkiLabel = null;
private JCheckBox pgpMethod = null;
private JLabel pgpLabel = null;
private JCheckBox spkiMethod = null;
private JLabel spkiLabel = null;
private JCheckBox xkmsMethod = null;
private JLabel xkmsLabel = null;
private JCheckBox xmlSignatureMethod = null;
private JLabel xmlSignatureLabel = null;
private JCheckBox unspecifiedMethod = null;
private JLabel unspecifiedLabel = null;
private TrustedIdPsWindow trustedIdPsWindow = null;
private JPanel attributesPanel = null;
private JLabel userIdNamespaceLabel = null;
private JTextField userIdNamespace = null;
private JLabel userIdAttributeLabel = null;
private JTextField userIdName = null;
private JLabel firstNameAttributeNamespaceLabel = null;
private JTextField firstNameNamespace = null;
private JLabel firstNameAttributeLabel = null;
private JTextField firstName = null;
private JLabel lastNameAttributeNamespaceLabel = null;
private JLabel lastNameAttributeLabel = null;
private JLabel emailAttributeNamespaceLabel = null;
private JLabel emailAttributeLabel = null;
private JTextField lastNameNamespace = null;
private JTextField lastName = null;
private JTextField emailNamespace = null;
private JTextField email = null;
private JPanel authenticationServicePanel = null;
private JLabel displayNameLabel = null;
private JTextField displayName = null;
private JLabel authServiceUrlLabel = null;
private JTextField authenticationServiceURL = null;
private JLabel authServiceIdentityLabel = null;
private JTextField authenticationServiceIdentity = null;
private DorianSession session = null;
private JPanel titlePanel = null;
private String titleStr = null;
private String subtitleStr = null;
private FederationAuditPanel auditPanel = null;
private JPanel lockoutsWrapperPanel = null;
private IdPLockoutsPanel lockoutsPanel = null;
private ProgressPanel progressPanel = null;
private JLabel publishLabel = null;
private JComboBox publish = null;
private JButton loadLockoutsButton;
/**
* @wbp.parser.constructor
*/
public TrustedIdPWindow(DorianSession session, TrustedIdPsWindow window, List<GridUserPolicy> policies) throws Exception {
super();
this.trustedIdPsWindow = window;
this.session = session;
this.idp = new TrustedIdP();
this.newTrustedIdP = true;
this.titleStr = "Add Identity Provider";
this.subtitleStr = this.session.getHandle().getServiceURL();
this.policies = policies;
initialize();
}
/**
* This is the default constructor
*
*/
public TrustedIdPWindow(DorianSession session, TrustedIdP idp, List<GridUserPolicy> policies) throws Exception {
super();
this.session = session;
this.idp = idp;
if (this.idp.getDisplayName() != null) {
this.titleStr = this.idp.getDisplayName();
} else {
this.titleStr = this.idp.getName();
}
this.subtitleStr = idp.getAuthenticationServiceURL();
this.newTrustedIdP = false;
this.policies = policies;
initialize();
}
public DorianSession getSession() {
return this.session;
}
public class UserPolicyCaddy {
private GridUserPolicy policy;
public UserPolicyCaddy(String className) {
this.policy = new GridUserPolicy(className, "");
}
public UserPolicyCaddy(GridUserPolicy policy) {
this.policy = policy;
}
public GridUserPolicy getPolicy() {
return policy;
}
public String toString() {
return policy.getName();
}
public boolean equals(Object o) {
UserPolicyCaddy up = (UserPolicyCaddy) o;
if (this.getPolicy().getClassName().equals(up.getPolicy().getClassName())) {
return true;
} else {
return false;
}
}
public int hashCode() {
return getPolicy().hashCode();
}
}
/**
* This method initializes this
* @throws Exception
*/
private void initialize() throws Exception {
this.setContentPane(getMainPanel());
if (this.newTrustedIdP) {
this.setTitle("Add Trusted IdP");
} else {
this.setTitle(this.titleStr);
}
this.setFrameIcon(DorianLookAndFeel.getTrustedIdPIcon());
this.setSize(600, 400);
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
* @throws Exception
*/
private JPanel getMainPanel() throws Exception {
if (mainPanel == null) {
GridBagConstraints gridBagConstraints27 = new GridBagConstraints();
gridBagConstraints27.gridx = 0;
gridBagConstraints27.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints27.weightx = 1.0D;
gridBagConstraints27.weighty = 0.0D;
gridBagConstraints27.anchor = GridBagConstraints.SOUTH;
gridBagConstraints27.gridy = 3;
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.weightx = 1.0D;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.gridy = 0;
GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
gridBagConstraints4.fill = GridBagConstraints.BOTH;
gridBagConstraints4.gridy = 1;
gridBagConstraints4.weightx = 1.0;
gridBagConstraints4.weighty = 1.0D;
gridBagConstraints4.gridx = 0;
GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
gridBagConstraints2.gridx = 0;
gridBagConstraints2.weightx = 1.0D;
gridBagConstraints2.gridy = 2;
gridBagConstraints2.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints2.anchor = java.awt.GridBagConstraints.SOUTH;
gridBagConstraints2.fill = java.awt.GridBagConstraints.HORIZONTAL;
mainPanel.add(getJTabbedPane(), gridBagConstraints4);
mainPanel.add(getButtonPanel(), gridBagConstraints2);
mainPanel.add(getTitlePanel(), gridBagConstraints);
mainPanel.add(getProgressPanel(), gridBagConstraints27);
}
return mainPanel;
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
*/
private JPanel getButtonPanel() {
if (buttonPanel == null) {
buttonPanel = new JPanel();
buttonPanel.add(getUpdateTrustedIdP(), null);
}
return buttonPanel;
}
/**
* This method initializes manageUser
*
* @return javax.swing.JButton
*/
private JButton getUpdateTrustedIdP() {
if (updateTrustedIdP == null) {
updateTrustedIdP = new JButton();
if (this.newTrustedIdP) {
updateTrustedIdP.setText("Add");
} else {
updateTrustedIdP.setText("Update");
}
updateTrustedIdP.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
getUpdateTrustedIdP().setEnabled(false);
Runner runner = new Runner() {
public void execute() {
updateTrustedIdP();
}
};
try {
GridApplication.getContext().executeInBackground(runner);
} catch (Exception t) {
t.getMessage();
}
}
});
}
return updateTrustedIdP;
}
private void updateTrustedIdP() {
if (newTrustedIdP) {
getProgressPanel().showProgress("Adding IdP...");
} else {
getProgressPanel().showProgress("Updating IdP...");
}
try {
if (getCredPanel().getCertificate() != null) {
idp.setIdPCertificate(CertUtil.writeCertificate(getCredPanel().getCertificate()));
}
idp.setName(getIdPName().getText().trim());
idp.setDisplayName(Utils.clean(getDisplayName().getText()));
idp.setAuthenticationServiceURL(getAuthenticationServiceURL().getText());
idp.setAuthenticationServiceIdentity(getAuthenticationServiceIdentity().getText());
idp.setStatus(getStatus().getSelectedStatus());
idp.setUserPolicyClass(((UserPolicyCaddy) getUserPolicy().getSelectedItem()).getPolicy().getClassName());
List<SAMLAuthenticationMethod> authMethod = new ArrayList<SAMLAuthenticationMethod>();
if (getPasswordMethod().isSelected()) {
authMethod.add(SAMLAuthenticationMethod.fromValue(PASSWORD));
}
if (getKerberosMethod().isSelected()) {
authMethod.add(SAMLAuthenticationMethod.fromValue(KERBEROS));
}
if (getSrpMethod().isSelected()) {
authMethod.add(SAMLAuthenticationMethod.fromValue(SRP));
}
if (getHardwareTokenMethod().isSelected()) {
authMethod.add(SAMLAuthenticationMethod.fromValue(HARDWARE_TOKEN));
}
if (getTlsMethod().isSelected()) {
authMethod.add(SAMLAuthenticationMethod.fromValue(TLS));
}
if (getPkiMethod().isSelected()) {
authMethod.add(SAMLAuthenticationMethod.fromValue(PKI));
}
if (getPgpMethod().isSelected()) {
authMethod.add(SAMLAuthenticationMethod.fromValue(PGP));
}
if (getSpkiMethod().isSelected()) {
authMethod.add(SAMLAuthenticationMethod.fromValue(SPKI));
}
if (getXkmsMethod().isSelected()) {
authMethod.add(SAMLAuthenticationMethod.fromValue(XKMS));
}
if (getXmlSignatureMethod().isSelected()) {
authMethod.add(SAMLAuthenticationMethod.fromValue(XML_SIGNATURE));
}
if (getUnspecifiedMethod().isSelected()) {
authMethod.add(SAMLAuthenticationMethod.fromValue(UNSPECIFIED));
}
SAMLAuthenticationMethod[] saml = new SAMLAuthenticationMethod[authMethod.size()];
for (int i = 0; i < authMethod.size(); i++) {
saml[i] = authMethod.get(i);
}
idp.setAuthenticationMethod(saml);
SAMLAttributeDescriptor uidDes = new SAMLAttributeDescriptor();
uidDes.setNamespaceURI(Utils.clean(this.getUserIdNamespace().getText()));
uidDes.setName(Utils.clean(this.getUserIdName().getText()));
idp.setUserIdAttributeDescriptor(uidDes);
SAMLAttributeDescriptor firstNameDes = new SAMLAttributeDescriptor();
firstNameDes.setNamespaceURI(Utils.clean(this.getFirstNameNamespace().getText()));
firstNameDes.setName(Utils.clean(this.getFirstName().getText()));
idp.setFirstNameAttributeDescriptor(firstNameDes);
SAMLAttributeDescriptor lastNameDes = new SAMLAttributeDescriptor();
lastNameDes.setNamespaceURI(Utils.clean(this.getLastNameNamespace().getText()));
lastNameDes.setName(Utils.clean(this.getLastName().getText()));
idp.setLastNameAttributeDescriptor(lastNameDes);
SAMLAttributeDescriptor emailDes = new SAMLAttributeDescriptor();
emailDes.setNamespaceURI(Utils.clean(this.getEmailNamespace().getText()));
emailDes.setName(Utils.clean(this.getEmail().getText()));
idp.setEmailAttributeDescriptor(emailDes);
GridAdministrationClient client = this.session.getAdminClient();
if (newTrustedIdP) {
TrustedIdP returnedIdP = client.addTrustedIdP(idp);
trustedIdPsWindow.addTrustedIdP(returnedIdP);
if (doesDorianSupportPublish()) {
if (getPublish().getSelectedItem().equals(PUBLISH_YES)) {
client.setPublish(returnedIdP, true);
} else {
client.setPublish(returnedIdP, false);
}
}
getProgressPanel().stopProgress("Successfully added IdP.");
dispose();
} else {
client.updateTrustedIdP(idp);
if (doesDorianSupportPublish()) {
if (getPublish().getSelectedItem().equals(PUBLISH_YES)) {
client.setPublish(idp, true);
} else {
client.setPublish(idp, false);
}
}
getProgressPanel().stopProgress("Successfully updated IdP.");
}
} catch (PermissionDeniedFault pdf) {
FaultUtil.logFault(log, pdf);
getProgressPanel().stopProgress("Error");
ErrorDialog.showError(pdf);
} catch (Exception e) {
FaultUtil.logFault(log, e);
getProgressPanel().stopProgress("Error");
ErrorDialog.showError(e);
} finally {
getUpdateTrustedIdP().setEnabled(true);
}
}
/**
* This method initializes jTabbedPane
*
* @return javax.swing.JTabbedPane
* @throws Exception
*/
private JTabbedPane getJTabbedPane() throws Exception {
if (jTabbedPane == null) {
jTabbedPane = new JTabbedPane();
jTabbedPane.addTab(INFO_PANEL, null, getInfoPanel());
jTabbedPane.addTab(AUTHENTICATION_SERVICE, null, getAuthenticationServicePanel(), null);
jTabbedPane.addTab(CERTIFICATE_PANEL, null, getCertificatePanel(), null);
jTabbedPane.addTab(ATTRIBUTES_PANEL, null, getAttributesPanel(), null);
// can only audit an existing IdP
if (!this.newTrustedIdP) {
jTabbedPane.addTab(AUDIT_PANEL, null, getAuditPanel(), null);
}
// can only see lockouts from an existing IdP
if (!this.newTrustedIdP) {
jTabbedPane.addTab(LOCKOUT_PANEL, null, getLockoutsWrapperPanel(), null);
}
}
return jTabbedPane;
}
/**
* This method initializes infoPanel
*
* @return javax.swing.JPanel
*/
private JPanel getInfoPanel() {
if (infoPanel == null) {
infoPanel = new JPanel();
GridBagConstraints gridBagConstraints58 = new GridBagConstraints();
gridBagConstraints58.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints58.gridy = 2;
gridBagConstraints58.weightx = 1.0;
gridBagConstraints58.insets = new Insets(2, 2, 2, 2);
gridBagConstraints58.anchor = GridBagConstraints.WEST;
gridBagConstraints58.gridx = 1;
GridBagConstraints gbc_displayNameLabel = new GridBagConstraints();
gbc_displayNameLabel.gridx = 0;
gbc_displayNameLabel.insets = new Insets(2, 2, 2, 2);
gbc_displayNameLabel.anchor = GridBagConstraints.WEST;
gbc_displayNameLabel.gridy = 2;
displayNameLabel = new JLabel();
displayNameLabel.setText("Display Name");
GridBagConstraints gridBagConstraints13 = new GridBagConstraints();
gridBagConstraints13.gridx = 0;
gridBagConstraints13.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints13.gridwidth = 2;
gridBagConstraints13.weightx = 1.0D;
gridBagConstraints13.weighty = 1.0D;
gridBagConstraints13.insets = new java.awt.Insets(5, 5, 5, 5);
gridBagConstraints13.gridy = 5;
GridBagConstraints gridBagConstraints12 = new GridBagConstraints();
gridBagConstraints12.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints12.gridy = 4;
gridBagConstraints12.weightx = 1.0;
gridBagConstraints12.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints12.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints12.gridx = 1;
GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
gridBagConstraints11.gridx = 0;
gridBagConstraints11.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints11.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints11.gridy = 4;
policyLabel = new JLabel();
policyLabel.setText("User Policy");
GridBagConstraints gridBagConstraints10 = new GridBagConstraints();
gridBagConstraints10.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints10.gridy = 3;
gridBagConstraints10.weightx = 1.0;
gridBagConstraints10.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints10.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints10.gridx = 1;
GridBagConstraints gridBagConstraints9 = new GridBagConstraints();
gridBagConstraints9.gridx = 0;
gridBagConstraints9.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints9.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints9.gridy = 3;
statusLabel = new JLabel();
statusLabel.setText("Status");
GridBagConstraints gridBagConstraints8 = new GridBagConstraints();
gridBagConstraints8.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints8.gridy = 1;
gridBagConstraints8.weightx = 1.0;
gridBagConstraints8.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints8.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints8.gridx = 1;
GridBagConstraints gridBagConstraints7 = new GridBagConstraints();
gridBagConstraints7.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints7.gridy = 1;
gridBagConstraints7.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints7.gridx = 0;
nameLabel = new JLabel();
nameLabel.setText("Name");
nameLabel.setName("Name");
GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
gridBagConstraints6.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints6.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints6.gridx = 1;
gridBagConstraints6.gridy = 0;
gridBagConstraints6.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints6.weightx = 1.0;
GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
gridBagConstraints5.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints5.gridy = 0;
gridBagConstraints5.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints5.gridx = 0;
idLabel = new JLabel();
idLabel.setText("IdP Id");
infoPanel.setLayout(new GridBagLayout());
infoPanel.setName(INFO_PANEL);
infoPanel.add(getStatus(), gridBagConstraints10);
infoPanel.add(statusLabel, gridBagConstraints9);
infoPanel.add(idLabel, gridBagConstraints5);
infoPanel.add(getIdpId(), gridBagConstraints6);
infoPanel.add(nameLabel, gridBagConstraints7);
infoPanel.add(getIdPName(), gridBagConstraints8);
infoPanel.add(policyLabel, gridBagConstraints11);
infoPanel.add(getUserPolicy(), gridBagConstraints12);
infoPanel.add(getAuthPanel(), gridBagConstraints13);
infoPanel.add(displayNameLabel, gbc_displayNameLabel);
infoPanel.add(getDisplayName(), gridBagConstraints58);
}
return infoPanel;
}
/**
* This method initializes certificatePanel
*
* @return javax.swing.JPanel
*/
private JPanel getCertificatePanel() {
if (certificatePanel == null) {
certificatePanel = new JPanel();
GridBagConstraints gridBagConstraints40 = new GridBagConstraints();
gridBagConstraints40.gridx = 0;
gridBagConstraints40.ipadx = 208;
gridBagConstraints40.weightx = 1.0D;
gridBagConstraints40.weighty = 1.0D;
gridBagConstraints40.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints40.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints40.gridy = 0;
certificatePanel.setLayout(new GridBagLayout());
certificatePanel.add(getCredPanel(), gridBagConstraints40);
}
return certificatePanel;
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
*/
private CertificatePanel getCredPanel() {
if (credPanel == null) {
try {
credPanel = new CertificatePanel();
if (idp.getIdPCertificate() != null) {
credPanel.setCertificate(CertUtil.loadCertificate(idp.getIdPCertificate()));
}
} catch (Exception e) {
FaultUtil.logFault(log, e);
}
}
return credPanel;
}
/**
* This method initializes idpId
*
* @return javax.swing.JTextField
*/
private JTextField getIdpId() {
if (idpId == null) {
idpId = new JTextField();
idpId.setEditable(false);
if (!newTrustedIdP) {
idpId.setText(String.valueOf(idp.getId()));
}
}
return idpId;
}
/**
* This method initializes idPName
*
* @return javax.swing.JTextField
*/
private JTextField getIdPName() {
if (idpName == null) {
idpName = new JTextField();
if (!newTrustedIdP) {
idpName.setText(idp.getName());
if (!this.newTrustedIdP) {
idpName.setEditable(false);
}
}
}
return idpName;
}
/**
* This method initializes status
*
* @return javax.swing.JComboBox
*/
private TrustedIdPStatusComboBox getStatus() {
if (status == null) {
status = new TrustedIdPStatusComboBox();
if (!newTrustedIdP) {
status.setSelectedItem(idp.getStatus());
}
}
return status;
}
/**
* This method initializes userPolicy
*
* @return javax.swing.JComboBox
*/
private JComboBox getUserPolicy() {
if (userPolicy == null) {
userPolicy = new JComboBox();
for (int i = 0; i < policies.size(); i++) {
userPolicy.addItem(new UserPolicyCaddy(policies.get(i)));
if (!newTrustedIdP) {
if (idp.getUserPolicyClass().equals(policies.get(i).getClassName())) {
int count = userPolicy.getItemCount();
userPolicy.setSelectedIndex((count - 1));
}
}
}
}
return userPolicy;
}
/**
* This method initializes authPanel
*
* @return javax.swing.JPanel
*/
private JPanel getAuthPanel() {
if (authPanel == null) {
GridBagConstraints gridBagConstraints39 = new GridBagConstraints();
gridBagConstraints39.gridx = 1;
gridBagConstraints39.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints39.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints39.gridy = 5;
unspecifiedLabel = new JLabel();
unspecifiedLabel.setText("Unspecified");
GridBagConstraints gridBagConstraints38 = new GridBagConstraints();
gridBagConstraints38.gridx = 0;
gridBagConstraints38.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints38.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints38.gridy = 5;
GridBagConstraints gridBagConstraints37 = new GridBagConstraints();
gridBagConstraints37.gridx = 3;
gridBagConstraints37.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints37.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints37.gridy = 4;
xmlSignatureLabel = new JLabel();
xmlSignatureLabel.setText("XML Digital Signature");
GridBagConstraints gridBagConstraints35 = new GridBagConstraints();
gridBagConstraints35.gridx = 2;
gridBagConstraints35.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints35.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints35.gridy = 4;
GridBagConstraints gridBagConstraints34 = new GridBagConstraints();
gridBagConstraints34.gridx = 1;
gridBagConstraints34.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints34.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints34.gridy = 4;
xkmsLabel = new JLabel();
xkmsLabel.setText("XML Key Management Specification (XKMS)");
GridBagConstraints gridBagConstraints33 = new GridBagConstraints();
gridBagConstraints33.gridx = 0;
gridBagConstraints33.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints33.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints33.gridy = 4;
GridBagConstraints gridBagConstraints32 = new GridBagConstraints();
gridBagConstraints32.gridx = 3;
gridBagConstraints32.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints32.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints32.gridy = 3;
spkiLabel = new JLabel();
spkiLabel.setText("Simple Public Key Infrastructure (SPKI)");
spkiLabel.setName("");
GridBagConstraints gridBagConstraints30 = new GridBagConstraints();
gridBagConstraints30.gridx = 2;
gridBagConstraints30.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints30.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints30.gridy = 3;
GridBagConstraints gridBagConstraints29 = new GridBagConstraints();
gridBagConstraints29.gridx = 1;
gridBagConstraints29.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints29.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints29.gridy = 3;
pgpLabel = new JLabel();
pgpLabel.setText("Pretty Good Privacy (PGP)");
GridBagConstraints gridBagConstraints26 = new GridBagConstraints();
gridBagConstraints26.gridx = 0;
gridBagConstraints26.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints26.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints26.gridy = 3;
GridBagConstraints gridBagConstraints25 = new GridBagConstraints();
gridBagConstraints25.gridx = 3;
gridBagConstraints25.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints25.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints25.gridy = 2;
pkiLabel = new JLabel();
pkiLabel.setText("X509 Public Key Infrastructure (PKI)");
GridBagConstraints gridBagConstraints24 = new GridBagConstraints();
gridBagConstraints24.gridx = 2;
gridBagConstraints24.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints24.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints24.gridy = 2;
GridBagConstraints gridBagConstraints23 = new GridBagConstraints();
gridBagConstraints23.gridx = 1;
gridBagConstraints23.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints23.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints23.gridy = 2;
tlsLabel = new JLabel();
tlsLabel.setText("Transport Layer Security (TLS)");
GridBagConstraints gridBagConstraints22 = new GridBagConstraints();
gridBagConstraints22.gridx = 0;
gridBagConstraints22.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints22.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints22.gridy = 2;
GridBagConstraints gridBagConstraints21 = new GridBagConstraints();
gridBagConstraints21.gridx = 3;
gridBagConstraints21.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints21.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints21.gridy = 1;
tokenLabel = new JLabel();
tokenLabel.setText("Hardware Token");
GridBagConstraints gridBagConstraints20 = new GridBagConstraints();
gridBagConstraints20.gridx = 2;
gridBagConstraints20.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints20.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints20.gridy = 1;
GridBagConstraints gridBagConstraints19 = new GridBagConstraints();
gridBagConstraints19.gridx = 1;
gridBagConstraints19.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints19.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints19.gridy = 1;
srpLabel = new JLabel();
srpLabel.setText("Secure Remote Password (SRP)");
srpLabel.setName("Secure Remote Password (SRP)");
GridBagConstraints gridBagConstraints18 = new GridBagConstraints();
gridBagConstraints18.gridx = 0;
gridBagConstraints18.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints18.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints18.gridy = 1;
GridBagConstraints gridBagConstraints17 = new GridBagConstraints();
gridBagConstraints17.gridx = 3;
gridBagConstraints17.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints17.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints17.gridy = 0;
kerberosLabel = new JLabel();
kerberosLabel.setText("Kerberos");
GridBagConstraints gridBagConstraints16 = new GridBagConstraints();
gridBagConstraints16.gridx = 2;
gridBagConstraints16.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints16.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints16.gridy = 0;
GridBagConstraints gridBagConstraints15 = new GridBagConstraints();
gridBagConstraints15.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints15.gridy = 0;
gridBagConstraints15.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints15.gridx = 1;
GridBagConstraints gridBagConstraints14 = new GridBagConstraints();
gridBagConstraints14.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints14.gridy = 0;
gridBagConstraints14.insets = new java.awt.Insets(2, 2, 2, 2);
gridBagConstraints14.gridx = 0;
passwordLabel = new JLabel();
passwordLabel.setText("Password");
authPanel = new JPanel();
authPanel.setLayout(new GridBagLayout());
authPanel.add(getSrpMethod(), gridBagConstraints18);
authPanel.add(getKerberosMethod(), gridBagConstraints16);
authPanel.add(kerberosLabel, gridBagConstraints17);
authPanel.add(srpLabel, gridBagConstraints19);
authPanel.add(getHardwareTokenMethod(), gridBagConstraints20);
authPanel.add(tokenLabel, gridBagConstraints21);
authPanel.add(getTlsMethod(), gridBagConstraints22);
authPanel.add(tlsLabel, gridBagConstraints23);
authPanel.add(getPkiMethod(), gridBagConstraints24);
authPanel.add(pkiLabel, gridBagConstraints25);
authPanel.add(getPgpMethod(), gridBagConstraints26);
authPanel.add(pgpLabel, gridBagConstraints29);
authPanel.add(getSpkiMethod(), gridBagConstraints30);
authPanel.add(spkiLabel, gridBagConstraints32);
authPanel.add(getXmlSignatureMethod(), gridBagConstraints35);
authPanel.add(getXkmsMethod(), gridBagConstraints33);
authPanel.add(xkmsLabel, gridBagConstraints34);
authPanel.add(xmlSignatureLabel, gridBagConstraints37);
authPanel.add(getUnspecifiedMethod(), gridBagConstraints38);
authPanel.add(unspecifiedLabel, gridBagConstraints39);
authPanel.setBorder(BorderFactory.createTitledBorder(null, "Accepted Authentication Methods",
TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, LookAndFeel
.getPanelLabelColor()));
authPanel.add(passwordLabel, gridBagConstraints15);
authPanel.add(getPasswordMethod(), gridBagConstraints14);
}
return authPanel;
}
/**
* This method initializes passwordMethod
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getPasswordMethod() {
if (passwordMethod == null) {
passwordMethod = new JCheckBox();
if (!newTrustedIdP) {
passwordMethod.setSelected(idpAcceptsMethod(PASSWORD));
}
}
return passwordMethod;
}
public boolean idpAcceptsMethod(String method) {
SAMLAuthenticationMethod[] methods = idp.getAuthenticationMethod();
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
if (methods[i].getValue().equals(method)) {
return true;
}
}
}
return false;
}
private JCheckBox getKerberosMethod() {
if (kerberosMethod == null) {
kerberosMethod = new JCheckBox();
if (!newTrustedIdP) {
kerberosMethod.setSelected(idpAcceptsMethod(KERBEROS));
}
}
return kerberosMethod;
}
private JCheckBox getSrpMethod() {
if (srpMethod == null) {
srpMethod = new JCheckBox();
if (!newTrustedIdP) {
srpMethod.setSelected(idpAcceptsMethod(SRP));
}
}
return srpMethod;
}
/**
* This method initializes hardwareTokenMethod
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getHardwareTokenMethod() {
if (hardwareTokenMethod == null) {
hardwareTokenMethod = new JCheckBox();
if (!newTrustedIdP) {
hardwareTokenMethod.setSelected(idpAcceptsMethod(HARDWARE_TOKEN));
}
}
return hardwareTokenMethod;
}
/**
* This method initializes tlsMethod
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getTlsMethod() {
if (tlsMethod == null) {
tlsMethod = new JCheckBox();
if (!newTrustedIdP) {
tlsMethod.setSelected(idpAcceptsMethod(TLS));
}
}
return tlsMethod;
}
/**
* This method initializes pkiMethod
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getPkiMethod() {
if (pkiMethod == null) {
pkiMethod = new JCheckBox();
if (!newTrustedIdP) {
pkiMethod.setSelected(idpAcceptsMethod(PKI));
}
}
return pkiMethod;
}
/**
* This method initializes pgpMethod
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getPgpMethod() {
if (pgpMethod == null) {
pgpMethod = new JCheckBox();
if (!newTrustedIdP) {
pgpMethod.setSelected(idpAcceptsMethod(PGP));
}
}
return pgpMethod;
}
/**
* This method initializes spkiMethod
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getSpkiMethod() {
if (spkiMethod == null) {
spkiMethod = new JCheckBox();
if (!newTrustedIdP) {
spkiMethod.setSelected(idpAcceptsMethod(SPKI));
}
}
return spkiMethod;
}
/**
* This method initializes xkmsMethod
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getXkmsMethod() {
if (xkmsMethod == null) {
xkmsMethod = new JCheckBox();
if (!newTrustedIdP) {
xkmsMethod.setSelected(idpAcceptsMethod(XKMS));
}
}
return xkmsMethod;
}
/**
* This method initializes xmlSignatureLabel
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getXmlSignatureMethod() {
if (xmlSignatureMethod == null) {
xmlSignatureMethod = new JCheckBox();
if (!newTrustedIdP) {
xmlSignatureMethod.setSelected(idpAcceptsMethod(XML_SIGNATURE));
}
}
return xmlSignatureMethod;
}
/**
* This method initializes unspecifiedMethod
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getUnspecifiedMethod() {
if (unspecifiedMethod == null) {
unspecifiedMethod = new JCheckBox();
if (!newTrustedIdP) {
unspecifiedMethod.setSelected(idpAcceptsMethod(UNSPECIFIED));
}
}
return unspecifiedMethod;
}
/**
* This method initializes attributesPanel
*
* @return javax.swing.JPanel
*/
private JPanel getAttributesPanel() {
if (attributesPanel == null) {
attributesPanel = new JPanel();
GridBagConstraints gridBagConstraints56 = new GridBagConstraints();
gridBagConstraints56.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints56.gridy = 7;
gridBagConstraints56.weightx = 1.0;
gridBagConstraints56.anchor = GridBagConstraints.WEST;
gridBagConstraints56.insets = new Insets(2, 2, 2, 2);
gridBagConstraints56.gridx = 1;
GridBagConstraints gridBagConstraints55 = new GridBagConstraints();
gridBagConstraints55.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints55.gridy = 6;
gridBagConstraints55.weightx = 1.0;
gridBagConstraints55.anchor = GridBagConstraints.WEST;
gridBagConstraints55.insets = new Insets(2, 2, 2, 2);
gridBagConstraints55.gridx = 1;
GridBagConstraints gridBagConstraints54 = new GridBagConstraints();
gridBagConstraints54.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints54.gridy = 5;
gridBagConstraints54.weightx = 1.0;
gridBagConstraints54.anchor = GridBagConstraints.WEST;
gridBagConstraints54.insets = new Insets(2, 2, 2, 2);
gridBagConstraints54.gridx = 1;
GridBagConstraints gridBagConstraints53 = new GridBagConstraints();
gridBagConstraints53.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints53.gridy = 4;
gridBagConstraints53.weightx = 1.0;
gridBagConstraints53.anchor = GridBagConstraints.WEST;
gridBagConstraints53.insets = new Insets(2, 2, 2, 2);
gridBagConstraints53.gridx = 1;
GridBagConstraints gbc_emailAttributeLabel = new GridBagConstraints();
gbc_emailAttributeLabel.gridx = 0;
gbc_emailAttributeLabel.insets = new Insets(2, 2, 2, 2);
gbc_emailAttributeLabel.anchor = GridBagConstraints.WEST;
gbc_emailAttributeLabel.gridy = 7;
emailAttributeLabel = new JLabel();
emailAttributeLabel.setText("Email Attribute");
GridBagConstraints gbc_emailAttributeNamespaceLabel = new GridBagConstraints();
gbc_emailAttributeNamespaceLabel.gridx = 0;
gbc_emailAttributeNamespaceLabel.anchor = GridBagConstraints.WEST;
gbc_emailAttributeNamespaceLabel.insets = new Insets(2, 2, 2, 2);
gbc_emailAttributeNamespaceLabel.gridy = 6;
emailAttributeNamespaceLabel = new JLabel();
emailAttributeNamespaceLabel.setText("Email Attribute Namespace");
GridBagConstraints gbc_lastNameAttributeLabel = new GridBagConstraints();
gbc_lastNameAttributeLabel.gridx = 0;
gbc_lastNameAttributeLabel.anchor = GridBagConstraints.WEST;
gbc_lastNameAttributeLabel.insets = new Insets(2, 2, 2, 2);
gbc_lastNameAttributeLabel.gridy = 5;
lastNameAttributeLabel = new JLabel();
lastNameAttributeLabel.setText("Last Name Attribute");
GridBagConstraints gbc_lastNameAttributeNamespaceLabel = new GridBagConstraints();
gbc_lastNameAttributeNamespaceLabel.gridx = 0;
gbc_lastNameAttributeNamespaceLabel.anchor = GridBagConstraints.WEST;
gbc_lastNameAttributeNamespaceLabel.insets = new Insets(2, 2, 2, 2);
gbc_lastNameAttributeNamespaceLabel.gridy = 4;
lastNameAttributeNamespaceLabel = new JLabel();
lastNameAttributeNamespaceLabel.setText("Last Name Attribute Namespace");
GridBagConstraints gridBagConstraints48 = new GridBagConstraints();
gridBagConstraints48.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints48.gridy = 3;
gridBagConstraints48.weightx = 1.0;
gridBagConstraints48.anchor = GridBagConstraints.WEST;
gridBagConstraints48.insets = new Insets(2, 2, 2, 2);
gridBagConstraints48.gridx = 1;
GridBagConstraints gbc_firstNameAttributeLabel = new GridBagConstraints();
gbc_firstNameAttributeLabel.gridx = 0;
gbc_firstNameAttributeLabel.anchor = GridBagConstraints.WEST;
gbc_firstNameAttributeLabel.insets = new Insets(2, 2, 2, 2);
gbc_firstNameAttributeLabel.gridy = 3;
firstNameAttributeLabel = new JLabel();
firstNameAttributeLabel.setText("First Name Attribute");
GridBagConstraints gridBagConstraints46 = new GridBagConstraints();
gridBagConstraints46.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints46.gridx = 1;
gridBagConstraints46.gridy = 2;
gridBagConstraints46.anchor = GridBagConstraints.WEST;
gridBagConstraints46.insets = new Insets(2, 2, 2, 2);
gridBagConstraints46.weightx = 1.0;
GridBagConstraints gbc_firstNameAttributeNamespaceLabel = new GridBagConstraints();
gbc_firstNameAttributeNamespaceLabel.gridx = 0;
gbc_firstNameAttributeNamespaceLabel.anchor = GridBagConstraints.WEST;
gbc_firstNameAttributeNamespaceLabel.insets = new Insets(2, 2, 2, 2);
gbc_firstNameAttributeNamespaceLabel.gridy = 2;
firstNameAttributeNamespaceLabel = new JLabel();
firstNameAttributeNamespaceLabel.setText("First Name Attribute Namespace");
GridBagConstraints gridBagConstraints44 = new GridBagConstraints();
gridBagConstraints44.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints44.gridy = 1;
gridBagConstraints44.weightx = 1.0;
gridBagConstraints44.anchor = GridBagConstraints.WEST;
gridBagConstraints44.insets = new Insets(2, 2, 2, 2);
gridBagConstraints44.gridx = 1;
GridBagConstraints gbc_userIdAttributeLabel = new GridBagConstraints();
gbc_userIdAttributeLabel.gridx = 0;
gbc_userIdAttributeLabel.anchor = GridBagConstraints.WEST;
gbc_userIdAttributeLabel.insets = new Insets(2, 2, 2, 2);
gbc_userIdAttributeLabel.gridy = 1;
userIdAttributeLabel = new JLabel();
userIdAttributeLabel.setText("User Id Attribute");
GridBagConstraints gbc_userIdNamespaceLabel = new GridBagConstraints();
gbc_userIdNamespaceLabel.anchor = GridBagConstraints.WEST;
gbc_userIdNamespaceLabel.gridx = 0;
gbc_userIdNamespaceLabel.gridy = 0;
gbc_userIdNamespaceLabel.insets = new Insets(2, 2, 2, 2);
GridBagConstraints gridBagConstraints41 = new GridBagConstraints();
gridBagConstraints41.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints41.gridx = 1;
gridBagConstraints41.gridy = 0;
gridBagConstraints41.anchor = GridBagConstraints.WEST;
gridBagConstraints41.insets = new Insets(2, 2, 2, 2);
gridBagConstraints41.weighty = 0.0D;
gridBagConstraints41.weightx = 1.0;
userIdNamespaceLabel = new JLabel();
userIdNamespaceLabel.setText("User Id Attribute Namespace");
attributesPanel.setLayout(new GridBagLayout());
attributesPanel.add(userIdNamespaceLabel, gbc_userIdNamespaceLabel);
attributesPanel.add(getUserIdNamespace(), gridBagConstraints41);
attributesPanel.add(userIdAttributeLabel, gbc_userIdAttributeLabel);
attributesPanel.add(getUserIdName(), gridBagConstraints44);
attributesPanel.add(firstNameAttributeNamespaceLabel, gbc_firstNameAttributeNamespaceLabel);
attributesPanel.add(getFirstNameNamespace(), gridBagConstraints46);
attributesPanel.add(firstNameAttributeLabel, gbc_firstNameAttributeLabel);
attributesPanel.add(getFirstName(), gridBagConstraints48);
attributesPanel.add(lastNameAttributeNamespaceLabel, gbc_lastNameAttributeNamespaceLabel);
attributesPanel.add(lastNameAttributeLabel, gbc_lastNameAttributeLabel);
attributesPanel.add(emailAttributeNamespaceLabel, gbc_emailAttributeNamespaceLabel);
attributesPanel.add(emailAttributeLabel, gbc_emailAttributeLabel);
attributesPanel.add(getLastNameNamespace(), gridBagConstraints53);
attributesPanel.add(getLastName(), gridBagConstraints54);
attributesPanel.add(getEmailNamespace(), gridBagConstraints55);
attributesPanel.add(getEmail(), gridBagConstraints56);
attributesPanel.setBorder(BorderFactory.createTitledBorder(null, "SAML Attribute Descriptions",
TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, LookAndFeel
.getPanelLabelColor()));
}
return attributesPanel;
}
/**
* This method initializes userIdNamespace
*
* @return javax.swing.JTextField
*/
private JTextField getUserIdNamespace() {
if (userIdNamespace == null) {
userIdNamespace = new JTextField();
if (newTrustedIdP) {
userIdNamespace.setText(SAMLConstants.UID_ATTRIBUTE_NAMESPACE);
} else {
userIdNamespace.setText(idp.getUserIdAttributeDescriptor().getNamespaceURI());
}
}
return userIdNamespace;
}
/**
* This method initializes userIdName
*
* @return javax.swing.JTextField
*/
private JTextField getUserIdName() {
if (userIdName == null) {
userIdName = new JTextField();
if (newTrustedIdP) {
userIdName.setText(SAMLConstants.UID_ATTRIBUTE);
} else {
userIdName.setText(idp.getUserIdAttributeDescriptor().getName());
}
}
return userIdName;
}
/**
* This method initializes firstNameNamespace
*
* @return javax.swing.JTextField
*/
private JTextField getFirstNameNamespace() {
if (firstNameNamespace == null) {
firstNameNamespace = new JTextField();
if (newTrustedIdP) {
firstNameNamespace.setText(SAMLConstants.FIRST_NAME_ATTRIBUTE_NAMESPACE);
} else {
firstNameNamespace.setText(idp.getFirstNameAttributeDescriptor().getNamespaceURI());
}
}
return firstNameNamespace;
}
/**
* This method initializes firstName
*
* @return javax.swing.JTextField
*/
private JTextField getFirstName() {
if (firstName == null) {
firstName = new JTextField();
if (newTrustedIdP) {
firstName.setText(SAMLConstants.FIRST_NAME_ATTRIBUTE);
} else {
firstName.setText(idp.getFirstNameAttributeDescriptor().getName());
}
}
return firstName;
}
/**
* This method initializes lastNameNamespace
*
* @return javax.swing.JTextField
*/
private JTextField getLastNameNamespace() {
if (lastNameNamespace == null) {
lastNameNamespace = new JTextField();
if (newTrustedIdP) {
lastNameNamespace.setText(SAMLConstants.LAST_NAME_ATTRIBUTE_NAMESPACE);
} else {
lastNameNamespace.setText(idp.getLastNameAttributeDescriptor().getNamespaceURI());
}
}
return lastNameNamespace;
}
/**
* This method initializes lastName
*
* @return javax.swing.JTextField
*/
private JTextField getLastName() {
if (lastName == null) {
lastName = new JTextField();
if (newTrustedIdP) {
lastName.setText(SAMLConstants.LAST_NAME_ATTRIBUTE);
} else {
lastName.setText(idp.getLastNameAttributeDescriptor().getName());
}
}
return lastName;
}
/**
* This method initializes emailNamespace
*
* @return javax.swing.JTextField
*/
private JTextField getEmailNamespace() {
if (emailNamespace == null) {
emailNamespace = new JTextField();
if (newTrustedIdP) {
emailNamespace.setText(SAMLConstants.EMAIL_ATTRIBUTE_NAMESPACE);
} else {
emailNamespace.setText(idp.getEmailAttributeDescriptor().getNamespaceURI());
}
}
return emailNamespace;
}
/**
* This method initializes email
*
* @return javax.swing.JTextField
*/
private JTextField getEmail() {
if (email == null) {
email = new JTextField();
if (newTrustedIdP) {
email.setText(SAMLConstants.EMAIL_ATTRIBUTE);
} else {
email.setText(idp.getEmailAttributeDescriptor().getName());
}
}
return email;
}
/**
* This method initializes authenticationServicePanel
*
* @return javax.swing.JPanel
* @throws Exception
*/
private JPanel getAuthenticationServicePanel() throws Exception {
if (authenticationServicePanel == null) {
authenticationServicePanel = new JPanel();
GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
gridBagConstraints3.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints3.gridx = 1;
gridBagConstraints3.gridy = 2;
gridBagConstraints3.anchor = GridBagConstraints.WEST;
gridBagConstraints3.insets = new Insets(2, 2, 2, 2);
gridBagConstraints3.weightx = 1.0;
GridBagConstraints gbc_publishLabel = new GridBagConstraints();
gbc_publishLabel.anchor = GridBagConstraints.WEST;
gbc_publishLabel.gridy = 2;
gbc_publishLabel.insets = new Insets(2, 2, 2, 2);
gbc_publishLabel.gridx = 0;
publishLabel = new JLabel();
publishLabel.setText("Publish");
GridBagConstraints gridBagConstraints62 = new GridBagConstraints();
gridBagConstraints62.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints62.gridy = 1;
gridBagConstraints62.weightx = 1.0;
gridBagConstraints62.insets = new Insets(2, 2, 2, 2);
gridBagConstraints62.anchor = GridBagConstraints.WEST;
gridBagConstraints62.gridx = 1;
GridBagConstraints gbc_authServiceIdentityLabel = new GridBagConstraints();
gbc_authServiceIdentityLabel.anchor = GridBagConstraints.WEST;
gbc_authServiceIdentityLabel.gridy = 1;
gbc_authServiceIdentityLabel.insets = new Insets(2, 2, 2, 2);
gbc_authServiceIdentityLabel.gridx = 0;
authServiceIdentityLabel = new JLabel();
authServiceIdentityLabel.setText("Authentication Service Identity");
GridBagConstraints gbc_authServiceUrlLabel = new GridBagConstraints();
gbc_authServiceUrlLabel.gridx = 0;
gbc_authServiceUrlLabel.insets = new Insets(2, 2, 2, 2);
gbc_authServiceUrlLabel.anchor = GridBagConstraints.WEST;
gbc_authServiceUrlLabel.gridy = 0;
GridBagConstraints gridBagConstraints59 = new GridBagConstraints();
gridBagConstraints59.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints59.gridx = 1;
gridBagConstraints59.gridy = 0;
gridBagConstraints59.anchor = GridBagConstraints.WEST;
gridBagConstraints59.insets = new Insets(2, 2, 2, 2);
gridBagConstraints59.weightx = 1.0;
authServiceUrlLabel = new JLabel();
authServiceUrlLabel.setText("Authentication Service URL");
authenticationServicePanel.setLayout(new GridBagLayout());
authenticationServicePanel.add(authServiceUrlLabel, gbc_authServiceUrlLabel);
authenticationServicePanel.add(getAuthenticationServiceURL(), gridBagConstraints59);
authenticationServicePanel.add(authServiceIdentityLabel, gbc_authServiceIdentityLabel);
authenticationServicePanel.add(getAuthenticationServiceIdentity(), gridBagConstraints62);
authenticationServicePanel.add(publishLabel, gbc_publishLabel);
if (doesDorianSupportPublish()) {
authenticationServicePanel.add(getPublish(), gridBagConstraints3);
}
}
return authenticationServicePanel;
}
/**
* This method initializes displayName
*
* @return javax.swing.JTextField
*/
private JTextField getDisplayName() {
if (displayName == null) {
displayName = new JTextField();
if (!newTrustedIdP) {
displayName.setText(idp.getDisplayName());
}
}
return displayName;
}
/**
* This method initializes authenticationServiceURL
*
* @return javax.swing.JTextField
*/
private JTextField getAuthenticationServiceURL() {
if (authenticationServiceURL == null) {
authenticationServiceURL = new JTextField();
if (!newTrustedIdP) {
authenticationServiceURL.setText(idp.getAuthenticationServiceURL());
}
}
return authenticationServiceURL;
}
/**
* This method initializes authenticationServiceIdentity
*
* @return javax.swing.JTextField
*/
private JTextField getAuthenticationServiceIdentity() {
if (authenticationServiceIdentity == null) {
authenticationServiceIdentity = new JTextField();
if (!newTrustedIdP) {
authenticationServiceIdentity.setText(idp.getAuthenticationServiceIdentity());
}
}
return authenticationServiceIdentity;
}
/**
* This method initializes titlePanel
*
* @return javax.swing.JPanel
*/
private JPanel getTitlePanel() {
if (titlePanel == null) {
titlePanel = new TitlePanel(titleStr, subtitleStr);
}
return titlePanel;
}
/**
* This method initializes auditPanel
*
* @return javax.swing.JPanel
*/
private FederationAuditPanel getAuditPanel() {
if (auditPanel == null) {
auditPanel = new FederationAuditPanel(this, FederationAuditPanel.IDP_MODE, this.idp.getName());
auditPanel.setProgess(getProgressPanel());
}
return auditPanel;
}
private JPanel getLockoutsWrapperPanel() {
if (lockoutsWrapperPanel == null) {
lockoutsWrapperPanel = new JPanel();
GridBagLayout gbl_lockoutsWrapperPanel = new GridBagLayout();
gbl_lockoutsWrapperPanel.columnWidths = new int[]{0, 0};
gbl_lockoutsWrapperPanel.rowHeights = new int[]{0, 0, 0};
gbl_lockoutsWrapperPanel.columnWeights = new double[]{0.0, Double.MIN_VALUE};
gbl_lockoutsWrapperPanel.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
lockoutsWrapperPanel.setLayout(gbl_lockoutsWrapperPanel);
GridBagConstraints gbc_loadLockoutsButton = new GridBagConstraints();
gbc_loadLockoutsButton.insets = new Insets(2, 2, 2, 2);
gbc_loadLockoutsButton.gridx = 0;
gbc_loadLockoutsButton.gridy = 1;
lockoutsWrapperPanel.add(getLoadLockoutsButton(), gbc_loadLockoutsButton);
GridBagConstraints gbc_lockoutsPanel = new GridBagConstraints();
gbc_lockoutsPanel.insets = new Insets(2,2,2,2);
gbc_lockoutsPanel.gridx = 0;
gbc_lockoutsPanel.gridy = 0;
gbc_lockoutsPanel.fill = GridBagConstraints.BOTH;
gbc_lockoutsPanel.weightx = 1.0;
gbc_lockoutsPanel.weighty = 1.0;
lockoutsWrapperPanel.add(getLockoutsPanel(), gbc_lockoutsPanel);
}
return lockoutsWrapperPanel;
}
private JButton getLoadLockoutsButton() {
if (loadLockoutsButton == null) {
loadLockoutsButton = new JButton("Load Lockouts");
loadLockoutsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// get a client to the authentication service
GlobusCredential credential = getSession().getCredential();
String url = idp.getAuthenticationServiceURL();
AuthenticationServiceClient client = null;
try {
client = new AuthenticationServiceClient(url, credential);
} catch (Exception ex) {
ErrorDialog.showError("Error communicating with the service: " + ex.getMessage(), ex);
}
try {
getLockoutsPanel().loadFromIdP(client);
} catch (RemoteException ex) {
boolean handled = false;
if (ex instanceof BaseFaultType) {
FaultHelper helper = new FaultHelper((BaseFaultType) ex, true);
String message = helper.getMessage();
if (message.contains("Operation name could not be determined")) {
ErrorDialog.showError("This authentication service does not support listing lockout information", ex);
handled = true;
}
}
if (!handled) {
ErrorDialog.showError("Error communicating with the service: " + ex.getMessage(), ex);
}
}
}
});
}
return loadLockoutsButton;
}
private IdPLockoutsPanel getLockoutsPanel() {
if (lockoutsPanel == null) {
lockoutsPanel = new IdPLockoutsPanel();
}
return lockoutsPanel;
}
/**
* This method initializes progressPanel
*
* @return javax.swing.JPanel
*/
private ProgressPanel getProgressPanel() {
if (progressPanel == null) {
progressPanel = new ProgressPanel();
}
return progressPanel;
}
/**
* This method initializes publish
*
* @return javax.swing.JComboBox
* @throws Exception
*/
private JComboBox getPublish() throws Exception {
if (publish == null) {
GridAdministrationClient client = this.session.getAdminClient();
publish = new JComboBox();
publish.addItem(PUBLISH_YES);
publish.addItem(PUBLISH_NO);
if (!newTrustedIdP) {
if (client.getPublish(idp)) {
publish.setSelectedItem(PUBLISH_YES);
} else {
publish.setSelectedItem(PUBLISH_NO);
}
} else {
publish.setSelectedItem(PUBLISH_YES);
}
}
return publish;
}
private boolean doesDorianSupportPublish() {
try {
if (Double.parseDouble(session.getHandle().getServiceVersion()) < 1.4) {
return false;
}
} catch (Exception e) {
}
return true;
}
}
| |
/*
* Copyright 2017 iserge.
*
* 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.cleanlogic.cesiumjs4gwt.showcase.examples;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.*;
import org.cesiumjs.cs.Cesium;
import org.cesiumjs.cs.core.Math;
import org.cesiumjs.cs.core.*;
import org.cesiumjs.cs.core.providers.CesiumTerrainProvider;
import org.cesiumjs.cs.core.providers.EllipsoidTerrainProvider;
import org.cesiumjs.cs.core.providers.GeoserverTerrainProvider;
import org.cesiumjs.cs.core.providers.VRTheWorldTerrainProvider;
import org.cesiumjs.cs.core.providers.options.CesiumTerrainProviderOptions;
import org.cesiumjs.cs.core.providers.options.GeoserverTerrainProviderOptions;
import org.cesiumjs.cs.core.providers.options.VRTheWorldTerrainProviderOptions;
import org.cesiumjs.cs.datasources.Entity;
import org.cesiumjs.cs.datasources.graphics.BillboardGraphics;
import org.cesiumjs.cs.datasources.graphics.LabelGraphics;
import org.cesiumjs.cs.datasources.graphics.options.BillboardGraphicsOptions;
import org.cesiumjs.cs.datasources.graphics.options.LabelGraphicsOptions;
import org.cesiumjs.cs.datasources.options.EntityOptions;
import org.cesiumjs.cs.datasources.properties.ConstantPositionProperty;
import org.cesiumjs.cs.datasources.properties.ConstantProperty;
import org.cesiumjs.cs.promise.Fulfill;
import org.cesiumjs.cs.promise.Promise;
import org.cesiumjs.cs.scene.enums.HorizontalOrigin;
import org.cesiumjs.cs.scene.enums.VerticalOrigin;
import org.cesiumjs.cs.widgets.ViewerPanel;
import org.cleanlogic.cesiumjs4gwt.showcase.basic.AbstractExample;
import org.cleanlogic.cesiumjs4gwt.showcase.components.store.ShowcaseExampleStore;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
/**
* @author Serge Silaev aka iSergio
*/
public class Terrain extends AbstractExample {
public CesiumTerrainProvider cesiumTerrainProviderMeshes;
private ViewerPanel csVPanel;
private List<Cartographic> terrainSamplePositions;
@Inject
public Terrain(ShowcaseExampleStore store) {
super("Terrain", "Visualize worldwide, high-resolution terrain",
new String[]{"Showcase", "Cesium", "3d", "Terrain", "CesiumTerrain", "GeoserverTerrain", "Promise"}, store);
}
@Override
public void buildPanel() {
csVPanel = new ViewerPanel();
CesiumTerrainProviderOptions cesiumTerrainProviderOptions = new CesiumTerrainProviderOptions();
cesiumTerrainProviderOptions.url = "https://assets.agi.com/stk-terrain/world";
cesiumTerrainProviderOptions.requestWaterMask = true;
cesiumTerrainProviderOptions.requestVertexNormals = true;
cesiumTerrainProviderMeshes = new CesiumTerrainProvider(cesiumTerrainProviderOptions);
csVPanel.getViewer().terrainProvider = cesiumTerrainProviderMeshes;
Cartesian3 target = new Cartesian3(300770.50872389384, 5634912.131394585, 2978152.2865545116);
Cartesian3 offset = new Cartesian3(6344.974098678562, -793.3419798081741, 2499.9508860763162);
csVPanel.getViewer().camera.lookAt(target, offset);
csVPanel.getViewer().camera.lookAtTransform(Matrix4.IDENTITY());
ListBox terrainsLBox = new ListBox();
terrainsLBox.setWidth("130px");
terrainsLBox.addItem("CesiumTerrainProvider - STK World Terrain", "0");
terrainsLBox.addItem("CesiumTerrainProvider - STK World Terrain - no effects", "1");
terrainsLBox.addItem("CesiumTerrainProvider - STK World Terrain w/ Lighting", "2");
terrainsLBox.addItem("CesiumTerrainProvider - STK World Terrain w/ Water", "3");
terrainsLBox.addItem("EllipsoidTerrainProvider", "4");
terrainsLBox.addItem("VRTheWorldTerrainProvider", "5");
terrainsLBox.addItem("GeoserverTerrainProvider", "6");
terrainsLBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent changeEvent) {
ListBox source = (ListBox) changeEvent.getSource();
switch (source.getSelectedValue()) {
case "0": {
csVPanel.getViewer().terrainProvider = cesiumTerrainProviderMeshes;
csVPanel.getViewer().scene().globe.enableLighting = true;
}
break;
case "1": {
CesiumTerrainProviderOptions options = new CesiumTerrainProviderOptions();
options.url = "https://assets.agi.com/stk-terrain/world";
csVPanel.getViewer().terrainProvider = new CesiumTerrainProvider(options);
}
break;
case "2": {
CesiumTerrainProviderOptions options = new CesiumTerrainProviderOptions();
options.url = "https://assets.agi.com/stk-terrain/world";
options.requestVertexNormals = true;
csVPanel.getViewer().terrainProvider = new CesiumTerrainProvider(options);
csVPanel.getViewer().scene().globe.enableLighting = true;
}
break;
case "3": {
CesiumTerrainProviderOptions options = new CesiumTerrainProviderOptions();
options.url = "https://assets.agi.com/stk-terrain/world";
options.requestWaterMask = true;
csVPanel.getViewer().terrainProvider = new CesiumTerrainProvider(options);
csVPanel.getViewer().scene().globe.enableLighting = true;
}
break;
case "4": {
csVPanel.getViewer().terrainProvider = new EllipsoidTerrainProvider();
}
break;
case "5": {
VRTheWorldTerrainProviderOptions options = new VRTheWorldTerrainProviderOptions();
options.url = "http://www.vr-theworld.com/vr-theworld/tiles1.0.0/73/";
csVPanel.getViewer().terrainProvider = new VRTheWorldTerrainProvider(options);
}
break;
case "6": {
GeoserverTerrainProviderOptions options = new GeoserverTerrainProviderOptions();
options.url = "http://sergeserver.noip.me/geobase-portal/ows";
options.layerName = "geoserver:geobase:SRTM90";
options.styleName = "geobase:grayToColor";
csVPanel.getViewer().terrainProvider = new GeoserverTerrainProvider(options);
}
break;
default:
break;
}
}
});
ListBox targetsLBox = new ListBox();
targetsLBox.addItem("Mount Everest", "0");
targetsLBox.addItem("Half Dome", "1");
targetsLBox.addItem("San Francisco Bay", "2");
targetsLBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent changeEvent) {
ListBox source = (ListBox) changeEvent.getSource();
switch (source.getSelectedValue()) {
case "0": {
Cartesian3 target = new Cartesian3(300770.50872389384, 5634912.131394585, 2978152.2865545116);
Cartesian3 offset = new Cartesian3(6344.974098678562, -793.3419798081741, 2499.9508860763162);
csVPanel.getViewer().camera.lookAt(target, offset);
csVPanel.getViewer().camera.lookAtTransform(Matrix4.IDENTITY());
}
break;
case "1": {
Cartesian3 target = new Cartesian3(-2489625.0836225147, -4393941.44443024, 3882535.9454173897);
Cartesian3 offset = new Cartesian3(-6857.40902037546, 412.3284835694358, 2147.5545426812023);
csVPanel.getViewer().camera.lookAt(target, offset);
csVPanel.getViewer().camera.lookAtTransform(Matrix4.IDENTITY());
}
break;
case "2": {
Cartesian3 target = new Cartesian3(-2708814.85583248, -4254159.450845907, 3891403.9457429945);
Cartesian3 offset = new Cartesian3(70642.66030209465, -31661.517948317807, 35505.179997143336);
csVPanel.getViewer().camera.lookAt(target, offset);
csVPanel.getViewer().camera.lookAtTransform(Matrix4.IDENTITY());
}
default:
break;
}
}
});
ToggleButton lightingTBtn = new ToggleButton("Toggle Lighting");
lightingTBtn.setWidth("130px");
lightingTBtn.setValue(true);
lightingTBtn.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> valueChangeEvent) {
csVPanel.getViewer().scene().globe.enableLighting = !csVPanel.getViewer().scene().globe.enableLighting;
}
});
ToggleButton fogTBtn = new ToggleButton("Toggle Fog");
fogTBtn.setWidth("130px");
fogTBtn.setValue(true);
fogTBtn.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> valueChangeEvent) {
csVPanel.getViewer().scene().fog.enabled = !csVPanel.getViewer().scene().fog.enabled;
}
});
Button sampleBtn = new Button("Sample Everest Terrain");
sampleBtn.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent clickEvent) {
int gridWidth = 41;
int gridHeight = 41;
double everestLatitude = Math.toRadians(27.988257);
double everestLongitude = Math.toRadians(86.925145);
double rectangleHalfSize = 0.005;
Rectangle e = new Rectangle(everestLongitude - rectangleHalfSize, everestLatitude - rectangleHalfSize,
everestLongitude + rectangleHalfSize, everestLatitude + rectangleHalfSize);
terrainSamplePositions = new ArrayList<>();
for (int y = 0; y < gridHeight; ++y) {
for (int x = 0; x < gridWidth; ++x) {
double lon = Math.lerp(e.west, e.east, (double) x / (gridWidth - 1.));
double lat = Math.lerp(e.south, e.north, (double) y / (gridHeight - 1.));
Cartographic position = new Cartographic(lon, lat);
terrainSamplePositions.add(position);
}
}
Promise<Cartographic[], Void> promise = Cesium.sampleTerrain(csVPanel.getViewer().terrainProvider, 9,
terrainSamplePositions.toArray(new Cartographic[terrainSamplePositions.size()]));
promise.then(new Fulfill<Cartographic[]>() {
@Override
public void onFulfilled(Cartographic[] value) {
sampleTerrainSuccess();
}
});
}
});
VerticalPanel vPanel = new VerticalPanel();
vPanel.add(targetsLBox);
vPanel.add(terrainsLBox);
vPanel.add(lightingTBtn);
vPanel.add(fogTBtn);
vPanel.add(sampleBtn);
AbsolutePanel aPanel = new AbsolutePanel();
aPanel.add(csVPanel);
aPanel.add(vPanel, 20, 20);
contentPanel.add(new HTML("<p>Visualize worldwide, high-resolution terrain.</p>"));
contentPanel.add(aPanel);
initWidget(contentPanel);
}
@Override
public String[] getSourceCodeURLs() {
String[] sourceCodeURLs = new String[1];
sourceCodeURLs[0] = GWT.getModuleBaseURL() + "examples/" + "Terrain.txt";
return sourceCodeURLs;
}
private void sampleTerrainSuccess() {
Ellipsoid ellipsoid = Ellipsoid.WGS84();
csVPanel.getViewer().scene().globe.depthTestAgainstTerrain = true;
csVPanel.getViewer().entities().suspendEvents();
csVPanel.getViewer().entities().removeAll();
for (Cartographic position : terrainSamplePositions) {
BigDecimal bd = new BigDecimal(position.height).setScale(1, RoundingMode.HALF_EVEN);
BillboardGraphicsOptions billboardGraphicsOptions = new BillboardGraphicsOptions();
billboardGraphicsOptions.verticalOrigin = new ConstantProperty<>(VerticalOrigin.BOTTOM());
billboardGraphicsOptions.scale = new ConstantProperty<>(0.7);
billboardGraphicsOptions.image = new ConstantProperty<>(GWT.getModuleBaseURL() + "images/facility.gif");
LabelGraphicsOptions labelGraphicsOptions = new LabelGraphicsOptions();
labelGraphicsOptions.text = new ConstantProperty<>(bd.toString());
labelGraphicsOptions.horizontalOrigin = new ConstantProperty<>(HorizontalOrigin.CENTER());// HorizontalOrigin.CENTER());
labelGraphicsOptions.scale = new ConstantProperty<>(0.3);
labelGraphicsOptions.pixelOffset = new ConstantProperty<>(new Cartesian2(0, -14));
labelGraphicsOptions.fillColor = new ConstantProperty<>(Color.RED());
labelGraphicsOptions.outlineColor = new ConstantProperty<>(Color.WHITE());
EntityOptions entityOptions = new EntityOptions();
entityOptions.name = bd.toString();
entityOptions.position = new ConstantPositionProperty(ellipsoid.cartographicToCartesian(position));
entityOptions.billboard = new BillboardGraphics(billboardGraphicsOptions);
entityOptions.label = new LabelGraphics(labelGraphicsOptions);
csVPanel.getViewer().entities().add(new Entity(entityOptions));
}
csVPanel.getViewer().entities().resumeEvents();
}
}
| |
package org.openprovenance.prov.model;
import java.util.Collection;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Date;
import java.util.Properties;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.GregorianCalendar;
import javax.xml.bind.JAXBException;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.DatatypeConfigurationException;
/** A stateless factory for PROV objects. */
public abstract class ProvFactory implements LiteralConstructor, ModelConstructor {
public static final String packageList = "org.openprovenance.prov.xml:org.openprovenance.prov.xml.validation";
private static String fileName = "toolbox.properties";
private static final String toolboxVersion = getPropertiesFromClasspath(fileName).getProperty("toolbox.version");
private static Properties getPropertiesFromClasspath(String propFileName) {
Properties props = new Properties();
InputStream inputStream = ProvFactory.class.getClassLoader().getResourceAsStream(propFileName);
if (inputStream == null) {
return null;
}
try {
props.load(inputStream);
} catch (IOException ee) {
return null;
}
return props;
}
public static String printURI(java.net.URI u) {
return u.toString();
}
protected DatatypeFactory dataFactory;
final protected ObjectFactory of;
public ProvFactory(ObjectFactory of) {
this.of = of;
init();
}
public void addAttribute(HasOther a, Other o) {
a.getOther().add(o);
}
public ActedOnBehalfOf addAttributes(ActedOnBehalfOf from,
ActedOnBehalfOf to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getOther().addAll(from.getOther());
return to;
}
public Activity addAttributes(Activity from, Activity to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getLocation().addAll(from.getLocation());
to.getOther().addAll(from.getOther());
return to;
}
public Agent addAttributes(Agent from, Agent to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
// to.getLocation().addAll(from.getLocation());
to.getOther().addAll(from.getOther());
return to;
}
public Entity addAttributes(Entity from, Entity to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getLocation().addAll(from.getLocation());
to.getOther().addAll(from.getOther());
return to;
}
public Used addAttributes(Used from, Used to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getLocation().addAll(from.getLocation());
to.getRole().addAll(from.getRole());
to.getOther().addAll(from.getOther());
return to;
}
public WasAssociatedWith addAttributes(WasAssociatedWith from,
WasAssociatedWith to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getRole().addAll(from.getRole());
to.getOther().addAll(from.getOther());
return to;
}
public WasAttributedTo addAttributes(WasAttributedTo from,
WasAttributedTo to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getOther().addAll(from.getOther());
return to;
}
public WasDerivedFrom addAttributes(WasDerivedFrom from, WasDerivedFrom to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getOther().addAll(from.getOther());
return to;
}
public WasEndedBy addAttributes(WasEndedBy from, WasEndedBy to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getLocation().addAll(from.getLocation());
to.getRole().addAll(from.getRole());
to.getOther().addAll(from.getOther());
return to;
}
public WasGeneratedBy addAttributes(WasGeneratedBy from, WasGeneratedBy to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getLocation().addAll(from.getLocation());
to.getRole().addAll(from.getRole());
to.getOther().addAll(from.getOther());
return to;
}
public WasInfluencedBy addAttributes(WasInfluencedBy from,
WasInfluencedBy to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getOther().addAll(from.getOther());
return to;
}
public WasInformedBy addAttributes(WasInformedBy from, WasInformedBy to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getOther().addAll(from.getOther());
return to;
}
public WasInvalidatedBy addAttributes(WasInvalidatedBy from,
WasInvalidatedBy to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getLocation().addAll(from.getLocation());
to.getRole().addAll(from.getRole());
to.getOther().addAll(from.getOther());
return to;
}
public WasStartedBy addAttributes(WasStartedBy from, WasStartedBy to) {
to.getLabel().addAll(from.getLabel());
to.getType().addAll(from.getType());
to.getLocation().addAll(from.getLocation());
to.getRole().addAll(from.getRole());
to.getOther().addAll(from.getOther());
return to;
}
public void addLabel(HasLabel a, String label) {
a.getLabel().add(newInternationalizedString(label));
}
public void addLabel(HasLabel a, String label, String language) {
a.getLabel().add(newInternationalizedString(label, language));
}
public void addPrimarySourceType(HasType a) {
a.getType().add(newType(getName().PROV_PRIMARY_SOURCE,
getName().PROV_QUALIFIED_NAME));
}
public void addQuotationType(HasType a) {
a.getType().add(newType(getName().PROV_QUOTATION,getName().PROV_QUALIFIED_NAME));
}
public void addRevisionType(HasType a) {
a.getType().add(newType(getName().PROV_REVISION,getName().PROV_QUALIFIED_NAME));
}
public void addBundleType(HasType a) {
a.getType().add(newType(getName().PROV_BUNDLE,getName().PROV_QUALIFIED_NAME));
}
public void addRole(HasRole a, Role role) {
if (role != null) {
a.getRole().add(role);
}
}
public void addType(HasType a, Object o, QualifiedName type) {
a.getType().add(newType(o,type));
}
public void addType(HasType a, Type type) {
a.getType().add(type);
}
public void addType(HasType a, URI type) {
a.getType().add(newType(type,getName().XSD_ANY_URI));
}
public byte [] base64Decoding(String s) {
return org.apache.commons.codec.binary.Base64.decodeBase64(s);
}
public String base64Encoding(byte [] b) {
return org.apache.commons.codec.binary.Base64.encodeBase64String(b);
}
/* Return the first label, it it exists */
public String getLabel(HasOther e) {
List<LangString> labels = ((HasLabel) e).getLabel();
if ((labels == null) || (labels.isEmpty()))
return null;
if (e instanceof HasLabel)
return labels.get(0).getValue();
return "pFact: label TODO";
}
private Name name=null;
public Name getName() {
if (name==null) {
name=new Name(this);
}
return name;
}
public ObjectFactory getObjectFactory() {
return of;
}
public String getPackageList() {
return packageList;
}
abstract public ProvSerialiser getSerializer() throws JAXBException;
public String getRole(HasOther e) {
return "pFact: role TODO";
}
public List<Type> getType(HasOther e) {
if (e instanceof HasType)
return ((HasType) e).getType();
List<Type> res = new LinkedList<Type>();
res.add(newType("pFact: type TODO",getName().XSD_STRING));
return res;
}
public String getVersion() {
return toolboxVersion;
}
public byte [] hexDecoding(String s) {
try {
return org.apache.commons.codec.binary.Hex.decodeHex(s.toCharArray());
} catch (Exception e) {
return s.getBytes(); // fall back, but obviously, this is not converted
}
}
public String hexEncoding(byte [] b) {
return org.apache.commons.codec.binary.Hex.encodeHexString(b);
}
protected void init() {
try {
dataFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException ex) {
throw new RuntimeException(ex);
}
}
public ActedOnBehalfOf newActedOnBehalfOf(ActedOnBehalfOf u) {
ActedOnBehalfOf u1 = newActedOnBehalfOf(u.getId(),
u.getDelegate(),
u.getResponsible(),
u.getActivity(),
null);
u1.getOther().addAll(u.getOther());
return u1;
}
/** A factory method to create an instance of a delegation {@link ActedOnBehalfOf}
* @param id identifier for the delegation association between delegate and responsible
* @param delegate identifier for the agent associated with an activity, acting on behalf of the responsible agent
* @param responsible identifier for the agent, on behalf of which the delegate agent acted
* @param activity optional identifier of an activity for which the delegation association holds
* @return an instance of {@link ActedOnBehalfOf}
*/
public ActedOnBehalfOf newActedOnBehalfOf(QualifiedName id,
QualifiedName delegate,
QualifiedName responsible,
QualifiedName activity) {
ActedOnBehalfOf res = of.createActedOnBehalfOf();
res.setId(id);
res.setActivity(activity);
res.setDelegate(delegate);
res.setResponsible(responsible);
return res;
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newActedOnBehalfOf(org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, java.util.Collection)
*/
public ActedOnBehalfOf newActedOnBehalfOf(QualifiedName id,
QualifiedName delegate,
QualifiedName responsible,
QualifiedName activity,
Collection<Attribute> attributes) {
ActedOnBehalfOf res = of.createActedOnBehalfOf();
res.setId(id);
res.setActivity(activity);
res.setDelegate(delegate);
res.setResponsible(responsible);
setAttributes(res, attributes);
return res;
}
/** A factory method to create an instance of a delegation {@link ActedOnBehalfOf}
* @param id identifier for the delegation association between delegate and responsible
* @param delegate identifier for the agent associated with an activity, acting on behalf of the responsible agent
* @param responsible identifier for the agent, on behalf of which the delegate agent acted
* @return an instance of {@link ActedOnBehalfOf}
*/
public ActedOnBehalfOf newActedOnBehalfOf(QualifiedName id, QualifiedName delegate, QualifiedName responsible) {
ActedOnBehalfOf res=newActedOnBehalfOf(id, delegate, responsible, null,null);
return res;
}
public Activity newActivity(Activity a) {
Activity res = newActivity(a.getId());
res.getType().addAll(a.getType());
res.getLabel().addAll(a.getLabel());
res.getLocation().addAll(a.getLocation());
res.setStartTime(a.getStartTime());
res.setEndTime(a.getEndTime());
return res;
}
public Activity newActivity(QualifiedName a) {
Activity res = of.createActivity();
res.setId(a);
return res;
}
public Activity newActivity(QualifiedName q, String label) {
Activity res = newActivity(q);
if (label != null)
res.getLabel().add(newInternationalizedString(label));
return res;
}
public Activity newActivity(QualifiedName id,
XMLGregorianCalendar startTime,
XMLGregorianCalendar endTime,
Collection<Attribute> attributes) {
Activity res = newActivity(id);
res.setStartTime(startTime);
res.setEndTime(endTime);
setAttributes(res, attributes);
return res;
}
/**
* Creates a copy of an agent. The copy is shallow in the sense that the new Agent shares the same attributes as the original Agent.
* @param a an {@link Agent} to copy
* @return a copy of the input {@link Agent}
*/
public Agent newAgent(Agent a) {
Agent res = newAgent(a.getId());
res.getType().addAll(a.getType());
res.getLabel().addAll(a.getLabel());
return res;
}
/**
* Creates a new {@link Agent} with provided identifier
* @param ag a {@link QualifiedName} for the agent
* @return an object of type {@link Agent}
*/
public Agent newAgent(QualifiedName ag) {
Agent res = of.createAgent();
res.setId(ag);
return res;
}
/**
* Creates a new {@link Agent} with provided identifier and attributes
* @param id a {@link QualifiedName} for the agent
* @param attributes a collection of {@link Attribute} for the agent
* @return an object of type {@link Agent}
*/
public Agent newAgent(QualifiedName id, Collection<Attribute> attributes) {
Agent res = newAgent(id);
setAttributes(res, attributes);
return res;
}
/**
* Creates a new {@link Agent} with provided identifier and label
* @param ag a {@link QualifiedName} for the agent
* @param label a String for the label property (see {@link HasLabel#getLabel()}
* @return an object of type {@link Agent}
*/
public Agent newAgent(QualifiedName ag, String label) {
Agent res = newAgent(ag);
if (label != null)
res.getLabel().add(newInternationalizedString(label));
return res;
}
/** A factory method to create an instance of an alternate {@link AlternateOf}
* @param entity1 an identifier for the first {@link Entity}
* @param entity2 an identifier for the second {@link Entity}
* @return an instance of {@link AlternateOf}
*/
public AlternateOf newAlternateOf(QualifiedName entity1, QualifiedName entity2) {
AlternateOf res = of.createAlternateOf();
res.setAlternate1(entity1);
res.setAlternate2(entity2);
return res;
}
abstract public org.openprovenance.prov.model.Attribute newAttribute(QualifiedName elementName, Object value, QualifiedName type) ;
abstract public org.openprovenance.prov.model.Attribute newAttribute(Attribute.AttributeKind kind, Object value, QualifiedName type);
public Attribute newAttribute(String namespace, String localName,
String prefix, Object value, QualifiedName type) {
Attribute res;
res = newAttribute(newQualifiedName(namespace, localName, prefix),
value, type);
return res;
}
public DerivedByInsertionFrom newDerivedByInsertionFrom(QualifiedName id,
QualifiedName after,
QualifiedName before,
List<Entry> keyEntitySet,
Collection<Attribute> attributes) {
DerivedByInsertionFrom res = of.createDerivedByInsertionFrom();
res.setId(id);
res.setNewDictionary(after);
res.setOldDictionary(before);
if (keyEntitySet != null)
res.getKeyEntityPair().addAll(keyEntitySet);
setAttributes(res, attributes);
return res;
}
public DerivedByRemovalFrom newDerivedByRemovalFrom(QualifiedName id,
QualifiedName after,
QualifiedName before,
List<Key> keys,
Collection<Attribute> attributes) {
DerivedByRemovalFrom res = of.createDerivedByRemovalFrom();
res.setId(id);
res.setNewDictionary(after);
res.setOldDictionary(before);
if (keys != null)
res.getKey().addAll(keys);
setAttributes(res, attributes);
return res;
}
public DictionaryMembership newDictionaryMembership(QualifiedName dict,
List<Entry> entitySet) {
DictionaryMembership res = of.createDictionaryMembership();
res.setDictionary(dict);
if (entitySet != null)
res.getKeyEntityPair().addAll(entitySet);
return res;
}
/**
* Factory method to construct a {@link Document}
* @return a new instance of {@link Document}
*/
public Document newDocument() {
Document res = of.createDocument();
return res;
}
public Document newDocument(Activity[] ps, Entity[] as, Agent[] ags,
Statement[] lks) {
return newDocument(((ps == null) ? null : Arrays.asList(ps)),
((as == null) ? null : Arrays.asList(as)),
((ags == null) ? null : Arrays.asList(ags)),
((lks == null) ? null : Arrays.asList(lks)));
}
public Document newDocument(Collection<Activity> ps, Collection<Entity> as,
Collection<Agent> ags, Collection<Statement> lks) {
Document res = of.createDocument();
res.getStatementOrBundle().addAll(ps);
res.getStatementOrBundle().addAll(as);
res.getStatementOrBundle().addAll(ags);
res.getStatementOrBundle().addAll(lks);
return res;
}
public Document newDocument(Document graph) {
Document res = of.createDocument();
res.getStatementOrBundle()
.addAll(graph.getStatementOrBundle());
if (graph.getNamespace()!=null) {
res.setNamespace(new Namespace(graph.getNamespace()));
}
return res;
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newDocument(org.openprovenance.prov.model.Namespace, java.util.Collection, java.util.Collection)
*/
@Override
public Document newDocument(Namespace namespace,
Collection<Statement> statements,
Collection<Bundle> bundles) {
Document res = of.createDocument();
res.setNamespace(namespace);
res.getStatementOrBundle()
.addAll(statements);
res.getStatementOrBundle()
.addAll(bundles);
return res;
}
public Duration newDuration(int durationInMilliSeconds) {
Duration dur=dataFactory.newDuration(durationInMilliSeconds);
return dur;
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.LiteralConstructor#newDuration(java.lang.String)
*/
public Duration newDuration(String lexicalRepresentation) {
Duration dur=dataFactory.newDuration(lexicalRepresentation);
return dur;
}
/**
* Creates a copy of an entity. The copy is shallow in the sense that the new Entity shares the same attributes as the original Entity.
* @param e an {@link Entity} to copy
* @return a copy of the input {@link Entity}
*/
public Entity newEntity(Entity e) {
Entity res = newEntity(e.getId());
res.getOther().addAll(e.getOther());
res.getType().addAll(e.getType());
res.getLabel().addAll(e.getLabel());
res.getLocation().addAll(e.getLocation());
return res;
}
/**
* Creates a new {@link Entity} with provided identifier
* @param id a {@link QualifiedName} for the entity
* @return an object of type {@link Entity}
*/
public Entity newEntity(QualifiedName id) {
Entity res = of.createEntity();
res.setId(id);
return res;
}
/**
* Creates a new {@link Entity} with provided identifier and attributes
* @param id a {@link QualifiedName} for the entity
* @param attributes a collection of {@link Attribute} for the entity
* @return an object of type {@link Entity}
*/
public Entity newEntity(QualifiedName id, Collection<Attribute> attributes) {
Entity res = newEntity(id);
setAttributes(res, attributes);
return res;
}
/**
* Creates a new {@link Entity} with provided identifier and label
* @param id a {@link QualifiedName} for the entity
* @param label a String for the label property (see {@link HasLabel#getLabel()}
* @return an object of type {@link Entity}
*/
public Entity newEntity(QualifiedName id, String label) {
Entity res = newEntity(id);
if (label != null)
res.getLabel().add(newInternationalizedString(label));
return res;
}
/** Factory method for Key-entity entries. Key-entity entries are used to identify the members of a dictionary.
* @param key indexing the entity in the dictionary
* @param entity a {@link QualifiedName} denoting an entity
* @return an instance of {@link Entry}
*/
public Entry newEntry(Key key, QualifiedName entity) {
Entry res = of.createEntry();
res.setKey(key);
res.setEntity(entity);
return res;
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.LiteralConstructor#newGDay(int)
*/
public XMLGregorianCalendar newGDay(int day) {
XMLGregorianCalendar cal=dataFactory.newXMLGregorianCalendar();
cal.setDay(day);
return cal;
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.LiteralConstructor#newGMonth(int)
*/
public XMLGregorianCalendar newGMonth(int month) {
XMLGregorianCalendar cal=dataFactory.newXMLGregorianCalendar();
cal.setMonth(month);
return cal;
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.LiteralConstructor#newGMonthDay(int, int)
*/
public XMLGregorianCalendar newGMonthDay(int month, int day) {
XMLGregorianCalendar cal=dataFactory.newXMLGregorianCalendar();
cal.setMonth(month);
cal.setDay(day);
return cal;
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.LiteralConstructor#newGYear(int)
*/
public XMLGregorianCalendar newGYear(int year) {
XMLGregorianCalendar cal=dataFactory.newXMLGregorianCalendar();
cal.setYear(year);
return cal;
}
public HadMember newHadMember(QualifiedName collection, QualifiedName... entities) {
HadMember res = of.createHadMember();
res.setCollection(collection);
if (entities != null) {
res.getEntity().addAll(Arrays.asList(entities));
}
return res;
}
public HadMember newHadMember(QualifiedName c, Collection<QualifiedName> e) {
List<QualifiedName> ll=new LinkedList<QualifiedName>();
if (e!=null) {
for (QualifiedName q: e) {
ll.add(q);
}
}
HadMember res = of.createHadMember();
res.setCollection(c);
res.getEntity().addAll(ll);
return res;
}
public LangString newInternationalizedString(String s) {
LangString res = of.createInternationalizedString();
res.setValue(s);
return res;
}
public LangString newInternationalizedString(String s,
String lang) {
LangString res = of.createInternationalizedString();
res.setValue(s);
res.setLang(lang);
return res;
}
public XMLGregorianCalendar newISOTime(String time) {
return newTime(javax.xml.bind.DatatypeConverter.parseDateTime(time)
.getTime());
}
/*ValueConverter vconv=new ValueConverter(this);
public Key newKey(Object o, QualifiedName type) {
if (getName().RDF_LITERAL.equals(type)&& (o instanceof String)) {
o=vconv.convertToJava(type,(String)o);
}
Key res=of.createKey();
res.setType(type);
res.setValueFromObject(o);
return res;
}
*/
public abstract Key newKey(Object o, QualifiedName type);
public Location newLocation(Object value, QualifiedName type) {
Location res = of.createLocation();
res.setType(type);
res.setValueFromObject(value);
return res;
}
public MentionOf newMentionOf(QualifiedName infra,
QualifiedName supra,
QualifiedName bundle) {
MentionOf res = of.createMentionOf();
res.setSpecificEntity(infra);
res.setBundle(bundle);
res.setGeneralEntity(supra);
return res;
}
public MentionOf newMentionOf(MentionOf r) {
MentionOf res = of.createMentionOf();
res.setSpecificEntity(r.getSpecificEntity());
res.setBundle(r.getBundle());
res.setGeneralEntity(r.getGeneralEntity());
return res;
}
public Bundle newNamedBundle(QualifiedName id,
Collection<Activity> ps,
Collection<Entity> as,
Collection<Agent> ags,
Collection<Statement> lks) {
Bundle res = of.createNamedBundle();
res.setId(id);
if (ps != null) {
res.getStatement().addAll(ps);
}
if (as != null) {
res.getStatement().addAll(as);
}
if (ags != null) {
res.getStatement().addAll(ags);
}
if (lks != null) {
res.getStatement().addAll(lks);
}
return res;
}
public Bundle newNamedBundle(QualifiedName id, Collection<Statement> lks) {
Bundle res = of.createNamedBundle();
res.setId(id);
if (lks != null) {
res.getStatement().addAll(lks);
}
return res;
}
public Bundle newNamedBundle(QualifiedName id, Namespace namespace, Collection<Statement> statements) {
Bundle res = of.createNamedBundle();
res.setId(id);
res.setNamespace(namespace);
if (statements != null) {
res.getStatement().addAll(statements);
}
return res;
}
public Other newOther(QualifiedName elementName, Object value, QualifiedName type) {
if (value==null) return null;
Other res = of.createOther();
res.setType(type);
res.setValueFromObject(value);
res.setElementName(elementName);
return res;
}
public Other newOther(String namespace, String local, String prefix, Object value, QualifiedName type) {
QualifiedName elementName=newQualifiedName(namespace,local,prefix);
return newOther(elementName,value,type);
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newQualifiedName(java.lang.String, java.lang.String, java.lang.String)
*/
abstract public QualifiedName newQualifiedName(String namespace, String local, String prefix);
abstract public QualifiedName newQualifiedName(String namespace, String local, String prefix, ProvUtilities.BuildFlag flag);
/* A convenience function. */
public QualifiedName newQualifiedName(javax.xml.namespace.QName qname) {
return newQualifiedName(qname.getNamespaceURI(), qname.getLocalPart(), qname.getPrefix());
}
public Role newRole(Object value, QualifiedName type) {
if (value==null) return null;
Role res = of.createRole();
res.setType(type);
res.setValueFromObject(value);
return res;
}
/** A factory method to create an instance of a specialization {@link SpecializationOf}
* @param specific an identifier ({@link QualifiedName}) for the specific {@link Entity}
* @param general an identifier ({@link QualifiedName}) for the general {@link Entity}
* @return an instance of {@link SpecializationOf}
*/
public SpecializationOf newSpecializationOf(QualifiedName specific, QualifiedName general) {
SpecializationOf res = of.createSpecializationOf();
res.setSpecificEntity(specific);
res.setGeneralEntity(general);
return res;
}
public XMLGregorianCalendar newTime(Date date) {
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
return newXMLGregorianCalendar(gc);
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.LiteralConstructor#newTimeNow()
*/
public XMLGregorianCalendar newTimeNow() {
return newTime(new Date());
}
public Type newType(Object value, QualifiedName type) {
if (value==null) return null;
Type res = of.createType();
res.setType(type);
res.setValueFromObject(value);
return res;
}
/** A factory method to create an instance of a usage {@link Used}
* @param id an optional identifier for a usage
* @return an instance of {@link Used}
*/
public Used newUsed(QualifiedName id) {
Used res = of.createUsed();
res.setId(id);
return res;
}
public Used newUsed(QualifiedName id, QualifiedName aid, String role, QualifiedName eid) {
Used res = newUsed(id);
res.setActivity(aid);
if (role!=null)
addRole(res, newRole(role,getName().XSD_STRING));
res.setEntity(eid);
return res;
}
/** A factory method to create an instance of a usage {@link Used}
* @param id an optional identifier for a usage
* @param activity the identifier of the <a href="http://www.w3.org/TR/prov-dm/#usage.activity">activity</a> that used an entity
* @param entity an optional identifier for the <a href="http://www.w3.org/TR/prov-dm/#usage.entity">entity</a> being used
* @return an instance of {@link Used}
*/
public Used newUsed(QualifiedName id, QualifiedName activity, QualifiedName entity) {
Used res = newUsed(id);
res.setActivity(activity);
res.setEntity(entity);
return res;
}
/** A factory method to create an instance of a usage {@link Used}
* @param activity the identifier of the <a href="http://www.w3.org/TR/prov-dm/#usage.activity">activity</a> that used an entity
* @param entity an optional identifier for the <a href="http://www.w3.org/TR/prov-dm/#usage.entity">entity</a> being used
* @return an instance of {@link Used}
*/
public Used newUsed(QualifiedName activity, QualifiedName entity) {
Used res = newUsed((QualifiedName)null);
res.setActivity(activity);
res.setEntity(entity);
return res;
}
/* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newUsed(org.openprovenance.model.QualifiedName, org.openprovenance.model.QualifiedName, org.openprovenance.model.QualifiedName, javax.xml.datatype.XMLGregorianCalendar, java.util.Collection)
*/
public Used newUsed(QualifiedName id, QualifiedName activity, QualifiedName entity,
XMLGregorianCalendar time,
Collection<Attribute> attributes) {
Used res = newUsed(id, activity, null, entity);
res.setTime(time);
setAttributes(res, attributes);
return res;
}
/** A factory method to create an instance of a usage {@link Used} from another
* @param u an instance of a usage
* @return an instance of {@link Used} equal (in the sense of @see Object.equals()) to the input
*/
public Used newUsed(Used u) {
Used u1 = newUsed(u.getId(), u.getActivity(), u.getEntity());
u1.setTime(u.getTime());
u1.getType().addAll(u.getType());
u1.getLabel().addAll(u.getLabel());
u1.getLocation().addAll(u.getLocation());
u1.getOther().addAll(u.getOther());
return u1;
}
/**
* Factory method to create an instance of of the PROV-DM prov:value attribute (see {@link Value}).
* @param value a String
* @return a new {@link Value} with type xsd:string (see {@link Name#XSD_STRING})
*/
public Value newValue(String value) {
return newValue(value,getName().XSD_STRING);
}
/**
* Factory method to create an instance of the PROV-DM prov:value attribute (see {@link Value}).
* @param value an integer
* @return a new {@link Value} with type xsd:int (see {@link Name#XSD_INT})
*/
public Value newValue(int value) {
return newValue(value,getName().XSD_INT);
}
/**
* Factory method to create an instance of the PROV-DM prov:value attribute (see {@link Value}).
* Use class {@link Name} for predefined {@link QualifiedName}s for the common types.
* @param value an {@link Object}
* @param type a {@link QualifiedName} to denote the type of value
* @return a new {@link Value}
*/
public Value newValue(Object value, QualifiedName type) {
if (value==null) return null;
Value res = of.createValue();
res.setType(type);
res.setValueFromObject(value);
return res;
}
/** A factory method to create an instance of an Association {@link WasAssociatedWith}
* @param id an identifier for the association
* @return an instance of {@link WasAssociatedWith}
*/
public WasAssociatedWith newWasAssociatedWith(QualifiedName id) {
return newWasAssociatedWith(id, (QualifiedName)null,(QualifiedName)null);
}
/** A factory method to create an instance of an Association {@link WasAssociatedWith}
* @param id an optional identifier for the association between an activity and an agent
* @param activity an identifier for the activity
* @param agent an optional identifier for the agent associated with the activity
* @return an instance of {@link WasAssociatedWith}
*/
public WasAssociatedWith newWasAssociatedWith(QualifiedName id,
QualifiedName activity,
QualifiedName agent) {
WasAssociatedWith res = of.createWasAssociatedWith();
res.setId(id);
res.setActivity(activity);
res.setAgent(agent);
return res;
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newWasAssociatedWith(org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, java.util.Collection)
*/
public WasAssociatedWith newWasAssociatedWith(QualifiedName id,
QualifiedName a,
QualifiedName ag,
QualifiedName plan,
Collection<Attribute> attributes) {
WasAssociatedWith res= newWasAssociatedWith(id,a,ag);
res.setPlan(plan);
setAttributes(res, attributes);
return res;
}
public WasAssociatedWith newWasAssociatedWith(WasAssociatedWith u) {
WasAssociatedWith u1 = newWasAssociatedWith(u.getId(), u.getActivity(),
u.getAgent());
u1.getOther().addAll(u.getOther());
u1.setPlan(u.getPlan());
u1.getType().addAll(u.getType());
u1.getLabel().addAll(u.getLabel());
return u1;
}
/** A factory method to create an instance of an attribution {@link WasAttributedTo}
* @param id an optional identifier for the relation
* @param entity an entity identifier
* @param agent the identifier of the agent whom the entity is ascribed to, and therefore bears some responsibility for its existence
* @return an instance of {@link WasAttributedTo}
*/
public WasAttributedTo newWasAttributedTo(QualifiedName id,
QualifiedName entity,
QualifiedName agent) {
WasAttributedTo res = of.createWasAttributedTo();
res.setId(id);
res.setEntity(entity);
res.setAgent(agent);
return res;
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newWasAttributedTo(org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, java.util.Collection)
*/
public WasAttributedTo newWasAttributedTo(QualifiedName id,
QualifiedName entity,
QualifiedName agent,
Collection<Attribute> attributes) {
WasAttributedTo res = of.createWasAttributedTo();
res.setId(id);
res.setEntity(entity);
res.setAgent(agent);
setAttributes(res, attributes);
return res;
}
public WasAttributedTo newWasAttributedTo(WasAttributedTo u) {
WasAttributedTo u1 = newWasAttributedTo(u.getId(), u.getEntity(),
u.getAgent());
u1.getOther().addAll(u.getOther());
u1.getType().addAll(u.getType());
u1.getLabel().addAll(u.getLabel());
return u1;
}
/** A factory method to create an instance of a derivation {@link WasDerivedFrom}
* @param id an optional identifier for a derivation
* @param e2 the identifier of the <a href="http://www.w3.org/TR/prov-dm/#derivation.generatedEntity">entity generated</a> by the derivation
* @param e1 the identifier of the <a href="http://www.w3.org/TR/prov-dm/#derivation.usedEntity">entity used</a> by the derivation
* @return an instance of {@link WasDerivedFrom}
*/
public WasDerivedFrom newWasDerivedFrom(QualifiedName id,
QualifiedName e2,
QualifiedName e1) {
WasDerivedFrom res = of.createWasDerivedFrom();
res.setId(id);
res.setUsedEntity(e1);
res.setGeneratedEntity(e2);
return res;
}
/** A factory method to create an instance of a derivation {@link WasDerivedFrom}
* @param e2 the identifier of the <a href="http://www.w3.org/TR/prov-dm/#derivation.generatedEntity">entity generated</a> by the derivation
* @param e1 the identifier of the <a href="http://www.w3.org/TR/prov-dm/#derivation.usedEntity">entity used</a> by the derivation
* @return an instance of {@link WasDerivedFrom}
*/
public WasDerivedFrom newWasDerivedFrom(QualifiedName e2,
QualifiedName e1) {
WasDerivedFrom res = of.createWasDerivedFrom();
res.setUsedEntity(e1);
res.setGeneratedEntity(e2);
return res;
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newWasDerivedFrom(org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, java.util.Collection)
*/
public WasDerivedFrom newWasDerivedFrom(QualifiedName id,
QualifiedName aid1,
QualifiedName aid2,
QualifiedName aid,
QualifiedName did1,
QualifiedName did2,
Collection<Attribute> attributes) {
WasDerivedFrom res = of.createWasDerivedFrom();
res.setId(id);
res.setUsedEntity(aid2);
res.setGeneratedEntity(aid1);
res.setActivity(aid);
res.setGeneration(did1);
res.setUsage(did2);
setAttributes(res, attributes);
return res;
}
public WasDerivedFrom newWasDerivedFrom(WasDerivedFrom d) {
WasDerivedFrom wdf = newWasDerivedFrom(d.getId(),
d.getGeneratedEntity(),
d.getUsedEntity());
wdf.setActivity(d.getActivity());
wdf.setGeneration(d.getGeneration());
wdf.setUsage(d.getUsage());
wdf.getOther().addAll(d.getOther());
wdf.getType().addAll(d.getType());
wdf.getLabel().addAll(d.getLabel());
return wdf;
}
/** A factory method to create an instance of an end {@link WasEndedBy}
* @param id
* @return an instance of {@link WasEndedBy}
*/
public WasEndedBy newWasEndedBy(QualifiedName id) {
WasEndedBy res = of.createWasEndedBy();
res.setId(id);
return res;
}
/** A factory method to create an instance of an end {@link WasEndedBy}
* @param id
* @param activity an identifier for the ended <a href="http://www.w3.org/TR/prov-dm/#end.activity">activity</a>
* @param trigger an optional identifier for the <a href="http://www.w3.org/TR/prov-dm/#end.trigger">entity triggering</a> the activity ending
* @return an instance of {@link WasEndedBy}
*/
public WasEndedBy newWasEndedBy(QualifiedName id, QualifiedName activity, QualifiedName trigger) {
WasEndedBy res = of.createWasEndedBy();
res.setId(id);
res.setActivity(activity);
res.setTrigger(trigger);
return res;
}
/** A factory method to create an instance of an end {@link WasEndedBy}
* @param id
* @param activity an identifier for the ended <a href="http://www.w3.org/TR/prov-dm/#end.activity">activity</a>
* @param trigger an optional identifier for the <a href="http://www.w3.org/TR/prov-dm/#end.trigger">entity triggering</a> the activity ending
* @param ender an optional identifier for the <a href="http://www.w3.org/TR/prov-dm/#end.ender">activity</a> that generated the (possibly unspecified) entity
* @return an instance of {@link WasEndedBy}
*/
public WasEndedBy newWasEndedBy(QualifiedName id, QualifiedName activity, QualifiedName trigger, QualifiedName ender) {
WasEndedBy res=newWasEndedBy(id,activity,trigger);
res.setEnder(ender);
return res;
}
/* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newWasEndedBy(org.openprovenance.model.QualifiedName, org.openprovenance.model.QualifiedName, org.openprovenance.model.QualifiedName, org.openprovenance.model.QualifiedName, javax.xml.datatype.XMLGregorianCalendar, java.util.Collection)
*/
public WasEndedBy newWasEndedBy(QualifiedName id, QualifiedName activity, QualifiedName trigger, QualifiedName ender, XMLGregorianCalendar time, Collection<Attribute> attributes) {
WasEndedBy res=newWasEndedBy(id,activity,trigger);
res.setTime(time);
res.setEnder(ender);
setAttributes(res, attributes);
return res;
}
public WasEndedBy newWasEndedBy(WasEndedBy u) {
WasEndedBy u1 = newWasEndedBy(u.getId(), u.getActivity(),
u.getTrigger());
u1.setEnder(u.getEnder());
u1.setTime(u.getTime());
u1.getType().addAll(u.getType());
u1.getLabel().addAll(u.getLabel());
u1.getLocation().addAll(u.getLocation());
u1.getOther().addAll(u.getOther());
return u1;
}
public WasGeneratedBy newWasGeneratedBy(Entity a, String role, Activity p) {
return newWasGeneratedBy((QualifiedName) null, a, role, p);
}
public WasGeneratedBy newWasGeneratedBy(QualifiedName id) {
WasGeneratedBy res = of.createWasGeneratedBy();
res.setId(id);
return res;
}
public WasGeneratedBy newWasGeneratedBy(QualifiedName id,
Entity a,
String role,
Activity p) {
WasGeneratedBy res=newWasGeneratedBy(id, a.getId(), p.getId());
if (role!=null) addRole(res, newRole(role,getName().XSD_STRING));
return res;
}
public WasGeneratedBy newWasGeneratedBy(QualifiedName id,
QualifiedName aid,
String role,
QualifiedName pid) {
WasGeneratedBy res = of.createWasGeneratedBy();
res.setId(id);
res.setActivity(pid);
res.setEntity(aid);
if (role!=null) addRole(res, newRole(role,getName().XSD_STRING));
return res;
}
/** A factory method to create an instance of a generation {@link WasGeneratedBy}
* @param id an optional identifier for a usage
* @param entity an identifier for the created <a href="http://www.w3.org/TR/prov-dm/#generation.entity">entity</a>
* @param activity an optional identifier for the <a href="http://www.w3.org/TR/prov-dm/#generation.activity">activity</a> that creates the entity
* @return an instance of {@link WasGeneratedBy}
*/
public WasGeneratedBy newWasGeneratedBy(QualifiedName id, QualifiedName entity, QualifiedName activity) {
WasGeneratedBy res=newWasGeneratedBy(id,entity,null,activity);
return res;
}
/* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newWasGeneratedBy(org.openprovenance.model.QualifiedName, org.openprovenance.model.QualifiedName, org.openprovenance.model.QualifiedName, javax.xml.datatype.XMLGregorianCalendar, java.util.Collection)
*/
public WasGeneratedBy newWasGeneratedBy(QualifiedName id, QualifiedName entity, QualifiedName activity, XMLGregorianCalendar time, Collection<Attribute> attributes) {
WasGeneratedBy res=newWasGeneratedBy(id,entity,null,activity);
res.setTime(time);
setAttributes(res, attributes);
return res;
}
public WasGeneratedBy newWasGeneratedBy(WasGeneratedBy g) {
WasGeneratedBy wgb = newWasGeneratedBy(g.getId(), g.getEntity(), null,
g.getActivity());
wgb.setId(g.getId());
wgb.setTime(g.getTime());
wgb.getOther().addAll(g.getOther());
wgb.getType().addAll(g.getType());
wgb.getLabel().addAll(g.getLabel());
wgb.getLocation().addAll(g.getLocation());
return wgb;
}
/**A factory method to create an instance of an influence {@link WasInfluencedBy}
* @param id optional identifier identifying the association
* @param influencee an identifier for an entity, activity, or agent
* @param influencer an identifier for an ancestor entity, activity, or agent that the former depends on
*
* @return an instance of {@link WasInfluencedBy}
*/
public WasInfluencedBy newWasInfluencedBy(QualifiedName id,
QualifiedName influencee,
QualifiedName influencer) {
WasInfluencedBy res = of.createWasInfluencedBy();
res.setId(id);
res.setInfluencee(influencee);
res.setInfluencer(influencer);
return res;
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newWasInfluencedBy(org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, java.util.Collection)
*/
public WasInfluencedBy newWasInfluencedBy(QualifiedName id, QualifiedName influencee, QualifiedName influencer, Collection<Attribute> attributes) {
WasInfluencedBy res=newWasInfluencedBy(id,influencee,influencer);
setAttributes(res, attributes);
return res;
}
public WasInfluencedBy newWasInfluencedBy(WasInfluencedBy in) {
WasInfluencedBy out = newWasInfluencedBy(in.getId(),
in.getInfluencee(),
in.getInfluencer());
out.setId(in.getId());
out.getOther().addAll(in.getOther());
out.getType().addAll(in.getType());
out.getLabel().addAll(in.getLabel());
return out;
}
/** A factory method to create an instance of an communication {@link WasInformedBy}
* @param id an optional identifier identifying the association;
* @param informed the identifier of the informed activity;
* @param informant the identifier of the informant activity;
* @return an instance of {@link WasInformedBy}
*/
public WasInformedBy newWasInformedBy(QualifiedName id,
QualifiedName informed,
QualifiedName informant) {
WasInformedBy res = of.createWasInformedBy();
res.setId(id);
res.setInformed(informed);
res.setInformant(informant);
return res;
}
/*
* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newWasInformedBy(org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, org.openprovenance.prov.model.QualifiedName, java.util.Collection)
*/
public WasInformedBy newWasInformedBy(QualifiedName id, QualifiedName a2, QualifiedName a1, Collection<Attribute> attributes) {
WasInformedBy res=newWasInformedBy(id,a2,a1);
setAttributes(res, attributes);
return res;
}
public WasInformedBy newWasInformedBy(WasInformedBy d) {
WasInformedBy wtb = newWasInformedBy(d.getId(),
d.getInformed(),
d.getInformant());
wtb.setId(d.getId());
wtb.getOther().addAll(d.getOther());
wtb.getType().addAll(d.getType());
wtb.getLabel().addAll(d.getLabel());
return wtb;
}
public WasInvalidatedBy newWasInvalidatedBy(QualifiedName eid,
QualifiedName aid) {
WasInvalidatedBy res = of.createWasInvalidatedBy();
res.setEntity(eid);
res.setActivity(aid);
return res;
}
/** A factory method to create an instance of an invalidation {@link WasInvalidatedBy}
* @param id an optional identifier for a usage
* @param entity an identifier for the created <a href="http://www.w3.org/TR/prov-dm/#invalidation.entity">entity</a>
* @param activity an optional identifier for the <a href="http://www.w3.org/TR/prov-dm/#invalidation.activity">activity</a> that creates the entity
* @return an instance of {@link WasInvalidatedBy}
*/
public WasInvalidatedBy newWasInvalidatedBy(QualifiedName id, QualifiedName entity, QualifiedName activity) {
WasInvalidatedBy res = of.createWasInvalidatedBy();
res.setId(id);
res.setEntity(entity);
res.setActivity(activity);
return res;
}
/* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newWasInvalidatedBy(org.openprovenance.model.QualifiedName, org.openprovenance.model.QualifiedName, org.openprovenance.model.QualifiedName, javax.xml.datatype.XMLGregorianCalendar, java.util.Collection)
*/
public WasInvalidatedBy newWasInvalidatedBy(QualifiedName id, QualifiedName entity, QualifiedName activity, XMLGregorianCalendar time, Collection<Attribute> attributes) {
WasInvalidatedBy res=newWasInvalidatedBy(id,entity,activity);
res.setTime(time);
setAttributes(res, attributes);
return res;
}
public WasInvalidatedBy newWasInvalidatedBy(WasInvalidatedBy u) {
WasInvalidatedBy u1 = newWasInvalidatedBy(u.getId(), u.getEntity(),
u.getActivity());
u1.setTime(u.getTime());
u1.getOther().addAll(u.getOther());
u1.getType().addAll(u.getType());
u1.getLabel().addAll(u.getLabel());
u1.getLocation().addAll(u.getLocation());
return u1;
}
/** A factory method to create an instance of a start {@link WasStartedBy}
* @param id
* @return an instance of {@link WasStartedBy}
*/
public WasStartedBy newWasStartedBy(QualifiedName id) {
WasStartedBy res = of.createWasStartedBy();
res.setId(id);
return res;
}
public WasStartedBy newWasStartedBy(QualifiedName id, QualifiedName aid, QualifiedName eid) {
WasStartedBy res = of.createWasStartedBy();
res.setId(id);
res.setActivity(aid);
res.setTrigger(eid);
return res;
}
/** A factory method to create an instance of a start {@link WasStartedBy}
* @param id
* @param activity an identifier for the started <a href="http://www.w3.org/TR/prov-dm/#start.activity">activity</a>
* @param trigger an optional identifier for the <a href="http://www.w3.org/TR/prov-dm/#start.trigger">entity triggering</a> the activity
* @param starter an optional identifier for the <a href="http://www.w3.org/TR/prov-dm/#start.starter">activity</a> that generated the (possibly unspecified) entity
* @return an instance of {@link WasStartedBy}
*/
public WasStartedBy newWasStartedBy(QualifiedName id, QualifiedName activity, QualifiedName trigger, QualifiedName starter) {
WasStartedBy res=newWasStartedBy(id,activity,trigger);
res.setStarter(starter);
return res;
}
/* (non-Javadoc)
* @see org.openprovenance.prov.model.ModelConstructor#newWasStartedBy(org.openprovenance.model.QualifiedName, org.openprovenance.model.QualifiedName, org.openprovenance.model.QualifiedName, org.openprovenance.model.QualifiedName, javax.xml.datatype.XMLGregorianCalendar, java.util.Collection)
*/
public WasStartedBy newWasStartedBy(QualifiedName id, QualifiedName activity, QualifiedName trigger, QualifiedName starter, XMLGregorianCalendar time, Collection<Attribute> attributes) {
WasStartedBy res=newWasStartedBy(id,activity,trigger);
res.setTime(time);
res.setStarter(starter);
setAttributes(res, attributes);
return res;
}
public WasStartedBy newWasStartedBy(WasStartedBy u) {
WasStartedBy u1 = newWasStartedBy(u.getId(), u.getActivity(),
u.getTrigger());
u1.setStarter(u.getStarter());
u1.setTime(u.getTime());
u1.getType().addAll(u.getType());
u1.getLabel().addAll(u.getLabel());
u1.getLocation().addAll(u.getLocation());
u1.getOther().addAll(u.getOther());
return u1;
}
public XMLGregorianCalendar newXMLGregorianCalendar(GregorianCalendar gc) {
return dataFactory.newXMLGregorianCalendar(gc);
}
public XMLGregorianCalendar newYear(int year) {
XMLGregorianCalendar res=dataFactory.newXMLGregorianCalendar();
res.setYear(year);
return res;
}
public Collection<Attribute> getAttributes(Statement statement) {
Collection<Attribute> result=new LinkedList<Attribute>();
if (statement instanceof HasType) result.addAll(((HasType)statement).getType());
if (statement instanceof HasLocation) result.addAll(((HasLocation)statement).getLocation());
if (statement instanceof HasRole) result.addAll(((HasRole)statement).getRole());
if (statement instanceof HasValue) {
Value val=((HasValue)statement).getValue();
if (val!=null) {
result.add(val);
}
}
if (statement instanceof HasOther) {
for (Other o: ((HasOther)statement).getOther()) {
result.add((Attribute)o);
}
}
return result;
}
public void setAttributes(HasOther res, Collection<Attribute> attributes) {
if (attributes==null) return;
HasType typ=(res instanceof HasType)? (HasType)res : null;
HasLocation loc=(res instanceof HasLocation)? (HasLocation)res : null;
HasLabel lab=(res instanceof HasLabel)? (HasLabel)res : null;
HasValue aval=(res instanceof HasValue)? (HasValue)res : null;
HasRole rol=(res instanceof HasRole)? (HasRole)res : null;
for (Attribute attr: attributes) {
Object aValue=attr.getValue();
ValueConverter vconv=new ValueConverter(this);
if (getName().RDF_LITERAL.equals(attr.getType())&& (aValue instanceof String)) {
aValue=vconv.convertToJava(attr.getType(),(String)aValue);
}
switch (attr.getKind()) {
case PROV_LABEL:
if (lab!=null) {
if (aValue instanceof LangString) {
lab.getLabel().add((LangString) aValue);
} else {
lab.getLabel().add(newInternationalizedString(aValue.toString()));
}
}
break;
case PROV_LOCATION:
if (loc!=null) {
loc.getLocation().add(newLocation(aValue,attr.getType()));
}
break;
case PROV_ROLE:
if (rol!=null) {
rol.getRole().add(newRole(aValue,attr.getType()));
}
break;
case PROV_TYPE:
if (typ!=null) {
typ.getType().add(newType(aValue,attr.getType()));
}
break;
case PROV_VALUE:
if (aval!=null) {
aval.setValue(newValue(aValue,attr.getType()));
}
break;
case OTHER:
res.getOther().add(newOther(attr.getElementName(), aValue, attr.getType()));
break;
default:
break;
}
}
}
@Override
public void startBundle(QualifiedName bundleId, Namespace namespaces) {
}
/* Uses the xsd:type to java:type mapping of JAXB */
@Override
public void startDocument(Namespace namespace) {
}
public Namespace newNamespace(Namespace ns) {
return new Namespace(ns);
}
public Namespace newNamespace() {
return new Namespace();
}
public AlternateOf newAlternateOf(AlternateOf s) {
AlternateOf res=newAlternateOf(s.getAlternate1(), s.getAlternate2());
return res;
}
public SpecializationOf newSpecializationOf(SpecializationOf s) {
SpecializationOf res=newSpecializationOf(s.getSpecificEntity(), s.getGeneralEntity());
return res;
}
public HadMember newHadMember(HadMember s) {
HadMember res=newHadMember(s.getCollection(), s.getEntity()); //FIXME: clone collection
return res;
}
ProvUtilities util=new ProvUtilities();
@SuppressWarnings("unchecked")
public <T extends Statement> T newStatement(T s) {
return (T) util.doAction(s,new Cloner());
}
public class Cloner implements StatementActionValue {
@Override
public Object doAction(Activity s) {
return newActivity(s);
}
@Override
public Object doAction(Used s) {
return newUsed(s);
}
@Override
public Object doAction(WasStartedBy s) {
return newWasStartedBy(s);
}
@Override
public Object doAction(Agent s) {
return newAgent(s);
}
@Override
public Object doAction(AlternateOf s) {
return newAlternateOf(s);
}
@Override
public Object doAction(WasAssociatedWith s) {
return newWasAssociatedWith(s);
}
@Override
public Object doAction(WasAttributedTo s) {
return newWasAttributedTo(s);
}
@Override
public Object doAction(WasInfluencedBy s) {
return newWasInfluencedBy(s);
}
@Override
public Object doAction(ActedOnBehalfOf s) {
return newActedOnBehalfOf(s);
}
@Override
public Object doAction(WasDerivedFrom s) {
return newWasDerivedFrom(s);
}
@Override
public Object doAction(DictionaryMembership s) {
throw new UnsupportedOperationException();
}
@Override
public Object doAction(DerivedByRemovalFrom s) {
throw new UnsupportedOperationException();
}
@Override
public Object doAction(WasEndedBy s) {
return newWasEndedBy(s);
}
@Override
public Object doAction(Entity s) {
return newEntity(s);
}
@Override
public Object doAction(WasGeneratedBy s) {
return newWasGeneratedBy(s);
}
@Override
public Object doAction(WasInvalidatedBy s) {
return newWasInvalidatedBy(s);
}
@Override
public Object doAction(HadMember s) {
return newHadMember(s);
}
@Override
public Object doAction(MentionOf s) {
return newMentionOf(s);
}
@Override
public Object doAction(SpecializationOf s) {
return newSpecializationOf(s);
}
@Override
public Object doAction(DerivedByInsertionFrom s) {
throw new UnsupportedOperationException();
}
@Override
public Object doAction(WasInformedBy s) {
return newWasInformedBy(s);
}
@Override
public Object doAction(Bundle s, ProvUtilities provUtilities) {
throw new UnsupportedOperationException();
}
}
}
| |
package thirdparty.ods;
import algorithms.util.ObjectSpaceEstimator;
import gnu.trove.iterator.TIntObjectIterator;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.set.TIntSet;
import gnu.trove.set.hash.TIntHashSet;
import java.util.ArrayList;
import java.util.List;
/*
The class is adapted from the open datastructures source code
http://opendatastructures.org/ods-java.pdf
"The source code available there is released under a Creative Commons
Attribution license, meaning that anyone is free to share: to copy, distribute
and transmit the work; and to remix: to adapt the work, including
the right to make commercial use of the work. The only condition on
these rights is attribution: you must acknowledge that the derived work
contains code and/or text from opendatastructures.org.
https://github.com/patmorin/ods
Edits were made to the code in project
https://github.com/nking/curvature-scale-space-corners-and-transformations
w/ Copyright (c) 2014 Climb With Your Feet, The MIT License (MIT)
and then moved to this project
*/
@SuppressWarnings("unchecked")
public class XFastTrie<S extends XFastTrieNode<T>, T>
extends BinaryTrie<S, T> {
/**
* The hash tables used to store prefixes
*/
protected final List<TIntObjectHashMap<S>> t;
public XFastTrie(S sampleNode, Integerizer<T> it) {
super(sampleNode, it);
t = new ArrayList<TIntObjectHashMap<S>>();
S nil = (S)new XFastTrieNode<T>();
nil.prefix = Integer.MIN_VALUE;
for (int i = 0; i <= w; i++) {
t.add(new TIntObjectHashMap<S>());
}
t.get(0).put(0, r);
}
public XFastTrie(S sampleNode, Integerizer<T> it,
int smallerWordSize) {
super(sampleNode, it, smallerWordSize);
t = new ArrayList<TIntObjectHashMap<S>>();
S nil = (S)new XFastTrieNode<T>();
nil.prefix = Integer.MIN_VALUE;
for (int i = 0; i <= w; i++) {
t.add(new TIntObjectHashMap<S>());
}
t.get(0).put(0, r);
}
@SuppressWarnings("unchecked")
public XFastTrie(Integerizer<T> it) {
this((S)new XFastTrieNode<T>(), it);
}
/**
* runtime complexity is O(log_2(w)) + O(w-l)
* where w is the number of
* bits set in the constructor, else is 32
* and l is the prefix tree already filled leading
* up to the value x.
* @param x
* @return
*/
public boolean add(T x) {
final int ix = it.intValue(x);
if (ix > maxC) {
throw new IllegalArgumentException("w=" + w
+ " so max value can add is " + maxC
+ " . ix=" + ix);
}
S u = r;
S v;
int i;
int l = 0, h = w+1;
int prefix = -1;
// binary search over range w; rt is < O(lg_2(w))
while (h-l > 1) {
i = (l+h)/2;
prefix = ix >>> w-i;
v = t.get(i).get(prefix);
if (v == null) {
h = i;
} else {
u = v;
l = i;
}
}
if (l == w) return false; // already contains x - abort
int c = (ix >>> w-l-1) & 1;
S pred = (c == right) ? (S)u.jump : (S)u.jump.child[0];
u.jump = null; // u will have two children shortly
i = l;
// 2 - add path to ix. rt is O(w-l)
for (; i < w; i++) {
c = (ix >>> w-i-1) & 1;
u.child[c] = newNode();
u.child[c].parent = u;
u = (S) u.child[c];
}
u.x = x;
// 3 - add u to linked list
u.child[prev] = pred;
u.child[next] = pred.child[next];
u.child[prev].child[next] = u;
u.child[next].child[prev] = u;
// 4 - walk back up, updating jump pointers
v = (u.parent != null) ? (S)u.parent : null;
while (v != null) {
if ((v.child[left] == null
&& (v.jump == null ||
it.intValue(v.jump.x) > ix))
|| (v.child[right] == null
&& (v.jump == null ||
(v.jump.x != null && it.intValue(v.jump.x) < ix))
)) {
v.jump = u;
}
v = (v.parent != null) ? (S)v.parent : null;
}
n++;
u = (S) r.child[(ix >>> w - 1) & 1];
for (i = 1; i <= w; i++) {
u.prefix = ix >>> w - i;
t.get(i).put(u.prefix, u);
c = (ix >>> w - i - 1) & 1;
u = (u.child[c] != null) ? (S) u.child[c] : null;
}
return true;
}
/**
* runtime complexity is O(log_2(w)) + O(w-l)
* where w is the number of
* bits set in the constructor, else is 32
* and l is the prefix tree already filled leading
* up to the value x.
*
* @param x
* @return
*/
@Override
public boolean remove(T x) {
// 1 - find leaf, u, containing x
int i = 0, c, ix = it.intValue(x);
if (ix > maxC) {
throw new IllegalArgumentException("w=" + w
+ " so max value can remove is " + maxC);
}
S u = r;
S v;
int l = 0, h = w+1;
int prefix = -1;
// binary search over range w
while (h-l > 1) {
i = (l+h)/2;
prefix = ix >>> w-i;
v = t.get(i).get(prefix);
if (v == null) {
h = i;
} else {
u = v;
l = i;
}
}
// 2 - remove u from linked list
S pred = (u.child[prev] != null) ? (S)u.child[prev] : null; // predecessor
S succ = (u.child[next] != null) ? (S)u.child[next] : null; // successor
if (pred != null) {
pred.child[next] = succ;
}
if (succ != null) {
succ.child[prev] = pred;
}
u.child[next] = u.child[prev] = null;
S w = u;
// 3 - delete nodes on path to u
while (w != r && w.child[left] == null && w.child[right] == null) {
if (w == w.parent.child[left]) {
w.parent.child[left] = null;
} else { // u == u.parent.child[right]
w.parent.child[right] = null;
}
prefix = w.prefix;
t.get(i--).remove(w.prefix);
w = (w.parent != null) ? (S)w.parent : null;
}
// 4 - update jump pointers
w.jump = (w.child[left] == null) ? succ : pred;
w = (w.parent != null) ? (S)w.parent : null;
while (w != null) {
if (w.jump == u)
w.jump = (w.child[left] == null) ? succ : pred;
w = (w.parent != null) ? (S)w.parent : null;
}
n--;
return true;
}
/**
* find node with key ix.
* runtime complexity is O(1)
* @param ix
* @return
*/
protected S findNode(int ix) {
if (ix > maxC) {
throw new IllegalArgumentException("w=" + w
+ " so max value can search for is " + maxC);
}
S q = t.get(w).get(ix);
return q;
}
/**
* find node key, with key x.
* runtime complexity is O(1).
* @param x
* @return
*/
public T find(T x) {
int ix = it.intValue(x);
S q = findNode(ix);
if (q == null) {
return null;
}
return q.x;
}
/**
* Find the key of the node that contains the successor of x.
* runtime complexity is O(log_2(w)) where w is the number of
* bits set in the constructor, else is 32.
* @param x
* @return The node before the node that contains x w.r.t.
* nodes in the internal the linked list.
*/
@Override
public T successor(T x) {
S q = successorNode(x);
if (q != null) {
return q.x;
}
return null;
}
protected T successor(int ix) {
S q = successorNode(ix);
if (q != null) {
return q.x;
}
return null;
}
protected S successorNode(T x) {
int ix = it.intValue(x);
return successorNode(ix);
}
protected S successorNode(int ix) {
if (ix > maxC) {
throw new IllegalArgumentException("w=" + w
+ " so max value can search for is " + maxC);
}
// find lowest node that is an ancestor of ix
int l = 0, h = w+1;
S v, u = r;
int prefix;
// binary search over range w
while (h-l > 1) {
int i = (l+h)/2;
prefix = ix >>> w-i;
v = t.get(i).get(prefix);
if (v == null) {
h = i;
} else {
u = v;
l = i;
}
}
BinaryTrieNode<T> successor;
if (l == w) {
successor = u.child[next];
} else {
int c = (ix >>> w-l-1) & 1;
successor = (c == 0) ? u.jump : u.jump.child[1];
}
return (successor != null) ? (S)successor : null;
}
/**
* Find the key of the node that contains the predecessor of x.
* runtime complexity is O(log_2(w)) where w is the number of
* bits set in the constructor, else is 32.
* @param x
* @return The node before the node that contains x w.r.t.
* nodes in the internal the linked list.
*/
@Override
public T predecessor(T x) {
S q = predecessorNode(x);
if (q != null) {
// root node will return null here too
return q.x;
}
return null;
}
protected T predecessor(int ix) {
S q = predecessorNode(ix);
if (q != null) {
return q.x;
}
return null;
}
protected S predecessorNode(T x) {
int ix = it.intValue(x);
return predecessorNode(ix);
}
protected S predecessorNode(int ix) {
if (ix > maxC) {
throw new IllegalArgumentException("w=" + w
+ " so max value can search for is " + maxC);
}
// find lowest node that is an ancestor of ix
int l = 0, h = w+1;
S v, u = r;
int prefix = -1;
// binary search over range w
while (h-l > 1) {
int i = (l+h)/2;
prefix = ix >>> w-i;
v = t.get(i).get(prefix);
if (v == null) {
h = i;
} else {
u = v;
l = i;
}
}
if (l == w) {
if (u.child[prev] == null) {
return null;
}
if (u.child[prev].x == null) {
return null;
}
return (S)u.child[prev];
}
int c = (ix >>> w-l-1) & 1;
if (c == 1 && u.jump != null) {
return (S)u.jump;
}
XFastTrieNode<T> pred;
if (u.jump.child[0] == null) {
pred = null;
} else {
pred = (XFastTrieNode<T>) u.jump.child[0];
}
return (pred != null) ? (S)pred : null;
}
public void clear() {
super.clear();
for (TIntObjectHashMap<S> m : t)
m.clear();
}
/**
* find the key of the minimum value node.
* runtime complexity is O(log_2(w)) where w is the number of
* bits set in the constructor, else is 32.
* @return
*/
@Override
public T minimum() {
if (t.get(w).containsKey(0)) {
return t.get(w).get(0).x;
}
return successor(0);
}
/**
* find the key of the minimum value node.
* runtime complexity is O(log_2(w)) where w is the number of
* bits set in the constructor, else is 32.
* @return
*/
@Override
public T maximum() {
if (t.get(w).containsKey(maxC)) {
return t.get(w).get(maxC).x;
}
return predecessor(maxC);
}
/**
* print out the dummy link keys then print the
* root tree in level traversal
*/
void debugNodes() {
TIntSet dummyHashCodes = new TIntHashSet();
S node = dummy;
//System.out.println("dummy.hashCode=" + dummy.hashCode());
System.out.print("\ndummy=");
do {
int dhc = node.hashCode();
System.out.print(node.x + ", ");
dummyHashCodes.add(dhc);
node = (S)node.child[1];
} while (!node.equals(dummy));
System.out.println();
if (r == null) {
return;
}
for (int i = 1; i <= w; ++i) {
System.out.println("level=" + i);
TIntObjectHashMap<S> nodesMap = t.get(i);
TIntObjectIterator<S> iter = nodesMap.iterator();
for (int ii = nodesMap.size(); ii-- > 0;) {
iter.advance();
S nodeL = iter.value();
System.out.println(nodeL.toString2());
}
}
}
public static long estimateSizeOnHeap(int numberOfNodes) {
long node = BinaryTrieNode.estimateSizeOnHeap();
node += ObjectSpaceEstimator.estimateIntSize();
node += ObjectSpaceEstimator.getArrayReferenceSize();
node += ObjectSpaceEstimator.getObjectOverhead();
long heapSize = BinaryTrie.estimateSizeOnHeap(numberOfNodes);
heapSize += ObjectSpaceEstimator.getObjectOverhead();
long total = heapSize + (numberOfNodes * node);
return total;
}
}
| |
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Utility class for working with Strings that have placeholder values in them. A placeholder takes the form
* {@code ${name}}. Using {@code PropertyPlaceholderHelper} these placeholders can be substituted for
* user-supplied values. <p> Values for substitution can be supplied using a {@link Properties} instance or
* using a {@link PlaceholderResolver}.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @since 3.0
*/
public class PropertyPlaceholderHelper {
private static final Log logger = LogFactory.getLog(PropertyPlaceholderHelper.class);
private static final Map<String, String> wellKnownSimplePrefixes = new HashMap<String, String>(4);
static {
wellKnownSimplePrefixes.put("}", "{");
wellKnownSimplePrefixes.put("]", "[");
wellKnownSimplePrefixes.put(")", "(");
}
private final String placeholderPrefix;
private final String placeholderSuffix;
private final String simplePrefix;
private final String valueSeparator;
private final boolean ignoreUnresolvablePlaceholders;
/**
* Creates a new {@code PropertyPlaceholderHelper} that uses the supplied prefix and suffix.
* Unresolvable placeholders are ignored.
* @param placeholderPrefix the prefix that denotes the start of a placeholder
* @param placeholderSuffix the suffix that denotes the end of a placeholder
*/
public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix) {
this(placeholderPrefix, placeholderSuffix, null, true);
}
/**
* Creates a new {@code PropertyPlaceholderHelper} that uses the supplied prefix and suffix.
* @param placeholderPrefix the prefix that denotes the start of a placeholder
* @param placeholderSuffix the suffix that denotes the end of a placeholder
* @param valueSeparator the separating character between the placeholder variable
* and the associated default value, if any
* @param ignoreUnresolvablePlaceholders indicates whether unresolvable placeholders should
* be ignored ({@code true}) or cause an exception ({@code false})
*/
public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix,
String valueSeparator, boolean ignoreUnresolvablePlaceholders) {
Assert.notNull(placeholderPrefix, "'placeholderPrefix' must not be null");
Assert.notNull(placeholderSuffix, "'placeholderSuffix' must not be null");
this.placeholderPrefix = placeholderPrefix;
this.placeholderSuffix = placeholderSuffix;
String simplePrefixForSuffix = wellKnownSimplePrefixes.get(this.placeholderSuffix);
if (simplePrefixForSuffix != null && this.placeholderPrefix.endsWith(simplePrefixForSuffix)) {
this.simplePrefix = simplePrefixForSuffix;
}
else {
this.simplePrefix = this.placeholderPrefix;
}
this.valueSeparator = valueSeparator;
this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
}
/**
* Replaces all placeholders of format {@code ${name}} with the corresponding
* property from the supplied {@link Properties}.
* @param value the value containing the placeholders to be replaced
* @param properties the {@code Properties} to use for replacement
* @return the supplied value with placeholders replaced inline
*/
public String replacePlaceholders(String value, final Properties properties) {
Assert.notNull(properties, "'properties' must not be null");
return replacePlaceholders(value, new PlaceholderResolver() {
@Override
public String resolvePlaceholder(String placeholderName) {
return properties.getProperty(placeholderName);
}
});
}
/**
* Replaces all placeholders of format {@code ${name}} with the value returned
* from the supplied {@link PlaceholderResolver}.
* @param value the value containing the placeholders to be replaced
* @param placeholderResolver the {@code PlaceholderResolver} to use for replacement
* @return the supplied value with placeholders replaced inline
*/
public String replacePlaceholders(String value, PlaceholderResolver placeholderResolver) {
Assert.notNull(value, "'value' must not be null");
return parseStringValue(value, placeholderResolver, new HashSet<String>());
}
protected String parseStringValue(
String strVal, PlaceholderResolver placeholderResolver, Set<String> visitedPlaceholders) {
StringBuilder result = new StringBuilder(strVal);
int startIndex = strVal.indexOf(this.placeholderPrefix);
while (startIndex != -1) {
int endIndex = findPlaceholderEndIndex(result, startIndex);
if (endIndex != -1) {
String placeholder = result.substring(startIndex + this.placeholderPrefix.length(), endIndex);
String originalPlaceholder = placeholder;
if (!visitedPlaceholders.add(originalPlaceholder)) {
throw new IllegalArgumentException(
"Circular placeholder reference '" + originalPlaceholder + "' in property definitions");
}
// Recursive invocation, parsing placeholders contained in the placeholder key.
placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders);
// Now obtain the value for the fully resolved key...
String propVal = placeholderResolver.resolvePlaceholder(placeholder);
if (propVal == null && this.valueSeparator != null) {
int separatorIndex = placeholder.indexOf(this.valueSeparator);
if (separatorIndex != -1) {
String actualPlaceholder = placeholder.substring(0, separatorIndex);
String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
if (propVal == null) {
propVal = defaultValue;
}
}
}
if (propVal != null) {
// Recursive invocation, parsing placeholders contained in the
// previously resolved placeholder value.
propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders);
result.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
if (logger.isTraceEnabled()) {
logger.trace("Resolved placeholder '" + placeholder + "'");
}
startIndex = result.indexOf(this.placeholderPrefix, startIndex + propVal.length());
}
else if (this.ignoreUnresolvablePlaceholders) {
// Proceed with unprocessed value.
startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
}
else {
throw new IllegalArgumentException("Could not resolve placeholder '" +
placeholder + "'" + " in string value \"" + strVal + "\"");
}
visitedPlaceholders.remove(originalPlaceholder);
}
else {
startIndex = -1;
}
}
return result.toString();
}
private int findPlaceholderEndIndex(CharSequence buf, int startIndex) {
int index = startIndex + this.placeholderPrefix.length();
int withinNestedPlaceholder = 0;
while (index < buf.length()) {
if (StringUtils.substringMatch(buf, index, this.placeholderSuffix)) {
if (withinNestedPlaceholder > 0) {
withinNestedPlaceholder--;
index = index + this.placeholderSuffix.length();
}
else {
return index;
}
}
else if (StringUtils.substringMatch(buf, index, this.simplePrefix)) {
withinNestedPlaceholder++;
index = index + this.simplePrefix.length();
}
else {
index++;
}
}
return -1;
}
/**
* Strategy interface used to resolve replacement values for placeholders contained in Strings.
*/
public static interface PlaceholderResolver {
/**
* Resolve the supplied placeholder name to the replacement value.
* @param placeholderName the name of the placeholder to resolve
* @return the replacement value, or {@code null} if no replacement is to be made
*/
String resolvePlaceholder(String placeholderName);
}
}
| |
/*
* YouPloader Copyright (c) 2016 genuineparts (itsme@genuineparts.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package at.becast.youploader.database;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import at.becast.youploader.Main;
import at.becast.youploader.templates.Template;
import at.becast.youploader.youtube.data.Video;
import at.becast.youploader.youtube.data.VideoMetadata;
import at.becast.youploader.youtube.playlists.Playlists;
import at.becast.youploader.youtube.playlists.Playlists.Item;
import at.becast.youploader.youtube.upload.UploadManager;
import at.becast.youploader.youtube.upload.UploadManager.Status;
/**
* A SQL abstraction class for SQLite
*
* @author genuineparts
* @version 1.0
*
*/
public class SQLite {
private static Connection c;
private static final Logger LOG = LoggerFactory.getLogger(SQLite.class);
private SQLite( String database ){
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:"+database);
} catch ( Exception e ) {
LOG.error("SQLite ", e);
}
}
public static Connection getInstance(){
if(c == null)
new SQLite(Main.DB_FILE);
return c;
}
/**
* A simple SQL query without any return.
*
* @param sql The SQL query
* @throws SQLException
*/
public static void query(String sql) throws SQLException{
PreparedStatement prest = null;
prest = c.prepareStatement(sql);
prest.executeUpdate();
prest.close();
}
/**
* Returns the DB Version for App Update purposes
*
* @return An Integer with the current DB Version or 0 if there was a Error getting the Version
* @throws SQLException
*/
public static int getVersion() throws SQLException{
PreparedStatement prest = null;
String sql = "PRAGMA `user_version`";
prest = c.prepareStatement(sql);
ResultSet rs = prest.executeQuery();
if (rs.next()){
int version = rs.getInt(1);
rs.close();
return version;
}else{
return 0;
}
}
/**
* Sets the DB Version for App Update purposes
*
* @param version The desired Version to set the DB to
* @throws SQLException
*/
public static void setVersion(int version) throws SQLException{
String sql = "PRAGMA `user_version`="+version;
query(sql);
}
public static int addUpload(File file, Video data, VideoMetadata metadata, Date startAt) throws SQLException, IOException{
PreparedStatement prest = null;
ObjectMapper mapper = new ObjectMapper();
String sql = "INSERT INTO `uploads` (`account`, `file`, `lenght`, `data`,`enddir`, `metadata`, `status`,`starttime`) " +
"VALUES (?,?,?,?,?,?,?,?)";
prest = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
prest.setInt(1, metadata.getAccount());
prest.setString(2, file.getAbsolutePath());
prest.setLong(3, file.length());
prest.setString(4, mapper.writeValueAsString(data));
prest.setString(5, metadata.getEndDirectory());
prest.setString(6, mapper.writeValueAsString(metadata));
prest.setString(7, UploadManager.Status.NOT_STARTED.toString());
if(startAt==null){
prest.setString(8, "");
}else{
prest.setDate(8, new java.sql.Date(startAt.getTime()));
}
prest.execute();
ResultSet rs = prest.getGeneratedKeys();
prest.close();
if (rs.next()){
int id = rs.getInt(1);
rs.close();
return id;
}else{
return -1;
}
}
public static Boolean prepareUpload(int id, String Url, String yt_id){
PreparedStatement prest = null;
String sql = "UPDATE `uploads` SET `status`=?,`url`=?,`yt_id`=? WHERE `id`=?";
try {
prest = c.prepareStatement(sql);
prest.setString(1, UploadManager.Status.PREPARED.toString());
prest.setString(2, Url);
prest.setString(3, yt_id);
prest.setInt(4, id);
boolean res = prest.execute();
prest.close();
return res;
} catch (SQLException e) {
LOG.error("Error preparing upload", e);
return false;
}
}
public static Boolean startUpload(int id, long progress){
PreparedStatement prest = null;
String sql = "UPDATE `uploads` SET `status`=?,`uploaded`=? WHERE `id`=?";
try {
prest = c.prepareStatement(sql);
prest.setString(1, UploadManager.Status.UPLOADING.toString());
prest.setLong(2, progress);
prest.setInt(3, id);
boolean res = prest.execute();
prest.close();
return res;
} catch (SQLException e) {
LOG.error("Error starting upload", e);
return false;
}
}
public static Boolean updateUploadProgress(int id, long progress){
PreparedStatement prest = null;
String sql = "UPDATE `uploads` SET `uploaded`=? WHERE `id`=?";
try {
prest = c.prepareStatement(sql);
prest.setLong(1, progress);
prest.setInt(2, id);
boolean res = prest.execute();
prest.close();
return res;
} catch (SQLException e) {
LOG.error("Error updating upload progress", e);
return false;
}
}
public static Boolean setUploadFinished(int upload_id, Status Status) {
PreparedStatement prest = null;
String sql = "UPDATE `uploads` SET `status`=?,`url`=?,`uploaded`=`lenght` WHERE `id`=?";
try {
prest = c.prepareStatement(sql);
prest.setString(1, Status.toString());
prest.setString(2, "");
prest.setInt(3, upload_id);
boolean res = prest.execute();
prest.close();
return res;
} catch (SQLException e) {
LOG.error("Error marking upload as finished", e);
return false;
}
}
public static Boolean deleteUpload(int upload_id) {
PreparedStatement prest = null;
String sql = "DELETE FROM `uploads` WHERE `id`=?";
try {
prest = c.prepareStatement(sql);
prest.setInt(1, upload_id);
boolean res = prest.execute();
prest.close();
return res;
} catch (SQLException e) {
LOG.error("Error deleting upload", e);
return false;
}
}
public static boolean failUpload(int upload_id) {
PreparedStatement prest = null;
String sql = "UPDATE `uploads` SET `status`=?,`uploaded`=? WHERE `id`=?";
try {
prest = c.prepareStatement(sql);
prest.setString(1, UploadManager.Status.FAILED.toString());
prest.setInt(3, upload_id);
boolean res = prest.execute();
prest.close();
return res;
} catch (SQLException e) {
LOG.error("Error marking upload as failed", e);
return false;
}
}
public static Boolean updateUpload(int account, File file, Video data, String enddir, VideoMetadata metadata, int id) throws SQLException, IOException{
PreparedStatement prest = null;
String sql = "UPDATE `uploads` SET `account`=?, `file`=?, `lenght`=?, `enddir`=? WHERE `id`=?";
prest = c.prepareStatement(sql);
prest.setInt(1, account);
prest.setString(2, file.getAbsolutePath());
prest.setLong(3, file.length());
prest.setString(4, enddir);
prest.setInt(5, id);
boolean res = prest.execute();
prest.close();
boolean upd = updateUploadData(data, metadata, id);
return res && upd;
}
public static Boolean updateUploadData(Video data, VideoMetadata metadata, int id) throws SQLException, IOException{
PreparedStatement prest = null;
ObjectMapper mapper = new ObjectMapper();
String sql = "UPDATE `uploads` SET `data`=?,`metadata`=? WHERE `id`=?";
prest = c.prepareStatement(sql);
prest.setString(1, mapper.writeValueAsString(data));
prest.setString(2, mapper.writeValueAsString(metadata));
prest.setInt(3, id);
boolean res = prest.execute();
prest.close();
return res;
}
public static int saveTemplate(Template template) throws SQLException, IOException{
PreparedStatement prest = null;
ObjectMapper mapper = new ObjectMapper();
String sql = "INSERT INTO `templates` (`name`, `data`) " +
"VALUES (?,?)";
prest = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
prest.setString(1, template.getName());
prest.setString(2, mapper.writeValueAsString(template));
prest.execute();
ResultSet rs = prest.getGeneratedKeys();
prest.close();
if (rs.next()){
int id = rs.getInt(1);
rs.close();
return id;
}else{
return -1;
}
}
public static Boolean updateTemplate(int id, Template template) throws SQLException, IOException {
PreparedStatement prest = null;
ObjectMapper mapper = new ObjectMapper();
String sql = "UPDATE `templates` SET `data`=? WHERE `id`=?";
prest = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
prest.setString(1, mapper.writeValueAsString(template));
prest.setInt(2, id);
boolean res = prest.execute();
prest.close();
return res;
}
public static Boolean deleteTemplate(int id) {
PreparedStatement prest = null;
String sql = "DELETE FROM `templates` WHERE `id`=?";
try {
prest = c.prepareStatement(sql);
prest.setInt(1, id);
boolean res = prest.execute();
prest.close();
return res;
} catch (SQLException e) {
LOG.error("Error deleting Template ", e);
return false;
}
}
public static void savePlaylists(Playlists playlists, int account) throws SQLException, IOException{
PreparedStatement prest = null;
String sql = "INSERT INTO `playlists` (`name`, `playlistid`,`image`,`account`) " +
"VALUES (?,?,?,?)";
for(Playlists.Item i : playlists.items){
prest = c.prepareStatement(sql);
prest.setString(1, i.snippet.title);
prest.setString(2, i.id);
URL url = new URL(i.snippet.thumbnails.default__.url);
InputStream is = null;
is = url.openStream ();
byte[] imageBytes = IOUtils.toByteArray(is);
prest.setBytes(3,imageBytes);
prest.setInt(4, account);
prest.execute();
prest.close();
}
}
public static void updatePlaylist(Item item) throws SQLException, IOException {
PreparedStatement prest = null;
String sql = "UPDATE `playlists` SET `name`=?,`image`=? WHERE `playlistid`=?";
prest = c.prepareStatement(sql);
prest.setString(1, item.snippet.title);
URL url = new URL(item.snippet.thumbnails.default__.url);
InputStream is = null;
is = url.openStream ();
byte[] imageBytes = IOUtils.toByteArray(is);
prest.setBytes(2,imageBytes);
prest.setString(3, item.id);
prest.execute();
prest.close();
}
public static void insertPlaylist(Item item, int account) throws SQLException, IOException {
PreparedStatement prest = null;
String sql = "INSERT INTO `playlists` (`name`, `playlistid`,`image`,`account`,`shown`) " +
"VALUES (?,?,?,?,1)";
prest = c.prepareStatement(sql);
prest.setString(1, item.snippet.title);
prest.setString(2, item.id);
URL url = new URL(item.snippet.thumbnails.default__.url);
InputStream is = null;
is = url.openStream ();
byte[] imageBytes = IOUtils.toByteArray(is);
prest.setBytes(3,imageBytes);
prest.setInt(4, account);
prest.execute();
prest.close();
}
public static void setPlaylistHidden(int id, String hidden) throws SQLException {
PreparedStatement prest = null;
String sql = "UPDATE `playlists` SET `shown`=? WHERE `id`=?";
prest = c.prepareStatement(sql);
prest.setString(1, hidden);
prest.setInt(2, id);
prest.execute();
prest.close();
}
public static void deletePlaylist(int id) {
PreparedStatement prest = null;
String sql = "DELETE FROM `playlists` WHERE `id`=?";
try {
prest = c.prepareStatement(sql);
prest.setInt(1, id);
prest.close();
} catch (SQLException e) {
LOG.error("Error deleting Playlist ", e);
}
}
/**
* Sets the Database up.
*
* @return True if the database was created successfully. False if there was an error.
*/
public static Boolean setup(){
if(c == null)
new SQLite(Main.DB_FILE);
try {
//Settings Table and Data
query("CREATE TABLE `settings` (`name` VARCHAR, `value` VARCHAR)");
query("INSERT INTO `settings` VALUES('client_id','581650568827-44vbqcoujflbo87hbirjdi6jcj3hlnbu.apps.googleusercontent.com')");
query("INSERT INTO `settings` VALUES('clientSecret','l2M4y-lu9uCkSgBdCKp1YAxX')");
query("INSERT INTO `settings` VALUES('tos_agreed','0')");
query("INSERT INTO `settings` VALUES('notify_updates','1')");
query("INSERT INTO `settings` VALUES('width','900')");
query("INSERT INTO `settings` VALUES('height','580')");
query("INSERT INTO `settings` VALUES('left','0')");
query("INSERT INTO `settings` VALUES('top','0')");
//Accounts
query("CREATE TABLE `accounts` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , `name` VARCHAR NOT NULL , `refresh_token` VARCHAR, `cookie` VARCHAR, `active` INTEGER DEFAULT 0)");
//Templates
query("CREATE TABLE `templates` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , `name` VARCHAR, `data` VARCHAR)");
//Uploads
query("CREATE TABLE `uploads` (`id` INTEGER PRIMARY KEY NOT NULL ,`file` VARCHAR,`account` INTEGER DEFAULT (null),`yt_id` VARCHAR, `enddir` VARCHAR ,`url` VARCHAR,`uploaded` INTEGER DEFAULT (null) ,`lenght` INTEGER DEFAULT (null) ,`data` VARCHAR,`metadata` VARCHAR, `status` VARCHAR, `starttime` DATETIME)");
//Playlists
query("CREATE TABLE `playlists` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , `name` VARCHAR, `playlistid` VARCHAR, `image` BLOB, `account` INTEGER DEFAULT (null),`shown` VARCHAR)");
//Set the DB Version
setVersion(Main.getDBVersion());
} catch (SQLException e) {
LOG.error("Error creating Database",e);
return false;
}
return true;
}
/**
* This method applies all required updates to the Database if necessary
*
*/
public static void update() {
try {
switch(getVersion()){
//This falls through intentionally since ALL updates since the version have to be applied.
case 2:
//Version 0.2 -> 0.3
query("INSERT INTO `settings` VALUES('notify_updates','1')");
query("ALTER TABLE `uploads` ADD COLUMN 'metadata' VARCHAR");
case 3:
//Version 0.3 -> 0.4
query("INSERT INTO `settings` VALUES('width','900')");
query("INSERT INTO `settings` VALUES('height','580')");
query("INSERT INTO `settings` VALUES('left','0')");
query("INSERT INTO `settings` VALUES('top','0')");
case 4:
//Version 0.4 -> 0.5
query("CREATE TABLE `playlists` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , `name` VARCHAR, `playlistid` VARCHAR, `image` BLOB, `account` INTEGER DEFAULT (null))");
case 5:
//Version 0.5 -> 0.6
query("ALTER TABLE `playlists` ADD COLUMN 'shown' VARCHAR");
query("ALTER TABLE `uploads` ADD COLUMN 'starttime' DATETIME");
case 6:
case 7:
case 8:
query("INSERT INTO `settings` VALUES('speed','0')");
case 9:
query("DELETE FROM `accounts`");
query("DELETE FROM `uploads`");
default:
setVersion(Main.getDBVersion());
break;
}
} catch (SQLException e) {
LOG.info("Could not update Database ", e);
}
}
public static void close() {
if(c!=null){
try {
c.close();
c = null;
} catch (SQLException e) {
LOG.info("Could not close DB");
}
}
}
public static void makeBackup() {
SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyhhmm");
Date today = new Date();
try {
FileUtils.copyFile(new File(Main.DB_FILE), new File(System.getProperty("user.home") + "/YouPloader/data/bak-" + formatter.format(today) +".db"));
} catch (IOException e) {
LOG.error("Could not create Database Backup ",e);
}
}
}
| |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.impl;
import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull;
import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureFalse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.camunda.bpm.engine.impl.cmd.CommandLogger;
import org.camunda.bpm.engine.impl.cmd.CorrelateAllMessageCmd;
import org.camunda.bpm.engine.impl.cmd.CorrelateMessageCmd;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.interceptor.CommandExecutor;
import org.camunda.bpm.engine.runtime.MessageCorrelationBuilder;
import org.camunda.bpm.engine.runtime.MessageCorrelationResult;
import org.camunda.bpm.engine.runtime.MessageCorrelationResultWithVariables;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
/**
* @author Daniel Meyer
* @author Christopher Zell
*
*/
public class MessageCorrelationBuilderImpl implements MessageCorrelationBuilder {
private final static CommandLogger LOG = ProcessEngineLogger.CMD_LOGGER;
protected CommandExecutor commandExecutor;
protected CommandContext commandContext;
protected boolean isExclusiveCorrelation = false;
protected String messageName;
protected String businessKey;
protected String processInstanceId;
protected String processDefinitionId;
protected VariableMap correlationProcessInstanceVariables;
protected VariableMap correlationLocalVariables;
protected VariableMap payloadProcessInstanceVariables;
protected VariableMap payloadProcessInstanceVariablesLocal;
protected String tenantId = null;
protected boolean isTenantIdSet = false;
protected boolean startMessagesOnly = false;
protected boolean executionsOnly = false;
public MessageCorrelationBuilderImpl(CommandExecutor commandExecutor, String messageName) {
this(messageName);
ensureNotNull("commandExecutor", commandExecutor);
this.commandExecutor = commandExecutor;
}
public MessageCorrelationBuilderImpl(CommandContext commandContext, String messageName) {
this(messageName);
ensureNotNull("commandContext", commandContext);
this.commandContext = commandContext;
}
private MessageCorrelationBuilderImpl(String messageName) {
this.messageName = messageName;
}
public MessageCorrelationBuilder processInstanceBusinessKey(String businessKey) {
ensureNotNull("businessKey", businessKey);
this.businessKey = businessKey;
return this;
}
public MessageCorrelationBuilder processInstanceVariableEquals(String variableName, Object variableValue) {
ensureNotNull("variableName", variableName);
ensureCorrelationProcessInstanceVariablesInitialized();
correlationProcessInstanceVariables.put(variableName, variableValue);
return this;
}
public MessageCorrelationBuilder processInstanceVariablesEqual(Map<String, Object> variables) {
ensureNotNull("variables", variables);
ensureCorrelationProcessInstanceVariablesInitialized();
correlationProcessInstanceVariables.putAll(variables);
return this;
}
public MessageCorrelationBuilder localVariableEquals(String variableName, Object variableValue) {
ensureNotNull("variableName", variableName);
ensureCorrelationLocalVariablesInitialized();
correlationLocalVariables.put(variableName, variableValue);
return this;
}
public MessageCorrelationBuilder localVariablesEqual(Map<String, Object> variables) {
ensureNotNull("variables", variables);
ensureCorrelationLocalVariablesInitialized();
correlationLocalVariables.putAll(variables);
return this;
}
protected void ensureCorrelationProcessInstanceVariablesInitialized() {
if(correlationProcessInstanceVariables == null) {
correlationProcessInstanceVariables = new VariableMapImpl();
}
}
protected void ensureCorrelationLocalVariablesInitialized() {
if(correlationLocalVariables == null) {
correlationLocalVariables = new VariableMapImpl();
}
}
public MessageCorrelationBuilder processInstanceId(String id) {
ensureNotNull("processInstanceId", id);
this.processInstanceId = id;
return this;
}
public MessageCorrelationBuilder processDefinitionId(String processDefinitionId) {
ensureNotNull("processDefinitionId", processDefinitionId);
this.processDefinitionId = processDefinitionId;
return this;
}
public MessageCorrelationBuilder setVariable(String variableName, Object variableValue) {
ensureNotNull("variableName", variableName);
ensurePayloadProcessInstanceVariablesInitialized();
payloadProcessInstanceVariables.put(variableName, variableValue);
return this;
}
public MessageCorrelationBuilder setVariableLocal(String variableName, Object variableValue) {
ensureNotNull("variableName", variableName);
ensurePayloadProcessInstanceVariablesLocalInitialized();
payloadProcessInstanceVariablesLocal.put(variableName, variableValue);
return this;
}
public MessageCorrelationBuilder setVariables(Map<String, Object> variables) {
if (variables != null) {
ensurePayloadProcessInstanceVariablesInitialized();
payloadProcessInstanceVariables.putAll(variables);
}
return this;
}
@Override
public MessageCorrelationBuilder setVariablesLocal(Map<String, Object> variables) {
if (variables != null) {
ensurePayloadProcessInstanceVariablesLocalInitialized();
payloadProcessInstanceVariablesLocal.putAll(variables);
}
return this;
}
protected void ensurePayloadProcessInstanceVariablesInitialized() {
if (payloadProcessInstanceVariables == null) {
payloadProcessInstanceVariables = new VariableMapImpl();
}
}
protected void ensurePayloadProcessInstanceVariablesLocalInitialized() {
if (payloadProcessInstanceVariablesLocal == null) {
payloadProcessInstanceVariablesLocal = new VariableMapImpl();
}
}
public MessageCorrelationBuilder tenantId(String tenantId) {
ensureNotNull(
"The tenant-id cannot be null. Use 'withoutTenantId()' if you want to correlate the message to a process definition or an execution which has no tenant-id.",
"tenantId", tenantId);
isTenantIdSet = true;
this.tenantId = tenantId;
return this;
}
public MessageCorrelationBuilder withoutTenantId() {
isTenantIdSet = true;
tenantId = null;
return this;
}
@Override
public MessageCorrelationBuilder startMessageOnly() {
ensureFalse("Either startMessageOnly or executionsOnly can be set", executionsOnly);
startMessagesOnly = true;
return this;
}
public MessageCorrelationBuilder executionsOnly() {
ensureFalse("Either startMessageOnly or executionsOnly can be set", startMessagesOnly);
executionsOnly = true;
return this;
}
@Override
public void correlate() {
correlateWithResult();
}
@Override
public MessageCorrelationResult correlateWithResult() {
if (startMessagesOnly) {
ensureCorrelationVariablesNotSet();
ensureProcessDefinitionAndTenantIdNotSet();
} else {
ensureProcessDefinitionIdNotSet();
ensureProcessInstanceAndTenantIdNotSet();
}
return execute(new CorrelateMessageCmd(this, false, false, startMessagesOnly));
}
@Override
public MessageCorrelationResultWithVariables correlateWithResultAndVariables(boolean deserializeValues) {
if (startMessagesOnly) {
ensureCorrelationVariablesNotSet();
ensureProcessDefinitionAndTenantIdNotSet();
} else {
ensureProcessDefinitionIdNotSet();
ensureProcessInstanceAndTenantIdNotSet();
}
return execute(new CorrelateMessageCmd(this, true, deserializeValues, startMessagesOnly));
}
@Override
public void correlateExclusively() {
isExclusiveCorrelation = true;
correlate();
}
@Override
public void correlateAll() {
correlateAllWithResult();
}
@Override
public List<MessageCorrelationResult> correlateAllWithResult() {
if (startMessagesOnly) {
ensureCorrelationVariablesNotSet();
ensureProcessDefinitionAndTenantIdNotSet();
// only one result can be expected
MessageCorrelationResult result = execute(new CorrelateMessageCmd(this, false, false, startMessagesOnly));
return Arrays.asList(result);
} else {
ensureProcessDefinitionIdNotSet();
ensureProcessInstanceAndTenantIdNotSet();
return (List) execute(new CorrelateAllMessageCmd(this, false, false));
}
}
@Override
public List<MessageCorrelationResultWithVariables> correlateAllWithResultAndVariables(boolean deserializeValues) {
if (startMessagesOnly) {
ensureCorrelationVariablesNotSet();
ensureProcessDefinitionAndTenantIdNotSet();
// only one result can be expected
MessageCorrelationResultWithVariables result = execute(new CorrelateMessageCmd(this, true, deserializeValues, startMessagesOnly));
return Arrays.asList(result);
} else {
ensureProcessDefinitionIdNotSet();
ensureProcessInstanceAndTenantIdNotSet();
return (List) execute(new CorrelateAllMessageCmd(this, true, deserializeValues));
}
}
public ProcessInstance correlateStartMessage() {
startMessageOnly();
MessageCorrelationResult result = correlateWithResult();
return result.getProcessInstance();
}
protected void ensureProcessDefinitionIdNotSet() {
if(processDefinitionId != null) {
throw LOG.exceptionCorrelateMessageWithProcessDefinitionId();
}
}
protected void ensureProcessInstanceAndTenantIdNotSet() {
if (processInstanceId != null && isTenantIdSet) {
throw LOG.exceptionCorrelateMessageWithProcessInstanceAndTenantId();
}
}
protected void ensureCorrelationVariablesNotSet() {
if (correlationProcessInstanceVariables != null || correlationLocalVariables != null) {
throw LOG.exceptionCorrelateStartMessageWithCorrelationVariables();
}
}
protected void ensureProcessDefinitionAndTenantIdNotSet() {
if (processDefinitionId != null && isTenantIdSet) {
throw LOG.exceptionCorrelateMessageWithProcessDefinitionAndTenantId();
}
}
protected <T> T execute(Command<T> command) {
if(commandExecutor != null) {
return commandExecutor.execute(command);
} else {
return command.execute(commandContext);
}
}
// getters //////////////////////////////////
public CommandExecutor getCommandExecutor() {
return commandExecutor;
}
public CommandContext getCommandContext() {
return commandContext;
}
public String getMessageName() {
return messageName;
}
public String getBusinessKey() {
return businessKey;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public Map<String, Object> getCorrelationProcessInstanceVariables() {
return correlationProcessInstanceVariables;
}
public Map<String, Object> getCorrelationLocalVariables() {
return correlationLocalVariables;
}
public Map<String, Object> getPayloadProcessInstanceVariables() {
return payloadProcessInstanceVariables;
}
public VariableMap getPayloadProcessInstanceVariablesLocal() {
return payloadProcessInstanceVariablesLocal;
}
public boolean isExclusiveCorrelation() {
return isExclusiveCorrelation;
}
public String getTenantId() {
return tenantId;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isExecutionsOnly() {
return executionsOnly;
}
}
| |
package org.apache.lucene.facet.collections;
import java.util.HashSet;
import java.util.Random;
import org.apache.lucene.facet.FacetTestCase;
import org.apache.lucene.facet.collections.FloatIterator;
import org.apache.lucene.facet.collections.IntIterator;
import org.apache.lucene.facet.collections.IntToFloatMap;
import org.junit.Test;
/*
* 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.
*/
public class IntToFloatMapTest extends FacetTestCase {
private static void assertGround(float value) {
assertEquals(IntToFloatMap.GROUND, value, Float.MAX_VALUE);
}
@Test
public void test0() {
IntToFloatMap map = new IntToFloatMap();
assertGround(map.get(0));
for (int i = 0; i < 100; ++i) {
int value = 100 + i;
assertFalse(map.containsValue(value));
map.put(i, value);
assertTrue(map.containsValue(value));
assertNotNull(map.get(i));
}
assertEquals(100, map.size());
for (int i = 0; i < 100; ++i) {
assertTrue(map.containsKey(i));
assertEquals(100 + i, map.get(i), Float.MAX_VALUE);
}
for (int i = 10; i < 90; ++i) {
map.remove(i);
assertGround(map.get(i));
}
assertEquals(20, map.size());
for (int i = 0; i < 100; ++i) {
assertEquals(map.containsKey(i), !(i >= 10 && i < 90));
}
for (int i = 5; i < 85; ++i) {
map.put(i, Integer.valueOf(5 + i));
}
assertEquals(95, map.size());
for (int i = 0; i < 100; ++i) {
assertEquals(map.containsKey(i), !(i >= 85 && i < 90));
}
for (int i = 0; i < 5; ++i) {
assertEquals(map.get(i), (100 + i), Float.MAX_VALUE);
}
for (int i = 5; i < 85; ++i) {
assertEquals(map.get(i), (5 + i), Float.MAX_VALUE);
}
for (int i = 90; i < 100; ++i) {
assertEquals(map.get(i), (100 + i), Float.MAX_VALUE);
}
}
@Test
public void test1() {
IntToFloatMap map = new IntToFloatMap();
for (int i = 0; i < 100; ++i) {
map.put(i, Integer.valueOf(100 + i));
}
HashSet<Float> set = new HashSet<Float>();
for (FloatIterator iterator = map.iterator(); iterator.hasNext();) {
set.add(iterator.next());
}
assertEquals(set.size(), map.size());
for (int i = 0; i < 100; ++i) {
assertTrue(set.contains(Float.valueOf(100+i)));
}
set.clear();
for (FloatIterator iterator = map.iterator(); iterator.hasNext();) {
float d = iterator.next();
if (d % 2 == 1) {
iterator.remove();
continue;
}
set.add(d);
}
assertEquals(set.size(), map.size());
for (int i = 0; i < 100; i+=2) {
assertTrue(set.contains(Float.valueOf(100+i)));
}
}
@Test
public void test2() {
IntToFloatMap map = new IntToFloatMap();
assertTrue(map.isEmpty());
assertGround(map.get(0));
for (int i = 0; i < 128; ++i) {
int value = i * 4096;
assertFalse(map.containsValue(value));
map.put(i, value);
assertTrue(map.containsValue(value));
assertNotNull(map.get(i));
assertFalse(map.isEmpty());
}
assertEquals(128, map.size());
for (int i = 0; i < 128; ++i) {
assertTrue(map.containsKey(i));
assertEquals(i * 4096, map.get(i), Float.MAX_VALUE);
}
for (int i = 0 ; i < 200; i+=2) {
map.remove(i);
}
assertEquals(64, map.size());
for (int i = 1; i < 128; i+=2) {
assertTrue(map.containsKey(i));
assertEquals(i * 4096, map.get(i), Float.MAX_VALUE);
map.remove(i);
}
assertTrue(map.isEmpty());
}
@Test
public void test3() {
IntToFloatMap map = new IntToFloatMap();
int length = 100;
for (int i = 0; i < length; ++i) {
map.put(i*64, 100 + i);
}
HashSet<Integer> keySet = new HashSet<Integer>();
for (IntIterator iit = map.keyIterator(); iit.hasNext(); ) {
keySet.add(iit.next());
}
assertEquals(length, keySet.size());
for (int i = 0; i < length; ++i) {
assertTrue(keySet.contains(i * 64));
}
HashSet<Float> valueSet = new HashSet<Float>();
for (FloatIterator iit = map.iterator(); iit.hasNext(); ) {
valueSet.add(iit.next());
}
assertEquals(length, valueSet.size());
float[] array = map.toArray();
assertEquals(length, array.length);
for (float value: array) {
assertTrue(valueSet.contains(value));
}
float[] array2 = new float[80];
array2 = map.toArray(array2);
assertEquals(length, array2.length);
for (float value: array2) {
assertTrue(valueSet.contains(value));
}
float[] array3 = new float[120];
array3 = map.toArray(array3);
for (int i = 0 ;i < length; ++i) {
assertTrue(valueSet.contains(array3[i]));
}
for (int i = 0; i < length; ++i) {
assertTrue(map.containsValue(i + 100));
assertTrue(map.containsKey(i*64));
}
for (IntIterator iit = map.keyIterator(); iit.hasNext(); ) {
iit.next();
iit.remove();
}
assertTrue(map.isEmpty());
assertEquals(0, map.size());
}
// now with random data.. and lots of it
@Test
public void test4() {
IntToFloatMap map = new IntToFloatMap();
int length = ArrayHashMapTest.RANDOM_TEST_NUM_ITERATIONS;
// for a repeatable random sequence
long seed = random().nextLong();
Random random = new Random(seed);
for (int i = 0; i < length; ++i) {
int value = random.nextInt(Integer.MAX_VALUE);
map.put(i*128, value);
}
assertEquals(length, map.size());
// now repeat
random.setSeed(seed);
for (int i = 0; i < length; ++i) {
int value = random.nextInt(Integer.MAX_VALUE);
assertTrue(map.containsValue(value));
assertTrue(map.containsKey(i*128));
assertEquals(0, Float.compare(value, map.remove(i*128)));
}
assertEquals(0, map.size());
assertTrue(map.isEmpty());
}
@Test
public void testEquals() {
IntToFloatMap map1 = new IntToFloatMap(100);
IntToFloatMap map2 = new IntToFloatMap(100);
assertEquals("Empty maps should be equal", map1, map2);
assertEquals("hashCode() for empty maps should be equal",
map1.hashCode(), map2.hashCode());
for (int i = 0; i < 100; ++i) {
map1.put(i, Float.valueOf(1f/i));
map2.put(i, Float.valueOf(1f/i));
}
assertEquals("Identical maps should be equal", map1, map2);
assertEquals("hashCode() for identical maps should be equal",
map1.hashCode(), map2.hashCode());
for (int i = 10; i < 20; i++) {
map1.remove(i);
}
assertFalse("Different maps should not be equal", map1.equals(map2));
for (int i = 19; i >=10; --i) {
map2.remove(i);
}
assertEquals("Identical maps should be equal", map1, map2);
assertEquals("hashCode() for identical maps should be equal",
map1.hashCode(), map2.hashCode());
map1.put(-1,-1f);
map2.put(-1,-1.1f);
assertFalse("Different maps should not be equal", map1.equals(map2));
map2.put(-1,-1f);
assertEquals("Identical maps should be equal", map1, map2);
assertEquals("hashCode() for identical maps should be equal",
map1.hashCode(), map2.hashCode());
}
}
| |
/*
* 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 androidx.camera.core;
import android.os.Build;
import android.util.Log;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
/**
* Handles logging requests inside CameraX. Log messages are output only if:
* - The minimum logging level allows for it. The minimum logging level is set via
* {@link #setMinLogLevel(int)}, which should typically be called during the process of configuring
* CameraX.
* - The log tag is {@linkplain Log#isLoggable(String, int) loggable}. This can be configured
* by setting the system property `setprop log.tag.TAG LEVEL`, where TAG is the log tag, and
* LEVEL is {@link Log#DEBUG}, {@link Log#INFO}, {@link Log#WARN} or {@link Log#ERROR}.
* <p> A typical usage of the Logger looks as follows:
* <pre>
* try {
* int quotient = dividend / divisor;
* } catch (ArithmeticException exception) {
* Logger.e(TAG, "Divide operation error", exception);
* }
* </pre>
* <p> If an action has to be performed alongside logging, or if building the log message is costly,
* perform a log level check before attempting to log.
* <pre>
* try {
* int quotient = dividend / divisor;
* } catch (ArithmeticException exception) {
* if (Logger.isErrorEnabled(TAG)) {
* Logger.e(TAG, "Divide operation error", exception);
* doSomething();
* }
* }
* </pre>
*
* @hide
*/
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public final class Logger {
/** On API levels strictly below 24, the log tag's length must not exceed 23 characters. */
private static final int MAX_TAG_LENGTH = 23;
static final int DEFAULT_MIN_LOG_LEVEL = Log.DEBUG;
private static int sMinLogLevel = DEFAULT_MIN_LOG_LEVEL;
private Logger() {
}
/**
* Returns {@code true} if logging with the truncated tag {@code truncatedTag} is
* enabled at the {@code logLevel} level.
*/
private static boolean isLogLevelEnabled(@NonNull String truncatedTag, int logLevel) {
return sMinLogLevel <= logLevel || Log.isLoggable(truncatedTag, logLevel);
}
/**
* Sets the minimum logging level to use in {@link Logger}. After calling this method, only logs
* at the level {@code logLevel} and above are output.
*/
static void setMinLogLevel(@IntRange(from = Log.DEBUG, to = Log.ERROR) int logLevel) {
sMinLogLevel = logLevel;
}
/**
* Returns current minimum logging level.
*/
static int getMinLogLevel() {
return sMinLogLevel;
}
/**
* Resets the minimum logging level to use in {@link Logger} to the default minimum logging
* level. After calling this method, only logs at the default level and above are output.
*/
static void resetMinLogLevel() {
sMinLogLevel = DEFAULT_MIN_LOG_LEVEL;
}
/**
* Returns {@code true} if logging with the tag {@code tag} is enabled at the {@link Log#DEBUG}
* level. This is true when the minimum logging level is less than or equal to
* {@link Log#DEBUG}, or if the log level of {@code tag} was explicitly set to
* {@link Log#DEBUG} at least.
*/
public static boolean isDebugEnabled(@NonNull String tag) {
return isLogLevelEnabled(truncateTag(tag), Log.DEBUG);
}
/**
* Returns {@code true} if logging with the tag {@code tag} is enabled at the {@link Log#INFO}
* level. This is true when the minimum logging level is less than or equal to
* {@link Log#INFO}, or if the log level of {@code tag} was explicitly set to
* {@link Log#INFO} at least.
*/
public static boolean isInfoEnabled(@NonNull String tag) {
return isLogLevelEnabled(truncateTag(tag), Log.INFO);
}
/**
* Returns {@code true} if logging with the tag {@code tag} is enabled at the {@link Log#WARN}
* level. This is true when the minimum logging level is less than or equal to
* {@link Log#WARN}, or if the log level of {@code tag} was explicitly set to
* {@link Log#WARN} at least.
*/
public static boolean isWarnEnabled(@NonNull String tag) {
return isLogLevelEnabled(truncateTag(tag), Log.WARN);
}
/**
* Returns {@code true} if logging with the tag {@code tag} is enabled at the {@link Log#ERROR}
* level. This is true when the minimum logging level is less than or equal to
* {@link Log#ERROR}, or if the log level of {@code tag} was explicitly set to
* {@link Log#ERROR} at least.
*/
public static boolean isErrorEnabled(@NonNull String tag) {
return isLogLevelEnabled(truncateTag(tag), Log.ERROR);
}
/**
* Logs the given {@link Log#DEBUG} message if the tag is
* {@linkplain #isDebugEnabled(String) loggable}.
*/
public static void d(@NonNull String tag, @NonNull String message) {
final String truncatedTag = truncateTag(tag);
if (isLogLevelEnabled(truncatedTag, Log.DEBUG)) {
Log.d(truncatedTag, message);
}
}
/**
* Logs the given {@link Log#DEBUG} message and the exception's stacktrace if the tag is
* {@linkplain #isDebugEnabled(String) loggable}.
*/
public static void d(@NonNull String tag, @NonNull String message,
@NonNull final Throwable throwable) {
final String truncatedTag = truncateTag(tag);
if (isLogLevelEnabled(truncatedTag, Log.DEBUG)) {
Log.d(truncatedTag, message, throwable);
}
}
/**
* Logs the given {@link Log#INFO} message if the tag is
* {@linkplain #isInfoEnabled(String) loggable}.
*/
public static void i(@NonNull String tag, @NonNull String message) {
final String truncatedTag = truncateTag(tag);
if (isLogLevelEnabled(truncatedTag, Log.INFO)) {
Log.i(truncatedTag, message);
}
}
/**
* Logs the given {@link Log#INFO} message and the exception's stacktrace if the tag is
* {@linkplain #isInfoEnabled(String) loggable}.
*/
public static void i(@NonNull String tag, @NonNull String message,
@NonNull final Throwable throwable) {
final String truncatedTag = truncateTag(tag);
if (isLogLevelEnabled(truncatedTag, Log.INFO)) {
Log.i(truncatedTag, message, throwable);
}
}
/**
* Logs the given {@link Log#WARN} message if the tag is
* {@linkplain #isWarnEnabled(String) loggable}.
*/
public static void w(@NonNull String tag, @NonNull String message) {
final String truncatedTag = truncateTag(tag);
if (isLogLevelEnabled(truncatedTag, Log.WARN)) {
Log.w(truncatedTag, message);
}
}
/**
* Logs the given {@link Log#WARN} message and the exception's stacktrace if the tag is
* {@linkplain #isWarnEnabled(String) loggable}.
*/
public static void w(@NonNull String tag, @NonNull String message,
@NonNull final Throwable throwable) {
final String truncatedTag = truncateTag(tag);
if (isLogLevelEnabled(truncatedTag, Log.WARN)) {
Log.w(truncatedTag, message, throwable);
}
}
/**
* Logs the given {@link Log#ERROR} message if the tag is
* {@linkplain #isErrorEnabled(String) loggable}.
*/
public static void e(@NonNull String tag, @NonNull String message) {
final String truncatedTag = truncateTag(tag);
if (isLogLevelEnabled(truncatedTag, Log.ERROR)) {
Log.e(truncatedTag, message);
}
}
/**
* Logs the given {@link Log#ERROR} message and the exception's stacktrace if the tag is
* {@linkplain #isErrorEnabled(String) loggable}.
*/
public static void e(@NonNull String tag, @NonNull String message,
@NonNull final Throwable throwable) {
final String truncatedTag = truncateTag(tag);
if (isLogLevelEnabled(truncatedTag, Log.ERROR)) {
Log.e(truncatedTag, message, throwable);
}
}
/**
* Truncates the tag so it can be used to log.
* <p>
* On API 26, the tag length limit of 23 characters was removed.
*/
@NonNull
private static String truncateTag(@NonNull String tag) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1 && MAX_TAG_LENGTH < tag.length()) {
return tag.substring(0, MAX_TAG_LENGTH);
}
return tag;
}
}
| |
/*
* 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.prestosql.server.ui;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Resources;
import com.google.inject.Key;
import io.airlift.http.server.HttpServerConfig;
import io.airlift.http.server.HttpServerInfo;
import io.airlift.http.server.testing.TestingHttpServer;
import io.airlift.node.NodeInfo;
import io.airlift.security.pem.PemReader;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.prestosql.server.security.PasswordAuthenticatorManager;
import io.prestosql.server.testing.TestingPrestoServer;
import io.prestosql.spi.security.AccessDeniedException;
import io.prestosql.spi.security.BasicPrincipal;
import okhttp3.FormBody;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Principal;
import java.security.PrivateKey;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Optional;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.net.HttpHeaders.AUTHORIZATION;
import static com.google.common.net.HttpHeaders.LOCATION;
import static com.google.common.net.HttpHeaders.X_FORWARDED_HOST;
import static com.google.common.net.HttpHeaders.X_FORWARDED_PORT;
import static com.google.common.net.HttpHeaders.X_FORWARDED_PROTO;
import static io.airlift.http.client.HttpUriBuilder.uriBuilderFrom;
import static io.prestosql.client.OkHttpUtil.setupSsl;
import static io.prestosql.server.ui.FormWebUiAuthenticationFilter.DISABLED_LOCATION;
import static io.prestosql.server.ui.FormWebUiAuthenticationFilter.LOGIN_FORM;
import static io.prestosql.server.ui.FormWebUiAuthenticationFilter.UI_LOGIN;
import static io.prestosql.server.ui.FormWebUiAuthenticationFilter.UI_LOGOUT;
import static io.prestosql.testing.assertions.Assert.assertEquals;
import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static javax.servlet.http.HttpServletResponse.SC_SEE_OTHER;
import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.testng.Assert.assertTrue;
@Test
public class TestWebUi
{
private static final String LOCALHOST_KEYSTORE = Resources.getResource("cert/localhost.pem").getPath();
private static final ImmutableMap<String, String> SECURE_PROPERTIES = ImmutableMap.<String, String>builder()
.put("http-server.https.enabled", "true")
.put("http-server.https.keystore.path", LOCALHOST_KEYSTORE)
.put("http-server.https.keystore.key", "")
.put("http-server.process-forwarded", "true")
.put("http-server.authentication.allow-insecure-over-http", "true")
.build();
private static final String TEST_USER = "test-user";
private static final String TEST_PASSWORD = "test-password";
private static final String HMAC_KEY = Resources.getResource("hmac_key.txt").getPath();
private static final PrivateKey JWK_PRIVATE_KEY;
static {
try {
JWK_PRIVATE_KEY = PemReader.loadPrivateKey(new File(Resources.getResource("jwk/jwk-rsa-private.pem").getPath()), Optional.empty());
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private OkHttpClient client;
@BeforeClass
public void setup()
{
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
.followRedirects(false);
setupSsl(
clientBuilder,
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.of(LOCALHOST_KEYSTORE),
Optional.empty(),
Optional.empty());
client = clientBuilder.build();
}
@Test
public void testInsecureAuthenticator()
throws Exception
{
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(SECURE_PROPERTIES)
.build()) {
HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
// insecure authenticator takes any username, but does not allow any password
testFormAuthentication(server, httpServerInfo, false);
}
}
@Test
public void testPasswordAuthenticator()
throws Exception
{
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(ImmutableMap.<String, String>builder()
.putAll(SECURE_PROPERTIES)
.put("http-server.authentication.type", "password")
.build())
.build()) {
server.getInstance(Key.get(PasswordAuthenticatorManager.class)).setAuthenticator(TestWebUi::authenticate);
HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
testFormAuthentication(server, httpServerInfo, true);
}
}
private void testFormAuthentication(TestingPrestoServer server, HttpServerInfo httpServerInfo, boolean sendPasswordForHttps)
throws Exception
{
testRootRedirect(httpServerInfo.getHttpUri(), client);
testRootRedirect(httpServerInfo.getHttpsUri(), client);
String nodeId = server.getInstance(Key.get(NodeInfo.class)).getNodeId();
testWorkerResource(nodeId, httpServerInfo.getHttpUri(), false);
testWorkerResource(nodeId, httpServerInfo.getHttpsUri(), sendPasswordForHttps);
testLoggedOut(httpServerInfo.getHttpUri());
testLoggedOut(httpServerInfo.getHttpsUri());
testLogIn(httpServerInfo.getHttpUri(), false);
testLogIn(httpServerInfo.getHttpsUri(), sendPasswordForHttps);
testFailedLogin(httpServerInfo.getHttpUri(), false);
testFailedLogin(httpServerInfo.getHttpsUri(), sendPasswordForHttps);
}
private static void testRootRedirect(URI baseUri, OkHttpClient client)
throws IOException
{
assertRedirect(client, uriBuilderFrom(baseUri).toString(), getUiLocation(baseUri));
}
private void testLoggedOut(URI baseUri)
throws IOException
{
assertRedirect(client, getUiLocation(baseUri), getLoginHtmlLocation(baseUri));
assertRedirect(client, getLocation(baseUri, "/ui/query.html", "abc123"), getLocation(baseUri, LOGIN_FORM, "/ui/query.html?abc123"), false);
assertResponseCode(client, getValidApiLocation(baseUri), SC_UNAUTHORIZED);
assertOk(client, getValidAssetsLocation(baseUri));
assertOk(client, getValidVendorLocation(baseUri));
}
private void testLogIn(URI baseUri, boolean sendPassword)
throws Exception
{
CookieManager cookieManager = new CookieManager();
OkHttpClient client = this.client.newBuilder()
.cookieJar(new JavaNetCookieJar(cookieManager))
.build();
String body = assertOk(client, getLoginHtmlLocation(baseUri))
.orElseThrow(() -> new AssertionError("No response body"));
assertThat(body).contains("action=\"/ui/login\"");
assertThat(body).contains("method=\"post\"");
assertThat(body).doesNotContain("// This value will be replaced");
if (sendPassword) {
assertThat(body).contains("var hidePassword = false;");
}
else {
assertThat(body).contains("var hidePassword = true;");
}
logIn(baseUri, client, sendPassword);
HttpCookie cookie = getOnlyElement(cookieManager.getCookieStore().getCookies());
assertEquals(cookie.getPath(), "/ui");
assertEquals(cookie.getDomain(), baseUri.getHost());
assertEquals(cookie.getMaxAge(), -1);
assertTrue(cookie.isHttpOnly());
assertOk(client, getUiLocation(baseUri));
assertOk(client, getValidApiLocation(baseUri));
assertResponseCode(client, getLocation(baseUri, "/ui/unknown"), SC_NOT_FOUND);
assertResponseCode(client, getLocation(baseUri, "/ui/api/unknown"), SC_NOT_FOUND);
assertRedirect(client, getLogoutLocation(baseUri), getLoginHtmlLocation(baseUri), false);
assertThat(cookieManager.getCookieStore().getCookies()).isEmpty();
}
private void testFailedLogin(URI uri, boolean passwordAllowed)
throws IOException
{
testFailedLogin(uri, Optional.empty(), Optional.empty());
testFailedLogin(uri, Optional.empty(), Optional.of(TEST_PASSWORD));
testFailedLogin(uri, Optional.empty(), Optional.of("unknown"));
if (passwordAllowed) {
testFailedLogin(uri, Optional.of(TEST_USER), Optional.of("unknown"));
testFailedLogin(uri, Optional.of("unknown"), Optional.of(TEST_PASSWORD));
testFailedLogin(uri, Optional.of(TEST_USER), Optional.empty());
testFailedLogin(uri, Optional.of("unknown"), Optional.empty());
}
}
private void testFailedLogin(URI httpsUrl, Optional<String> username, Optional<String> password)
throws IOException
{
CookieManager cookieManager = new CookieManager();
OkHttpClient client = this.client.newBuilder()
.cookieJar(new JavaNetCookieJar(cookieManager))
.build();
FormBody.Builder formData = new FormBody.Builder();
username.ifPresent(value -> formData.add("username", value));
password.ifPresent(value -> formData.add("password", value));
Request request = new Request.Builder()
.url(getLoginLocation(httpsUrl))
.post(formData.build())
.build();
try (Response response = client.newCall(request).execute()) {
assertEquals(response.code(), SC_SEE_OTHER);
assertEquals(response.header(LOCATION), getLoginHtmlLocation(httpsUrl));
assertTrue(cookieManager.getCookieStore().getCookies().isEmpty());
}
}
private void testWorkerResource(String nodeId, URI baseUri, boolean sendPassword)
throws Exception
{
OkHttpClient client = this.client.newBuilder()
.cookieJar(new JavaNetCookieJar(new CookieManager()))
.build();
logIn(baseUri, client, sendPassword);
testWorkerResource(nodeId, baseUri, client);
}
private static void testWorkerResource(String nodeId, URI baseUri, OkHttpClient authorizedClient)
throws IOException
{
assertOk(authorizedClient, getLocation(baseUri, "/ui/api/worker/" + nodeId + "/status"));
assertOk(authorizedClient, getLocation(baseUri, "/ui/api/worker/" + nodeId + "/thread"));
}
private static void logIn(URI baseUri, OkHttpClient client, boolean sendPassword)
throws IOException
{
FormBody.Builder formData = new FormBody.Builder()
.add("username", TEST_USER);
if (sendPassword) {
formData.add("password", TEST_PASSWORD);
}
Request request = new Request.Builder()
.url(getLoginLocation(baseUri))
.post(formData.build())
.build();
Response response = client.newCall(request).execute();
assertEquals(response.code(), SC_SEE_OTHER);
assertEquals(response.header(LOCATION), getUiLocation(baseUri));
}
@Test
public void testDisabled()
throws Exception
{
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(ImmutableMap.<String, String>builder()
.putAll(SECURE_PROPERTIES)
.put("web-ui.enabled", "false")
.build())
.build()) {
server.getInstance(Key.get(PasswordAuthenticatorManager.class)).setAuthenticator(TestWebUi::authenticate);
HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
testDisabled(httpServerInfo.getHttpUri());
testDisabled(httpServerInfo.getHttpsUri());
}
}
private void testDisabled(URI baseUri)
throws Exception
{
assertRedirect(client, getUiLocation(baseUri), getDisabledLocation(baseUri));
assertRedirect(client, getLocation(baseUri, "/ui/query.html", "abc123"), getDisabledLocation(baseUri));
assertResponseCode(client, getValidApiLocation(baseUri), SC_UNAUTHORIZED);
assertRedirect(client, getLoginLocation(baseUri), getDisabledLocation(baseUri));
assertRedirect(client, getLogoutLocation(baseUri), getDisabledLocation(baseUri));
assertOk(client, getValidAssetsLocation(baseUri));
assertOk(client, getValidVendorLocation(baseUri));
}
@Test
public void testNoPasswordAuthenticator()
throws Exception
{
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(ImmutableMap.<String, String>builder()
.putAll(SECURE_PROPERTIES)
.put("http-server.authentication.type", "password")
.build())
.build()) {
// a password manager is required, so a secure request will fail
// a real server will fail to start, but verify that we get an exception here to be safe
FormAuthenticator formAuthenticator = server.getInstance(Key.get(FormAuthenticator.class));
assertThatThrownBy(() -> formAuthenticator
.isValidCredential(TEST_USER, TEST_USER, true))
.hasMessage("authenticator was not loaded")
.isInstanceOf(IllegalStateException.class);
assertTrue(formAuthenticator.isLoginEnabled(true));
}
}
@Test
public void testFixedAuthenticator()
throws Exception
{
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(ImmutableMap.<String, String>builder()
.putAll(SECURE_PROPERTIES)
.put("web-ui.authentication.type", "fixed")
.put("web-ui.user", "test-user")
.build())
.build()) {
HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
String nodeId = server.getInstance(Key.get(NodeInfo.class)).getNodeId();
testAlwaysAuthorized(httpServerInfo.getHttpUri(), client, nodeId);
testAlwaysAuthorized(httpServerInfo.getHttpsUri(), client, nodeId);
testFixedAuthenticator(httpServerInfo.getHttpUri());
testFixedAuthenticator(httpServerInfo.getHttpsUri());
}
}
private void testFixedAuthenticator(URI baseUri)
throws Exception
{
assertOk(client, getUiLocation(baseUri));
assertOk(client, getValidApiLocation(baseUri));
assertResponseCode(client, getLocation(baseUri, "/ui/unknown"), SC_NOT_FOUND);
assertResponseCode(client, getLocation(baseUri, "/ui/api/unknown"), SC_NOT_FOUND);
}
@Test
public void testCertAuthenticator()
throws Exception
{
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(ImmutableMap.<String, String>builder()
.putAll(SECURE_PROPERTIES)
.put("http-server.authentication.type", "certificate")
.put("http-server.https.truststore.path", LOCALHOST_KEYSTORE)
.put("http-server.https.truststore.key", "")
.build())
.build()) {
HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
String nodeId = server.getInstance(Key.get(NodeInfo.class)).getNodeId();
testLogIn(httpServerInfo.getHttpUri(), false);
testNeverAuthorized(httpServerInfo.getHttpsUri(), client);
OkHttpClient.Builder clientBuilder = client.newBuilder();
setupSsl(
clientBuilder,
Optional.of(LOCALHOST_KEYSTORE),
Optional.empty(),
Optional.empty(),
Optional.of(LOCALHOST_KEYSTORE),
Optional.empty(),
Optional.empty());
OkHttpClient clientWithCert = clientBuilder.build();
testAlwaysAuthorized(httpServerInfo.getHttpsUri(), clientWithCert, nodeId);
}
}
@Test
public void testJwtAuthenticator()
throws Exception
{
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(ImmutableMap.<String, String>builder()
.putAll(SECURE_PROPERTIES)
.put("http-server.authentication.type", "jwt")
.put("http-server.authentication.jwt.key-file", HMAC_KEY)
.build())
.build()) {
HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
String nodeId = server.getInstance(Key.get(NodeInfo.class)).getNodeId();
testLogIn(httpServerInfo.getHttpUri(), false);
testNeverAuthorized(httpServerInfo.getHttpsUri(), client);
String hmac = Files.readString(Paths.get(HMAC_KEY));
String token = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, hmac)
.setSubject("test-user")
.setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant()))
.compact();
OkHttpClient clientWithJwt = client.newBuilder()
.authenticator((route, response) -> response.request().newBuilder()
.header(AUTHORIZATION, "Bearer " + token)
.build())
.build();
testAlwaysAuthorized(httpServerInfo.getHttpsUri(), clientWithJwt, nodeId);
}
}
@Test
public void testJwtWithJwkAuthenticator()
throws Exception
{
TestingHttpServer jwkServer = createTestingJwkServer();
jwkServer.start();
try (TestingPrestoServer server = TestingPrestoServer.builder()
.setProperties(ImmutableMap.<String, String>builder()
.putAll(SECURE_PROPERTIES)
.put("http-server.authentication.type", "jwt")
.put("http-server.authentication.jwt.key-file", jwkServer.getBaseUrl().toString())
.build())
.build()) {
HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
String nodeId = server.getInstance(Key.get(NodeInfo.class)).getNodeId();
testLogIn(httpServerInfo.getHttpUri(), false);
testNeverAuthorized(httpServerInfo.getHttpsUri(), client);
String token = Jwts.builder()
.signWith(SignatureAlgorithm.RS256, JWK_PRIVATE_KEY)
.setHeaderParam(JwsHeader.KEY_ID, "test-rsa")
.setSubject("test-user")
.setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant()))
.compact();
OkHttpClient clientWithJwt = client.newBuilder()
.authenticator((route, response) -> response.request().newBuilder()
.header(AUTHORIZATION, "Bearer " + token)
.build())
.build();
testAlwaysAuthorized(httpServerInfo.getHttpsUri(), clientWithJwt, nodeId);
}
finally {
jwkServer.stop();
}
}
private static void testAlwaysAuthorized(URI baseUri, OkHttpClient authorizedClient, String nodeId)
throws IOException
{
testRootRedirect(baseUri, authorizedClient);
testWorkerResource(nodeId, baseUri, authorizedClient);
assertOk(authorizedClient, getUiLocation(baseUri));
assertOk(authorizedClient, getValidApiLocation(baseUri));
assertRedirect(authorizedClient, getLoginHtmlLocation(baseUri), getUiLocation(baseUri), false);
assertRedirect(authorizedClient, getLoginLocation(baseUri), getUiLocation(baseUri), false);
assertRedirect(authorizedClient, getLogoutLocation(baseUri), getUiLocation(baseUri), false);
assertResponseCode(authorizedClient, getLocation(baseUri, "/ui/unknown"), SC_NOT_FOUND);
assertResponseCode(authorizedClient, getLocation(baseUri, "/ui/api/unknown"), SC_NOT_FOUND);
}
private static void testNeverAuthorized(URI baseUri, OkHttpClient notAuthorizedClient)
throws IOException
{
testRootRedirect(baseUri, notAuthorizedClient);
assertResponseCode(notAuthorizedClient, getUiLocation(baseUri), SC_UNAUTHORIZED);
assertResponseCode(notAuthorizedClient, getValidApiLocation(baseUri), SC_UNAUTHORIZED);
assertResponseCode(notAuthorizedClient, getLoginLocation(baseUri), SC_UNAUTHORIZED, true);
assertResponseCode(notAuthorizedClient, getLogoutLocation(baseUri), SC_UNAUTHORIZED);
assertResponseCode(notAuthorizedClient, getLocation(baseUri, "/ui/unknown"), SC_UNAUTHORIZED);
assertResponseCode(notAuthorizedClient, getLocation(baseUri, "/ui/api/unknown"), SC_UNAUTHORIZED);
}
private static Optional<String> assertOk(OkHttpClient client, String url)
throws IOException
{
return assertResponseCode(client, url, SC_OK);
}
private static void assertRedirect(OkHttpClient client, String url, String redirectLocation)
throws IOException
{
assertRedirect(client, url, redirectLocation, true);
}
private static void assertRedirect(OkHttpClient client, String url, String redirectLocation, boolean testProxy)
throws IOException
{
Request request = new Request.Builder()
.url(url)
.build();
if (url.endsWith(UI_LOGIN)) {
RequestBody formBody = new FormBody.Builder()
.add("username", "test")
.add("password", "test")
.build();
request = request.newBuilder().post(formBody).build();
}
try (Response response = client.newCall(request).execute()) {
assertEquals(response.code(), SC_SEE_OTHER);
assertEquals(response.header(LOCATION), redirectLocation);
}
if (testProxy) {
request = new Request.Builder()
.url(url)
.header(X_FORWARDED_PROTO, "test")
.header(X_FORWARDED_HOST, "my-load-balancer.local")
.header(X_FORWARDED_PORT, "123")
.build();
try (Response response = client.newCall(request).execute()) {
assertEquals(response.code(), SC_SEE_OTHER);
assertEquals(
response.header(LOCATION),
uriBuilderFrom(URI.create(redirectLocation))
.scheme("test")
.host("my-load-balancer.local")
.port(123)
.toString());
}
request = new Request.Builder()
.url(url)
.header(X_FORWARDED_PROTO, "test")
.header(X_FORWARDED_HOST, "my-load-balancer.local:123")
.build();
try (Response response = client.newCall(request).execute()) {
assertEquals(response.code(), SC_SEE_OTHER);
assertEquals(
response.header(LOCATION),
uriBuilderFrom(URI.create(redirectLocation))
.scheme("test")
.host("my-load-balancer.local")
.port(123)
.toString());
}
request = new Request.Builder()
.url(url)
.header(X_FORWARDED_PROTO, "test")
.header(X_FORWARDED_PORT, "123")
.build();
try (Response response = client.newCall(request).execute()) {
assertEquals(response.code(), SC_SEE_OTHER);
assertEquals(
response.header(LOCATION),
uriBuilderFrom(URI.create(redirectLocation))
.scheme("test")
.port(123)
.toString());
}
request = new Request.Builder()
.url(url)
.header(X_FORWARDED_PROTO, "test")
.build();
try (Response response = client.newCall(request).execute()) {
assertEquals(response.code(), SC_SEE_OTHER);
assertEquals(
response.header(LOCATION),
uriBuilderFrom(URI.create(redirectLocation))
.scheme("test")
.toString());
}
request = new Request.Builder()
.url(url)
.header(X_FORWARDED_HOST, "my-load-balancer.local")
.header(X_FORWARDED_PORT, "123")
.build();
try (Response response = client.newCall(request).execute()) {
assertEquals(response.code(), SC_SEE_OTHER);
assertEquals(
response.header(LOCATION),
uriBuilderFrom(URI.create(redirectLocation))
.host("my-load-balancer.local")
.port(123)
.toString());
}
request = new Request.Builder()
.url(url)
.header(X_FORWARDED_HOST, "my-load-balancer.local:123")
.build();
try (Response response = client.newCall(request).execute()) {
assertEquals(response.code(), SC_SEE_OTHER);
assertEquals(
response.header(LOCATION),
uriBuilderFrom(URI.create(redirectLocation))
.host("my-load-balancer.local")
.port(123)
.toString());
}
request = new Request.Builder()
.url(url)
.header(X_FORWARDED_HOST, "my-load-balancer.local")
.build();
try (Response response = client.newCall(request).execute()) {
assertEquals(response.code(), SC_SEE_OTHER);
assertEquals(
response.header(LOCATION),
uriBuilderFrom(URI.create(redirectLocation))
.host("my-load-balancer.local")
.defaultPort()
.toString());
}
}
}
private static Optional<String> assertResponseCode(OkHttpClient client, String url, int expectedCode)
throws IOException
{
return assertResponseCode(client, url, expectedCode, false);
}
private static Optional<String> assertResponseCode(OkHttpClient client,
String url,
int expectedCode,
boolean postLogin)
throws IOException
{
Request request = new Request.Builder()
.url(url)
.build();
if (postLogin) {
RequestBody formBody = new FormBody.Builder()
.add("username", "fake")
.add("password", "bad")
.build();
request = request.newBuilder().post(formBody).build();
}
try (Response response = client.newCall(request).execute()) {
assertEquals(response.code(), expectedCode, url);
return Optional.ofNullable(response.body())
.map(responseBody -> {
try {
return responseBody.string();
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}
private static Principal authenticate(String user, String password)
{
if (TEST_USER.equals(user) && TEST_PASSWORD.equals(password)) {
return new BasicPrincipal(user);
}
throw new AccessDeniedException("Invalid credentials");
}
private static String getUiLocation(URI baseUri)
{
return getLocation(baseUri, "/ui/");
}
private static String getLoginHtmlLocation(URI baseUri)
{
return getLocation(baseUri, LOGIN_FORM);
}
private static String getLoginLocation(URI httpsUrl)
{
return getLocation(httpsUrl, UI_LOGIN);
}
private static String getLogoutLocation(URI baseUri)
{
return getLocation(baseUri, UI_LOGOUT);
}
private static String getDisabledLocation(URI baseUri)
{
return getLocation(baseUri, DISABLED_LOCATION);
}
private static String getValidApiLocation(URI baseUri)
{
return getLocation(baseUri, "/ui/api/cluster");
}
private static String getValidAssetsLocation(URI baseUri)
{
return getLocation(baseUri, "/ui/assets/favicon.ico");
}
private static String getValidVendorLocation(URI baseUri)
{
return getLocation(baseUri, "/ui/vendor/bootstrap/css/bootstrap.css");
}
private static String getLocation(URI baseUri, String path)
{
return uriBuilderFrom(baseUri).replacePath(path).toString();
}
private static String getLocation(URI baseUri, String path, String query)
{
return uriBuilderFrom(baseUri).replacePath(path).replaceParameter(query).toString();
}
private static TestingHttpServer createTestingJwkServer()
throws IOException
{
NodeInfo nodeInfo = new NodeInfo("test");
HttpServerConfig config = new HttpServerConfig().setHttpPort(0);
HttpServerInfo httpServerInfo = new HttpServerInfo(config, nodeInfo);
return new TestingHttpServer(httpServerInfo, nodeInfo, config, new JwkServlet(), ImmutableMap.of());
}
private static class JwkServlet
extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
String jwkKeys = Resources.toString(Resources.getResource("jwk/jwk-public.json"), UTF_8);
response.getWriter().println(jwkKeys);
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2015 Daniel Gerighausen, Lydia Mueller, and Dirk Zeckzer
*
* 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 biovis.sierra.client.GUI;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import biovis.sierra.client.GUI.GUIHelper.BoxPlot;
import biovis.sierra.client.GUI.GUIHelper.ChartCanvas;
import biovis.sierra.client.GUI.GUIHelper.LogarithmicAxis;
import biovis.sierra.data.DataMapper;
import biovis.sierra.data.Replicate;
import biovis.sierra.data.IO.ExportSnapshot;
import biovis.sierra.data.peakcaller.IntBoxplotData;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.chart.Axis;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
/**
*
* @author Daniel Gerighausen
*/
public class SingleFigure {
private StackPane pane;
@SuppressWarnings({ "unchecked", "rawtypes" })
public void createSingleFigure(ObservableList observableList ,boolean range, String title, boolean hist, boolean pvalue,int max)
{
final Stage myDialog = new Stage();
myDialog.setTitle(title);
myDialog.setHeight(768);
myDialog.setWidth(1024);
myDialog.initModality(Modality.WINDOW_MODAL);
Image ico = new Image(getClass().getResource("sierra.png").toExternalForm());
myDialog.getIcons().add(ico);
pane = new StackPane();
Series<Object, Object> serie1 = new Series();
Series<Object, Object> serie2 = new Series();
Series<Object, Object> temp = (Series<Object, Object>) observableList.get(0);
for(int i = 0; i < temp.getData().size(); i++)
{
serie1.setName(temp.getName());
serie1.getData().add(temp.getData().get(i));
}
temp = (Series<Object, Object>) observableList.get(1);
for(int i = 0; i < temp.getData().size(); i++)
{
serie2.setName(temp.getName());
serie2.getData().add(temp.getData().get(i));
}
final Axis gxAxis;
if(hist)
{
gxAxis = new LogarithmicAxis(0.4, max);
}
else
{
gxAxis = new NumberAxis();
}
Axis gyAxis = new NumberAxis();
if(pvalue)
{
gyAxis = new LogarithmicAxis(100, max+10000);
}
LineChart figure = new LineChart(gxAxis, gyAxis);
figure.getData().add(serie1);
figure.getData().add(serie2);
figure.setCreateSymbols(false);
figure.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent event) {
if (event.getButton() == MouseButton.SECONDARY) {
WritableImage snapshot = figure.snapshot(new SnapshotParameters(), null);
ExportSnapshot.exportImage(snapshot, pane);
event.consume();
}
}
}
);
if(range)
{
final double SCALE_DELTA = 1.1;
figure.setOnScroll(new EventHandler<ScrollEvent>() {
public void handle(ScrollEvent event) {
event.consume();
// System.err.println("bla");
if (event.getDeltaY() == 0) {
return;
}
gxAxis.setAutoRanging(false);
double scaleFactor = (event.getDeltaY() > 0) ? SCALE_DELTA : 1 / SCALE_DELTA;
((NumberAxis)gxAxis).setUpperBound(((NumberAxis)gxAxis).getUpperBound()*scaleFactor);
}
});
figure.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
if (event.getClickCount() == 2) {
// x.setUpperBound(upperNorm);
gxAxis.setAutoRanging(true);
}
}
});
}
pane.getChildren().add(figure);
Scene myDialogScene = new Scene(pane);
// File line = new File("linechart.css");
// File progress = new File("progress.css");
if(pvalue)
{
myDialogScene.getStylesheets().clear();
myDialogScene.getStylesheets().add(getClass().getResource("histogram.css").toExternalForm());
}
else
{
myDialogScene.getStylesheets().clear();
myDialogScene.getStylesheets().add(getClass().getResource("linechart.css").toExternalForm());
}
myDialog.setScene(myDialogScene);
myDialog.show();
}
public void createBoxPlot(String string, String replicate, Replicate rep)
{
final BoxPlot demo = new BoxPlot("Tag quality", replicate, rep);
demo.setVisible(true);
demo.setBackground(new Color(244,244,244));
ChartCanvas canvas = new ChartCanvas(demo.chart);
final Stage myDialog = new Stage();
myDialog.setTitle(replicate);
myDialog.setHeight(768);
myDialog.setWidth(1024);
myDialog.initModality(Modality.WINDOW_MODAL);
// URL picture = getClass().getResource("sierra.png");
Image ico = new Image(getClass().getResource("sierra.png").toExternalForm());
myDialog.getIcons().add(ico);
canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent event) {
if (event.getButton() == MouseButton.SECONDARY) {
WritableImage snapshot = canvas.snapshot(new SnapshotParameters(), null);
ExportSnapshot.exportImage(snapshot, pane);
event.consume();
}
}
}
);
pane = new StackPane();
// pane.getChildren().add(new Label("foo"));
Scene myDialogScene = new Scene(pane);
canvas.widthProperty().bind( pane.widthProperty());
canvas.heightProperty().bind(pane.heightProperty());
pane.getChildren().add(canvas);
// File line = new File("linechart.css");
// File progress = new File("progress.css");
myDialogScene.getStylesheets().clear();
myDialogScene.getStylesheets().add(getClass().getResource("linechart.css").toExternalForm());
myDialog.setScene(myDialogScene);
myDialog.show();
}
public void createSingleBarChart(Replicate rep, DataMapper mapper, String title, String name, String type, int max)
{
final Stage myDialog = new Stage();
myDialog.setTitle(title);
myDialog.setHeight(768);
myDialog.setWidth(1024);
myDialog.initModality(Modality.WINDOW_MODAL);
Image ico = new Image(getClass().getResource("sierra.png").toExternalForm());
myDialog.getIcons().add(ico);
pane = new StackPane();
Series<String, Integer> serie1 = null;
Series<String, Integer> serie2 = null;
final CategoryAxis gxAxis = new CategoryAxis();
Axis gyAxis;// = new NumberAxis();
gyAxis = new NumberAxis();
if(type.equals("pValueHist"))
{
gyAxis = new LogarithmicAxis(0.4,max);
}
BarChart figure = new BarChart(gxAxis, gyAxis);
if(type.equals("sigHist"))
{
serie1= biovis.sierra.client.GUI.GUIHelper.BarChart.getSigHist(rep, name);
serie2 = biovis.sierra.client.GUI.GUIHelper.BarChart.getBarChart( mapper, "Median");
figure.setCategoryGap(2);
figure.setBarGap(0);
figure.getData().add(serie1);
figure.getData().add(serie2);
for (final Data data : serie1.getData()) {
Tooltip tooltip = new Tooltip();
tooltip.setText(data.getYValue().toString());
Tooltip.install(data.getNode(), tooltip);
}
for (final Data data : serie2.getData()) {
Tooltip tooltip = new Tooltip();
tooltip.setText(data.getYValue().toString());
Tooltip.install(data.getNode(), tooltip);
}
// figure.
// figure.getData().add(serie2);
}
if(type.equals("pValueHist"))
{
biovis.sierra.client.GUI.GUIHelper.BarChart.getPValueHist(rep, name, mapper, figure);
}
figure.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent event) {
if (event.getButton() == MouseButton.SECONDARY) {
WritableImage snapshot = figure.snapshot(new SnapshotParameters(), null);
ExportSnapshot.exportImage(snapshot, pane);
event.consume();
}
}
}
);
pane.getChildren().add(figure);
Scene myDialogScene = new Scene(pane);
myDialog.setScene(myDialogScene);
myDialog.show();
}
public void createBoxPlot(String string, String replicate, IntBoxplotData experimentData, IntBoxplotData backgroundData)
{
final BoxPlot demo = new BoxPlot("Tag quality", replicate, experimentData, backgroundData);
demo.setVisible(true);
demo.setBackground(new Color(244,244,244));
ChartCanvas canvas = new ChartCanvas(demo.chart);
final Stage myDialog = new Stage();
myDialog.setTitle(replicate);
myDialog.setHeight(768);
myDialog.setWidth(1024);
myDialog.initModality(Modality.WINDOW_MODAL);
// URL picture = getClass().getResource("sierra.png");
Image ico = new Image(getClass().getResource("sierra.png").toExternalForm());
myDialog.getIcons().add(ico);
canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent event) {
if (event.getButton() == MouseButton.SECONDARY) {
WritableImage snapshot = canvas.snapshot(new SnapshotParameters(), null);
ExportSnapshot.exportImage(snapshot, pane);
event.consume();
}
}
}
);
pane = new StackPane();
// pane.getChildren().add(new Label("foo"));
Scene myDialogScene = new Scene(pane);
canvas.widthProperty().bind( pane.widthProperty());
canvas.heightProperty().bind(pane.heightProperty());
pane.getChildren().add(canvas);
// File line = new File("linechart.css");
// File progress = new File("progress.css");
myDialogScene.getStylesheets().clear();
myDialogScene.getStylesheets().add(getClass().getResource("linechart.css").toExternalForm());
myDialog.setScene(myDialogScene);
myDialog.show();
}
public void createSingleBarChart(DataMapper mapper , String title, boolean logScale, int max)
{
final Stage myDialog = new Stage();
myDialog.setTitle(title);
myDialog.setHeight(768);
myDialog.setWidth(1024);
myDialog.initModality(Modality.WINDOW_MODAL);
Image ico = new Image(getClass().getResource("sierra.png").toExternalForm());
myDialog.getIcons().add(ico);
pane = new StackPane();
final CategoryAxis gxAxis = new CategoryAxis();
final Axis gyAxis;// = new NumberAxis();
if(logScale)
{
gyAxis = new LogarithmicAxis(0.4,max);
gyAxis.setTickMarkVisible(false);
}
else
{
gyAxis = new NumberAxis();
}
BarChart figure = new BarChart(gxAxis, gyAxis);
figure.setCategoryGap(2);
figure.setBarGap(0);
if(logScale)
{
int start = mapper.getFinalPValueExp().keySet().size()-7;
for(Integer run : mapper.getFinalPValueExp().keySet())
{
if(start > run)
{
continue;
}
Series<String, Integer> pvalues = new XYChart.Series<>();
max = 0;
for(int i = 0; i < mapper.getFinalPValueExp().get(run).size(); i++)
{
pvalues.getData().add(
new XYChart.Data<>(
String.valueOf(mapper.getFinalPValueExp().get(run).get(i).getFirst()),
mapper.getFinalPValueExp().get(run).get(i).getSecond()));
if(max < mapper.getFinalPValueExp().get(run).get(i).getSecond())
{
max = mapper.getFinalPValueExp().get(run).get(i).getSecond();
}
}
pvalues.setName("Run " + run + " - Max-value: "+ max);
figure.getData().add(pvalues);
for (final Data data : pvalues.getData()) {
Tooltip tooltip = new Tooltip();
tooltip.setText(data.getYValue().toString());
Tooltip.install(data.getNode(), tooltip);
}
}
// for(Integer run : mapper.getFinalPValueExp().keySet())
// {
// if(start > run)
// {
// continue;
// }
// Series<String, Integer> pvalues = new XYChart.Series<>();
//
// for(int i = 0; i < mapper.getFinalPValueExp().get(run).size(); i++)
// {
// pvalues.getData().add(
// new XYChart.Data<>(
// String.valueOf(mapper.getFinalPValueExp().get(run).get(i).getFirst()),
// mapper.getFinalPValueExp().get(run).get(i).getSecond()));
// if(max < mapper.getFinalPValueExp().get(run).get(i).getSecond())
// {
// max = mapper.getFinalPValueExp().get(run).get(i).getSecond();
// }
// figure.getData().add(pvalues);
// for (final Data data : pvalues.getData()) {
// Tooltip tooltip = new Tooltip();
// tooltip.setText(data.getYValue().toString());
// Tooltip.install(data.getNode(), tooltip);
// }
// }
// }
}
else
{
int start = mapper.getFinalPValueExp().keySet().size()-7;
for(Integer run : mapper.getOverlapWithReplicates().keySet())
{
if(start > run)
{
continue;
}
Series<String, Double> serie1 = new XYChart.Series<>();
serie1.setName("Run " + run);
List<Double> values = new ArrayList<>(mapper.getOverlapWithReplicates().get(run).values());
List<Integer> keys = new ArrayList<>(mapper.getOverlapWithReplicates().get(run).keySet());
for(int i = 0 ; i < values.size(); i++)
{
serie1.getData().add(new XYChart.Data<>(mapper.getReplicates().get(i).getName(), values.get(i)));
}
figure.getData().add(serie1);
for (final Data data : serie1.getData()) {
Tooltip tooltip = new Tooltip();
tooltip.setText(data.getYValue().toString());
Tooltip.install(data.getNode(), tooltip);
}
}
}
// figure.
// figure.getData().add(serie2);
figure.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent event) {
if (event.getButton() == MouseButton.SECONDARY) {
WritableImage snapshot = figure.snapshot(new SnapshotParameters(), null);
ExportSnapshot.exportImage(snapshot, pane);
event.consume();
}
}
}
);
pane.getChildren().add(figure);
Scene myDialogScene = new Scene(pane);
// File line = new File("linechart.css");
// File progress = new File("progress.css");
// myDialogScene.getStylesheets().clear();
// myDialogScene.getStylesheets().add(getClass().getResource("histogram.css").toExternalForm());
myDialog.setScene(myDialogScene);
myDialog.show();
}
}
| |
package org.systemsbiology.xtandem;
import com.lordjoe.distributed.*;
import com.lordjoe.distributed.spark.*;
import com.sun.org.glassfish.external.arc.*;
import org.systemsbiology.hadoop.*;
import org.systemsbiology.xml.*;
import org.systemsbiology.xtandem.hadoop.*;
import java.io.*;
import java.util.*;
/**
* org.systemsbiology.xtandem.XTandemMain
* User: steven
* Date: Jan 5, 2011
* Singleton representing a JXTandem job -
* This has the program main
*/
public class XTandemMain extends AbstractParameterHolder {
public static final IMainData[] EMPTY_ARRAY = {};
public static final String HARDCODED_MODIFICATIONS_PROPERTY = "org.systemsbiology.xtandem.HardCodeModifications";
public static final String NUMBER_REMEMBERED_MATCHES = "org.systemsbiology.numberRememberedMatches";
private static boolean gShowParameters = true;
public static boolean isShowParameters() {
return gShowParameters;
}
public static void setShowParameters(final boolean pGShowParameters) {
gShowParameters = pGShowParameters;
}
private static final List<IStreamOpener> gPreLoadOpeners =
new ArrayList<IStreamOpener>();
public static void addPreLoadOpener(IStreamOpener opener) {
gPreLoadOpeners.add(opener);
}
public static IStreamOpener[] getPreloadOpeners() {
return gPreLoadOpeners.toArray(new IStreamOpener[gPreLoadOpeners.size()]);
}
public static final int MAX_SCANS = Integer.MAX_VALUE;
public static int getMaxScans() {
return MAX_SCANS;
}
private static String gRequiredPathPrefix;
public static String getRequiredPathPrefix() {
return gRequiredPathPrefix;
}
public static void setRequiredPathPrefix(final String pRequiredPathPrefix) {
gRequiredPathPrefix = pRequiredPathPrefix;
}
private String m_DefaultParameters;
private String m_TaxonomyInfo;
private String m_SpectrumPath;
private String m_OutputPath;
private String m_OutputResults;
private String m_TaxonomyName;
private final StringBuffer m_Log = new StringBuffer();
// private IScoringAlgorithm m_Scorer;
// private ElapsedTimer m_Elapsed = new ElapsedTimer();
private final Map<String, String> m_PerformanceParameters = new HashMap<String, String>();
private final DelegatingFileStreamOpener m_Openers = new DelegatingFileStreamOpener();
// used by Map Reduce
protected XTandemMain() {
// Protein.resetNextId();
initOpeners();
}
public XTandemMain(final File pTaskFile) {
String m_TaskFile = pTaskFile.getAbsolutePath();
// Protein.resetNextId();
initOpeners();
Properties predefined = XTandemHadoopUtilities.getHadoopProperties();
for (String key : predefined.stringPropertyNames()) {
setPredefinedParameter(key, predefined.getProperty(key));
}
try {
InputStream is = new FileInputStream(m_TaskFile);
handleInputs(is, pTaskFile.getName());
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
// if (gInstance != null)
// throw new IllegalStateException("Only one XTandemMain allowed");
}
public static final String DO_DEBUGGING_KEY = "org.systemsbiology.xtandem.XTandemMain.DO_DEBUGGING"; // fix this
public XTandemMain(final InputStream is, String url) {
// Protein.resetNextId();
initOpeners();
Properties predefined = XTandemHadoopUtilities.getHadoopProperties();
for (String key : predefined.stringPropertyNames()) {
setPredefinedParameter(key, predefined.getProperty(key));
}
handleInputs(is, url);
// if (gInstance != null)
// throw new IllegalStateException("Only one XTandemMain allowed");
}
private void setPredefinedParameter(String key, String value) {
setParameter(key, value);
}
public void appendLog(String added) {
m_Log.append(added);
}
public void clearLog() {
m_Log.setLength(0);
}
public String getLog() {
return m_Log.toString();
}
public void setPerformanceParameter(String key, String value) {
m_PerformanceParameters.put(key, value);
}
/**
* return a parameter configured in default parameters
*
* @param key !null key
* @return possibly null parameter
*/
public String getPerformanceParameter(String key) {
return m_PerformanceParameters.get(key);
}
@SuppressWarnings("UnusedDeclaration")
public String[] getPerformanceKeys() {
String[] ret = m_PerformanceParameters.keySet().toArray(new String[0]);
Arrays.sort(ret);
return ret;
}
/**
* add new ways to open files
*/
protected void initOpeners() {
addOpener(new FileStreamOpener());
addOpener(new StreamOpeners.ResourceStreamOpener(XTandemUtilities.class));
for (IStreamOpener opener : getPreloadOpeners())
addOpener(opener);
}
/**
* open a file from a string
*
* @param fileName string representing the file
* @param otherData any other required data
* @return possibly null stream
*/
@Override
public InputStream open(String fileName, Object... otherData) {
return m_Openers.open(fileName, otherData);
}
public void addOpener(IStreamOpener opener) {
m_Openers.addOpener(opener);
}
/**
* what do we call the database or output directory
*
* @return !null name
*/
public String getDatabaseName() {
String ret = m_TaxonomyName; //getParameter("protein, taxon");
// System.err.println("database name = " + m_TaxonomyName);
return conditionDatabaseName(ret);
}
protected String conditionDatabaseName(String s) {
if (s == null)
return "database";
s = s.replace(".fasta", "");
s = s.replace(":", "");
s = s.replace(".;", "");
return s;
}
/**
* parse the initial file and get run parameters
*
* @param is
*/
public void handleInputs(final InputStream is, String url) {
Map<String, String> notes = XTandemUtilities.readNotes(is, url);
for (String key : notes.keySet()) {
setParameter(key, notes.get(key));
}
if (isShowParameters()) {
for (String key : notes.keySet()) {
System.err.println(key + " = " + notes.get(key));
}
}
m_DefaultParameters = notes.get(
"list path, default parameters"); //, "default_input.xml");
m_TaxonomyInfo = notes.get(
"list path, taxonomy information"); //, "taxonomy.xml");
m_TaxonomyName = notes.get("protein, taxon");
m_SpectrumPath = notes.get("spectrum, path"); //, "test_spectra.mgf");
m_OutputPath = notes.get("output, path"); //, "output.xml");
// little hack to separate real tandem and hydra results
if (m_OutputPath != null)
m_OutputPath = m_OutputPath.replace(".tandem.xml", ".hydra.xml");
m_OutputResults = notes.get("output, results");
String requiredPrefix = getRequiredPathPrefix();
//System.err.println("requiredPrefix " + requiredPrefix);
if (requiredPrefix != null) {
if (m_DefaultParameters != null && !m_DefaultParameters.startsWith(requiredPrefix))
m_DefaultParameters = requiredPrefix + m_DefaultParameters;
if (m_TaxonomyInfo != null && !m_TaxonomyInfo.startsWith(requiredPrefix))
m_TaxonomyInfo = requiredPrefix + m_TaxonomyInfo;
if (m_OutputPath != null && !m_OutputPath.startsWith(requiredPrefix))
m_OutputPath = requiredPrefix + m_OutputPath;
if (m_SpectrumPath != null && !m_SpectrumPath.startsWith(requiredPrefix))
m_SpectrumPath = requiredPrefix + m_SpectrumPath;
}
try {
readDefaultParameters(notes);
} catch (Exception e) {
// e.printStackTrace();
// forgive
System.err.println("Cannot find file " + m_DefaultParameters);
}
XTandemUtilities.validateParameters(this);
// maybe limit the number of scans to save memory
XTandemUtilities.setMaxHandledScans(getIntParameter("org.systemsbiology.xtandem.MaxScoredScans", Integer.MAX_VALUE));
String digesterSpec = getParameter("protein, cleavage site", "trypsin");
int missedCleavages = getIntParameter("scoring, maximum missed cleavage sites", 0);
}
protected static File getInputFile(Map<String, String> notes, String key) {
File ret = new File(notes.get(key));
if (!ret.exists() || !ret.canRead())
throw new IllegalArgumentException("cannot access file " + ret.getName());
return ret;
}
protected static File getOutputFile(Map<String, String> notes, String key) {
String athname = notes.get(key);
File ret = new File(athname);
File parentFile = ret.getParentFile();
if ((parentFile != null && (!parentFile.exists() || parentFile.canWrite())))
throw new IllegalArgumentException("cannot access file " + ret.getName());
if (ret.exists() && !ret.canWrite())
throw new IllegalArgumentException("cannot rewrite file file " + ret.getName());
return ret;
}
public String getDefaultParameters() {
return m_DefaultParameters;
}
public String getTaxonomyInfo() {
return m_TaxonomyInfo;
}
public String getSpectrumPath() {
return m_SpectrumPath;
}
public String getOutputPath() {
return m_OutputPath;
}
public String getOutputResults() {
return m_OutputResults;
}
public String getTaxonomyName() {
return m_TaxonomyName;
}
// public void setScorer(IScoringAlgorithm pScorer) {
// m_Scorer = pScorer;
// }
/*
* modify checks the input parameters for known parameters that are use to modify
* a protein sequence. these parameters are stored in the m_pScore member object's
* msequenceutilities member object
*/
protected String[] readModifications() {
List<String> holder = new ArrayList<String>();
String value;
String strKey = "residue, modification mass";
value = getParameter(strKey);
if (value != null)
holder.add(value);
String strKeyBase = "residue, modification mass ";
int a = 1;
value = getParameter(strKeyBase + (a++));
while (value != null) {
holder.add(value);
value = getParameter(strKeyBase + (a++));
}
strKeyBase = "residue, potential modification mass";
value = getParameter(strKeyBase + (a++));
value = getParameter(strKey);
if (true)
throw new UnsupportedOperationException("Fix This"); // ToDo
// if (m_xmlValues.get(strKey, strValue)) {
// m_pScore - > m_seqUtil.modify_maybe(strValue);
// m_pScore - > m_seqUtilAvg.modify_maybe(strValue);
// }
// strKey = "residue, potential modification motif";
// if (m_xmlValues.get(strKey, strValue)) {
// m_pScore - > m_seqUtil.modify_motif(strValue);
// m_pScore - > m_seqUtilAvg.modify_motif(strValue);
// }
// strKey = "protein, N-terminal residue modification mass";
// if (m_xmlValues.get(strKey, strValue)) {
// m_pScore - > m_seqUtil.modify_n((float) atof(strValue.c_str()));
// m_pScore - > m_seqUtilAvg.modify_n((float) atof(strValue.c_str()));
// }
// strKey = "protein, C-terminal residue modification mass";
// if (m_xmlValues.get(strKey, strValue)) {
// m_pScore - > m_seqUtil.modify_c((float) atof(strValue.c_str()));
// m_pScore - > m_seqUtilAvg.modify_c((float) atof(strValue.c_str()));
// }
// strKey = "protein, cleavage N-terminal mass change";
// if (m_xmlValues.get(strKey, strValue)) {
// m_pScore - > m_seqUtil.m_dCleaveN = atof(strValue.c_str());
// m_pScore - > m_seqUtilAvg.m_dCleaveN = atof(strValue.c_str());
// }
// strKey = "protein, cleavage C-terminal mass change";
// if (m_xmlValues.get(strKey, strValue)) {
// m_pScore - > m_seqUtil.m_dCleaveC = atof(strValue.c_str());
// m_pScore - > m_seqUtilAvg.m_dCleaveC = atof(strValue.c_str());
// }
String[] ret = new String[holder.size()];
holder.toArray(ret);
return ret;
}
protected void setTranch(final Taxonomy pTaxonomy, final String pTranchData) {
throw new UnsupportedOperationException("Fix This"); // ToDo
// String[] items = pTranchData.split(",");
// switch (items.length) {
// case 2:
// int index = Integer.parseInt(items[0]);
// int repeat = Integer.parseInt(items[1]);
// pTaxonomy.setTranch(new TaxonomyTranch(index, repeat));
// break;
// case 4:
// int index1 = Integer.parseInt(items[0]);
// int repeat1 = Integer.parseInt(items[1]);
// int start = Integer.parseInt(items[2]);
// int end = Integer.parseInt(items[3]);
// pTaxonomy.setTranch(new TaxonomyTranch(index1, repeat1, start, end));
// break;
// default:
// throw new IllegalArgumentException("bad TranchData " + pTranchData);
// }
}
/**
* read the parameters dscribed in the bioml file
* listed in "list path, default parameters"
* These look like
* <note>spectrum parameters</note>
* <note type="input" label="spectrum, fragment monoisotopic mass error">0.4</note>
* <note type="input" label="spectrum, parent monoisotopic mass error plus">100</note>
* <note type="input" label="spectrum, parent monoisotopic mass error minus">100</note>
* <note type="input" label="spectrum, parent monoisotopic mass isotope error">yes</note>
*/
protected void readDefaultParameters(Map<String, String> inputParameters) {
Map<String, String> parametersMap = getParametersMap();
if (m_DefaultParameters != null) {
String paramName = m_DefaultParameters;
InputStream is;
final String path = SparkUtilities.buildPath(m_DefaultParameters);
if (m_DefaultParameters.startsWith("res://")) {
is = XTandemUtilities.getDescribedStream(m_DefaultParameters);
paramName = m_DefaultParameters;
} else {
is = HydraSparkUtilities.readFrom(path);
// File f = new File(defaults);
// if (f.exists() && f.isFile() && f.canRead()) {
// try {
// is = new FileInputStream(f);
// } catch (FileNotFoundException e) {
// throw new RuntimeException(e);
//
// }
// paramName = f.getName();
// } else {
// paramName = XMLUtilities.asLocalFile(m_DefaultParameters);
// is = open(paramName);
// }
}
Map<String, String> map = XTandemUtilities.readNotes(is, paramName);
for (String key : map.keySet()) {
if (!parametersMap.containsKey(key)) {
String value = map.get(key);
parametersMap.put(key, value);
}
}
}
// parameters in the input file override parameters in the default file
parametersMap.putAll(inputParameters);
inputParameters.putAll(parametersMap);
}
public static void usage() {
XMLUtilities.outputLine("Usage - JXTandem <inputfile>");
}
}
| |
/*
* Copyright 2014 The Error Prone 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.errorprone.refaster;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.apply.DescriptionBasedDiff;
import com.google.errorprone.apply.ImportOrganizer;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.tools.javac.tree.EndPosTable;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@code DescriptionBasedDiff}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@RunWith(JUnit4.class)
public class DescriptionBasedDiffTest extends CompilerBasedTest {
private JCCompilationUnit compilationUnit;
private static final String[] lines = {
"package foo.bar;",
"import org.bar.Baz;",
"import com.foo.Bar;",
"",
"class Foo {",
" public static void main(String[] args) {",
" System.out.println(\"foo\");",
" }",
"}"
};
@Before
public void setUp() {
compile(lines);
compilationUnit = Iterables.getOnlyElement(compilationUnits);
}
private DescriptionBasedDiff createDescriptionBasedDiff() {
return DescriptionBasedDiff.create(compilationUnit, ImportOrganizer.STATIC_FIRST_ORGANIZER);
}
@Test
public void noDiffs() {
DescriptionBasedDiff diff = createDescriptionBasedDiff();
diff.applyDifferences(sourceFile);
assertThat(sourceFile.getLines()).containsExactly((Object[]) lines).inOrder();
}
@Test
public void oneDiff() {
DescriptionBasedDiff diff = createDescriptionBasedDiff();
diff.onDescribed(dummyDescription(SuggestedFix.replace(137, 140, "bar")));
diff.applyDifferences(sourceFile);
assertThat(sourceFile.getLines())
.containsExactly(
"package foo.bar;",
"import org.bar.Baz;",
"import com.foo.Bar;",
"",
"class Foo {",
" public static void main(String[] args) {",
" System.out.println(\"bar\");",
" }",
"}")
.inOrder();
}
@Test
public void prefixDiff() {
DescriptionBasedDiff diff = createDescriptionBasedDiff();
diff.onDescribed(dummyDescription(SuggestedFix.replace(140, 140, "bar")));
diff.applyDifferences(sourceFile);
assertThat(sourceFile.getLines())
.containsExactly(
"package foo.bar;",
"import org.bar.Baz;",
"import com.foo.Bar;",
"",
"class Foo {",
" public static void main(String[] args) {",
" System.out.println(\"foobar\");",
" }",
"}")
.inOrder();
}
@Test
public void twoDiffs() {
DescriptionBasedDiff diff = createDescriptionBasedDiff();
diff.onDescribed(
dummyDescription(
SuggestedFix.builder().replace(124, 127, "longer").replace(137, 140, "bar").build()));
diff.applyDifferences(sourceFile);
assertThat(sourceFile.getLines())
.containsExactly(
"package foo.bar;",
"import org.bar.Baz;",
"import com.foo.Bar;",
"",
"class Foo {",
" public static void main(String[] args) {",
" System.longer.println(\"bar\");",
" }",
"}")
.inOrder();
}
@Test
public void overlappingDiffs_throws() {
DescriptionBasedDiff diff = createDescriptionBasedDiff();
assertThrows(
IllegalArgumentException.class,
() ->
diff.onDescribed(
dummyDescription(
SuggestedFix.builder()
.replace(137, 140, "baz")
.replace(137, 140, "bar")
.build())));
DescriptionBasedDiff diff2 = createDescriptionBasedDiff();
diff2.onDescribed(dummyDescription(SuggestedFix.replace(137, 140, "baz")));
assertThrows(
IllegalArgumentException.class,
() -> diff2.onDescribed(dummyDescription(SuggestedFix.replace(137, 140, "bar"))));
DescriptionBasedDiff diff3 =
DescriptionBasedDiff.createIgnoringOverlaps(
compilationUnit, ImportOrganizer.STATIC_FIRST_ORGANIZER);
diff3.onDescribed(dummyDescription(SuggestedFix.replace(137, 140, "baz")));
// No throw, since it's lenient. Refactors to the first "baz" replacement and ignores this.
diff3.onDescribed(dummyDescription(SuggestedFix.replace(137, 140, "bar")));
diff3.applyDifferences(sourceFile);
assertThat(sourceFile.getLines())
.containsExactly(
"package foo.bar;",
"import org.bar.Baz;",
"import com.foo.Bar;",
"",
"class Foo {",
" public static void main(String[] args) {",
" System.out.println(\"baz\");",
" }",
"}")
.inOrder();
}
@Test
public void applyDifferences_addsImportAndSorts_whenAddingNewImport() {
DescriptionBasedDiff diff = createDescriptionBasedDiff();
diff.onDescribed(
dummyDescription(SuggestedFix.builder().addImport("com.google.foo.Bar").build()));
diff.applyDifferences(sourceFile);
assertThat(sourceFile.getLines())
.containsExactly(
"package foo.bar;",
"import com.foo.Bar;",
"import com.google.foo.Bar;",
"import org.bar.Baz;",
"",
"class Foo {",
" public static void main(String[] args) {",
" System.out.println(\"foo\");",
" }",
"}")
.inOrder();
}
@Test
public void applyDifferences_preservesImportOrder_whenAddingExistingImport() {
DescriptionBasedDiff diff = createDescriptionBasedDiff();
diff.onDescribed(dummyDescription(SuggestedFix.builder().addImport("com.foo.Bar").build()));
diff.applyDifferences(sourceFile);
assertThat(sourceFile.getLines())
.containsExactly(
"package foo.bar;",
"import org.bar.Baz;",
"import com.foo.Bar;",
"",
"class Foo {",
" public static void main(String[] args) {",
" System.out.println(\"foo\");",
" }",
"}")
.inOrder();
}
@Test
public void removeImport() {
DescriptionBasedDiff diff = createDescriptionBasedDiff();
diff.onDescribed(
dummyDescription(
SuggestedFix.builder()
.removeImport("com.foo.Bar")
.removeImport("org.bar.Baz")
.build()));
diff.applyDifferences(sourceFile);
assertThat(sourceFile.getLines())
.containsExactly(
"package foo.bar;",
"",
"",
"class Foo {",
" public static void main(String[] args) {",
" System.out.println(\"foo\");",
" }",
"}")
.inOrder();
}
@Test
public void applyDifferences_preservesOrder_whenRemovingNonExistentImport() {
DescriptionBasedDiff diff = createDescriptionBasedDiff();
diff.onDescribed(
dummyDescription(SuggestedFix.builder().removeImport("com.google.foo.Bar").build()));
diff.applyDifferences(sourceFile);
assertThat(sourceFile.getLines())
.containsExactly(
"package foo.bar;",
"import org.bar.Baz;",
"import com.foo.Bar;",
"",
"class Foo {",
" public static void main(String[] args) {",
" System.out.println(\"foo\");",
" }",
"}")
.inOrder();
}
@Test
public void twoDiffsWithImport() {
DescriptionBasedDiff diff = createDescriptionBasedDiff();
diff.onDescribed(
dummyDescription(
SuggestedFix.builder()
.replace(124, 127, "longer")
.replace(137, 140, "bar")
.addImport("com.google.foo.Bar")
.build()));
diff.applyDifferences(sourceFile);
assertThat(sourceFile.getLines())
.containsExactly(
"package foo.bar;",
"import com.foo.Bar;",
"import com.google.foo.Bar;",
"import org.bar.Baz;",
"",
"class Foo {",
" public static void main(String[] args) {",
" System.longer.println(\"bar\");",
" }",
"}")
.inOrder();
}
@BugPattern(name = "Test", summary = "", severity = SeverityLevel.WARNING)
static final class DummyChecker extends BugChecker {}
private static Description dummyDescription(SuggestedFix fix) {
return new DummyChecker()
.buildDescription(
new DiagnosticPosition() {
@Override
public JCTree getTree() {
return null;
}
@Override
public int getStartPosition() {
return 0;
}
@Override
public int getPreferredPosition() {
return 0;
}
@Override
public int getEndPosition(EndPosTable endPosTable) {
return 0;
}
})
.addFix(fix)
.build();
}
}
| |
package redis.clients.jedis;
import static redis.clients.jedis.Protocol.toByteArray;
import java.util.List;
import java.util.Map;
import java.util.Set;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
public abstract class PipelineBase extends Queable implements BinaryRedisPipeline, RedisPipeline {
protected abstract Client getClient(String key);
protected abstract Client getClient(byte[] key);
public Response<Long> append(String key, String value) {
getClient(key).append(key, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> append(byte[] key, byte[] value) {
getClient(key).append(key, value);
return getResponse(BuilderFactory.LONG);
}
public Response<List<String>> blpop(String key) {
String[] temp = new String[1];
temp[0] = key;
getClient(key).blpop(temp);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<List<String>> brpop(String key) {
String[] temp = new String[1];
temp[0] = key;
getClient(key).brpop(temp);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<List<byte[]>> blpop(byte[] key) {
byte[][] temp = new byte[1][];
temp[0] = key;
getClient(key).blpop(temp);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
public Response<List<byte[]>> brpop(byte[] key) {
byte[][] temp = new byte[1][];
temp[0] = key;
getClient(key).brpop(temp);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
public Response<Long> decr(String key) {
getClient(key).decr(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> decr(byte[] key) {
getClient(key).decr(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> decrBy(String key, long integer) {
getClient(key).decrBy(key, integer);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> decrBy(byte[] key, long integer) {
getClient(key).decrBy(key, integer);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> del(String key) {
getClient(key).del(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> del(byte[] key) {
getClient(key).del(key);
return getResponse(BuilderFactory.LONG);
}
public Response<String> echo(String string) {
getClient(string).echo(string);
return getResponse(BuilderFactory.STRING);
}
public Response<byte[]> echo(byte[] string) {
getClient(string).echo(string);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<Boolean> exists(String key) {
getClient(key).exists(key);
return getResponse(BuilderFactory.BOOLEAN);
}
public Response<Boolean> exists(byte[] key) {
getClient(key).exists(key);
return getResponse(BuilderFactory.BOOLEAN);
}
public Response<Long> expire(String key, int seconds) {
getClient(key).expire(key, seconds);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> expire(byte[] key, int seconds) {
getClient(key).expire(key, seconds);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> expireAt(String key, long unixTime) {
getClient(key).expireAt(key, unixTime);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> expireAt(byte[] key, long unixTime) {
getClient(key).expireAt(key, unixTime);
return getResponse(BuilderFactory.LONG);
}
public Response<String> get(String key) {
getClient(key).get(key);
return getResponse(BuilderFactory.STRING);
}
public Response<byte[]> get(byte[] key) {
getClient(key).get(key);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<Boolean> getbit(String key, long offset) {
getClient(key).getbit(key, offset);
return getResponse(BuilderFactory.BOOLEAN);
}
public Response<Boolean> getbit(byte[] key, long offset) {
getClient(key).getbit(key, offset);
return getResponse(BuilderFactory.BOOLEAN);
}
public Response<Long> bitpos(final String key, final boolean value) {
return bitpos(key, value, new BitPosParams());
}
public Response<Long> bitpos(final String key, final boolean value, final BitPosParams params) {
getClient(key).bitpos(key, value, params);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> bitpos(final byte[] key, final boolean value) {
return bitpos(key, value, new BitPosParams());
}
public Response<Long> bitpos(final byte[] key, final boolean value, final BitPosParams params) {
getClient(key).bitpos(key, value, params);
return getResponse(BuilderFactory.LONG);
}
public Response<String> getrange(String key, long startOffset, long endOffset) {
getClient(key).getrange(key, startOffset, endOffset);
return getResponse(BuilderFactory.STRING);
}
public Response<String> getSet(String key, String value) {
getClient(key).getSet(key, value);
return getResponse(BuilderFactory.STRING);
}
public Response<byte[]> getSet(byte[] key, byte[] value) {
getClient(key).getSet(key, value);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<Long> getrange(byte[] key, long startOffset, long endOffset) {
getClient(key).getrange(key, startOffset, endOffset);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> hdel(String key, String... field) {
getClient(key).hdel(key, field);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> hdel(byte[] key, byte[]... field) {
getClient(key).hdel(key, field);
return getResponse(BuilderFactory.LONG);
}
public Response<Boolean> hexists(String key, String field) {
getClient(key).hexists(key, field);
return getResponse(BuilderFactory.BOOLEAN);
}
public Response<Boolean> hexists(byte[] key, byte[] field) {
getClient(key).hexists(key, field);
return getResponse(BuilderFactory.BOOLEAN);
}
public Response<String> hget(String key, String field) {
getClient(key).hget(key, field);
return getResponse(BuilderFactory.STRING);
}
public Response<byte[]> hget(byte[] key, byte[] field) {
getClient(key).hget(key, field);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<Map<String, String>> hgetAll(String key) {
getClient(key).hgetAll(key);
return getResponse(BuilderFactory.STRING_MAP);
}
public Response<Map<byte[], byte[]>> hgetAll(byte[] key) {
getClient(key).hgetAll(key);
return getResponse(BuilderFactory.BYTE_ARRAY_MAP);
}
public Response<Long> hincrBy(String key, String field, long value) {
getClient(key).hincrBy(key, field, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> hincrBy(byte[] key, byte[] field, long value) {
getClient(key).hincrBy(key, field, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Set<String>> hkeys(String key) {
getClient(key).hkeys(key);
return getResponse(BuilderFactory.STRING_SET);
}
public Response<Set<byte[]>> hkeys(byte[] key) {
getClient(key).hkeys(key);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<Long> hlen(String key) {
getClient(key).hlen(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> hlen(byte[] key) {
getClient(key).hlen(key);
return getResponse(BuilderFactory.LONG);
}
public Response<List<String>> hmget(String key, String... fields) {
getClient(key).hmget(key, fields);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<List<byte[]>> hmget(byte[] key, byte[]... fields) {
getClient(key).hmget(key, fields);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
public Response<String> hmset(String key, Map<String, String> hash) {
getClient(key).hmset(key, hash);
return getResponse(BuilderFactory.STRING);
}
public Response<String> hmset(byte[] key, Map<byte[], byte[]> hash) {
getClient(key).hmset(key, hash);
return getResponse(BuilderFactory.STRING);
}
public Response<Long> hset(String key, String field, String value) {
getClient(key).hset(key, field, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> hset(byte[] key, byte[] field, byte[] value) {
getClient(key).hset(key, field, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> hsetnx(String key, String field, String value) {
getClient(key).hsetnx(key, field, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> hsetnx(byte[] key, byte[] field, byte[] value) {
getClient(key).hsetnx(key, field, value);
return getResponse(BuilderFactory.LONG);
}
public Response<List<String>> hvals(String key) {
getClient(key).hvals(key);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<List<byte[]>> hvals(byte[] key) {
getClient(key).hvals(key);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
public Response<Long> incr(String key) {
getClient(key).incr(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> incr(byte[] key) {
getClient(key).incr(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> incrBy(String key, long integer) {
getClient(key).incrBy(key, integer);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> incrBy(byte[] key, long integer) {
getClient(key).incrBy(key, integer);
return getResponse(BuilderFactory.LONG);
}
public Response<String> lindex(String key, long index) {
getClient(key).lindex(key, index);
return getResponse(BuilderFactory.STRING);
}
public Response<byte[]> lindex(byte[] key, long index) {
getClient(key).lindex(key, index);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<Long> linsert(String key, LIST_POSITION where, String pivot, String value) {
getClient(key).linsert(key, where, pivot, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> linsert(byte[] key, LIST_POSITION where, byte[] pivot, byte[] value) {
getClient(key).linsert(key, where, pivot, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> llen(String key) {
getClient(key).llen(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> llen(byte[] key) {
getClient(key).llen(key);
return getResponse(BuilderFactory.LONG);
}
public Response<String> lpop(String key) {
getClient(key).lpop(key);
return getResponse(BuilderFactory.STRING);
}
public Response<byte[]> lpop(byte[] key) {
getClient(key).lpop(key);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<Long> lpush(String key, String... string) {
getClient(key).lpush(key, string);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> lpush(byte[] key, byte[]... string) {
getClient(key).lpush(key, string);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> lpushx(String key, String... string) {
getClient(key).lpushx(key, string);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> lpushx(byte[] key, byte[]... bytes) {
getClient(key).lpushx(key, bytes);
return getResponse(BuilderFactory.LONG);
}
public Response<List<String>> lrange(String key, long start, long end) {
getClient(key).lrange(key, start, end);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<List<byte[]>> lrange(byte[] key, long start, long end) {
getClient(key).lrange(key, start, end);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
public Response<Long> lrem(String key, long count, String value) {
getClient(key).lrem(key, count, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> lrem(byte[] key, long count, byte[] value) {
getClient(key).lrem(key, count, value);
return getResponse(BuilderFactory.LONG);
}
public Response<String> lset(String key, long index, String value) {
getClient(key).lset(key, index, value);
return getResponse(BuilderFactory.STRING);
}
public Response<String> lset(byte[] key, long index, byte[] value) {
getClient(key).lset(key, index, value);
return getResponse(BuilderFactory.STRING);
}
public Response<String> ltrim(String key, long start, long end) {
getClient(key).ltrim(key, start, end);
return getResponse(BuilderFactory.STRING);
}
public Response<String> ltrim(byte[] key, long start, long end) {
getClient(key).ltrim(key, start, end);
return getResponse(BuilderFactory.STRING);
}
public Response<Long> move(String key, int dbIndex) {
getClient(key).move(key, dbIndex);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> move(byte[] key, int dbIndex) {
getClient(key).move(key, dbIndex);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> persist(String key) {
getClient(key).persist(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> persist(byte[] key) {
getClient(key).persist(key);
return getResponse(BuilderFactory.LONG);
}
public Response<String> rpop(String key) {
getClient(key).rpop(key);
return getResponse(BuilderFactory.STRING);
}
public Response<byte[]> rpop(byte[] key) {
getClient(key).rpop(key);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<Long> rpush(String key, String... string) {
getClient(key).rpush(key, string);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> rpush(byte[] key, byte[]... string) {
getClient(key).rpush(key, string);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> rpushx(String key, String... string) {
getClient(key).rpushx(key, string);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> rpushx(byte[] key, byte[]... string) {
getClient(key).rpushx(key, string);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> sadd(String key, String... member) {
getClient(key).sadd(key, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> sadd(byte[] key, byte[]... member) {
getClient(key).sadd(key, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> scard(String key) {
getClient(key).scard(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> scard(byte[] key) {
getClient(key).scard(key);
return getResponse(BuilderFactory.LONG);
}
public Response<String> set(String key, String value) {
getClient(key).set(key, value);
return getResponse(BuilderFactory.STRING);
}
public Response<String> set(byte[] key, byte[] value) {
getClient(key).set(key, value);
return getResponse(BuilderFactory.STRING);
}
public Response<Boolean> setbit(String key, long offset, boolean value) {
getClient(key).setbit(key, offset, value);
return getResponse(BuilderFactory.BOOLEAN);
}
public Response<Boolean> setbit(byte[] key, long offset, byte[] value) {
getClient(key).setbit(key, offset, value);
return getResponse(BuilderFactory.BOOLEAN);
}
public Response<String> setex(String key, int seconds, String value) {
getClient(key).setex(key, seconds, value);
return getResponse(BuilderFactory.STRING);
}
public Response<String> setex(byte[] key, int seconds, byte[] value) {
getClient(key).setex(key, seconds, value);
return getResponse(BuilderFactory.STRING);
}
public Response<Long> setnx(String key, String value) {
getClient(key).setnx(key, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> setnx(byte[] key, byte[] value) {
getClient(key).setnx(key, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> setrange(String key, long offset, String value) {
getClient(key).setrange(key, offset, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> setrange(byte[] key, long offset, byte[] value) {
getClient(key).setrange(key, offset, value);
return getResponse(BuilderFactory.LONG);
}
public Response<Boolean> sismember(String key, String member) {
getClient(key).sismember(key, member);
return getResponse(BuilderFactory.BOOLEAN);
}
public Response<Boolean> sismember(byte[] key, byte[] member) {
getClient(key).sismember(key, member);
return getResponse(BuilderFactory.BOOLEAN);
}
public Response<Set<String>> smembers(String key) {
getClient(key).smembers(key);
return getResponse(BuilderFactory.STRING_SET);
}
public Response<Set<byte[]>> smembers(byte[] key) {
getClient(key).smembers(key);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<List<String>> sort(String key) {
getClient(key).sort(key);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<List<byte[]>> sort(byte[] key) {
getClient(key).sort(key);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
public Response<List<String>> sort(String key, SortingParams sortingParameters) {
getClient(key).sort(key, sortingParameters);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<List<byte[]>> sort(byte[] key, SortingParams sortingParameters) {
getClient(key).sort(key, sortingParameters);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
public Response<String> spop(String key) {
getClient(key).spop(key);
return getResponse(BuilderFactory.STRING);
}
public Response<Set<String>> spop(String key, long count) {
getClient(key).spop(key, count);
return getResponse(BuilderFactory.STRING_SET);
}
public Response<byte[]> spop(byte[] key) {
getClient(key).spop(key);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<Set<byte[]>> spop(byte[] key, long count) {
getClient(key).spop(key, count);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<String> srandmember(String key) {
getClient(key).srandmember(key);
return getResponse(BuilderFactory.STRING);
}
public Response<List<String>> srandmember(String key, int count) {
getClient(key).srandmember(key, count);
return getResponse(BuilderFactory.STRING_LIST);
}
public Response<byte[]> srandmember(byte[] key) {
getClient(key).srandmember(key);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<List<byte[]>> srandmember(byte[] key, int count) {
getClient(key).srandmember(key, count);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
public Response<Long> srem(String key, String... member) {
getClient(key).srem(key, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> srem(byte[] key, byte[]... member) {
getClient(key).srem(key, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> strlen(String key) {
getClient(key).strlen(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> strlen(byte[] key) {
getClient(key).strlen(key);
return getResponse(BuilderFactory.LONG);
}
public Response<String> substr(String key, int start, int end) {
getClient(key).substr(key, start, end);
return getResponse(BuilderFactory.STRING);
}
public Response<String> substr(byte[] key, int start, int end) {
getClient(key).substr(key, start, end);
return getResponse(BuilderFactory.STRING);
}
public Response<Long> ttl(String key) {
getClient(key).ttl(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> ttl(byte[] key) {
getClient(key).ttl(key);
return getResponse(BuilderFactory.LONG);
}
public Response<String> type(String key) {
getClient(key).type(key);
return getResponse(BuilderFactory.STRING);
}
public Response<String> type(byte[] key) {
getClient(key).type(key);
return getResponse(BuilderFactory.STRING);
}
public Response<Long> zadd(String key, double score, String member) {
getClient(key).zadd(key, score, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zadd(String key, Map<String, Double> scoreMembers) {
getClient(key).zadd(key, scoreMembers);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zadd(byte[] key, double score, byte[] member) {
getClient(key).zadd(key, score, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zcard(String key) {
getClient(key).zcard(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zcard(byte[] key) {
getClient(key).zcard(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zcount(String key, double min, double max) {
getClient(key).zcount(key, min, max);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zcount(String key, String min, String max) {
getClient(key).zcount(key, min, max);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zcount(byte[] key, double min, double max) {
getClient(key).zcount(key, toByteArray(min), toByteArray(max));
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zcount(byte[] key, byte[] min, byte[] max) {
getClient(key).zcount(key, min, max);
return getResponse(BuilderFactory.LONG);
}
public Response<Double> zincrby(String key, double score, String member) {
getClient(key).zincrby(key, score, member);
return getResponse(BuilderFactory.DOUBLE);
}
public Response<Double> zincrby(byte[] key, double score, byte[] member) {
getClient(key).zincrby(key, score, member);
return getResponse(BuilderFactory.DOUBLE);
}
public Response<Set<String>> zrange(String key, long start, long end) {
getClient(key).zrange(key, start, end);
return getResponse(BuilderFactory.STRING_ZSET);
}
public Response<Set<byte[]>> zrange(byte[] key, long start, long end) {
getClient(key).zrange(key, start, end);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<Set<String>> zrangeByScore(String key, double min, double max) {
getClient(key).zrangeByScore(key, min, max);
return getResponse(BuilderFactory.STRING_ZSET);
}
public Response<Set<byte[]>> zrangeByScore(byte[] key, double min, double max) {
return zrangeByScore(key, toByteArray(min), toByteArray(max));
}
public Response<Set<String>> zrangeByScore(String key, String min, String max) {
getClient(key).zrangeByScore(key, min, max);
return getResponse(BuilderFactory.STRING_ZSET);
}
public Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, byte[] max) {
getClient(key).zrangeByScore(key, min, max);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<Set<String>> zrangeByScore(String key, double min, double max, int offset,
int count) {
getClient(key).zrangeByScore(key, min, max, offset, count);
return getResponse(BuilderFactory.STRING_ZSET);
}
public Response<Set<String>> zrangeByScore(String key, String min, String max, int offset,
int count) {
getClient(key).zrangeByScore(key, min, max, offset, count);
return getResponse(BuilderFactory.STRING_ZSET);
}
public Response<Set<byte[]>> zrangeByScore(byte[] key, double min, double max, int offset,
int count) {
return zrangeByScore(key, toByteArray(min), toByteArray(max), offset, count);
}
public Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset,
int count) {
getClient(key).zrangeByScore(key, min, max, offset, count);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<Set<Tuple>> zrangeByScoreWithScores(String key, double min, double max) {
getClient(key).zrangeByScoreWithScores(key, min, max);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
public Response<Set<Tuple>> zrangeByScoreWithScores(String key, String min, String max) {
getClient(key).zrangeByScoreWithScores(key, min, max);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
public Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, double min, double max) {
return zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max));
}
public Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max) {
getClient(key).zrangeByScoreWithScores(key, min, max);
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
}
public Response<Set<Tuple>> zrangeByScoreWithScores(String key, double min, double max,
int offset, int count) {
getClient(key).zrangeByScoreWithScores(key, min, max, offset, count);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
public Response<Set<Tuple>> zrangeByScoreWithScores(String key, String min, String max,
int offset, int count) {
getClient(key).zrangeByScoreWithScores(key, min, max, offset, count);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
public Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, double min, double max,
int offset, int count) {
getClient(key).zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max), offset, count);
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
}
public Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max,
int offset, int count) {
getClient(key).zrangeByScoreWithScores(key, min, max, offset, count);
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
}
public Response<Set<String>> zrevrangeByScore(String key, double max, double min) {
getClient(key).zrevrangeByScore(key, max, min);
return getResponse(BuilderFactory.STRING_ZSET);
}
public Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max, double min) {
getClient(key).zrevrangeByScore(key, toByteArray(max), toByteArray(min));
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<Set<String>> zrevrangeByScore(String key, String max, String min) {
getClient(key).zrevrangeByScore(key, max, min);
return getResponse(BuilderFactory.STRING_ZSET);
}
public Response<Set<byte[]>> zrevrangeByScore(byte[] key, byte[] max, byte[] min) {
getClient(key).zrevrangeByScore(key, max, min);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<Set<String>> zrevrangeByScore(String key, double max, double min, int offset,
int count) {
getClient(key).zrevrangeByScore(key, max, min, offset, count);
return getResponse(BuilderFactory.STRING_ZSET);
}
public Response<Set<String>> zrevrangeByScore(String key, String max, String min, int offset,
int count) {
getClient(key).zrevrangeByScore(key, max, min, offset, count);
return getResponse(BuilderFactory.STRING_ZSET);
}
public Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max, double min, int offset,
int count) {
getClient(key).zrevrangeByScore(key, toByteArray(max), toByteArray(min), offset, count);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<Set<byte[]>> zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset,
int count) {
getClient(key).zrevrangeByScore(key, max, min, offset, count);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<Set<Tuple>> zrevrangeByScoreWithScores(String key, double max, double min) {
getClient(key).zrevrangeByScoreWithScores(key, max, min);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
public Response<Set<Tuple>> zrevrangeByScoreWithScores(String key, String max, String min) {
getClient(key).zrevrangeByScoreWithScores(key, max, min);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
public Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, double max, double min) {
getClient(key).zrevrangeByScoreWithScores(key, toByteArray(max), toByteArray(min));
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
}
public Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min) {
getClient(key).zrevrangeByScoreWithScores(key, max, min);
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
}
public Response<Set<Tuple>> zrevrangeByScoreWithScores(String key, double max, double min,
int offset, int count) {
getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
public Response<Set<Tuple>> zrevrangeByScoreWithScores(String key, String max, String min,
int offset, int count) {
getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
public Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, double max, double min,
int offset, int count) {
getClient(key).zrevrangeByScoreWithScores(key, toByteArray(max), toByteArray(min), offset,
count);
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
}
public Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min,
int offset, int count) {
getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count);
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
}
public Response<Set<Tuple>> zrangeWithScores(String key, long start, long end) {
getClient(key).zrangeWithScores(key, start, end);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
public Response<Set<Tuple>> zrangeWithScores(byte[] key, long start, long end) {
getClient(key).zrangeWithScores(key, start, end);
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
}
public Response<Long> zrank(String key, String member) {
getClient(key).zrank(key, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zrank(byte[] key, byte[] member) {
getClient(key).zrank(key, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zrem(String key, String... member) {
getClient(key).zrem(key, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zrem(byte[] key, byte[]... member) {
getClient(key).zrem(key, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zremrangeByRank(String key, long start, long end) {
getClient(key).zremrangeByRank(key, start, end);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zremrangeByRank(byte[] key, long start, long end) {
getClient(key).zremrangeByRank(key, start, end);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zremrangeByScore(String key, double start, double end) {
getClient(key).zremrangeByScore(key, start, end);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zremrangeByScore(String key, String start, String end) {
getClient(key).zremrangeByScore(key, start, end);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zremrangeByScore(byte[] key, double start, double end) {
getClient(key).zremrangeByScore(key, toByteArray(start), toByteArray(end));
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zremrangeByScore(byte[] key, byte[] start, byte[] end) {
getClient(key).zremrangeByScore(key, start, end);
return getResponse(BuilderFactory.LONG);
}
public Response<Set<String>> zrevrange(String key, long start, long end) {
getClient(key).zrevrange(key, start, end);
return getResponse(BuilderFactory.STRING_ZSET);
}
public Response<Set<byte[]>> zrevrange(byte[] key, long start, long end) {
getClient(key).zrevrange(key, start, end);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
public Response<Set<Tuple>> zrevrangeWithScores(String key, long start, long end) {
getClient(key).zrevrangeWithScores(key, start, end);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
public Response<Set<Tuple>> zrevrangeWithScores(byte[] key, long start, long end) {
getClient(key).zrevrangeWithScores(key, start, end);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
public Response<Long> zrevrank(String key, String member) {
getClient(key).zrevrank(key, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> zrevrank(byte[] key, byte[] member) {
getClient(key).zrevrank(key, member);
return getResponse(BuilderFactory.LONG);
}
public Response<Double> zscore(String key, String member) {
getClient(key).zscore(key, member);
return getResponse(BuilderFactory.DOUBLE);
}
public Response<Double> zscore(byte[] key, byte[] member) {
getClient(key).zscore(key, member);
return getResponse(BuilderFactory.DOUBLE);
}
@Override
public Response<Long> zlexcount(final byte[] key, final byte[] min, final byte[] max) {
getClient(key).zlexcount(key, min, max);
return getResponse(BuilderFactory.LONG);
}
@Override
public Response<Long> zlexcount(final String key, final String min, final String max) {
getClient(key).zlexcount(key, min, max);
return getResponse(BuilderFactory.LONG);
}
@Override
public Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min, final byte[] max) {
getClient(key).zrangeByLex(key, min, max);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
@Override
public Response<Set<String>> zrangeByLex(final String key, final String min, final String max) {
getClient(key).zrangeByLex(key, min, max);
return getResponse(BuilderFactory.STRING_ZSET);
}
@Override
public Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min, final byte[] max,
final int offset, final int count) {
getClient(key).zrangeByLex(key, min, max, offset, count);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
@Override
public Response<Set<String>> zrangeByLex(final String key, final String min, final String max,
final int offset, final int count) {
getClient(key).zrangeByLex(key, min, max, offset, count);
return getResponse(BuilderFactory.STRING_ZSET);
}
@Override
public Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min) {
getClient(key).zrevrangeByLex(key, max, min);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
@Override
public Response<Set<String>> zrevrangeByLex(final String key, final String max, final String min) {
getClient(key).zrevrangeByLex(key, max, min);
return getResponse(BuilderFactory.STRING_ZSET);
}
@Override
public Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min,
final int offset, final int count) {
getClient(key).zrevrangeByLex(key, max, min, offset, count);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
@Override
public Response<Set<String>> zrevrangeByLex(final String key, final String max, final String min,
final int offset, final int count) {
getClient(key).zrevrangeByLex(key, max, min, offset, count);
return getResponse(BuilderFactory.STRING_ZSET);
}
@Override
public Response<Long> zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) {
getClient(key).zremrangeByLex(key, min, max);
return getResponse(BuilderFactory.LONG);
}
@Override
public Response<Long> zremrangeByLex(final String key, final String min, final String max) {
getClient(key).zremrangeByLex(key, min, max);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> bitcount(String key) {
getClient(key).bitcount(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> bitcount(String key, long start, long end) {
getClient(key).bitcount(key, start, end);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> bitcount(byte[] key) {
getClient(key).bitcount(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> bitcount(byte[] key, long start, long end) {
getClient(key).bitcount(key, start, end);
return getResponse(BuilderFactory.LONG);
}
public Response<byte[]> dump(String key) {
getClient(key).dump(key);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<byte[]> dump(byte[] key) {
getClient(key).dump(key);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<String> migrate(String host, int port, String key, int destinationDb, int timeout) {
getClient(key).migrate(host, port, key, destinationDb, timeout);
return getResponse(BuilderFactory.STRING);
}
public Response<String> migrate(byte[] host, int port, byte[] key, int destinationDb, int timeout) {
getClient(key).migrate(host, port, key, destinationDb, timeout);
return getResponse(BuilderFactory.STRING);
}
public Response<Long> objectRefcount(String key) {
getClient(key).objectRefcount(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> objectRefcount(byte[] key) {
getClient(key).objectRefcount(key);
return getResponse(BuilderFactory.LONG);
}
public Response<String> objectEncoding(String key) {
getClient(key).objectEncoding(key);
return getResponse(BuilderFactory.STRING);
}
public Response<byte[]> objectEncoding(byte[] key) {
getClient(key).objectEncoding(key);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
public Response<Long> objectIdletime(String key) {
getClient(key).objectIdletime(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> objectIdletime(byte[] key) {
getClient(key).objectIdletime(key);
return getResponse(BuilderFactory.LONG);
}
@Deprecated
public Response<Long> pexpire(String key, int milliseconds) {
return pexpire(key, (long) milliseconds);
}
@Deprecated
public Response<Long> pexpire(byte[] key, int milliseconds) {
return pexpire(key, (long) milliseconds);
}
public Response<Long> pexpire(String key, long milliseconds) {
getClient(key).pexpire(key, milliseconds);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> pexpire(byte[] key, long milliseconds) {
getClient(key).pexpire(key, milliseconds);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> pexpireAt(String key, long millisecondsTimestamp) {
getClient(key).pexpireAt(key, millisecondsTimestamp);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> pexpireAt(byte[] key, long millisecondsTimestamp) {
getClient(key).pexpireAt(key, millisecondsTimestamp);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> pttl(String key) {
getClient(key).pttl(key);
return getResponse(BuilderFactory.LONG);
}
public Response<Long> pttl(byte[] key) {
getClient(key).pttl(key);
return getResponse(BuilderFactory.LONG);
}
public Response<String> restore(String key, int ttl, byte[] serializedValue) {
getClient(key).restore(key, ttl, serializedValue);
return getResponse(BuilderFactory.STRING);
}
public Response<String> restore(byte[] key, int ttl, byte[] serializedValue) {
getClient(key).restore(key, ttl, serializedValue);
return getResponse(BuilderFactory.STRING);
}
public Response<Double> incrByFloat(String key, double increment) {
getClient(key).incrByFloat(key, increment);
return getResponse(BuilderFactory.DOUBLE);
}
public Response<Double> incrByFloat(byte[] key, double increment) {
getClient(key).incrByFloat(key, increment);
return getResponse(BuilderFactory.DOUBLE);
}
@Deprecated
public Response<String> psetex(String key, int milliseconds, String value) {
return psetex(key, (long) milliseconds, value);
}
@Deprecated
public Response<String> psetex(byte[] key, int milliseconds, byte[] value) {
return psetex(key, (long) milliseconds, value);
}
public Response<String> psetex(String key, long milliseconds, String value) {
getClient(key).psetex(key, milliseconds, value);
return getResponse(BuilderFactory.STRING);
}
public Response<String> psetex(byte[] key, long milliseconds, byte[] value) {
getClient(key).psetex(key, milliseconds, value);
return getResponse(BuilderFactory.STRING);
}
public Response<String> set(String key, String value, String nxxx) {
getClient(key).set(key, value, nxxx);
return getResponse(BuilderFactory.STRING);
}
public Response<String> set(byte[] key, byte[] value, byte[] nxxx) {
getClient(key).set(key, value, nxxx);
return getResponse(BuilderFactory.STRING);
}
public Response<String> set(String key, String value, String nxxx, String expx, int time) {
getClient(key).set(key, value, nxxx, expx, time);
return getResponse(BuilderFactory.STRING);
}
public Response<String> set(byte[] key, byte[] value, byte[] nxxx, byte[] expx, int time) {
getClient(key).set(key, value, nxxx, expx, time);
return getResponse(BuilderFactory.STRING);
}
public Response<Double> hincrByFloat(String key, String field, double increment) {
getClient(key).hincrByFloat(key, field, increment);
return getResponse(BuilderFactory.DOUBLE);
}
public Response<Double> hincrByFloat(byte[] key, byte[] field, double increment) {
getClient(key).hincrByFloat(key, field, increment);
return getResponse(BuilderFactory.DOUBLE);
}
public Response<String> eval(String script) {
return this.eval(script, 0);
}
public Response<String> eval(String script, List<String> keys, List<String> args) {
String[] argv = Jedis.getParams(keys, args);
return this.eval(script, keys.size(), argv);
}
public Response<String> eval(String script, int numKeys, String... args) {
getClient(script).eval(script, numKeys, args);
return getResponse(BuilderFactory.STRING);
}
public Response<String> evalsha(String script) {
return this.evalsha(script, 0);
}
public Response<String> evalsha(String sha1, List<String> keys, List<String> args) {
String[] argv = Jedis.getParams(keys, args);
return this.evalsha(sha1, keys.size(), argv);
}
public Response<String> evalsha(String sha1, int numKeys, String... args) {
getClient(sha1).evalsha(sha1, numKeys, args);
return getResponse(BuilderFactory.STRING);
}
@Override
public Response<Long> pfadd(byte[] key, byte[]... elements) {
getClient(key).pfadd(key, elements);
return getResponse(BuilderFactory.LONG);
}
@Override
public Response<Long> pfcount(byte[] key) {
getClient(key).pfcount(key);
return getResponse(BuilderFactory.LONG);
}
@Override
public Response<Long> pfadd(String key, String... elements) {
getClient(key).pfadd(key, elements);
return getResponse(BuilderFactory.LONG);
}
@Override
public Response<Long> pfcount(String key) {
getClient(key).pfcount(key);
return getResponse(BuilderFactory.LONG);
}
}
| |
/**
* Copyright 2005-2013 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.ken.test;
import org.kuali.rice.core.api.lifecycle.BaseLifecycle;
import org.kuali.rice.core.api.lifecycle.Lifecycle;
import org.kuali.rice.core.framework.resourceloader.RiceResourceLoaderFactory;
import org.kuali.rice.core.framework.resourceloader.SpringResourceLoader;
import org.kuali.rice.ken.core.SpringNotificationServiceLocator;
import org.kuali.rice.kew.batch.KEWXmlDataLoader;
import org.kuali.rice.test.BaselineTestCase;
import org.kuali.rice.test.BaselineTestCase.BaselineMode;
import org.kuali.rice.test.BaselineTestCase.Mode;
import org.kuali.rice.test.CompositeBeanFactory;
import org.kuali.rice.test.SQLDataLoader;
import org.kuali.rice.test.lifecycles.KEWXmlDataLoaderLifecycle;
import org.kuali.rice.test.lifecycles.SQLDataLoaderLifecycle;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.transaction.PlatformTransactionManager;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.List;
/**
* Base test case for KEN that extends RiceTestCase
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
@BaselineMode(Mode.ROLLBACK_CLEAR_DB)
public abstract class KENTestCase extends BaselineTestCase {
private static final String KEN_MODULE_NAME = "ken";
private static final String TX_MGR_BEAN_NAME = "transactionManager";
protected SpringNotificationServiceLocator services;
protected PlatformTransactionManager transactionManager;
public KENTestCase() {
super(KEN_MODULE_NAME);
}
@Override
protected List<Lifecycle> getSuiteLifecycles() {
List<Lifecycle> suiteLifecycles = super.getSuiteLifecycles();
suiteLifecycles.add(new KEWXmlDataLoaderLifecycle("classpath:org/kuali/rice/ken/test/DefaultSuiteTestData.xml"));
return suiteLifecycles;
}
@Override
protected Lifecycle getLoadApplicationLifecycle() {
SpringResourceLoader springResourceLoader = new SpringResourceLoader(new QName("KENTestHarnessApplicationResourceLoader"), "classpath:KENTestHarnessSpringBeans.xml", null);
springResourceLoader.setParentSpringResourceLoader(getTestHarnessSpringResourceLoader());
return springResourceLoader;
}
@Override
protected List<Lifecycle> getPerTestLifecycles() {
List<Lifecycle> lifecycles = super.getPerTestLifecycles();
lifecycles.add(new ClearCacheLifecycle());
lifecycles.addAll(getNotificationPerTestLifecycles());
return lifecycles;
}
protected List<Lifecycle> getNotificationPerTestLifecycles() {
List<Lifecycle> lifecycles = new ArrayList<Lifecycle>();
lifecycles.add(new BaseLifecycle() {
@Override
public void start() throws Exception {
// get the composite Rice Spring context
BeanFactory moduleContext = CompositeBeanFactory.createBeanFactory(
RiceResourceLoaderFactory.getSpringResourceLoaders());
// This method sets up the Spring services so that they can be accessed by the tests.
services = new SpringNotificationServiceLocator(moduleContext);
// grab the module's transaction manager
transactionManager = (PlatformTransactionManager) moduleContext.getBean(TX_MGR_BEAN_NAME, PlatformTransactionManager.class);
super.start();
}
});
// clear out the KEW cache
lifecycles.add(new BaseLifecycle() {
@Override
public void start() throws Exception {
super.start();
LOG.info("Status of Ken scheduler on start: " + (services.getScheduler().isStarted() ? "started" : "stopped"));
// stop quartz if a test failed to do so
disableQuartzJobs();
}
public void stop() throws Exception {
//KsbApiServiceLocator.getCacheAdministrator().flushAll();
LOG.info("Status of Ken scheduler on stop: " + (services.getScheduler().isStarted() ? "started" : "stopped"));
// stop quartz if a test failed to do so
disableQuartzJobs();
super.stop();
}
});
// load the default SQL
//lifecycles.add(new SQLDataLoaderLifecycle("classpath:org/kuali/rice/ken/test/DefaultPerTestData.sql", ";"));
//lifecycles.add(new KEWXmlDataLoaderLifecycle("classpath:org/kuali/rice/ken/test/DefaultPerTestData.xml"));
return lifecycles;
}
/**
* By default this loads the "default" data set from the DefaultTestData.sql
* and DefaultTestData.xml files. Subclasses can override this to change
* this behaviour
*/
protected void loadDefaultTestData() throws Exception {
// at this point this is constants. loading these through xml import is
// problematic because of cache notification
// issues in certain low level constants.
new SQLDataLoader(
"classpath:org/kuali/rice/ken/test/DefaultPerTestData.sql", ";")
.runSql();
KEWXmlDataLoader.loadXmlClassLoaderResource(KENTestCase.class, "DefaultPerTestData.xml");
}
/**
* Returns the List of tables that should be cleared on every test run.
*/
@Override
protected List<String> getPerTestTablesToClear() {
List<String> tablesToClear = new ArrayList<String>();
tablesToClear.add("KREW_.*");
tablesToClear.add("KRSB_.*");
tablesToClear.add("KREN_.*");
return tablesToClear;
}
protected void setUpAfterDataLoad() throws Exception {
// override this to load your own test data
}
/**
* Initiates loading of per-test data
*/
@Override
protected void loadPerTestData() throws Exception {
loadDefaultTestData();
setUpAfterDataLoad();
final long t4 = System.currentTimeMillis();
}
/**
* Flushes the KEW cache(s)
*/
public class ClearCacheLifecycle extends BaseLifecycle {
@Override
public void stop() throws Exception {
//KsbApiServiceLocator.getCacheAdministrator().flushAll();
//KimApiServiceLocator.getIdentityManagementService().flushAllCaches();
//KimApiServiceLocator.getRoleService().flushRoleCaches();
super.stop();
}
}
/**
* This method makes sure to disable the Quartz scheduler
* @throws SchedulerException
*/
protected void disableQuartzJobs() throws SchedulerException {
// do this so that our quartz jobs don't go off - we don't care about
// these in our unit tests
Scheduler scheduler = services.getScheduler();
scheduler.standby();
//scheduler.shutdown();
}
/**
* This method enables the Quartz scheduler
* @throws SchedulerException
*/
protected void enableQuartzJobs() throws SchedulerException {
// do this so that our quartz jobs don't go off - we don't care about
// these in our unit tests
Scheduler scheduler = services.getScheduler();
scheduler.start();
}
}
| |
package org.workcraft.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Scanner;
import org.workcraft.gui.DesktopApi;
public class FileUtils {
public static final String TEMP_DIRECTORY_PREFIX = "workcraft-";
public static void copyFile(File in, File out) throws IOException {
out.getParentFile().mkdirs();
FileOutputStream outStream = new FileOutputStream(out);
try {
copyFileToStream(in, outStream);
} finally {
outStream.close();
}
}
public static String getFileNameWithoutExtension(File file) {
String name = file.getName();
int k = name.lastIndexOf('.');
if (k == -1) {
return name;
} else {
return name.substring(0, k);
}
}
public static void dumpString(File out, String string) throws IOException {
FileOutputStream fos = new FileOutputStream(out);
fos.write(string.getBytes());
fos.close();
}
public static void copyFileToStream(File in, OutputStream out) throws IOException {
FileInputStream is = new FileInputStream(in);
FileChannel inChannel = is.getChannel();
WritableByteChannel outChannel = Channels.newChannel(out);
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (is != null) is.close();
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
public static String getTempPrefix(String title) {
String prefix = TEMP_DIRECTORY_PREFIX;
if ((title != null) && !title.isEmpty()) {
prefix = TEMP_DIRECTORY_PREFIX + title + "-";
}
return getCorrectTempPrefix(prefix);
}
private static String getCorrectTempPrefix(String prefix) {
if (prefix == null) {
prefix = "";
}
// Prefix must be without spaces (replace spaces with underscores).
prefix = prefix.replaceAll("\\s", "_");
// Prefix must be at least 3 symbols long (prepend short prefix with
// underscores).
while (prefix.length() < 3) {
prefix = "_" + prefix;
}
return prefix;
}
public static File createTempFile(String prefix, String suffix) {
return createTempFile(prefix, suffix, null);
}
public static File createTempFile(String prefix, String suffix, File directory) {
File tempFile = null;
prefix = getCorrectTempPrefix(prefix);
String errorMessage = "Cannot create a temporary file with prefix '" + prefix + "'";
if (suffix == null) {
suffix = "";
} else {
errorMessage += " and suffix '" + suffix + "'.";
}
if (directory == null) {
try {
tempFile = File.createTempFile(prefix, suffix);
} catch (IOException e) {
throw new RuntimeException(errorMessage + ".");
}
} else {
try {
tempFile = File.createTempFile(prefix, suffix, directory);
} catch (IOException e) {
throw new RuntimeException(errorMessage + " under '" + directory.getAbsolutePath() + "' path.");
}
}
tempFile.deleteOnExit();
return tempFile;
}
public static File createTempDirectory() {
return createTempDirectory(getCorrectTempPrefix(null));
}
public static File createTempDirectory(String prefix) {
File tempDir = null;
String errorMessage = "Cannot create a temporary directory with prefix '" + prefix + "'.";
try {
tempDir = File.createTempFile(getCorrectTempPrefix(prefix), "");
} catch (IOException e) {
throw new RuntimeException(errorMessage);
}
tempDir.delete();
if (!tempDir.mkdir()) {
throw new RuntimeException(errorMessage);
}
tempDir.deleteOnExit();
return tempDir;
}
public static void copyAll(File source, File targetDir) throws IOException {
if (!targetDir.isDirectory()) {
throw new RuntimeException("Cannot copy files to a file that is not a directory.");
}
File target = new File(targetDir, source.getName());
if (source.isDirectory()) {
if (!target.mkdir()) {
throw new RuntimeException("Cannot create directory " + target.getAbsolutePath());
}
for (File f : source.listFiles()) {
copyAll(f, target);
}
} else {
copyFile(source, target);
}
}
public static void writeAllText(File file, String source) throws IOException {
FileWriter writer = new FileWriter(file);
writer.write(source);
writer.close();
}
/**
* Reads all text from the file using the default charset.
*/
public static String readAllText(File file) throws IOException {
InputStream stream = new FileInputStream(file);
try {
return readAllText(stream);
} finally {
stream.close();
}
}
/**
* Reads all text from the stream using the default charset.
* Does not close the stream.
*/
public static String readAllText(InputStream stream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder result = new StringBuilder();
while (true) {
String s = reader.readLine();
if (s == null) {
return result.toString();
}
result.append(s);
result.append('\n');
}
}
/**
* Reads first count characters from the file using the default charset.
*/
public static String readHeader(File file, int count) throws IOException {
InputStream stream = new FileInputStream(file);
try {
return readHeader(stream, count);
} finally {
stream.close();
}
}
/**
* Reads first count characters from a stream using the default charset.
* Does not close the stream.
*/
public static String readHeader(InputStream stream, int count) throws IOException {
byte[] buf = new byte[count];
int len = stream.read(buf);
return new String(buf, 0, len);
}
public static void moveFile(File from, File to) throws IOException {
copyFile(from, to);
from.delete();
}
public static byte[] readAllBytes(File in) throws IOException {
ByteArrayOutputStream mem = new ByteArrayOutputStream();
copyFileToStream(in, mem);
return mem.toByteArray();
}
public static void writeAllBytes(byte[] bytes, File out) throws IOException {
OutputStream stream = new FileOutputStream(out);
stream.write(bytes);
stream.close();
}
public static void appendAllText(File file, String text) throws IOException {
FileWriter writer = new FileWriter(file, true);
writer.write(text);
writer.close();
}
public static String readAllTextFromSystemResource(String path) throws IOException {
InputStream stream = ClassLoader.getSystemResourceAsStream(path);
try {
return readAllText(stream);
} finally {
stream.close();
}
}
public static boolean fileContainsKeyword(File file, String keyword) {
boolean result = false;
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (line.contains(keyword)) {
result = true;
break;
}
}
} catch (FileNotFoundException e) {
} finally {
if (scanner != null) {
scanner.close();
}
}
return result;
}
public static void deleteOnExitRecursively(File file) {
if (file != null) {
// Note that deleteOnExit() for a directory needs to be called BEFORE the deletion of its content.
file.deleteOnExit();
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
deleteOnExitRecursively(f);
}
}
}
}
public static boolean checkAvailability(File file, String title) {
boolean result = true;
if (title == null) {
title = "File access error";
}
if (file == null) {
DialogUtils.showError("The file name is undefined.\n", title);
result = false;
} else if (!file.exists()) {
DialogUtils.showError("The path \"" + file.getPath() + "\" does not exisit.\n", title);
result = false;
} else if (!file.isFile()) {
DialogUtils.showError("The path \"" + file.getPath() + "\" is not a file.\n", title);
result = false;
} else if (!file.canRead()) {
DialogUtils.showError("The file \"" + file.getPath() + "\" cannot be read.\n", title);
result = false;
}
return result;
}
public static void openExternally(String fileName, String errorTitle) {
File file = new File(fileName);
if (checkAvailability(file, errorTitle)) {
DesktopApi.open(file);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.test;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelOptRule;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.plan.hep.HepPlanner;
import org.apache.calcite.plan.hep.HepProgram;
import org.apache.calcite.plan.hep.HepProgramBuilder;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.RelRoot;
import org.apache.calcite.rel.metadata.ChainedRelMetadataProvider;
import org.apache.calcite.rel.metadata.DefaultRelMetadataProvider;
import org.apache.calcite.rel.metadata.RelMetadataProvider;
import org.apache.calcite.runtime.FlatLists;
import org.apache.calcite.runtime.Hook;
import org.apache.calcite.sql2rel.RelDecorrelator;
import org.apache.calcite.util.Closer;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* RelOptTestBase is an abstract base for tests which exercise a planner and/or
* rules via {@link DiffRepository}.
*/
abstract class RelOptTestBase extends SqlToRelTestBase {
//~ Methods ----------------------------------------------------------------
@Override protected Tester createTester() {
return super.createTester().withDecorrelation(false);
}
/**
* Checks the plan for a SQL statement before/after executing a given rule.
*
* @param rule Planner rule
* @param sql SQL query
*/
protected void checkPlanning(
RelOptRule rule,
String sql) {
HepProgramBuilder programBuilder = HepProgram.builder();
programBuilder.addRuleInstance(rule);
checkPlanning(
programBuilder.build(),
sql);
}
/**
* Checks the plan for a SQL statement before/after executing a given
* program.
*
* @param program Planner program
* @param sql SQL query
*/
protected void checkPlanning(HepProgram program, String sql) {
checkPlanning(new HepPlanner(program), sql);
}
/**
* Checks the plan for a SQL statement before/after executing a given
* planner.
*
* @param planner Planner
* @param sql SQL query
*/
protected void checkPlanning(RelOptPlanner planner, String sql) {
checkPlanning(tester, null, planner, sql);
}
/**
* Checks that the plan is the same before and after executing a given
* planner. Useful for checking circumstances where rules should not fire.
*
* @param planner Planner
* @param sql SQL query
*/
protected void checkPlanUnchanged(RelOptPlanner planner, String sql) {
checkPlanning(tester, null, planner, sql, true);
}
/**
* Checks the plan for a SQL statement before/after executing a given rule,
* with a pre-program to prepare the tree.
*
* @param tester Tester
* @param preProgram Program to execute before comparing before state
* @param planner Planner
* @param sql SQL query
*/
protected void checkPlanning(Tester tester, HepProgram preProgram,
RelOptPlanner planner, String sql) {
checkPlanning(tester, preProgram, planner, sql, false);
}
/**
* Checks the plan for a SQL statement before/after executing a given rule,
* with a pre-program to prepare the tree.
*
* @param tester Tester
* @param preProgram Program to execute before comparing before state
* @param planner Planner
* @param sql SQL query
* @param unchanged Whether the rule is to have no effect
*/
protected void checkPlanning(Tester tester, HepProgram preProgram,
RelOptPlanner planner, String sql, boolean unchanged) {
final DiffRepository diffRepos = getDiffRepos();
String sql2 = diffRepos.expand("sql", sql);
final RelRoot root = tester.convertSqlToRel(sql2);
final RelNode relInitial = root.rel;
assertTrue(relInitial != null);
List<RelMetadataProvider> list = Lists.newArrayList();
list.add(DefaultRelMetadataProvider.INSTANCE);
planner.registerMetadataProviders(list);
RelMetadataProvider plannerChain =
ChainedRelMetadataProvider.of(list);
relInitial.getCluster().setMetadataProvider(plannerChain);
RelNode relBefore;
if (preProgram == null) {
relBefore = relInitial;
} else {
HepPlanner prePlanner = new HepPlanner(preProgram);
prePlanner.setRoot(relInitial);
relBefore = prePlanner.findBestExp();
}
assertThat(relBefore, notNullValue());
final String planBefore = NL + RelOptUtil.toString(relBefore);
diffRepos.assertEquals("planBefore", "${planBefore}", planBefore);
SqlToRelTestBase.assertValid(relBefore);
planner.setRoot(relBefore);
RelNode r = planner.findBestExp();
if (tester.isLateDecorrelate()) {
final String planMid = NL + RelOptUtil.toString(r);
diffRepos.assertEquals("planMid", "${planMid}", planMid);
SqlToRelTestBase.assertValid(r);
r = RelDecorrelator.decorrelateQuery(r);
}
final String planAfter = NL + RelOptUtil.toString(r);
if (unchanged) {
assertThat(planAfter, is(planBefore));
} else {
diffRepos.assertEquals("planAfter", "${planAfter}", planAfter);
if (planBefore.equals(planAfter)) {
throw new AssertionError("Expected plan before and after is the same.\n"
+ "You must use unchanged=true or call checkPlanUnchanged");
}
}
SqlToRelTestBase.assertValid(r);
}
/** Sets the SQL statement for a test. */
Sql sql(String sql) {
return new Sql(sql, null, null,
ImmutableMap.<Hook, Function>of(),
ImmutableList.<Function<Tester, Tester>>of());
}
/** Allows fluent testing. */
class Sql {
private final String sql;
private HepProgram preProgram;
private final HepPlanner hepPlanner;
private final ImmutableMap<Hook, Function> hooks;
private ImmutableList<Function<Tester, Tester>> transforms;
Sql(String sql, HepProgram preProgram, HepPlanner hepPlanner,
ImmutableMap<Hook, Function> hooks,
ImmutableList<Function<Tester, Tester>> transforms) {
this.sql = sql;
this.preProgram = preProgram;
this.hepPlanner = hepPlanner;
this.hooks = hooks;
this.transforms = transforms;
}
public Sql withPre(HepProgram preProgram) {
return new Sql(sql, preProgram, hepPlanner, hooks, transforms);
}
public Sql with(HepPlanner hepPlanner) {
return new Sql(sql, preProgram, hepPlanner, hooks, transforms);
}
public Sql with(HepProgram program) {
return new Sql(sql, preProgram, new HepPlanner(program), hooks,
transforms);
}
public Sql withRule(RelOptRule rule) {
return with(HepProgram.builder().addRuleInstance(rule).build());
}
/** Adds a transform that will be applied to {@link #tester}
* just before running the query. */
private Sql withTransform(Function<Tester, Tester> transform) {
return new Sql(sql, preProgram, hepPlanner, hooks,
FlatLists.append(transforms, transform));
}
/** Adds a hook and a handler for that hook. Calcite will create a thread
* hook (by calling {@link Hook#addThread(com.google.common.base.Function)})
* just before running the query, and remove the hook afterwards. */
public <T> Sql withHook(Hook hook, Function<T, Void> handler) {
return new Sql(sql, preProgram, hepPlanner,
FlatLists.append(hooks, hook, handler), transforms);
}
public <V> Sql withProperty(Hook hook, V value) {
return withHook(hook, Hook.property(value));
}
public Sql expand(final boolean b) {
return withTransform(
new Function<Tester, Tester>() {
public Tester apply(Tester tester) {
return tester.withExpand(b);
}
});
}
public Sql withLateDecorrelation(final boolean b) {
return withTransform(
new Function<Tester, Tester>() {
public Tester apply(Tester tester) {
return tester.withLateDecorrelation(b);
}
});
}
public Sql withDecorrelation(final boolean b) {
return withTransform(
new Function<Tester, Tester>() {
public Tester apply(Tester tester) {
return tester.withDecorrelation(b);
}
});
}
public Sql withTrim(final boolean b) {
return withTransform(
new Function<Tester, Tester>() {
public Tester apply(Tester tester) {
return tester.withTrim(b);
}
});
}
public void check() {
check(false);
}
public void checkUnchanged() {
check(true);
}
private void check(boolean unchanged) {
try (final Closer closer = new Closer()) {
for (Map.Entry<Hook, Function> entry : hooks.entrySet()) {
closer.add(entry.getKey().addThread(entry.getValue()));
}
Tester t = tester;
for (Function<Tester, Tester> transform : transforms) {
t = transform.apply(t);
}
checkPlanning(t, preProgram, hepPlanner, sql, unchanged);
}
}
}
}
// End RelOptTestBase.java
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.connectors.kinesis.util;
import org.apache.flink.streaming.connectors.kinesis.FlinkKinesisConsumer;
import org.apache.flink.streaming.connectors.kinesis.FlinkKinesisProducer;
import org.apache.flink.streaming.connectors.kinesis.config.AWSConfigConstants;
import org.apache.flink.streaming.connectors.kinesis.config.AWSConfigConstants.CredentialProvider;
import org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants;
import org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.InitialPosition;
import org.apache.flink.streaming.connectors.kinesis.config.ProducerConfigConstants;
import com.amazonaws.regions.Regions;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
/**
* Utilities for Flink Kinesis connector configuration.
*/
public class KinesisConfigUtil {
/**
* Validate configuration properties for {@link FlinkKinesisConsumer}.
*/
public static void validateConsumerConfiguration(Properties config) {
checkNotNull(config, "config can not be null");
validateAwsConfiguration(config);
if (config.containsKey(ConsumerConfigConstants.STREAM_INITIAL_POSITION)) {
String initPosType = config.getProperty(ConsumerConfigConstants.STREAM_INITIAL_POSITION);
// specified initial position in stream must be either LATEST, TRIM_HORIZON or AT_TIMESTAMP
try {
InitialPosition.valueOf(initPosType);
} catch (IllegalArgumentException e) {
StringBuilder sb = new StringBuilder();
for (InitialPosition pos : InitialPosition.values()) {
sb.append(pos.toString()).append(", ");
}
throw new IllegalArgumentException("Invalid initial position in stream set in config. Valid values are: " + sb.toString());
}
// specified initial timestamp in stream when using AT_TIMESTAMP
if (InitialPosition.valueOf(initPosType) == InitialPosition.AT_TIMESTAMP) {
if (!config.containsKey(ConsumerConfigConstants.STREAM_INITIAL_TIMESTAMP)) {
throw new IllegalArgumentException("Please set value for initial timestamp ('"
+ ConsumerConfigConstants.STREAM_INITIAL_TIMESTAMP + "') when using AT_TIMESTAMP initial position.");
}
validateOptionalDateProperty(config,
ConsumerConfigConstants.STREAM_INITIAL_TIMESTAMP,
config.getProperty(ConsumerConfigConstants.STREAM_TIMESTAMP_DATE_FORMAT, ConsumerConfigConstants.DEFAULT_STREAM_TIMESTAMP_DATE_FORMAT),
"Invalid value given for initial timestamp for AT_TIMESTAMP initial position in stream. "
+ "Must be a valid format: yyyy-MM-dd'T'HH:mm:ss.SSSXXX or non-negative double value. For example, 2016-04-04T19:58:46.480-00:00 or 1459799926.480 .");
}
}
validateOptionalPositiveIntProperty(config, ConsumerConfigConstants.SHARD_GETRECORDS_MAX,
"Invalid value given for maximum records per getRecords shard operation. Must be a valid non-negative integer value.");
validateOptionalPositiveIntProperty(config, ConsumerConfigConstants.SHARD_GETRECORDS_RETRIES,
"Invalid value given for maximum retry attempts for getRecords shard operation. Must be a valid non-negative integer value.");
validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.SHARD_GETRECORDS_BACKOFF_BASE,
"Invalid value given for get records operation base backoff milliseconds. Must be a valid non-negative long value.");
validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.SHARD_GETRECORDS_BACKOFF_MAX,
"Invalid value given for get records operation max backoff milliseconds. Must be a valid non-negative long value.");
validateOptionalPositiveDoubleProperty(config, ConsumerConfigConstants.SHARD_GETRECORDS_BACKOFF_EXPONENTIAL_CONSTANT,
"Invalid value given for get records operation backoff exponential constant. Must be a valid non-negative double value.");
validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.SHARD_GETRECORDS_INTERVAL_MILLIS,
"Invalid value given for getRecords sleep interval in milliseconds. Must be a valid non-negative long value.");
validateOptionalPositiveIntProperty(config, ConsumerConfigConstants.SHARD_GETITERATOR_RETRIES,
"Invalid value given for maximum retry attempts for getShardIterator shard operation. Must be a valid non-negative integer value.");
validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.SHARD_GETITERATOR_BACKOFF_BASE,
"Invalid value given for get shard iterator operation base backoff milliseconds. Must be a valid non-negative long value.");
validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.SHARD_GETITERATOR_BACKOFF_MAX,
"Invalid value given for get shard iterator operation max backoff milliseconds. Must be a valid non-negative long value.");
validateOptionalPositiveDoubleProperty(config, ConsumerConfigConstants.SHARD_GETITERATOR_BACKOFF_EXPONENTIAL_CONSTANT,
"Invalid value given for get shard iterator operation backoff exponential constant. Must be a valid non-negative double value.");
validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.SHARD_DISCOVERY_INTERVAL_MILLIS,
"Invalid value given for shard discovery sleep interval in milliseconds. Must be a valid non-negative long value.");
validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.STREAM_DESCRIBE_BACKOFF_BASE,
"Invalid value given for describe stream operation base backoff milliseconds. Must be a valid non-negative long value.");
validateOptionalPositiveLongProperty(config, ConsumerConfigConstants.STREAM_DESCRIBE_BACKOFF_MAX,
"Invalid value given for describe stream operation max backoff milliseconds. Must be a valid non-negative long value.");
validateOptionalPositiveDoubleProperty(config, ConsumerConfigConstants.STREAM_DESCRIBE_BACKOFF_EXPONENTIAL_CONSTANT,
"Invalid value given for describe stream operation backoff exponential constant. Must be a valid non-negative double value.");
if (config.containsKey(ConsumerConfigConstants.SHARD_GETRECORDS_INTERVAL_MILLIS)) {
checkArgument(
Long.parseLong(config.getProperty(ConsumerConfigConstants.SHARD_GETRECORDS_INTERVAL_MILLIS))
< ConsumerConfigConstants.MAX_SHARD_GETRECORDS_INTERVAL_MILLIS,
"Invalid value given for getRecords sleep interval in milliseconds. Must be lower than " +
ConsumerConfigConstants.MAX_SHARD_GETRECORDS_INTERVAL_MILLIS + " milliseconds."
);
}
}
/**
* Validate configuration properties for {@link FlinkKinesisProducer}.
*/
public static void validateProducerConfiguration(Properties config) {
checkNotNull(config, "config can not be null");
validateAwsConfiguration(config);
validateOptionalPositiveLongProperty(config, ProducerConfigConstants.COLLECTION_MAX_COUNT,
"Invalid value given for maximum number of items to pack into a PutRecords request. Must be a valid non-negative long value.");
validateOptionalPositiveLongProperty(config, ProducerConfigConstants.AGGREGATION_MAX_COUNT,
"Invalid value given for maximum number of items to pack into an aggregated record. Must be a valid non-negative long value.");
}
/**
* Validate configuration properties related to Amazon AWS service.
*/
public static void validateAwsConfiguration(Properties config) {
if (config.containsKey(AWSConfigConstants.AWS_CREDENTIALS_PROVIDER)) {
String credentialsProviderType = config.getProperty(AWSConfigConstants.AWS_CREDENTIALS_PROVIDER);
// value specified for AWSConfigConstants.AWS_CREDENTIALS_PROVIDER needs to be recognizable
CredentialProvider providerType;
try {
providerType = CredentialProvider.valueOf(credentialsProviderType);
} catch (IllegalArgumentException e) {
StringBuilder sb = new StringBuilder();
for (CredentialProvider type : CredentialProvider.values()) {
sb.append(type.toString()).append(", ");
}
throw new IllegalArgumentException("Invalid AWS Credential Provider Type set in config. Valid values are: " + sb.toString());
}
// if BASIC type is used, also check that the Access Key ID and Secret Key is supplied
if (providerType == CredentialProvider.BASIC) {
if (!config.containsKey(AWSConfigConstants.AWS_ACCESS_KEY_ID)
|| !config.containsKey(AWSConfigConstants.AWS_SECRET_ACCESS_KEY)) {
throw new IllegalArgumentException("Please set values for AWS Access Key ID ('" + AWSConfigConstants.AWS_ACCESS_KEY_ID + "') " +
"and Secret Key ('" + AWSConfigConstants.AWS_SECRET_ACCESS_KEY + "') when using the BASIC AWS credential provider type.");
}
}
}
if (!config.containsKey(AWSConfigConstants.AWS_REGION)) {
throw new IllegalArgumentException("The AWS region ('" + AWSConfigConstants.AWS_REGION + "') must be set in the config.");
} else {
// specified AWS Region name must be recognizable
if (!AWSUtil.isValidRegion(config.getProperty(AWSConfigConstants.AWS_REGION))) {
StringBuilder sb = new StringBuilder();
for (Regions region : Regions.values()) {
sb.append(region.getName()).append(", ");
}
throw new IllegalArgumentException("Invalid AWS region set in config. Valid values are: " + sb.toString());
}
}
}
private static void validateOptionalPositiveLongProperty(Properties config, String key, String message) {
if (config.containsKey(key)) {
try {
long value = Long.parseLong(config.getProperty(key));
if (value < 0) {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException(message);
}
}
}
private static void validateOptionalPositiveIntProperty(Properties config, String key, String message) {
if (config.containsKey(key)) {
try {
int value = Integer.parseInt(config.getProperty(key));
if (value < 0) {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException(message);
}
}
}
private static void validateOptionalPositiveDoubleProperty(Properties config, String key, String message) {
if (config.containsKey(key)) {
try {
double value = Double.parseDouble(config.getProperty(key));
if (value < 0) {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException(message);
}
}
}
private static void validateOptionalDateProperty(Properties config, String timestampKey, String format, String message) {
if (config.containsKey(timestampKey)) {
try {
SimpleDateFormat customDateFormat = new SimpleDateFormat(format);
customDateFormat.parse(config.getProperty(timestampKey));
} catch (IllegalArgumentException | NullPointerException exception) {
throw new IllegalArgumentException(message);
} catch (ParseException exception) {
try {
double value = Double.parseDouble(config.getProperty(timestampKey));
if (value < 0) {
throw new IllegalArgumentException(message);
}
} catch (NumberFormatException numberFormatException) {
throw new IllegalArgumentException(message);
}
}
}
}
}
| |
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sbql4j8.com.sun.tools.doclets.internal.toolkit.builders;
import java.io.*;
import java.util.*;
import sbql4j8.com.sun.javadoc.*;
import sbql4j8.com.sun.tools.doclets.internal.toolkit.*;
import sbql4j8.com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Builds the Constants Summary Page.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*
* @author Jamie Ho
* @author Bhavesh Patel (Modified)
* @since 1.5
*/
public class ConstantsSummaryBuilder extends AbstractBuilder {
/**
* The root element of the constant summary XML is {@value}.
*/
public static final String ROOT = "ConstantSummary";
/**
* The maximum number of package directories shown in the constant
* value index.
*/
public static final int MAX_CONSTANT_VALUE_INDEX_LENGTH = 2;
/**
* The writer used to write the results.
*/
protected final ConstantsSummaryWriter writer;
/**
* The set of ClassDocs that have constant fields.
*/
protected final Set<ClassDoc> classDocsWithConstFields;
/**
* The set of printed package headers.
*/
protected Set<String> printedPackageHeaders;
/**
* The current package being documented.
*/
private PackageDoc currentPackage;
/**
* The current class being documented.
*/
private ClassDoc currentClass;
/**
* The content tree for the constant summary documentation.
*/
private Content contentTree;
/**
* Construct a new ConstantsSummaryBuilder.
*
* @param context the build context.
* @param writer the writer for the summary.
*/
private ConstantsSummaryBuilder(Context context,
ConstantsSummaryWriter writer) {
super(context);
this.writer = writer;
this.classDocsWithConstFields = new HashSet<ClassDoc>();
}
/**
* Construct a ConstantsSummaryBuilder.
*
* @param context the build context.
* @param writer the writer for the summary.
*/
public static ConstantsSummaryBuilder getInstance(Context context,
ConstantsSummaryWriter writer) {
return new ConstantsSummaryBuilder(context, writer);
}
/**
* {@inheritDoc}
*/
public void build() throws IOException {
if (writer == null) {
//Doclet does not support this output.
return;
}
build(layoutParser.parseXML(ROOT), contentTree);
}
/**
* {@inheritDoc}
*/
public String getName() {
return ROOT;
}
/**
* Build the constant summary.
*
* @param node the XML element that specifies which components to document
* @param contentTree the content tree to which the documentation will be added
*/
public void buildConstantSummary(XMLNode node, Content contentTree) throws Exception {
contentTree = writer.getHeader();
buildChildren(node, contentTree);
writer.addFooter(contentTree);
writer.printDocument(contentTree);
writer.close();
}
/**
* Build the list of packages.
*
* @param node the XML element that specifies which components to document
* @param contentTree the content tree to which the content list will be added
*/
public void buildContents(XMLNode node, Content contentTree) {
Content contentListTree = writer.getContentsHeader();
PackageDoc[] packages = configuration.packages;
printedPackageHeaders = new HashSet<String>();
for (int i = 0; i < packages.length; i++) {
if (hasConstantField(packages[i]) && ! hasPrintedPackageIndex(packages[i].name())) {
writer.addLinkToPackageContent(packages[i],
parsePackageName(packages[i].name()),
printedPackageHeaders, contentListTree);
}
}
contentTree.addContent(writer.getContentsList(contentListTree));
}
/**
* Build the summary for each documented package.
*
* @param node the XML element that specifies which components to document
* @param contentTree the tree to which the summaries will be added
*/
public void buildConstantSummaries(XMLNode node, Content contentTree) {
PackageDoc[] packages = configuration.packages;
printedPackageHeaders = new HashSet<String>();
Content summariesTree = writer.getConstantSummaries();
for (int i = 0; i < packages.length; i++) {
if (hasConstantField(packages[i])) {
currentPackage = packages[i];
//Build the documentation for the current package.
buildChildren(node, summariesTree);
}
}
contentTree.addContent(summariesTree);
}
/**
* Build the header for the given package.
*
* @param node the XML element that specifies which components to document
* @param summariesTree the tree to which the package header will be added
*/
public void buildPackageHeader(XMLNode node, Content summariesTree) {
String parsedPackageName = parsePackageName(currentPackage.name());
if (! printedPackageHeaders.contains(parsedPackageName)) {
writer.addPackageName(currentPackage,
parsePackageName(currentPackage.name()), summariesTree);
printedPackageHeaders.add(parsedPackageName);
}
}
/**
* Build the summary for the current class.
*
* @param node the XML element that specifies which components to document
* @param summariesTree the tree to which the class constant summary will be added
*/
public void buildClassConstantSummary(XMLNode node, Content summariesTree) {
ClassDoc[] classes = currentPackage.name().length() > 0 ?
currentPackage.allClasses() :
configuration.classDocCatalog.allClasses(
DocletConstants.DEFAULT_PACKAGE_NAME);
Arrays.sort(classes);
Content classConstantTree = writer.getClassConstantHeader();
for (int i = 0; i < classes.length; i++) {
if (! classDocsWithConstFields.contains(classes[i]) ||
! classes[i].isIncluded()) {
continue;
}
currentClass = classes[i];
//Build the documentation for the current class.
buildChildren(node, classConstantTree);
}
summariesTree.addContent(classConstantTree);
}
/**
* Build the summary of constant members in the class.
*
* @param node the XML element that specifies which components to document
* @param classConstantTree the tree to which the constant members table
* will be added
*/
public void buildConstantMembers(XMLNode node, Content classConstantTree) {
new ConstantFieldBuilder(currentClass).buildMembersSummary(node, classConstantTree);
}
/**
* Return true if the given package has constant fields to document.
*
* @param pkg the package being checked.
* @return true if the given package has constant fields to document.
*/
private boolean hasConstantField(PackageDoc pkg) {
ClassDoc[] classes;
if (pkg.name().length() > 0) {
classes = pkg.allClasses();
} else {
classes = configuration.classDocCatalog.allClasses(
DocletConstants.DEFAULT_PACKAGE_NAME);
}
boolean found = false;
for (int j = 0; j < classes.length; j++){
if (classes[j].isIncluded() && hasConstantField(classes[j])) {
found = true;
}
}
return found;
}
/**
* Return true if the given class has constant fields to document.
*
* @param classDoc the class being checked.
* @return true if the given package has constant fields to document.
*/
private boolean hasConstantField (ClassDoc classDoc) {
VisibleMemberMap visibleMemberMapFields = new VisibleMemberMap(classDoc,
VisibleMemberMap.FIELDS, configuration);
List<?> fields = visibleMemberMapFields.getLeafClassMembers(configuration);
for (Iterator<?> iter = fields.iterator(); iter.hasNext(); ) {
FieldDoc field = (FieldDoc) iter.next();
if (field.constantValueExpression() != null) {
classDocsWithConstFields.add(classDoc);
return true;
}
}
return false;
}
/**
* Return true if the given package name has been printed. Also
* return true if the root of this package has been printed.
*
* @param pkgname the name of the package to check.
*/
private boolean hasPrintedPackageIndex(String pkgname) {
String[] list = printedPackageHeaders.toArray(new String[] {});
for (int i = 0; i < list.length; i++) {
if (pkgname.startsWith(list[i])) {
return true;
}
}
return false;
}
/**
* Print the table of constants.
*
* @author Jamie Ho
* @since 1.4
*/
private class ConstantFieldBuilder {
/**
* The map used to get the visible variables.
*/
protected VisibleMemberMap visibleMemberMapFields = null;
/**
* The map used to get the visible variables.
*/
protected VisibleMemberMap visibleMemberMapEnumConst = null;
/**
* The classdoc that we are examining constants for.
*/
protected ClassDoc classdoc;
/**
* Construct a ConstantFieldSubWriter.
* @param classdoc the classdoc that we are examining constants for.
*/
public ConstantFieldBuilder(ClassDoc classdoc) {
this.classdoc = classdoc;
visibleMemberMapFields = new VisibleMemberMap(classdoc,
VisibleMemberMap.FIELDS, configuration);
visibleMemberMapEnumConst = new VisibleMemberMap(classdoc,
VisibleMemberMap.ENUM_CONSTANTS, configuration);
}
/**
* Builds the table of constants for a given class.
*
* @param node the XML element that specifies which components to document
* @param classConstantTree the tree to which the class constants table
* will be added
*/
protected void buildMembersSummary(XMLNode node, Content classConstantTree) {
List<FieldDoc> members = new ArrayList<FieldDoc>(members());
if (members.size() > 0) {
Collections.sort(members);
writer.addConstantMembers(classdoc, members, classConstantTree);
}
}
/**
* Return the list of visible constant fields for the given classdoc.
* @return the list of visible constant fields for the given classdoc.
*/
protected List<FieldDoc> members() {
List<ProgramElementDoc> l = visibleMemberMapFields.getLeafClassMembers(configuration);
l.addAll(visibleMemberMapEnumConst.getLeafClassMembers(configuration));
Iterator<ProgramElementDoc> iter;
if(l != null){
iter = l.iterator();
} else {
return null;
}
List<FieldDoc> inclList = new LinkedList<FieldDoc>();
FieldDoc member;
while(iter.hasNext()){
member = (FieldDoc)iter.next();
if(member.constantValue() != null){
inclList.add(member);
}
}
return inclList;
}
}
/**
* Parse the package name. We only want to display package name up to
* 2 levels.
*/
private String parsePackageName(String pkgname) {
int index = -1;
for (int j = 0; j < MAX_CONSTANT_VALUE_INDEX_LENGTH; j++) {
index = pkgname.indexOf(".", index + 1);
}
if (index != -1) {
pkgname = pkgname.substring(0, index);
}
return pkgname;
}
}
| |
package org.wikidata.wdtk.datamodel.helpers;
/*
* #%L
* Wikidata Toolkit Data Model
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.wikidata.wdtk.datamodel.interfaces.Claim;
import org.wikidata.wdtk.datamodel.interfaces.DatatypeIdValue;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.GlobeCoordinatesValue;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue;
import org.wikidata.wdtk.datamodel.interfaces.NoValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import org.wikidata.wdtk.datamodel.interfaces.QuantityValue;
import org.wikidata.wdtk.datamodel.interfaces.Reference;
import org.wikidata.wdtk.datamodel.interfaces.SiteLink;
import org.wikidata.wdtk.datamodel.interfaces.SnakGroup;
import org.wikidata.wdtk.datamodel.interfaces.SomeValueSnak;
import org.wikidata.wdtk.datamodel.interfaces.Statement;
import org.wikidata.wdtk.datamodel.interfaces.StatementGroup;
import org.wikidata.wdtk.datamodel.interfaces.StringValue;
import org.wikidata.wdtk.datamodel.interfaces.TermedDocument;
import org.wikidata.wdtk.datamodel.interfaces.TimeValue;
import org.wikidata.wdtk.datamodel.interfaces.ValueSnak;
/**
* Static class for computing a hashcode of arbitrary data objects using only
* their interfaces. This can be used to implement the hashCode() method of
* arbitrary interface implementations. More efficient solutions might exist if
* the object that implements an interface is of a specific known type, but the
* methods here could always be used as a fallback or default.
*
* @author Markus Kroetzsch
*
*/
public class Hash {
/**
* Prime number used to build hashes.
*/
final static int prime = 31;
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(EntityIdValue o) {
int result;
result = o.getId().hashCode();
result = prime * result + o.getSiteIri().hashCode();
result = prime * result + o.getEntityType().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(DatatypeIdValue o) {
return o.getIri().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(TimeValue o) {
int result;
result = new Long(o.getYear()).hashCode();
result = prime * result + o.getMonth();
result = prime * result + o.getDay();
result = prime * result + o.getHour();
result = prime * result + o.getMinute();
result = prime * result + o.getSecond();
result = prime * result + o.getPrecision();
result = prime * result + o.getBeforeTolerance();
result = prime * result + o.getAfterTolerance();
result = prime * result + o.getTimezoneOffset();
result = prime * result + o.getPreferredCalendarModel().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(GlobeCoordinatesValue o) {
int result;
result = o.getGlobe().hashCode();
long value;
value = Double.valueOf(o.getLatitude()).hashCode();
result = prime * result + (int) (value ^ (value >>> 32));
value = Double.valueOf(o.getLongitude()).hashCode();
result = prime * result + (int) (value ^ (value >>> 32));
value = Double.valueOf(o.getPrecision()).hashCode();
result = prime * result + (int) (value ^ (value >>> 32));
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(StringValue o) {
return o.getString().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(MonolingualTextValue o) {
int result;
result = o.getLanguageCode().hashCode();
result = prime * result + o.getText().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(QuantityValue o) {
int result;
result = o.getNumericValue().hashCode();
result = prime * result + o.getLowerBound().hashCode();
result = prime * result + o.getUpperBound().hashCode();
result = prime * result + o.getUnit().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(ValueSnak o) {
int result;
result = o.getValue().hashCode();
result = prime * result + o.getPropertyId().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(SomeValueSnak o) {
return o.getPropertyId().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(NoValueSnak o) {
return o.getPropertyId().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(SnakGroup o) {
return o.getSnaks().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(Claim o) {
int result;
result = o.getSubject().hashCode();
result = prime * result + o.getMainSnak().hashCode();
result = prime * result + o.getQualifiers().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(Reference o) {
return o.getSnakGroups().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(Statement o) {
int result;
result = o.getClaim().hashCode();
result = prime * result + o.getReferences().hashCode();
result = prime * result + o.getRank().hashCode();
result = prime * result + o.getStatementId().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(StatementGroup o) {
return o.getStatements().hashCode();
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(SiteLink o) {
int result;
result = o.getBadges().hashCode();
result = prime * result + o.getPageTitle().hashCode();
result = prime * result + o.getSiteKey().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(PropertyDocument o) {
int result;
result = hashCodeForTermedDocument(o);
result = prime * result + o.getStatementGroups().hashCode();
result = prime * result + o.getDatatype().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
public static int hashCode(ItemDocument o) {
int result;
result = hashCodeForTermedDocument(o);
result = prime * result + o.getStatementGroups().hashCode();
result = prime * result + o.getSiteLinks().hashCode();
return result;
}
/**
* Returns a hash code for the given object.
*
* @see java.lang.Object#hashCode()
* @param o
* the object to create a hash for
* @return the hash code of the object
*/
protected static int hashCodeForTermedDocument(TermedDocument o) {
int result;
result = o.getAliases().hashCode();
result = prime * result + o.getDescriptions().hashCode();
result = prime * result + o.getLabels().hashCode();
result = prime * result + new Long(o.getRevisionId()).hashCode();
return result;
}
}
| |
package net.soundvibe.reacto.types.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.*;
import static java.util.Optional.of;
import static org.junit.Assert.*;
/**
* @author OZY on 2017.01.18.
*/
public class JsonObjectBuilderTest {
@Test
public void shouldBuildJsonObject() throws Exception {
final JsonObject actual = JsonObjectBuilder.create()
.put("key", "value1")
.put("key2", "value2")
.put("metadata", JsonObjectBuilder.create()
.put("sub1", "value3")
.put("sub2", "value4")
.build()
)
.put("long", 155L)
.put("double", 155.0)
.put("boolean", true)
.put("instant", Instant.MIN)
.put("bytes", "foo".getBytes())
.put("bigDecimal", new BigDecimal("4565869874589877.2"))
.putObject("metadata2", object -> object.put("sub3", "value5"))
.putArray("array", arr -> arr.add(true).add(false))
.put("count", 150L)
.put("gender", Gender.MALE)
.put("charSequence", new StringBuilder().append("ok"))
.build();
System.out.println(actual);
assertEquals(of("value1"), actual.valueOf("key", String.class));
assertEquals(of("value2"), actual.valueOf("key2", String.class));
assertEquals(of(155L), actual.asLong("long"));
assertEquals(of(155.0), actual.asDouble("double"));
assertEquals(of(true), actual.asBoolean("boolean"));
assertEquals(of(Instant.MIN), actual.asInstant("instant"));
assertArrayEquals("foo".getBytes(), actual.asBytes("bytes").orElseThrow(NoSuchElementException::new));
assertEquals(of(new BigDecimal("4565869874589877.2")), actual.asNumber("bigDecimal"));
assertTrue(actual.containsKey("key"));
assertFalse(actual.containsKey("randomKey-sd"));
assertFalse(actual.isEmpty());
assertTrue(actual.hasElements());
assertEquals(14, actual.size());
assertNotEquals(0, actual.size());
assertEquals(of(150L), actual.valueOf("count", Long.class));
assertEquals(of(Gender.MALE), actual.valueOf("gender", Gender.class));
assertEquals(of("ok"), actual.valueOf("charSequence", String.class));
assertEquals(of("value3"), actual.asObject("metadata")
.orElse(JsonObject.empty())
.valueOf("sub1", String.class));
assertEquals(of("value4"), actual.asObject("metadata")
.orElse(JsonObject.empty())
.valueOf("sub2", String.class));
assertEquals(of("value5"), actual.asObject("metadata2")
.orElse(JsonObject.empty())
.valueOf("sub3", String.class));
assertEquals(of(true), actual.asArray("array").orElse(JsonArray.empty()).valueOf(0, Boolean.class));
assertEquals(of(false), actual.asArray("array").orElse(JsonArray.empty()).valueOf(1, Boolean.class));
}
@Test
public void shouldReturnNewMap() throws Exception {
final JsonObject sut = JsonObjectBuilder.create()
.put("key", "value1")
.build();
final Map<String, Object> actual = sut.toMap();
assertEquals(1, actual.size());
assertEquals("value1", actual.get("key"));
actual.clear();
assertEquals("value1", sut.asString("key").orElse(""));
}
@Test
public void shouldReturnNewFieldNamesSet() throws Exception {
final JsonObject sut = JsonObjectBuilder.create()
.put("key", "value1")
.put("key2", "value2")
.build();
final Set<String> actual = sut.fieldNames();
assertEquals(2, actual.size());
assertEquals(2L, sut.stream().count());
assertEquals(2L, sut.parallelStream().count());
assertEquals(2L, sut.streamOfKeys().count());
assertEquals(2L, sut.streamOfValues().count());
assertTrue(actual.contains("key"));
assertTrue(actual.contains("key2"));
assertFalse(actual.contains("___"));
actual.clear();
assertEquals("value1", sut.asString("key").orElse(""));
}
@Test
public void shouldIterateUsingForEach() throws Exception {
final JsonObject sut = JsonObjectBuilder.create()
.put("key", "value1")
.put("key2", "value2")
.build();
int count = 0;
for (final Map.Entry<String, Object> entry : sut) {
count++;
if (count == 1) {
assertEquals("key", entry.getKey());
assertEquals("value1", entry.getValue());
} else if (count == 2) {
assertEquals("key2", entry.getKey());
assertEquals("value2", entry.getValue());
} else {
fail("Should be at most 2 iterations");
}
}
assertEquals(2, count);
}
@Test
public void shouldIterate() throws Exception {
Map<String, Object> map = new LinkedHashMap<>();
map.put("key1", Collections.singletonList("value1"));
Map<String, Object> subMap = new LinkedHashMap<>();
subMap.put("foo", "bar");
map.put("key2", subMap);
final JsonObject sut = new JsonObject(map);
int count = 0;
for (final Map.Entry<String, Object> entry : sut) {
count++;
if (count == 1) {
assertEquals("key1", entry.getKey());
assertEquals(JsonArray.class, entry.getValue().getClass());
assertEquals("value1", ((JsonArray) entry.getValue()).asString(0).orElse(""));
} else if (count == 2) {
assertEquals("key2", entry.getKey());
assertEquals(JsonObject.class, entry.getValue().getClass());
assertEquals("bar", ((JsonObject) entry.getValue()).asString("foo").orElse(""));
} else {
fail("Should be at most 2 iterations");
}
}
assertEquals(2, count);
}
@Test(expected = UnsupportedOperationException.class)
public void shouldThrowWhenTryingToMutateItemWhileIterating() throws Exception {
final Map<String, Object> map = new HashMap<>();
map.put("foo", Collections.singletonList("bar"));
final JsonObject actual = JsonObjectBuilder.from(new JsonObject(map))
.build();
for (Map.Entry<String, Object> next : actual) {
next.setValue("value");
}
}
@Test
public void shouldMerge() throws Exception {
final JsonObject jsonObject1 = JsonObjectBuilder.create()
.put("key", "value1")
.put("key2", "value2")
.build();
final JsonObject jsonObject2 = JsonObjectBuilder.create()
.put("key", "value1")
.put("key2", "valueNew")
.put("new", "value3")
.build();
final JsonObject merged1 = JsonObjectBuilder.from(jsonObject1)
.merge(jsonObject2)
.build();
assertEquals(3, merged1.size());
assertEquals("value1", merged1.asString("key").orElse(""));
assertEquals("valueNew", merged1.asString("key2").orElse(""));
assertEquals("value3", merged1.asString("new").orElse(""));
final JsonObject merged2 = JsonObjectBuilder.from(jsonObject1)
.merge(JsonObjectBuilder.from(jsonObject2))
.build();
assertEquals(3, merged2.size());
assertEquals("value1", merged2.asString("key").orElse(""));
assertEquals("valueNew", merged2.asString("key2").orElse(""));
assertEquals("value3", merged2.asString("new").orElse(""));
}
@Test
public void shouldRemove() throws Exception {
final JsonObject jsonObject = JsonObjectBuilder.create()
.put("key", "value1")
.put("key2", "value2")
.build();
assertEquals(2, jsonObject.size());
final JsonObject actual = JsonObjectBuilder.from(jsonObject)
.remove("key2")
.build();
assertEquals(1, actual.size());
assertEquals("value1", actual.asString("key").orElse(""));
final JsonObject empty = JsonObjectBuilder.from(jsonObject)
.clear()
.build();
assertEquals(0, empty.size());
assertTrue(empty.isEmpty());
assertFalse(empty.hasElements());
}
@Test
public void shouldEncode() throws Exception {
final JsonObject sut = JsonObjectBuilder.create()
.put("key", "value1")
.put("key2", "value2")
.build();
final String actual = sut.encode(Object::toString);
assertEquals(sut.values.toString(), actual);
}
@Test
public void shouldConvertToJson() throws Exception {
final JsonObject sut = JsonObjectBuilder.create()
.put("key", "value1")
.put("key2", "value2")
.build();
final String actual = sut.toJson();
assertEquals("{\"key\":\"value1\",\"key2\":\"value2\"}", actual);
}
@Test
public void shouldGetBytesValue() throws Exception {
final JsonObject actual = JsonObjectBuilder.create()
.put("payload", "someData".getBytes())
.build();
assertArrayEquals("someData".getBytes(), actual.valueOf("payload", byte[].class).orElse(new byte[0]));
}
@Test
public void shouldGetInstantValue() throws Exception {
final Instant now = Instant.now();
final JsonObject actual = JsonObjectBuilder.create()
.put("timestamp", now)
.build();
assertEquals(now, actual.valueOf("timestamp", Instant.class).orElse(Instant.MIN));
}
@Test
public void shouldGetEnumValue() throws Exception {
final JsonObject actual = JsonObjectBuilder.create()
.put("gender", Gender.MALE)
.build();
assertEquals(Gender.MALE, actual.valueOf("gender", Gender.class).orElse(Gender.FEMALE));
}
@Test
public void shouldGetNull() throws Exception {
final JsonObject actual = JsonObjectBuilder.create()
.putNull("foo")
.build();
assertEquals(Optional.empty(), actual.valueOf("foo", String.class));
}
private final static ObjectMapper json = new ObjectMapper();
@Test
public void shouldBuildFromJsonString() throws Exception {
final String jsonString = "{ \"key1\": \"value1\", \"key2\": \"value2\" }";
final JsonObject actual = JsonObjectBuilder.from(jsonString,
s -> json.readValue(s, Map.class))
.build();
assertEquals("value1", actual.asString("key1").orElse(""));
assertEquals("value2", actual.asString("key2").orElse(""));
final JsonObject actual2 = JsonObject.fromJson(jsonString);
assertEquals("value1", actual2.asString("key1").orElse(""));
assertEquals("value2", actual2.asString("key2").orElse(""));
}
}
| |
package gavilcode.bot;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import static java.util.Objects.isNull;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.stream.Collectors.joining;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vdurmont.emoji.EmojiParser;
import static gavilcode.bot.Follower.pad;
import java.io.File;
import static java.util.Arrays.asList;
import java.util.HashSet;
public class Utils {
public final static String BOT_NAME = "gavilbot";
private static final Logger LOG = LoggerFactory.getLogger(Utils.class);
public static String encode(String s) {
try {
return URLEncoder.encode(s, UTF_8.displayName());
}
catch (UnsupportedEncodingException ex) {
LOG.error("", ex);
}
return s;
}
public static String toJson(Object o) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(o);
}
catch (JsonProcessingException ex) {
LOG.error("", ex);
return "{'error': true}";
}
}
public static String command(String s) {
if (s.startsWith("!") || s.startsWith("?") || s.startsWith("@")) {
return s;
}
else {
return "?" + s;
}
}
public static String findData(TwitchChatMessage e) {
return e.getMessage().replaceFirst("[^ ]+ *", "");
}
public static Consumer<TwitchChatMessage> consumeDataFn(Consumer<String> fn) {
return e -> fn.accept(findData(e));
}
public static Function<TwitchChatMessage, String> replyFromDataFn(Function<String, String> fn) {
return e -> fn.apply(findData(e));
}
public static String findCommand(String s) {
return s.replaceFirst("[, ]+.*$", "");
}
public static String findCommand(TwitchChatMessage m) {
return m.getMessage().replaceFirst("[, ]+.*$", "");
}
public static String getConfDir() {
return System.getProperty("user.home") + "/." + BOT_NAME + "/";
}
public static String getConf(String filename) {
return getConfDir() + "/" + filename;
}
public static String getChannelsRoot() {
return getConf("channels");
}
public static String getChannelDir(String channel) {
return getChannelsRoot() + "/" + channel + "/";
}
public static JsonObject jsonParse(String s) {
return Json.createReader(new StringReader(s)).readObject();
}
public static JsonObject jsonError(String s) {
return jsonParse("{\"error\": \"" + s + "\"}");
}
public static JsonObject jsonException(Throwable t) {
return jsonError(t.getMessage());
}
public static JsonObject twitchConnect(PropertyManager propertyManager, URL url) throws IOException {
URLConnection conn = url.openConnection();
conn.setRequestProperty("Accept", "application/vnd.twitchtv.v5+json");
conn.setRequestProperty("Client-ID", propertyManager.get("app-id"));
conn.connect();
JsonObject json;
try (JsonReader reader = Json.createReader(new BufferedReader(new InputStreamReader(conn.getInputStream(), UTF_8)))) {
json = reader.readObject();
}
return json;
}
public static TemporalAccessor trimTime(String dt) {
if (null == dt) {
return null;
}
else {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX");
return formatter.parse(dt.replaceFirst("\\.[0-9]+Z$", "Z"));
}
}
public static String simpleDateAndTime(TemporalAccessor ta) {
StringBuilder sb = new StringBuilder();
sb.append(ta.get(ChronoField.YEAR));
sb.append("-");
sb.append(ta.get(ChronoField.MONTH_OF_YEAR));
sb.append("-");
sb.append(ta.get(ChronoField.DAY_OF_MONTH));
sb.append(" ");
sb.append(pad(ta.get(ChronoField.HOUR_OF_DAY)));
sb.append(":");
sb.append(pad(ta.get(ChronoField.MINUTE_OF_HOUR)));
return sb.toString();
}
public static String simpleDate(TemporalAccessor ta) {
StringBuilder sb = new StringBuilder();
sb.append(ta.get(ChronoField.YEAR));
sb.append("-");
sb.append(ta.get(ChronoField.MONTH_OF_YEAR));
sb.append("-");
sb.append(ta.get(ChronoField.DAY_OF_MONTH));
return sb.toString();
}
public static String nowString() {
String s = LocalTime.now().truncatedTo(ChronoUnit.SECONDS).toString();
return (s.length() < 6) ? s + ":00" : s;
}
public static String e(String e) {
return isNull(e) ? "" : e;
}
public static String commaSep(Collection<String> c) {
return c.stream().collect(joining(", "));
}
public static void showThreads() {
Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
allStackTraces.keySet().stream()
.forEach(k -> {
System.out.println();
Arrays.stream(allStackTraces.get(k)).forEach(System.out::println);
});
}
public static Map<String, String> getTags(String line) {
Map<String, String> results = new HashMap<>();
if (line.startsWith("@")) {
String tags = line.substring(1, line.indexOf(" "));
for (String tag : tags.split(";")) {
if (tag.contains("=")) {
String[] parts = tag.split("=");
results.put(parts[0], (2 == parts.length ? parts[1] : ""));
}
else {
results.put(tag, "");
}
}
}
return results;
}
/*
* Tokenize IRC raw input into its components, keeping the 'sender' and
* 'message' fields intact.
*/
public static List<String> tokenizeLine(String line) {
List<String> fields = new ArrayList<>();
String trimmed = line.trim();
if (trimmed.isEmpty()) {
return fields;
}
int pos = 0;
int end = trimmed.indexOf(' ', pos);
while (end >= 0) {
fields.add(trimmed.substring(pos, end));
pos = end + 1;
if (':' == trimmed.charAt(pos)) {
fields.add(trimmed.substring(pos + 1));
return fields;
}
end = trimmed.indexOf(' ', pos);
}
// No more spaces, add last part of line
fields.add(trimmed.substring(pos));
return fields;
}
public static boolean isNullOrEmpty(String s) {
return (null == s) || s.isEmpty();
}
public static boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
}
catch (NumberFormatException e) {
return false;
}
}
public static String[] words(String message, String extraSeparators) {
return message.split("[" + extraSeparators + " ,!\\.]+");
}
public static String[] words(TwitchChatMessage cm) {
return words(cm.getMessage(), "");
}
public static String[] sentenceWords(String message) {
return words(message, "\\?");
}
public static String[] sentenceWords(TwitchChatMessage cm) {
return sentenceWords(cm.getMessage());
}
public static String emojiToText(TwitchChatMessage cm) {
String rawMessage = cm.getMessage();
return EmojiParser.parseToAliases(rawMessage).replaceAll("::", ": :");
}
public static void mkdir(String name) {
new File(name).mkdirs();
}
public static String removePrefix(String s) {
return s.replaceFirst("[@#:]", "");
}
public static String at(String name) {
if (isNullOrEmpty(name)) {
return "";
}
else {
if (name.startsWith("@")) {
return name;
}
else {
return "@" + name;
}
}
}
public static long getUnicode(int h, int l) {
return (h - 0xD800) * 0x400 + l - 0xDC00 + 0x10000;
}
public static boolean largelyAsciiOrEmoji(String message) {
int ok = 0;
var pending = false;
var pendingChar = ' ';
for (Character c : message.toCharArray()) {
if (pending) {
pending = false;
var code = getUnicode(pendingChar, c);
if ((0x1F18E <= code) && (code <= 0x1F9FF)) {
ok += 2;
}
else {
System.out.println("out of range unicode " + code + " " + Long.toHexString(code));
}
}
else if ((0xd83c == c) || (0xd83d == c) || (0xd83e == c)) {
pending = true;
pendingChar = c;
}
else if (c <= 127) {
++ok;
}
else if ((0x1CE4 <= c) && (c <= 0x1FEF)) {
++ok;
}
else if ((0x2600 <= c) && (c <= 0x26FF)) {
++ok;
}
else if ((0x2700 <= c) && (c <= 0x27BF)) {
++ok;
}
}
var result = ok >= (message.length() / 2);
if (!result) {
for (var c : message.toCharArray()) {
System.out.println(c + " " + (int) c + " " + Integer.toHexString(c));
}
}
return result;
}
public static boolean containsGreeting(TwitchChatMessage cm) {
var greetings = new HashSet<>(asList("goodnight", "cya", "bye", "hello", "hi", "hey", "heya", "hiya", "welcome", "yo"));
var fields = Utils.words(cm);
return Arrays.stream(fields)
.map(String::toLowerCase)
.anyMatch(greetings::contains);
}
}
| |
/*******************************************************************************
* Copyright 2015 MobileMan GmbH
* www.mobileman.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.
******************************************************************************/
/**
* PatientMedicationServiceTest.java
*
* Project: projecth
*
* @author mobileman
* @date 1.12.2010
* @version 1.0
*
* (c) 2010 MobileMan GmbH
*/
package com.mobileman.projecth.business.patient;
import static org.junit.Assert.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.mobileman.projecth.TestCaseBase;
import com.mobileman.projecth.business.DiseaseService;
import com.mobileman.projecth.business.MedicationService;
import com.mobileman.projecth.business.PatientMedicationService;
import com.mobileman.projecth.business.PatientService;
import com.mobileman.projecth.business.UserService;
import com.mobileman.projecth.domain.disease.Disease;
import com.mobileman.projecth.domain.medicine.Medication;
import com.mobileman.projecth.domain.patient.Patient;
import com.mobileman.projecth.domain.patient.medication.PatientMedication;
import com.mobileman.projecth.domain.util.medication.MedicationFrequency;
import com.mobileman.projecth.persistence.patient.PatientMedicationDao;
import com.mobileman.projecth.util.disease.DiseaseCodes;
/**
* @author mobileman
*
*/
public class PatientMedicationServiceTest extends TestCaseBase {
@Autowired
PatientMedicationService patientMedicationService;
@Autowired
PatientService patientService;
@Autowired
MedicationService medicationService;
@Autowired
PatientMedicationDao patientMedicationDao;
@Autowired
UserService userService;
@Autowired
private DiseaseService diseaseService;
/**
*
* @throws Exception
*/
@Test
public void addConsumedMedication() throws Exception {
int oldSize = patientMedicationDao.findAll().size();
Patient patient = (Patient)userService.findUserByLogin("sysuser1");
assertNotNull(patient);
Medication medication = medicationService.findByName("Kort 2", Locale.GERMANY).get(0);
assertNotNull(medication);
Disease disease = diseaseService.findByCode("M79.0");
assertNotNull(disease);
patientMedicationService.addConsumedMedication(patient.getId(), disease.getId(), medication.getId(), 2.0d, new Date(), null);
assertEquals(oldSize + 1, patientMedicationDao.findAll().size());
patientMedicationService.addConsumedMedication(patient.getId(), disease.getId(), medication.getId(), 2.0d, new Date(), "test");
assertEquals(oldSize + 2, patientMedicationDao.findAll().size());
List<Medication> result = patientMedicationService.findAllConsumedMedications(patient.getId(), disease.getId());
assertEquals(4, result.size());
assertFalse(result.get(0).equals(result.get(1)));
result = patientMedicationService.findAllConsumedMedications(patient.getId(), 0L);
assertEquals(0, result.size());
}
/**
*
* @throws Exception
*/
@Test
public void addConsumedMedicationWeekly() throws Exception {
int oldSize = patientMedicationDao.findAll().size();
Patient patient = (Patient)userService.findUserByLogin("sysuser1");
assertNotNull(patient);
Medication medication = medicationService.findByName("Kort 2", Locale.GERMANY).get(0);
Disease disease = diseaseService.findByCode(DiseaseCodes.RHEUMA_CODE);
assertNotNull(disease);
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date startDate = dateFormat.parse("1.11.2010");
Date endDate = dateFormat.parse("28.11.2010");
patientMedicationService.addConsumedMedication(
patient.getId(), disease.getId(), medication.getId(), 2.0d,
MedicationFrequency.WEEKLY,
startDate,
endDate, null);
assertEquals(oldSize + 4, patientMedicationDao.findAll().size());
}
/**
*
* @throws Exception
*/
@Test
public void addConsumedMedicationBiWeekly() throws Exception {
int oldSize = patientMedicationDao.findAll().size();
Patient patient = (Patient)userService.findUserByLogin("sysuser1");
assertNotNull(patient);
Medication medication = medicationService.findByName("Kort 2", Locale.GERMANY).get(0);
Disease disease = diseaseService.findByCode(DiseaseCodes.RHEUMA_CODE);
assertNotNull(disease);
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date startDate = dateFormat.parse("1.11.2010");
Date endDate = dateFormat.parse("28.11.2010");
patientMedicationService.addConsumedMedication(
patient.getId(), disease.getId(), medication.getId(), 2.0d,
MedicationFrequency.BI_WEEKLY,
startDate,
endDate, null);
assertEquals(oldSize + 2, patientMedicationDao.findAll().size());
}
/**
* @throws Exception
*/
@Test
public void findConsumedMedications() throws Exception {
Patient patient = (Patient)userService.findUserByLogin("sysuser1");
assertNotNull(patient);
Disease disease = diseaseService.findByCode("M79.0");
assertNotNull(disease);
List<Medication> result = patientMedicationService.findAllConsumedMedications(patient.getId(), disease.getId());
assertEquals(4, result.size());
Medication medication = result.get(0);
assertNotNull(medication);
}
/**
* @throws Exception
*/
@Test
public void findAllForDisease() throws Exception {
Patient patient = (Patient)userService.findUserByLogin("sysuser1");
assertNotNull(patient);
Disease disease = diseaseService.findByCode("M79.0");
assertNotNull(disease);
List<PatientMedication> result = patientMedicationService.findAllForDisease(patient.getId(), disease.getId());
assertEquals(6, result.size());
PatientMedication medication = result.get(0);
assertNotNull(medication);
}
/**
* {@link PatientMedicationService#findConsumedMedicationsDiary(Long, Long, java.util.Date, java.util.Date)}
* @throws Exception
*/
@Test
public void findPatientConsumedMedicationsDiary() throws Exception {
Patient patient = (Patient)userService.findUserByLogin("sysuser1");
assertNotNull(patient);
Disease disease = diseaseService.findByCode("M79.0");
assertNotNull(disease);
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date startDate = dateFormat.parse("1.11.2010");
Date endDate = dateFormat.parse("3.11.2010");
List<Object[]> result = patientMedicationService.findConsumedMedicationsDiary(patient.getId(), disease.getId(), startDate, endDate);
assertNotNull(result);
assertEquals(5, result.size());
assertEquals(2, Number.class.cast(result.get(2)[2]).intValue());
assertEquals(2, Number.class.cast(result.get(3)[2]).intValue());
for (Object[] row : result) {
assertTrue(Medication.class.isInstance(row[1]));
}
}
/**
* {@link PatientMedicationService#findConsumedMedicationsDiary(Long, java.util.Date, java.util.Date)}
* @throws Exception
*/
@Test
public void findPatientConsumedMedicationsDiary2() throws Exception {
Patient patient = (Patient)userService.findUserByLogin("sysuser1");
assertNotNull(patient);
Disease disease = diseaseService.findByCode("M79.0");
assertNotNull(disease);
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date startDate = dateFormat.parse("1.11.2010");
Date endDate = dateFormat.parse("3.11.2010");
List<Object[]> result = patientMedicationService.findConsumedMedicationsDiary(patient.getId(), startDate, endDate);
assertNotNull(result);
assertEquals(5, result.size());
assertEquals(2, Number.class.cast(result.get(2)[2]).intValue());
assertEquals(2, Number.class.cast(result.get(3)[2]).intValue());
for (Object[] row : result) {
assertTrue(Medication.class.isInstance(row[1]));
}
}
}
| |
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.configure.ui;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.synapse.SynapseConstants;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.emf.edit.command.SetCommand;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.wso2.developerstudio.eclipse.gmf.esb.CallTemplateParameter;
import org.wso2.developerstudio.eclipse.gmf.esb.CloudConnectorOperation;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;
import org.wso2.developerstudio.eclipse.gmf.esb.NamespacedProperty;
import org.wso2.developerstudio.eclipse.gmf.esb.RuleOptionType;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.Activator;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.EditorUtils;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.factory.ConnectionFileCreator;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.factory.LocalEntryFileCreator;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.utils.DiagramImageUtils;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;
//import org.wso2.developerstudio.eclipse.artifact.localentry.model.LocalEntryModel;
public class CloudConnectorInitialConfigurationDialog extends TitleAreaDialog {
private String droppedCloudConnector;
private String droppedCloudConnectorComponentName;
/**
* Value type constant.
*/
private static final String VALUE_TYPE = "Value";
/**
* Expression type constant.
*/
private static final String EXPRESSION_TYPE = "Expression";
/**
* Table for add/edit/remove parameters.
*/
private Table paramTable;
protected static final OMFactory fac = OMAbstractFactory.getOMFactory();
protected static final OMNamespace synNS = SynapseConstants.SYNAPSE_OMNAMESPACE;
private final String connectorProperties = "cloudConnector.properties";
private final String configNameSeparator = "::";
private final String configExistsErrorMessage = "Connector configuration already exists";
private final String emptyNameErrorMessage = "Configuration name cannot be empty";
private static String operationName = "init";
private CloudConnectorOperation operation;
private String cloudConnectorAuthenticationInfo;
private TableEditor paramTypeEditor;
private TableEditor paramNameEditor;
private TableEditor paramValueEditor;
private Combo cmbParamType;
private Text txtParamName;
private PropertyText paramValue;
private Text nameText;
private Label configurationNameLabel;
private String configName;
private Collection<String> parameters;
//private Label saveOptionLabel;
private Combo saveOptionCombo;
private List<String> availableConfigs;
private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID);
public CloudConnectorInitialConfigurationDialog(Shell parent,CloudConnectorOperation operation,Collection<String> parameters, String cloudConnectorAuthenticationInfo) {
super(parent);
this.parameters=parameters;
this.operation=operation;
this.cloudConnectorAuthenticationInfo = cloudConnectorAuthenticationInfo;
setTitleImage(DiagramImageUtils.getInstance().getImageDescriptor("connectorInit.png").createImage());
//parent.setText("Connector Configuration.");
}
public String getDroppedCloudConnectorComponentName() {
return droppedCloudConnectorComponentName;
}
public void setDroppedCloudConnectorComponentName(String droppedCloudConnectorComponentName) {
this.droppedCloudConnectorComponentName = droppedCloudConnectorComponentName;
}
private String getDroppedCloudConnector() {
return droppedCloudConnector;
}
public void setDroppedCloudConnector(String droppedCloudConnector) {
this.droppedCloudConnector = droppedCloudConnector;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite area = (Composite) super.createDialogArea(parent);
Composite container = new Composite(area, SWT.NONE);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
gridLayout.verticalSpacing = 20;
container.setLayout(gridLayout);
configurationNameLabel = new Label(container, SWT.NONE);
{
configurationNameLabel.setText("Name: ");
configurationNameLabel.setBounds(10, 10, 50, 25);
}
// Text box for add new parameter.
nameText = new Text(container, SWT.BORDER);
{
/*FormData logCategoryLabelLayoutData = new FormData(160,SWT.DEFAULT);
logCategoryLabelLayoutData.top = new FormAttachment(
configurationNameLabel, 0, SWT.CENTER);
logCategoryLabelLayoutData.left = new FormAttachment(
configurationNameLabel, 5);
nameText.setLayoutData(logCategoryLabelLayoutData);*/
nameText.setBounds(65, 10, 100, 25);
GridData gridDataNameText2 = new GridData();
gridDataNameText2.horizontalAlignment = SWT.FILL;
gridDataNameText2.grabExcessHorizontalSpace = true;
nameText.setLayoutData(gridDataNameText2);
}
nameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
configName=nameText.getText();
//CustomPaletteToolTransferDropTargetListener.definedName=nameText.getText();
if (StringUtils.isNotBlank(configName)) {
if (availableConfigs.contains(configName)) {
setErrorMessage(configExistsErrorMessage);
updateOKButtonStatus(false);
} else {
setErrorMessage(null);
updateOKButtonStatus(true);
}
} else {
setErrorMessage(emptyNameErrorMessage);
updateOKButtonStatus(false);
}
}
});
Link link = new Link(container, SWT.NONE);
if (cloudConnectorAuthenticationInfo != null && !cloudConnectorAuthenticationInfo.isEmpty()) {
link.setText("<a href=\"" + cloudConnectorAuthenticationInfo + "\">How to get Authentication info..</a>");
}
link.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
try {
// Open default external browser
PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL(e.text));
} catch (PartInitException | MalformedURLException ex) {
log.error("Error while opening URL : " + e.text, ex);
}
}
});
link.setSize(180, 10);
/* saveOptionLabel = new Label(container, SWT.NONE);
{
saveOptionLabel.setText("Save as : ");
FormData logCategoryLabelLayoutData1 = new FormData(80,SWT.DEFAULT);
logCategoryLabelLayoutData1.top = new FormAttachment(configurationNameLabel, 20);
logCategoryLabelLayoutData1.left = new FormAttachment(0);
saveOptionLabel.setLayoutData(logCategoryLabelLayoutData1);
}
saveOptionCombo = new Combo(container, SWT.DROP_DOWN | SWT.READ_ONLY);
{
saveOptionCombo.add("Inline Config");
saveOptionCombo.add("Sequence Config");
saveOptionCombo.select(0);
FormData logCategoryComboLayoutData = new FormData(160,SWT.DEFAULT);
logCategoryComboLayoutData.top = new FormAttachment(
saveOptionLabel, 0, SWT.CENTER);
logCategoryComboLayoutData.left = new FormAttachment(
saveOptionLabel, 5);
saveOptionCombo.setLayoutData(logCategoryComboLayoutData);
}*/
// Table for show the parameters.
paramTable = new Table(container, SWT.BORDER | SWT.FULL_SELECTION
| SWT.HIDE_SELECTION);
paramTable.setBounds(10, 50, 600, 200);
GridData gridData3 = new GridData();
gridData3.horizontalSpan = 3;
gridData3.horizontalAlignment = SWT.FILL;
gridData3.grabExcessHorizontalSpace = true;
gridData3.verticalAlignment = SWT.FILL;
gridData3.grabExcessVerticalSpace = true;
paramTable.setLayoutData(gridData3);
TableColumn nameColumn = new TableColumn(paramTable, SWT.LEFT);
TableColumn valueColumn = new TableColumn(paramTable, SWT.LEFT);
TableColumn typeColumn = new TableColumn(paramTable, SWT.LEFT);
nameColumn.setText("Parameter Name");
nameColumn.setWidth(200);
valueColumn.setText("Value/Expression");
valueColumn.setWidth(250);
typeColumn.setText("Parameter Type");
typeColumn.setWidth(150);
paramTable.setHeaderVisible(true);
paramTable.setLinesVisible(true);
Listener tblPropertiesListener = new Listener() {
public void handleEvent(Event evt) {
if (null != evt.item) {
if (evt.item instanceof TableItem) {
TableItem item = (TableItem) evt.item;
editItem(item);
}
}
}
};
paramTable.addListener(SWT.Selection, tblPropertiesListener);
if (parameters != null) {
for (String param : parameters) {
CallTemplateParameter callTemplateParameter=EsbFactory.eINSTANCE.createCallTemplateParameter();
callTemplateParameter.setParameterName(param);
callTemplateParameter.setParameterValue("");
callTemplateParameter.setTemplateParameterType(RuleOptionType.VALUE);
bindPram(callTemplateParameter);
}
}
//setupTableEditor(paramTable);
/*FormData logPropertiesTableLayoutData = new FormData(SWT.DEFAULT, 150);
logPropertiesTableLayoutData.top = new FormAttachment(configurationNameLabel, 20);
logPropertiesTableLayoutData.left = new FormAttachment(0);
logPropertiesTableLayoutData.bottom = new FormAttachment(100);
paramTable.setLayoutData(logPropertiesTableLayoutData);*/
availableConfigs = getAvailableConfigs();
return parent;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("Connector Configuration");
}
@Override
public void create() {
super.create();
setTitle("Enter authentication details");
setMessage("Please provide required parameters to authenticate user", IMessageProvider.INFORMATION);
}
/**
* Return the initial size of the dialog.
*/
@Override
protected Point getInitialSize() {
return new Point(630, 400);
}
private TableItem bindPram(CallTemplateParameter param) {
TableItem item = new TableItem(paramTable, SWT.NONE);
if (param.getTemplateParameterType().getLiteral().equals(VALUE_TYPE)) {
item.setText(new String[] { param.getParameterName(),
param.getParameterValue(),
param.getTemplateParameterType().getLiteral() });
}
if (param.getTemplateParameterType().getLiteral()
.equals(EXPRESSION_TYPE)) {
item.setText(new String[] { param.getParameterName(),
param.getParameterExpression().getPropertyValue(),
param.getTemplateParameterType().getLiteral()});
}
item.setData(param);
item.setData("exp", EsbFactory.eINSTANCE.copyNamespacedProperty(param.getParameterExpression()));
return item;
}
private TableEditor initTableEditor(TableEditor editor, Table table) {
if (null != editor) {
Control lastCtrl = editor.getEditor();
if (null != lastCtrl) {
lastCtrl.dispose();
}
}
editor = new TableEditor(table);
editor.horizontalAlignment = SWT.LEFT;
editor.grabHorizontal = true;
return editor;
}
private void editItem(final TableItem item) {
NamespacedProperty expression = (NamespacedProperty)item.getData("exp");
paramNameEditor = initTableEditor(paramNameEditor, item.getParent());
txtParamName = new Text(item.getParent(), SWT.NONE);
txtParamName.setText(item.getText(0));
paramNameEditor.setEditor(txtParamName, item, 0);
txtParamName.setEditable(false);
item.getParent().redraw();
item.getParent().layout();
txtParamName.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
item.setText(0,txtParamName.getText());
}
});
paramTypeEditor = initTableEditor(paramTypeEditor,
item.getParent());
cmbParamType = new Combo(item.getParent(), SWT.READ_ONLY);
cmbParamType.setItems(new String[] { VALUE_TYPE, EXPRESSION_TYPE });
cmbParamType.setText(item.getText(2));
paramTypeEditor.setEditor(cmbParamType, item, 2);
item.getParent().redraw();
item.getParent().layout();
cmbParamType.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event evt) {
item.setText(2, cmbParamType.getText());
}
});
paramValueEditor = initTableEditor(paramValueEditor,
item.getParent());
paramValue = new PropertyText(item.getParent(), SWT.NONE, cmbParamType);
paramValue.addProperties(item.getText(1),expression);
paramValueEditor.setEditor(paramValue, item, 1);
item.getParent().redraw();
item.getParent().layout();
paramValue.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
item.setText(1,paramValue.getText());
Object property = paramValue.getProperty();
if(property instanceof NamespacedProperty){
item.setData("exp",(NamespacedProperty)property);
}
}
});
}
private void serializeParams(OMElement invokeElem) {
OMElement connectorEl = fac.createOMElement(getDroppedCloudConnectorComponentName()+"."+operationName,synNS);
for(int i=0;i<paramTable.getItems().length;++i){
TableItem tableItem=paramTable.getItems()[i];
CallTemplateParameter callTemplateParameter=(CallTemplateParameter) tableItem.getData();
if (!"".equals(callTemplateParameter.getParameterName())) {
OMElement paramEl = fac.createOMElement(callTemplateParameter.getParameterName(),
synNS);
paramEl.setText(tableItem.getText(1));
// new ValueSerializer().serializeValue(value, "value", paramEl);
connectorEl.addChild(paramEl);
}
}
invokeElem.addChild(connectorEl);
}
/**
* Create contents of the button bar.
*
* @param parent
*/
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
true);
createButton(parent, IDialogConstants.CANCEL_ID,
IDialogConstants.CANCEL_LABEL, false);
updateOKButtonStatus(false);
}
private void updateOKButtonStatus(boolean status) {
getButton(IDialogConstants.OK_ID).setEnabled(status);
}
@Override
protected void okPressed() {
IProject activeProject = EditorUtils.getActiveProject();
boolean isIntegrationProject = false;
try {
if(Arrays.asList(activeProject.getDescription().getNatureIds()).contains("org.wso2.developerstudio.eclipse.integration.project.nature")){
isIntegrationProject = true;
}
} catch (CoreException e) {
log.error("Error occured when getting project nature", e);
}
if(isIntegrationProject){
IContainer location = activeProject.getFolder("src" + File.separator + "main"
+ File.separator + "integration-config" + File.separator
+ "connections");
try {
ConnectionFileCreator connectionFileCreator = new ConnectionFileCreator();
String content="<?xml version=\"1.0\" encoding=\"UTF-8\"?><localEntry xmlns=\"http://ws.apache.org/ns/synapse\" key=\""+configName+"\"/>";
OMElement payload = AXIOMUtil.stringToOM(content);
serializeParams(payload);
connectionFileCreator.createConnectionFile(payload.toString(), location, configName);
} catch (Exception e) {
log.error("Error occured while creating the connection file", e);
}
}else{
IContainer location = activeProject.getFolder("src" + File.separator + "main"
+ File.separator + "synapse-config" + File.separator
+ "local-entries");
try {
LocalEntryFileCreator localEntryFileCreator = new LocalEntryFileCreator();
String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><localEntry xmlns=\"http://ws.apache.org/ns/synapse\" key=\""
+ configName + "\"/>";
OMElement payload = AXIOMUtil.stringToOM(content);
serializeParams(payload);
localEntryFileCreator.createLocalEntryFile(payload.toString(), location, configName);
} catch (Exception e) {
log.error("Error occured while creating the Local entry file", e);
}
}
/**
* put a entry in cloudConnector.properties file
*/
String pathName=activeProject.getLocation().toOSString()+File.separator+"resources";
File resources=new File(pathName);
try {
resources.mkdir();
File cloudConnectorConfig = new File(pathName + File.separator + connectorProperties);
cloudConnectorConfig.createNewFile();
Properties prop = new Properties();
prop.load(new FileInputStream(pathName + File.separator + connectorProperties));
String localEntryConfigs = prop.getProperty("LOCAL_ENTRY_CONFIGS");
if (localEntryConfigs == null || "".equals(localEntryConfigs)) {
prop.setProperty("LOCAL_ENTRY_CONFIGS", configName + configNameSeparator
+ getDroppedCloudConnector());
} else {
prop.setProperty("LOCAL_ENTRY_CONFIGS", localEntryConfigs + "," + configName
+ configNameSeparator + getDroppedCloudConnector());
}
prop.setProperty("INLINE_CONFIGS", "");
prop.store(new FileOutputStream(cloudConnectorConfig.getAbsolutePath()), null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* Display.getCurrent().asyncExec(new Runnable() {
public void run() {
IEditorReference editorReferences[] = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getEditorReferences();
IEditorPart activeEditor=PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getActiveEditor();
for (int i = 0; i < editorReferences.length; i++) {
IEditorPart editor = editorReferences[i].getEditor(false);
if ((editor instanceof EsbMultiPageEditor)) {
* This must be altered. 'addDefinedSequences' and 'addDefinedEndpoints' methods should not exist inside EsbPaletteFactory class.
* Creating new instance of 'EsbPaletteFactory' must be avoided.
EsbPaletteFactory esbPaletteFactory=new EsbPaletteFactory();
if(!editor.equals(activeEditor)){
//esbPaletteFactory.addDefinedSequences(((EsbMultiPageEditor) editor).getGraphicalEditor());
//esbPaletteFactory.addDefinedEndpoints(((EsbMultiPageEditor) editor).getGraphicalEditor());
}else{
//esbPaletteFactory.addCloudConnectorOperations(((EsbMultiPageEditor) editor).getGraphicalEditor(),configName,getDroppedCloudConnector());
}
}
}
}
});*/
SetCommand setCmd = new SetCommand(TransactionUtil.getEditingDomain(operation), operation,
EsbPackage.Literals.CLOUD_CONNECTOR_OPERATION__CONFIG_REF,
configName);
if(setCmd.canExecute()){
TransactionUtil.getEditingDomain(operation).getCommandStack().execute(setCmd);
}
super.okPressed();
}
/**
* Get available configurations for the given connector.
* @return available configurations
*/
private ArrayList<String> getAvailableConfigs() {
ArrayList<String> availableConfigs = new ArrayList<String>();
String pathName = EditorUtils.getActiveProject().getLocation().toOSString()+File.separator+"resources";
File resources = new File(pathName);
if (resources.exists()) {
File connectorConfig = new File(pathName + File.separator + connectorProperties);
if (connectorConfig.exists()) {
Properties prop = new Properties();
try {
prop.load(new FileInputStream(pathName + File.separator + connectorProperties));
String localEntryConfigs = prop.getProperty("LOCAL_ENTRY_CONFIGS");
if (localEntryConfigs != null) {
String[] configs = localEntryConfigs.split(",");
for (int i = 0; i < configs.length; ++i) {
if (!"".equals(configs[i])) {
availableConfigs.add(configs[i].split(configNameSeparator)[0]);
}
}
}
} catch (FileNotFoundException e) {
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
}
}
}
return availableConfigs;
}
}
| |
/**
* 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.falcon.regression;
import org.apache.falcon.regression.Entities.FeedMerlin;
import org.apache.falcon.regression.core.bundle.Bundle;
import org.apache.falcon.entity.v0.feed.ActionType;
import org.apache.falcon.entity.v0.feed.ClusterType;
import org.apache.falcon.regression.core.helpers.ColoHelper;
import org.apache.falcon.regression.core.response.ServiceResponse;
import org.apache.falcon.regression.core.util.AssertUtil;
import org.apache.falcon.regression.core.util.BundleUtil;
import org.apache.falcon.regression.core.util.HadoopUtil;
import org.apache.falcon.regression.core.util.OSUtil;
import org.apache.falcon.regression.core.util.OozieUtil;
import org.apache.falcon.regression.core.util.TimeUtil;
import org.apache.falcon.regression.core.util.Util;
import org.apache.falcon.regression.core.util.XmlUtil;
import org.apache.falcon.regression.testHelper.BaseTestClass;
import org.apache.hadoop.fs.FileSystem;
import org.apache.log4j.Logger;
import org.apache.oozie.client.OozieClient;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Feed cluster update tests.
*/
@Test(groups = "distributed")
public class FeedClusterUpdateTest extends BaseTestClass {
private String baseTestDir = cleanAndGetTestDir();
private String aggregateWorkflowDir = baseTestDir + "/aggregator";
private ColoHelper cluster1 = servers.get(0);
private ColoHelper cluster2 = servers.get(1);
private ColoHelper cluster3 = servers.get(2);
private OozieClient cluster1OC = serverOC.get(0);
private OozieClient cluster2OC = serverOC.get(1);
private OozieClient cluster3OC = serverOC.get(2);
private FileSystem cluster2FS = serverFS.get(1);
private FileSystem cluster3FS = serverFS.get(2);
private String feed;
private String feedName;
private String startTime;
private String feedOriginalSubmit;
private String feedUpdated;
private String cluster1Name;
private String cluster2Name;
private String cluster3Name;
private static final Logger LOGGER = Logger.getLogger(FeedClusterUpdateTest.class);
@BeforeClass(alwaysRun = true)
public void createTestData() throws Exception {
uploadDirToClusters(aggregateWorkflowDir, OSUtil.RESOURCES_OOZIE);
Bundle bundle = BundleUtil.readELBundle();
for (int i = 0; i < 3; i++) {
bundles[i] = new Bundle(bundle, servers.get(i));
bundles[i].generateUniqueBundle(this);
bundles[i].setProcessWorkflow(aggregateWorkflowDir);
}
try {
String postFix = "/US/" + servers.get(1).getClusterHelper().getColoName();
HadoopUtil.deleteDirIfExists(baseTestDir, cluster2FS);
HadoopUtil.lateDataReplenish(cluster2FS, 80, 1, baseTestDir, postFix);
postFix = "/UK/" + servers.get(2).getClusterHelper().getColoName();
HadoopUtil.deleteDirIfExists(baseTestDir, cluster3FS);
HadoopUtil.lateDataReplenish(cluster3FS, 80, 1, baseTestDir, postFix);
} finally {
removeTestClassEntities();
}
}
@BeforeMethod(alwaysRun = true)
public void setup() throws Exception {
Bundle bundle = BundleUtil.readELBundle();
for (int i = 0; i < 3; i++) {
bundles[i] = new Bundle(bundle, servers.get(i));
bundles[i].generateUniqueBundle(this);
bundles[i].setProcessWorkflow(aggregateWorkflowDir);
}
BundleUtil.submitAllClusters(prism, bundles[0], bundles[1], bundles[2]);
feed = bundles[0].getDataSets().get(0);
feed = FeedMerlin.fromString(feed).clearFeedClusters().toString();
startTime = TimeUtil.getTimeWrtSystemTime(-50);
feedName = Util.readEntityName(feed);
cluster1Name = Util.readEntityName(bundles[0].getClusters().get(0));
cluster2Name = Util.readEntityName(bundles[1].getClusters().get(0));
cluster3Name = Util.readEntityName(bundles[2].getClusters().get(0));
}
@AfterMethod(alwaysRun = true)
public void tearDown() {
removeTestClassEntities();
}
@Test(enabled = true, groups = {"multiCluster"})
public void addSourceCluster() throws Exception {
//add one source and one target , schedule only on source
feedOriginalSubmit = FeedMerlin.fromString(feed)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.build())
.toString();
feedOriginalSubmit = FeedMerlin.fromString(feedOriginalSubmit).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster1Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 20),
TimeUtil.addMinsToTime(startTime, 85))
.withClusterType(ClusterType.TARGET)
.build())
.toString();
LOGGER.info("Feed: " + Util.prettyPrintXml(feedOriginalSubmit));
ServiceResponse response = prism.getFeedHelper().submitEntity(feedOriginalSubmit);
TimeUtil.sleepSeconds(10);
AssertUtil.assertSucceeded(response);
//schedule on source
response = cluster2.getFeedHelper().schedule(feedOriginalSubmit);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 0);
//prepare updated Feed
feedUpdated = FeedMerlin.fromString(feed)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.withPartition("UK/${cluster.colo}")
.build())
.toString();
feedUpdated = FeedMerlin.fromString(feedUpdated).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster1Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 20),
TimeUtil.addMinsToTime(startTime, 85))
.withClusterType(ClusterType.TARGET)
.build())
.toString();
feedUpdated = FeedMerlin.fromString(feedUpdated).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster3Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 40),
TimeUtil.addMinsToTime(startTime, 110))
.withClusterType(ClusterType.SOURCE)
.withPartition("UK/${cluster.colo}")
.build())
.toString();
response = prism.getFeedHelper().update(feedUpdated, feedUpdated);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
prism.getFeedHelper().submitAndSchedule(feedUpdated);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 2);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 2);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 1);
}
@Test(enabled = true, groups = {"multiCluster"})
public void addTargetCluster() throws Exception {
//add one source and one target , schedule only on source
feedOriginalSubmit = FeedMerlin.fromString(feed)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.build())
.toString();
feedOriginalSubmit = FeedMerlin.fromString(feedOriginalSubmit).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster3Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 40),
TimeUtil.addMinsToTime(startTime, 110))
.withClusterType(ClusterType.SOURCE)
.withPartition("UK/${cluster.colo}")
.build())
.toString();
LOGGER.info("Feed: " + Util.prettyPrintXml(feedOriginalSubmit));
ServiceResponse response = prism.getFeedHelper().submitEntity(feedOriginalSubmit);
TimeUtil.sleepSeconds(10);
AssertUtil.assertSucceeded(response);
//schedule on source
response = cluster2.getFeedHelper().schedule(feedOriginalSubmit);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 0);
//prepare updated Feed
feedUpdated = FeedMerlin.fromString(feed)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.withPartition("US/${cluster.colo}")
.build())
.toString();
feedUpdated = FeedMerlin.fromString(feedUpdated).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster1Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 20),
TimeUtil.addMinsToTime(startTime, 85))
.withClusterType(ClusterType.TARGET)
.build())
.toString();
feedUpdated = FeedMerlin.fromString(feedUpdated).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster3Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 40),
TimeUtil.addMinsToTime(startTime, 110))
.withClusterType(ClusterType.SOURCE)
.withPartition("UK/${cluster.colo}")
.build())
.toString();
LOGGER.info("Updated Feed: " + Util.prettyPrintXml(feedUpdated));
response = prism.getFeedHelper().update(feedUpdated, feedUpdated);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
prism.getFeedHelper().submitAndSchedule(feedUpdated);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 2);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 2);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 1);
}
@Test(enabled = true, groups = {"multiCluster"})
public void add2SourceCluster() throws Exception {
//add one source , schedule only on source
feedOriginalSubmit = FeedMerlin.fromString(feed)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.build())
.toString();
LOGGER.info("Feed: " + Util.prettyPrintXml(feedOriginalSubmit));
ServiceResponse response = prism.getFeedHelper().submitEntity(feedOriginalSubmit);
TimeUtil.sleepSeconds(10);
AssertUtil.assertSucceeded(response);
//schedule on source
response = cluster2.getFeedHelper().schedule(feedOriginalSubmit);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 0);
//prepare updated Feed
feedUpdated = FeedMerlin.fromString(feed)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.withPartition("US/${cluster.colo}")
.build())
.toString();
feedUpdated = FeedMerlin.fromString(feedUpdated).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster1Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 20),
TimeUtil.addMinsToTime(startTime, 85))
.withClusterType(ClusterType.SOURCE)
.build())
.toString();
feedUpdated = FeedMerlin.fromString(feedUpdated).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster3Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 40),
TimeUtil.addMinsToTime(startTime, 110))
.withClusterType(ClusterType.SOURCE)
.withPartition("UK/${cluster.colo}")
.build())
.toString();
LOGGER.info("Updated Feed: " + Util.prettyPrintXml(feedUpdated));
response = prism.getFeedHelper().update(feedUpdated, feedUpdated);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
prism.getFeedHelper().submitAndSchedule(feedUpdated);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 2);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 1);
}
@Test(enabled = true, groups = {"multiCluster"})
public void add2TargetCluster() throws Exception {
//add one source and one target , schedule only on source
feedOriginalSubmit = FeedMerlin.fromString(feed)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.build())
.toString();
LOGGER.info("Feed: " + Util.prettyPrintXml(feedOriginalSubmit));
ServiceResponse response = prism.getFeedHelper().submitEntity(feedOriginalSubmit);
TimeUtil.sleepSeconds(10);
AssertUtil.assertSucceeded(response);
//schedule on source
response = cluster2.getFeedHelper().schedule(feedOriginalSubmit);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 0);
//prepare updated Feed
feedUpdated = FeedMerlin.fromString(feed)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.build())
.toString();
feedUpdated = FeedMerlin.fromString(feedUpdated).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster1Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 20),
TimeUtil.addMinsToTime(startTime, 85))
.withClusterType(ClusterType.TARGET)
.build())
.toString();
feedUpdated = FeedMerlin.fromString(feedUpdated).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster3Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 40),
TimeUtil.addMinsToTime(startTime, 110))
.withClusterType(ClusterType.TARGET)
.build())
.toString();
LOGGER.info("Updated Feed: " + Util.prettyPrintXml(feedUpdated));
response = prism.getFeedHelper().update(feedUpdated, feedUpdated);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
prism.getFeedHelper().submitAndSchedule(feedUpdated);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 1);
}
@Test(enabled = true, groups = {"multiCluster"})
public void add1Source1TargetCluster() throws Exception {
//add one source and one target , schedule only on source
feedOriginalSubmit = FeedMerlin.fromString(feed)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.build())
.toString();
LOGGER.info("Feed: " + Util.prettyPrintXml(feedOriginalSubmit));
ServiceResponse response = prism.getFeedHelper().submitEntity(feedOriginalSubmit);
TimeUtil.sleepSeconds(10);
AssertUtil.assertSucceeded(response);
//schedule on source
response = cluster2.getFeedHelper().schedule(feedOriginalSubmit);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 0);
//prepare updated Feed
feedUpdated = FeedMerlin.fromString(feed)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.withPartition("US/${cluster.colo}")
.build())
.toString();
feedUpdated = FeedMerlin.fromString(feedUpdated).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster1Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 20),
TimeUtil.addMinsToTime(startTime, 85))
.withClusterType(ClusterType.TARGET)
.build())
.toString();
feedUpdated = FeedMerlin.fromString(feedUpdated).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster3Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 40),
TimeUtil.addMinsToTime(startTime, 110))
.withClusterType(ClusterType.SOURCE)
.withPartition("UK/${cluster.colo}")
.build())
.toString();
LOGGER.info("Updated Feed: " + Util.prettyPrintXml(feedUpdated));
response = prism.getFeedHelper().update(feedUpdated, feedUpdated);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
prism.getFeedHelper().submitAndSchedule(feedUpdated);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 2);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 2);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 1);
}
@Test(enabled = true, groups = {"multiCluster"})
public void deleteSourceCluster() throws Exception {
//add one source and one target , schedule only on source
feedOriginalSubmit = FeedMerlin.fromString(feed)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.withPartition("US/${cluster.colo}")
.build())
.toString();
feedOriginalSubmit = FeedMerlin.fromString(feedOriginalSubmit).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster1Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 20),
TimeUtil.addMinsToTime(startTime, 85))
.withClusterType(ClusterType.TARGET)
.build())
.toString();
feedOriginalSubmit = FeedMerlin.fromString(feedOriginalSubmit).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster3Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 40),
TimeUtil.addMinsToTime(startTime, 110))
.withClusterType(ClusterType.SOURCE)
.withPartition("UK/${cluster.colo}")
.build())
.toString();
LOGGER.info("Feed: " + Util.prettyPrintXml(feedOriginalSubmit));
ServiceResponse response = prism.getFeedHelper().submitEntity(feedOriginalSubmit);
TimeUtil.sleepSeconds(10);
AssertUtil.assertSucceeded(response);
//schedule on source
response = prism.getFeedHelper().schedule(feedOriginalSubmit);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 2);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 1);
//prepare updated Feed
feedUpdated = FeedMerlin.fromString(feed)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.build())
.toString();
feedUpdated = FeedMerlin.fromString(feedUpdated).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster1Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 20),
TimeUtil.addMinsToTime(startTime, 85))
.withClusterType(ClusterType.TARGET)
.build())
.toString();
response = prism.getFeedHelper().update(feedUpdated, feedUpdated);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
response = cluster3.getFeedHelper().getEntityDefinition(feedUpdated);
AssertUtil.assertFailed(response);
prism.getFeedHelper().submitAndSchedule(feedUpdated);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 2);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 3);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 2);
}
@Test(enabled = true, groups = {"multiCluster"})
public void deleteTargetCluster() throws Exception {
/*
this test creates a multiCluster feed. Cluster1 is the target cluster
and cluster3 and Cluster2 are the source cluster.
feed is submitted through prism so submitted to both target and
source. Feed is scheduled through prism, so only on Cluster3 and
Cluster2 retention coord should exists. Cluster1 one which
is target both retention and replication coord should exists. there
will be 2 replication coord, one each for each source cluster.
then we update feed by deleting cluster1 and cluster2 from the feed
xml and send update request.
Once update is over. definition should go missing from cluster1 and
cluster2 and prism and cluster3 should have new def
there should be a new retention coord on cluster3 and old number of
coord on cluster1 and cluster2
*/
//add two source and one target
feedOriginalSubmit = FeedMerlin.fromString(feed).clearFeedClusters().toString();
feedOriginalSubmit = FeedMerlin.fromString(feedOriginalSubmit)
.addFeedCluster(new FeedMerlin.FeedClusterBuilder(cluster2Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(startTime, TimeUtil.addMinsToTime(startTime, 65))
.withClusterType(ClusterType.SOURCE)
.withPartition("US/${cluster.colo}")
.build())
.toString();
feedOriginalSubmit = FeedMerlin.fromString(feedOriginalSubmit).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster1Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 20),
TimeUtil.addMinsToTime(startTime, 85))
.withClusterType(ClusterType.TARGET)
.build())
.toString();
feedOriginalSubmit = FeedMerlin.fromString(feedOriginalSubmit).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster3Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 40),
TimeUtil.addMinsToTime(startTime, 110))
.withClusterType(ClusterType.SOURCE)
.withPartition("UK/${cluster.colo}")
.build())
.toString();
LOGGER.info("Feed: " + Util.prettyPrintXml(feedOriginalSubmit));
ServiceResponse response = prism.getFeedHelper().submitEntity(feedOriginalSubmit);
TimeUtil.sleepSeconds(10);
AssertUtil.assertSucceeded(response);
//schedule on source
response = prism.getFeedHelper().schedule(feedOriginalSubmit);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 2);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 1);
//prepare updated Feed
feedUpdated = FeedMerlin.fromString(feed).clearFeedClusters().toString();
feedUpdated = FeedMerlin.fromString(feedUpdated).addFeedCluster(
new FeedMerlin.FeedClusterBuilder(cluster3Name)
.withRetention("hours(10)", ActionType.DELETE)
.withValidity(TimeUtil.addMinsToTime(startTime, 40),
TimeUtil.addMinsToTime(startTime, 110))
.withClusterType(ClusterType.SOURCE)
.withPartition("UK/${cluster.colo}")
.build())
.toString();
LOGGER.info("Feed: " + Util.prettyPrintXml(feedUpdated));
response = prism.getFeedHelper().update(feedUpdated, feedUpdated);
TimeUtil.sleepSeconds(20);
AssertUtil.assertSucceeded(response);
//verify xmls definitions
response = cluster1.getFeedHelper().getEntityDefinition(feedUpdated);
AssertUtil.assertFailed(response);
response = cluster2.getFeedHelper().getEntityDefinition(feedUpdated);
AssertUtil.assertFailed(response);
response = cluster3.getFeedHelper().getEntityDefinition(feedUpdated);
Assert.assertTrue(XmlUtil.isIdentical(feedUpdated, response.getMessage()));
response = prism.getFeedHelper().getEntityDefinition(feedUpdated);
Assert.assertTrue(XmlUtil.isIdentical(feedUpdated, response.getMessage()));
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "REPLICATION"), 0);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feedName, "RETENTION"), 1);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "REPLICATION"), 2);
Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feedName, "RETENTION"), 1);
}
/*
@Test(enabled = false)
public void delete2SourceCluster() {
}
@Test(enabled = false)
public void delete2TargetCluster() {
}
@Test(enabled = false)
public void delete1Source1TargetCluster() {
}
*/
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.audit;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.cql3.CQLStatement;
import org.apache.cassandra.cql3.QueryHandler;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.statements.BatchStatement;
import org.apache.cassandra.exceptions.AuthenticationException;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.UnauthorizedException;
import org.apache.cassandra.schema.SchemaConstants;
import org.apache.cassandra.service.QueryState;
import org.apache.cassandra.utils.FBUtilities;
/**
* Central location for managing the logging of client/user-initated actions (like queries, log in commands, and so on).
*
* We can run multiple {@link IAuditLogger}s at the same time, including the standard audit logger ({@link #auditLogger}
* and the full query logger ({@link #fullQueryLogger}.
*/
public class AuditLogManager
{
private static final Logger logger = LoggerFactory.getLogger(AuditLogManager.class);
private static final AuditLogManager instance = new AuditLogManager();
// FQL always writes to a BinLog, but it is a type of IAuditLogger
private final FullQueryLogger fullQueryLogger;
private final ImmutableSet<AuditLogEntryCategory> fqlIncludeFilter = ImmutableSet.of(AuditLogEntryCategory.OTHER,
AuditLogEntryCategory.QUERY,
AuditLogEntryCategory.DCL,
AuditLogEntryCategory.DML,
AuditLogEntryCategory.DDL);
// auditLogger can write anywhere, as it's pluggable (logback, BinLog, DiagnosticEvents, etc ...)
private volatile IAuditLogger auditLogger;
private volatile AuditLogFilter filter;
private volatile boolean isAuditLogEnabled;
private AuditLogManager()
{
fullQueryLogger = new FullQueryLogger();
if (DatabaseDescriptor.getAuditLoggingOptions().enabled)
{
logger.info("Audit logging is enabled.");
auditLogger = getAuditLogger(DatabaseDescriptor.getAuditLoggingOptions().logger);
isAuditLogEnabled = true;
}
else
{
logger.debug("Audit logging is disabled.");
isAuditLogEnabled = false;
auditLogger = new NoOpAuditLogger();
}
filter = AuditLogFilter.create(DatabaseDescriptor.getAuditLoggingOptions());
}
public static AuditLogManager getInstance()
{
return instance;
}
private IAuditLogger getAuditLogger(String loggerClassName) throws ConfigurationException
{
if (loggerClassName != null)
{
return FBUtilities.newAuditLogger(loggerClassName);
}
return FBUtilities.newAuditLogger(BinAuditLogger.class.getName());
}
@VisibleForTesting
public IAuditLogger getLogger()
{
return auditLogger;
}
public boolean isAuditingEnabled()
{
return isAuditLogEnabled;
}
public boolean isLoggingEnabled()
{
return isAuditingEnabled() || isFQLEnabled();
}
private boolean isFQLEnabled()
{
return fullQueryLogger.enabled();
}
private boolean isSystemKeyspace(String keyspaceName)
{
return SchemaConstants.isLocalSystemKeyspace(keyspaceName);
}
/**
* Logs AuditLogEntry to standard audit logger
* @param logEntry AuditLogEntry to be logged
*/
private void logAuditLoggerEntry(AuditLogEntry logEntry)
{
if ((logEntry.getKeyspace() == null || !isSystemKeyspace(logEntry.getKeyspace()))
&& !filter.isFiltered(logEntry))
{
auditLogger.log(logEntry);
}
}
/**
* Logs AudigLogEntry to both FQL and standard audit logger
* @param logEntry AuditLogEntry to be logged
*/
public void log(AuditLogEntry logEntry)
{
if (logEntry == null)
return;
if (isAuditingEnabled())
{
logAuditLoggerEntry(logEntry);
}
if (isFQLEnabled() && fqlIncludeFilter.contains(logEntry.getType().getCategory()))
{
fullQueryLogger.log(logEntry);
}
}
public void log(AuditLogEntry logEntry, Exception e)
{
if ((logEntry != null) && (isAuditingEnabled()))
{
AuditLogEntry.Builder builder = new AuditLogEntry.Builder(logEntry);
if (e instanceof UnauthorizedException)
{
builder.setType(AuditLogEntryType.UNAUTHORIZED_ATTEMPT);
}
else if (e instanceof AuthenticationException)
{
builder.setType(AuditLogEntryType.LOGIN_ERROR);
}
else
{
builder.setType(AuditLogEntryType.REQUEST_FAILURE);
}
builder.appendToOperation(e.getMessage());
log(builder.build());
}
}
/**
* Logs Batch queries to both FQL and standard audit logger.
*/
public void logBatch(BatchStatement.Type type,
List<Object> queryOrIdList,
List<List<ByteBuffer>> values,
List<QueryHandler.Prepared> prepared,
QueryOptions options,
QueryState state,
long queryStartTimeMillis)
{
if (isAuditingEnabled())
{
List<AuditLogEntry> entries = buildEntriesForBatch(queryOrIdList, prepared, state, options, queryStartTimeMillis);
for (AuditLogEntry auditLogEntry : entries)
{
logAuditLoggerEntry(auditLogEntry);
}
}
if (isFQLEnabled())
{
List<String> queryStrings = new ArrayList<>(queryOrIdList.size());
for (QueryHandler.Prepared prepStatment : prepared)
{
queryStrings.add(prepStatment.rawCQLStatement);
}
fullQueryLogger.logBatch(type, queryStrings, values, options, state, queryStartTimeMillis);
}
}
private static List<AuditLogEntry> buildEntriesForBatch(List<Object> queryOrIdList, List<QueryHandler.Prepared> prepared, QueryState state, QueryOptions options, long queryStartTimeMillis)
{
List<AuditLogEntry> auditLogEntries = new ArrayList<>(queryOrIdList.size() + 1);
UUID batchId = UUID.randomUUID();
String queryString = String.format("BatchId:[%s] - BATCH of [%d] statements", batchId, queryOrIdList.size());
AuditLogEntry entry = new AuditLogEntry.Builder(state)
.setOperation(queryString)
.setOptions(options)
.setTimestamp(queryStartTimeMillis)
.setBatch(batchId)
.setType(AuditLogEntryType.BATCH)
.build();
auditLogEntries.add(entry);
for (int i = 0; i < queryOrIdList.size(); i++)
{
CQLStatement statement = prepared.get(i).statement;
entry = new AuditLogEntry.Builder(state)
.setType(statement.getAuditLogContext().auditLogEntryType)
.setOperation(prepared.get(i).rawCQLStatement)
.setTimestamp(queryStartTimeMillis)
.setScope(statement)
.setKeyspace(state, statement)
.setOptions(options)
.setBatch(batchId)
.build();
auditLogEntries.add(entry);
}
return auditLogEntries;
}
/**
* Disables AuditLog, designed to be invoked only via JMX/ Nodetool, not from anywhere else in the codepath.
*/
public synchronized void disableAuditLog()
{
if (isAuditLogEnabled)
{
// Disable isAuditLogEnabled before attempting to cleanup/ stop AuditLogger so that any incoming log() requests will be dropped.
isAuditLogEnabled = false;
IAuditLogger oldLogger = auditLogger;
auditLogger = new NoOpAuditLogger();
oldLogger.stop();
}
}
/**
* Enables AuditLog, designed to be invoked only via JMX/ Nodetool, not from anywhere else in the codepath.
* @param auditLogOptions AuditLogOptions to be used for enabling AuditLog
* @throws ConfigurationException It can throw configuration exception when provided logger class does not exist in the classpath
*/
public synchronized void enableAuditLog(AuditLogOptions auditLogOptions) throws ConfigurationException
{
if (isFQLEnabled() && fullQueryLogger.path().toString().equals(auditLogOptions.audit_logs_dir))
throw new IllegalArgumentException(String.format("audit log path (%s) cannot be the same as the " +
"running full query logger (%s)",
auditLogOptions.audit_logs_dir,
fullQueryLogger.path()));
// always reload the filters
filter = AuditLogFilter.create(auditLogOptions);
// next, check to see if we're changing the logging implementation; if not, keep the same instance and bail.
// note: auditLogger should never be null
IAuditLogger oldLogger = auditLogger;
if (oldLogger.getClass().getSimpleName().equals(auditLogOptions.logger))
return;
auditLogger = getAuditLogger(auditLogOptions.logger);
isAuditLogEnabled = true;
// ensure oldLogger's stop() is called after we swap it with new logger,
// otherwise, we might be calling log() on the stopped logger.
oldLogger.stop();
}
public void configureFQL(Path path, String rollCycle, boolean blocking, int maxQueueWeight, long maxLogSize, String archiveCommand, int maxArchiveRetries)
{
if (path.equals(auditLogger.path()))
throw new IllegalArgumentException(String.format("fullquerylogger path (%s) cannot be the same as the " +
"running audit logger (%s)",
path,
auditLogger.path()));
fullQueryLogger.configure(path, rollCycle, blocking, maxQueueWeight, maxLogSize, archiveCommand, maxArchiveRetries);
}
public void resetFQL(String fullQueryLogPath)
{
fullQueryLogger.reset(fullQueryLogPath);
}
public void disableFQL()
{
fullQueryLogger.stop();
}
/**
* ONLY FOR TESTING
*/
FullQueryLogger getFullQueryLogger()
{
return fullQueryLogger;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNode;
import org.apache.hadoop.yarn.util.resource.Resources;
@Private
@Unstable
public class FSSchedulerNode extends SchedulerNode {
private static final Log LOG = LogFactory.getLog(FSSchedulerNode.class);
private static final RecordFactory recordFactory = RecordFactoryProvider
.getRecordFactory(null);
private Resource availableResource;
private Resource usedResource = recordFactory.newRecordInstance(Resource.class);
private volatile int numContainers;
private RMContainer reservedContainer;
private AppSchedulable reservedAppSchedulable;
/* set of containers that are allocated containers */
private final Map<ContainerId, RMContainer> launchedContainers =
new HashMap<ContainerId, RMContainer>();
private final RMNode rmNode;
public FSSchedulerNode(RMNode node) {
this.rmNode = node;
this.availableResource = Resources.clone(node.getTotalCapability());
// correct!
LOG.info("Avail CPU" + availableResource.getVirtualCores() + ", Avail GPU" + availableResource.getGPUCores());
}
public RMNode getRMNode() {
return rmNode;
}
public NodeId getNodeID() {
return rmNode.getNodeID();
}
public String getHttpAddress() {
return rmNode.getHttpAddress();
}
@Override
public String getHostName() {
return rmNode.getHostName();
}
@Override
public String getRackName() {
return rmNode.getRackName();
}
/**
* The Scheduler has allocated containers on this node to the
* given application.
*
* @param applicationId application
* @param rmContainer allocated container
*/
public synchronized void allocateContainer(ApplicationId applicationId,
RMContainer rmContainer) {
Container container = rmContainer.getContainer();
deductAvailableResource(container.getResource());
++numContainers;
launchedContainers.put(container.getId(), rmContainer);
LOG.info("Assigned container " + container.getId() +
" of capacity " + container.getResource() + " on host " + rmNode.getNodeAddress() +
", which currently has " + numContainers + " containers, " +
getUsedResource() + " used and " +
getAvailableResource() + " available");
}
@Override
public synchronized Resource getAvailableResource() {
return availableResource;
}
@Override
public synchronized Resource getUsedResource() {
return usedResource;
}
private synchronized boolean isValidContainer(Container c) {
if (launchedContainers.containsKey(c.getId())) {
return true;
}
return false;
}
private synchronized void updateResource(Container container) {
addAvailableResource(container.getResource());
--numContainers;
}
/**
* Release an allocated container on this node.
* @param container container to be released
*/
public synchronized void releaseContainer(Container container) {
if (!isValidContainer(container)) {
LOG.error("Invalid container released " + container);
return;
}
/* remove the containers from the nodemanger */
launchedContainers.remove(container.getId());
updateResource(container);
LOG.info("Released container " + container.getId() +
" of capacity " + container.getResource() + " on host " + rmNode.getNodeAddress() +
", which currently has " + numContainers + " containers, " +
getUsedResource() + " used and " + getAvailableResource()
+ " available" + ", release resources=" + true);
}
private synchronized void addAvailableResource(Resource resource) {
if (resource == null) {
LOG.error("Invalid resource addition of null resource for "
+ rmNode.getNodeAddress());
return;
}
Resources.addTo(availableResource, resource);
Resources.subtractFrom(usedResource, resource);
}
private synchronized void deductAvailableResource(Resource resource) {
if (resource == null) {
LOG.error("Invalid deduction of null resource for "
+ rmNode.getNodeAddress());
return;
}
Resources.subtractFrom(availableResource, resource);
Resources.addTo(usedResource, resource);
}
@Override
public String toString() {
return "host: " + rmNode.getNodeAddress() + " #containers=" + getNumContainers() +
" available=" + getAvailableResource() +
" used=" + getUsedResource();
}
@Override
public int getNumContainers() {
return numContainers;
}
public synchronized List<RMContainer> getRunningContainers() {
return new ArrayList<RMContainer>(launchedContainers.values());
}
public synchronized void reserveResource(
FSSchedulerApp application, Priority priority,
RMContainer reservedContainer) {
// Check if it's already reserved
if (this.reservedContainer != null) {
// Sanity check
if (!reservedContainer.getContainer().getNodeId().equals(getNodeID())) {
throw new IllegalStateException("Trying to reserve" +
" container " + reservedContainer +
" on node " + reservedContainer.getReservedNode() +
" when currently" + " reserved resource " + this.reservedContainer +
" on node " + this.reservedContainer.getReservedNode());
}
// Cannot reserve more than one application on a given node!
if (!this.reservedContainer.getContainer().getId().getApplicationAttemptId().equals(
reservedContainer.getContainer().getId().getApplicationAttemptId())) {
throw new IllegalStateException("Trying to reserve" +
" container " + reservedContainer +
" for application " + application.getApplicationId() +
" when currently" +
" reserved container " + this.reservedContainer +
" on node " + this);
}
LOG.info("Updated reserved container " +
reservedContainer.getContainer().getId() + " on node " +
this + " for application " + application);
} else {
LOG.info("Reserved container " + reservedContainer.getContainer().getId() +
" on node " + this + " for application " + application);
}
this.reservedContainer = reservedContainer;
this.reservedAppSchedulable = application.getAppSchedulable();
}
public synchronized void unreserveResource(
FSSchedulerApp application) {
// Cannot unreserve for wrong application...
ApplicationAttemptId reservedApplication =
reservedContainer.getContainer().getId().getApplicationAttemptId();
if (!reservedApplication.equals(
application.getApplicationAttemptId())) {
throw new IllegalStateException("Trying to unreserve " +
" for application " + application.getApplicationId() +
" when currently reserved " +
" for application " + reservedApplication.getApplicationId() +
" on node " + this);
}
this.reservedContainer = null;
this.reservedAppSchedulable = null;
}
public synchronized RMContainer getReservedContainer() {
return reservedContainer;
}
public synchronized AppSchedulable getReservedAppSchedulable() {
return reservedAppSchedulable;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tika.parser.ocr;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Locale;
import java.util.Properties;
/**
* Configuration for TesseractOCRParser.
* <p>
* This allows to enable TesseractOCRParser and set its parameters:
* <p>
* TesseractOCRConfig config = new TesseractOCRConfig();<br>
* config.setTesseractPath(tesseractFolder);<br>
* parseContext.set(TesseractOCRConfig.class, config);<br>
* </p>
* <p>
* Parameters can also be set by either editing the existing TesseractOCRConfig.properties file in,
* tika-parser/src/main/resources/org/apache/tika/parser/ocr, or overriding it by creating your own
* and placing it in the package org/apache/tika/parser/ocr on the classpath.
*/
public class TesseractOCRConfig implements Serializable {
private static final long serialVersionUID = -4861942486845757891L;
public enum OUTPUT_TYPE {
TXT,
HOCR
}
// Path to tesseract installation folder, if not on system path.
private String tesseractPath = "";
// Path to the 'tessdata' folder, which contains language files and config files.
private String tessdataPath = "";
// Language dictionary to be used.
private String language = "eng";
// Tesseract page segmentation mode.
private String pageSegMode = "1";
// Minimum file size to submit file to ocr.
private int minFileSizeToOcr = 0;
// Maximum file size to submit file to ocr.
private int maxFileSizeToOcr = Integer.MAX_VALUE;
// Maximum time (seconds) to wait for the ocring process termination
private int timeout = 120;
// The format of the ocr'ed output to be returned, txt or hocr.
private OUTPUT_TYPE outputType = OUTPUT_TYPE.TXT;
// enable image processing (optional)
private int enableImageProcessing = 0;
// Path to ImageMagick program, if not on system path.
private String ImageMagickPath = "";
// resolution of processed image (in dpi).
private int density = 300;
// number of bits in a color sample within a pixel.
private int depth = 4;
// colorspace of processed image.
private String colorspace = "gray";
// filter to be applied to the processed image.
private String filter = "triangle";
// factor by which image is to be scaled.
private int resize = 900;
// whether or not to preserve interword spacing
private boolean preserveInterwordSpacing = false;
/**
* Default contructor.
*/
public TesseractOCRConfig() {
init(this.getClass().getResourceAsStream("TesseractOCRConfig.properties"));
}
/**
* Loads properties from InputStream and then tries to close InputStream.
* If there is an IOException, this silently swallows the exception
* and goes back to the default.
*
* @param is
*/
public TesseractOCRConfig(InputStream is) {
init(is);
}
private void init(InputStream is) {
if (is == null) {
return;
}
Properties props = new Properties();
try {
props.load(is);
} catch (IOException e) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
//swallow
}
}
}
// set parameters for Tesseract
setTesseractPath(
getProp(props, "tesseractPath", getTesseractPath()));
setTessdataPath(
getProp(props, "tessdataPath", getTessdataPath()));
setLanguage(
getProp(props, "language", getLanguage()));
setPageSegMode(
getProp(props, "pageSegMode", getPageSegMode()));
setMinFileSizeToOcr(
getProp(props, "minFileSizeToOcr", getMinFileSizeToOcr()));
setMaxFileSizeToOcr(
getProp(props, "maxFileSizeToOcr", getMaxFileSizeToOcr()));
setTimeout(
getProp(props, "timeout", getTimeout()));
String outputTypeString = props.getProperty("outputType");
if ("txt".equals(outputTypeString)) {
setOutputType(OUTPUT_TYPE.TXT);
} else if ("hocr".equals(outputTypeString)) {
setOutputType(OUTPUT_TYPE.HOCR);
}
setPreserveInterwordSpacing(getProp(props, "preserveInterwordSpacing", false));
// set parameters for ImageMagick
setEnableImageProcessing(
getProp(props, "enableImageProcessing", isEnableImageProcessing()));
setImageMagickPath(
getProp(props, "ImageMagickPath", getImageMagickPath()));
setDensity(
getProp(props, "density", getDensity()));
setDepth(
getProp(props, "depth", getDepth()));
setColorspace(
getProp(props, "colorspace", getColorspace()));
setFilter(
getProp(props, "filter", getFilter()));
setResize(
getProp(props, "resize", getResize()));
}
/**
* @see #setTesseractPath(String tesseractPath)
*/
public String getTesseractPath() {
return tesseractPath;
}
/**
* Set the path to the Tesseract executable, needed if it is not on system path.
* <p>
* Note that if you set this value, it is highly recommended that you also
* set the path to the 'tessdata' folder using {@link #setTessdataPath}.
* </p>
*/
public void setTesseractPath(String tesseractPath) {
if (!tesseractPath.isEmpty() && !tesseractPath.endsWith(File.separator))
tesseractPath += File.separator;
this.tesseractPath = tesseractPath;
}
/**
* @see #setTessdataPath(String tessdataPath)
*/
public String getTessdataPath() {
return tessdataPath;
}
/**
* Set the path to the 'tessdata' folder, which contains language files and config files. In some cases (such
* as on Windows), this folder is found in the Tesseract installation, but in other cases
* (such as when Tesseract is built from source), it may be located elsewhere.
*/
public void setTessdataPath(String tessdataPath) {
if (!tessdataPath.isEmpty() && !tessdataPath.endsWith(File.separator))
tessdataPath += File.separator;
this.tessdataPath = tessdataPath;
}
/**
* @see #setLanguage(String language)
*/
public String getLanguage() {
return language;
}
/**
* Set tesseract language dictionary to be used. Default is "eng".
* Multiple languages may be specified, separated by plus characters.
* e.g. "chi_tra+chi_sim"
*/
public void setLanguage(String language) {
if (!language.matches("([a-zA-Z]{3}(_[a-zA-Z]{3,4})?(\\+?))+")
|| language.endsWith("+")) {
throw new IllegalArgumentException("Invalid language code");
}
this.language = language;
}
/**
* @see #setPageSegMode(String pageSegMode)
*/
public String getPageSegMode() {
return pageSegMode;
}
/**
* Set tesseract page segmentation mode.
* Default is 1 = Automatic page segmentation with OSD (Orientation and Script Detection)
*/
public void setPageSegMode(String pageSegMode) {
if (!pageSegMode.matches("[0-9]|10|11|12|13")) {
throw new IllegalArgumentException("Invalid page segmentation mode");
}
this.pageSegMode = pageSegMode;
}
/**
* Whether or not to maintain interword spacing. Default is <code>false</code>.
*
* @param preserveInterwordSpacing
*/
public void setPreserveInterwordSpacing(boolean preserveInterwordSpacing) {
this.preserveInterwordSpacing = preserveInterwordSpacing;
}
/**
*
* @return whether or not to maintain interword spacing.
*/
public boolean getPreserveInterwordSpacing() {
return preserveInterwordSpacing;
}
/**
* @see #setMinFileSizeToOcr(int minFileSizeToOcr)
*/
public int getMinFileSizeToOcr() {
return minFileSizeToOcr;
}
/**
* Set minimum file size to submit file to ocr.
* Default is 0.
*/
public void setMinFileSizeToOcr(int minFileSizeToOcr) {
this.minFileSizeToOcr = minFileSizeToOcr;
}
/**
* @see #setMaxFileSizeToOcr(int maxFileSizeToOcr)
*/
public int getMaxFileSizeToOcr() {
return maxFileSizeToOcr;
}
/**
* Set maximum file size to submit file to ocr.
* Default is Integer.MAX_VALUE.
*/
public void setMaxFileSizeToOcr(int maxFileSizeToOcr) {
this.maxFileSizeToOcr = maxFileSizeToOcr;
}
/**
* Set maximum time (seconds) to wait for the ocring process to terminate.
* Default value is 120s.
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* @return timeout value for Tesseract
* @see #setTimeout(int timeout)
*/
public int getTimeout() {
return timeout;
}
/**
* Set output type from ocr process. Default is "txt", but can be "hocr".
* Default value is 120s.
*/
public void setOutputType(OUTPUT_TYPE outputType) {
this.outputType = outputType;
}
/**
* @see #setOutputType(OUTPUT_TYPE outputType)
*/
public OUTPUT_TYPE getOutputType() {
return outputType;
}
/**
* @return image processing is enabled or not
* @see #setEnableImageProcessing(int)
*/
public int isEnableImageProcessing() {
return enableImageProcessing;
}
/**
* Set the value to true if processing is to be enabled.
* Default value is false.
*/
public void setEnableImageProcessing(int enableImageProcessing) {
this.enableImageProcessing = enableImageProcessing;
}
/**
* @return the density
*/
public int getDensity() {
return density;
}
/**
* @param density the density to set. Valid range of values is 150-1200.
* Default value is 300.
*/
public void setDensity(int density) {
if (density < 150 || density > 1200) {
throw new IllegalArgumentException("Invalid density value. Valid range of values is 150-1200.");
}
this.density = density;
}
/**
* @return the depth
*/
public int getDepth() {
return depth;
}
/**
* @param depth the depth to set. Valid values are 2, 4, 8, 16, 32, 64, 256, 4096.
* Default value is 4.
*/
public void setDepth(int depth) {
int[] allowedValues = {2, 4, 8, 16, 32, 64, 256, 4096};
for (int i = 0; i < allowedValues.length; i++) {
if (depth == allowedValues[i]) {
this.depth = depth;
return;
}
}
throw new IllegalArgumentException("Invalid depth value. Valid values are 2, 4, 8, 16, 32, 64, 256, 4096.");
}
/**
* @return the colorspace
*/
public String getColorspace() {
return colorspace;
}
/**
* @param colorspace the colorspace to set
* Deafult value is gray.
*/
public void setColorspace(String colorspace) {
if (!colorspace.equals(null)) {
this.colorspace = colorspace;
} else {
throw new IllegalArgumentException("Colorspace value cannot be null.");
}
}
/**
* @return the filter
*/
public String getFilter() {
return filter;
}
/**
* @param filter the filter to set. Valid values are point, hermite, cubic, box, gaussian, catrom, triangle, quadratic and mitchell.
* Default value is triangle.
*/
public void setFilter(String filter) {
if (filter.equals(null)) {
throw new IllegalArgumentException("Filter value cannot be null. Valid values are point, hermite, "
+ "cubic, box, gaussian, catrom, triangle, quadratic and mitchell.");
}
String[] allowedFilters = {"Point", "Hermite", "Cubic", "Box", "Gaussian", "Catrom", "Triangle", "Quadratic", "Mitchell"};
for (int i = 0; i < allowedFilters.length; i++) {
if (filter.equalsIgnoreCase(allowedFilters[i])) {
this.filter = filter;
return;
}
}
throw new IllegalArgumentException("Invalid filter value. Valid values are point, hermite, "
+ "cubic, box, gaussian, catrom, triangle, quadratic and mitchell.");
}
/**
* @return the resize
*/
public int getResize() {
return resize;
}
/**
* @param resize the resize to set. Valid range of values is 100-900.
* Default value is 900.
*/
public void setResize(int resize) {
for (int i = 1; i < 10; i++) {
if (resize == i * 100) {
this.resize = resize;
return;
}
}
throw new IllegalArgumentException("Invalid resize value. Valid range of values is 100-900.");
}
/**
* @return path to ImageMagick file.
* @see #setImageMagickPath(String ImageMagickPath)
*/
public String getImageMagickPath() {
return ImageMagickPath;
}
/**
* Set the path to the ImageMagick executable, needed if it is not on system path.
*
* @param ImageMagickPath to ImageMagick file.
*/
public void setImageMagickPath(String ImageMagickPath) {
if (!ImageMagickPath.isEmpty() && !ImageMagickPath.endsWith(File.separator))
ImageMagickPath += File.separator;
this.ImageMagickPath = ImageMagickPath;
}
/**
* Get property from the properties file passed in.
*
* @param properties properties file to read from.
* @param property the property to fetch.
* @param defaultMissing default parameter to use.
* @return the value.
*/
private int getProp(Properties properties, String property, int defaultMissing) {
String p = properties.getProperty(property);
if (p == null || p.isEmpty()) {
return defaultMissing;
}
try {
return Integer.parseInt(p);
} catch (Throwable ex) {
throw new RuntimeException(String.format(Locale.ROOT, "Cannot parse TesseractOCRConfig variable %s, invalid integer value",
property), ex);
}
}
/**
* Get property from the properties file passed in.
*
* @param properties properties file to read from.
* @param property the property to fetch.
* @param defaultMissing default parameter to use.
* @return the value.
*/
private String getProp(Properties properties, String property, String defaultMissing) {
return properties.getProperty(property, defaultMissing);
}
private boolean getProp(Properties properties, String property, boolean defaultMissing) {
String propVal = properties.getProperty(property);
if (propVal == null) {
return defaultMissing;
}
if (propVal.equalsIgnoreCase("true")) {
return true;
} else if (propVal.equalsIgnoreCase("false")) {
return false;
}
throw new RuntimeException(String.format(Locale.ROOT,
"Cannot parse TesseractOCRConfig variable %s, invalid boolean value: %s",
property, propVal));
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gemstone.gemfire.internal;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.After;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
/**
* @author dsmith
*
*/
@Category(IntegrationTest.class)
public class ScheduledThreadPoolExecutorWithKeepAliveJUnitTest {
ScheduledThreadPoolExecutorWithKeepAlive ex;
@After
public void tearDown() throws Exception {
ex.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
ex.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
ex.shutdownNow();
assertTrue(ex.awaitTermination(10, TimeUnit.SECONDS));
}
@Test
public void testFuture() throws InterruptedException, ExecutionException {
ex = new ScheduledThreadPoolExecutorWithKeepAlive(
5, 60, TimeUnit.SECONDS, Executors.defaultThreadFactory());
final AtomicBoolean done = new AtomicBoolean();
Future f = ex.submit(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
fail("interrupted");
}
done.set(true);
}
});
f.get();
assertTrue("Task did not complete", done.get());
Thread.sleep(2000); // let the thread finish with the task
f = ex.submit(new Callable() {
public Object call() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
fail("interrupted");
}
return Boolean.TRUE;
}
});
assertTrue("Task did not complete", ((Boolean)f.get()).booleanValue());
assertEquals(2, ex.getLargestPoolSize());
}
@Test
public void testConcurrentExecutionAndExpiration() throws InterruptedException, ExecutionException {
ex = new ScheduledThreadPoolExecutorWithKeepAlive(
50, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
Runnable waitForABit = new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
fail("interrupted");
}
}
};
Future[] futures = new Future[50];
for(int i = 0; i < 50; i++) {
futures[i] = ex.submit(waitForABit);
}
long start = System.nanoTime();
for(int i = 0; i < 50; i++) {
futures[i].get();
}
long end = System.nanoTime();
assertTrue("Tasks executed in parallel", TimeUnit.NANOSECONDS.toSeconds(end - start) < 50);
assertEquals(50, ex.getLargestPoolSize());
//now make sure we expire back down.
Thread.sleep(5000);
assertEquals(1, ex.getPoolSize());
}
@Test
public void testConcurrentRepeatedTasks() throws InterruptedException, ExecutionException {
ex = new ScheduledThreadPoolExecutorWithKeepAlive(
50, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
final AtomicInteger counter = new AtomicInteger();
Runnable waitForABit = new Runnable() {
public void run() {
try {
counter.incrementAndGet();
Thread.sleep(500);
} catch (InterruptedException e) {
fail("interrupted");
}
}
};
Future[] futures = new Future[50];
for(int i = 0; i < 50; i++) {
futures[i] = ex.scheduleAtFixedRate(waitForABit,0, 1, TimeUnit.SECONDS);
}
Thread.sleep(10000);
for(int i = 0; i < 50; i++) {
futures[i].cancel(true);
}
System.err.println("Counter = " + counter);
assertTrue("Tasks did not execute in parallel. Expected more than 300 executions, got " + counter.get(), counter.get() > 300);
assertEquals(50, ex.getLargestPoolSize());
//now make sure we expire back down.
Thread.sleep(5000);
assertEquals(1, ex.getPoolSize());
}
/**
* time, in nanoseconds, that we should tolerate as slop
* (evidently needed for windows)
*/
private static final long SLOP = TimeUnit.MILLISECONDS.toNanos(20);
@Test
public void testDelayedExcecution() throws InterruptedException, ExecutionException {
ex = new ScheduledThreadPoolExecutorWithKeepAlive(
50, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
long start = System.nanoTime();
Future f = ex.schedule(new Runnable() { public void run() {}}, 10, TimeUnit.SECONDS);
f.get();
long end = System.nanoTime();
assertTrue("Execution was not delayed 10 seconds, only " + (end - start),
TimeUnit.SECONDS.toNanos(10) <= end - start + SLOP);
}
@Test
public void testRepeatedExecution() throws InterruptedException {
ex = new ScheduledThreadPoolExecutorWithKeepAlive(
50, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
final AtomicInteger counter = new AtomicInteger();
Runnable run = new Runnable() {
public void run() {
counter.incrementAndGet();
}
};
ScheduledFuture f = ex.scheduleAtFixedRate(run, 0, 1, TimeUnit.SECONDS);
Thread.sleep(5000);
f.cancel(true);
assertTrue("Task was not executed repeatedly", counter.get() > 1);
int oldValue = counter.get();
Thread.sleep(5000);
assertEquals("Task was not cancelled", oldValue, counter.get());
}
@Test
public void testShutdown() throws InterruptedException {
ex = new ScheduledThreadPoolExecutorWithKeepAlive(
50, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
ex.schedule(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
fail("interrupted");
}
}
}, 2, TimeUnit.SECONDS);
ex.shutdown();
long start = System.nanoTime();
assertTrue(ex.awaitTermination(10, TimeUnit.SECONDS));
long elapsed = System.nanoTime() - start;
assertTrue("Shutdown did not wait to task to complete. Only waited "
+ TimeUnit.NANOSECONDS.toMillis(elapsed),
TimeUnit.SECONDS.toNanos(4) < elapsed + SLOP);
}
@Test
public void testShutdown2() throws InterruptedException {
ex = new ScheduledThreadPoolExecutorWithKeepAlive(
50, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
ex.submit(new Runnable() {
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
fail("interrupted");
}
}
});
//give it a chance to get in the worker pool
Thread.sleep(500);
ex.shutdown();
long start = System.nanoTime();
assertTrue(ex.awaitTermination(10, TimeUnit.SECONDS));
long elapsed = System.nanoTime() - start;
assertTrue("Shutdown did not wait to task to complete. Only waited "
+ TimeUnit.NANOSECONDS.toMillis(elapsed), TimeUnit.SECONDS.toNanos(2) < elapsed);
}
@Test
public void testShutdownNow() throws InterruptedException {
ex = new ScheduledThreadPoolExecutorWithKeepAlive(
50, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
ex.schedule(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
fail("interrupted");
}
}
}, 2, TimeUnit.SECONDS);
ex.shutdownNow();
long start = System.nanoTime();
assertTrue(ex.awaitTermination(1, TimeUnit.SECONDS));
long elapsed = System.nanoTime() - start;
assertTrue("ShutdownNow should not have waited. Waited "
+ TimeUnit.NANOSECONDS.toMillis(elapsed), TimeUnit.SECONDS.toNanos(2) > elapsed);
}
@Test
public void testShutdownNow2() throws InterruptedException {
ex = new ScheduledThreadPoolExecutorWithKeepAlive(
50, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
ex.submit(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
fail("interrupted");
}
}
});
//give it a chance to get in the worker pool.
Thread.sleep(500);
ex.shutdownNow();
long start = System.nanoTime();
assertTrue(ex.awaitTermination(1, TimeUnit.SECONDS));
long elapsed = System.nanoTime() - start;
assertTrue("ShutdownNow should not have waited. Waited "
+ TimeUnit.NANOSECONDS.toMillis(elapsed), TimeUnit.SECONDS.toNanos(2) > elapsed);
}
@Test
public void testShutdownDelayedTasks() throws InterruptedException {
ex = new ScheduledThreadPoolExecutorWithKeepAlive(
50, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
ex.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
ex.schedule(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
fail("interrupted");
}
}
}, 5000, TimeUnit.MILLISECONDS);
ex.shutdown();
long start = System.nanoTime();
assertTrue(ex.awaitTermination(30, TimeUnit.SECONDS));
long elapsed = System.nanoTime() - start;
assertTrue("Shutdown should not have waited. Waited "
+ TimeUnit.NANOSECONDS.toMillis(elapsed), TimeUnit.SECONDS.toNanos(2) > elapsed);
}
@Test
public void testAllWorkersActive() throws InterruptedException {
ex = new ScheduledThreadPoolExecutorWithKeepAlive(
6, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
final AtomicInteger counter = new AtomicInteger();
long start = System.nanoTime();
for(int i = 0; i < 100; i++) {
ex.submit(new Runnable() {
public void run() {
try {
Thread.sleep(500);
counter.incrementAndGet();
} catch (InterruptedException e) {
fail("interrupted");
}
}
});
}
long elapsed = System.nanoTime() - start;
assertTrue("calling ex.submit blocked the caller", TimeUnit.SECONDS.toNanos(1) > elapsed);
Thread.sleep(20 * 500 + 1000);
assertEquals(100, counter.get());
assertEquals(6, ex.getMaximumPoolSize());
}
}
| |
//----------------------------------------------------------------------------
// Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// To contact the authors:
// http://www.inf.ufrgs.br/~bordini
// http://www.das.ufsc.br/~jomi
//
//----------------------------------------------------------------------------
package jason.util;
import jason.jeditplugin.Config;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileFilter;
public class ConfigGUI {
protected JTextField jasonTF;
protected JTextField javaTF;
protected JTextField antTF;
protected JTextArea infraTP;
//JCheckBox insideJIDECBox;
protected JCheckBox closeAllCBox;
protected JCheckBox checkVersionCBox;
protected JCheckBox warnSingVarsCBox;
protected JTextField jadeJarTF;
protected JTextField jadeArgsTF;
protected JCheckBox jadeSnifferCB;
protected JCheckBox jadeRmaCB;
protected JCheckBox shortUnnamedVarCB;
protected static Config userProperties = Config.get();
static {
String currJasonVersion = userProperties.getJasonRunningVersion();
// check new version
//File jasonConfFile = getUserConfFile();
if (userProperties.getProperty("version") != null) {
//userProperties.load(new FileInputStream(jasonConfFile));
if (!userProperties.getProperty("version").equals(currJasonVersion) && !currJasonVersion.equals("?")) {
// new version, set all values to default
System.out.println("This is a new version of Jason, reseting configuration...");
//userProperties.clear();
userProperties.remove(Config.JADE_JAR);
userProperties.remove(Config.JASON_JAR);
userProperties.remove(Config.ANT_LIB);
userProperties.remove(Config.CHECK_VERSION);
}
}
userProperties.fix();
userProperties.store();
}
public static void main(String[] args) {
new ConfigGUI().run();
}
protected static ConfigGUI getNewInstance() {
return new ConfigGUI();
}
public void run() {
final ConfigGUI jid = getNewInstance();
JFrame f = new JFrame(jid.getWindowTitle());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pBt = new JPanel(new FlowLayout());
JButton bSave = new JButton("Save configuration and Exit");
bSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
jid.save();
System.exit(0);
}
});
pBt.add(bSave);
JButton bQuit = new JButton("Exit without saving");
bQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
pBt.add(bQuit);
JPanel p = new JPanel(new BorderLayout());
p.add(BorderLayout.CENTER, jid.getJasonConfigPanel());
p.add(BorderLayout.SOUTH, pBt);
f.getContentPane().add(p);
f.pack();
f.setVisible(true);
}
protected String getWindowTitle() {
return "Jason Configuration -- "+userProperties.getProperty("version");
}
public JPanel getJasonConfigPanel() {
JPanel pop = new JPanel();
pop.setLayout(new BoxLayout(pop, BoxLayout.Y_AXIS));
// jason home
jasonTF = new JTextField(25);
JPanel jasonHomePanel = new JPanel(new GridLayout(0,1));
jasonHomePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(), "Jason", TitledBorder.LEFT, TitledBorder.TOP));
JPanel jasonJarPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
jasonJarPanel.add(new JLabel("jason.jar location"));
jasonJarPanel.add(jasonTF);
jasonJarPanel.add(createBrowseButton("jason.jar", jasonTF));
jasonHomePanel.add(jasonJarPanel);
// jason check version
JPanel checkVersionPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
//checkVersionPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Jason options", TitledBorder.LEFT, TitledBorder.TOP));
checkVersionCBox = new JCheckBox("Check for new Jason versions on startup", false);
checkVersionPanel.add(checkVersionCBox);
jasonHomePanel.add(checkVersionPanel);
// warn sing vars
JPanel wsvPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
warnSingVarsCBox = new JCheckBox("Print out warnings about singleton variables in plans and rules", false);
wsvPanel.add(warnSingVarsCBox);
jasonHomePanel.add(wsvPanel);
// unamed vars style
JPanel unvPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
shortUnnamedVarCB = new JCheckBox("Use short names for unamed variables (those starting with _)", false);
unvPanel.add(shortUnnamedVarCB);
jasonHomePanel.add(unvPanel);
pop.add(jasonHomePanel);
// java home
JPanel javaHomePanel = new JPanel();
javaHomePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(), "Java Home", TitledBorder.LEFT, TitledBorder.TOP));
javaHomePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
javaHomePanel.add(new JLabel("Directory"));
javaTF = new JTextField(25);
javaHomePanel.add(javaTF);
JButton setJava = new JButton("Browse");
setJava.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JFileChooser chooser = new JFileChooser(System.getProperty("user.dir"));
chooser.setDialogTitle("Select the Java JDK home directory");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
String javaHome = (new File(chooser.getSelectedFile().getPath())).getCanonicalPath();
if (Config.checkJavaHomePath(javaHome)) {
javaTF.setText(javaHome);
} else {
JOptionPane.showMessageDialog(null, "The selected JDK home directory doesn't have the bin/javac file!");
}
}
} catch (Exception e) {}
}
});
javaHomePanel.add(setJava);
pop.add(javaHomePanel);
// ant lib home
JPanel antHomePanel = new JPanel();
antHomePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(), "Ant libs", TitledBorder.LEFT, TitledBorder.TOP));
antHomePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
antHomePanel.add(new JLabel("Directory"));
antTF = new JTextField(25);
antHomePanel.add(antTF);
JButton setAnt = new JButton("Browse");
setAnt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JFileChooser chooser = new JFileChooser(System.getProperty("user.dir"));
chooser.setDialogTitle("Select the directory with ant.jar and ant-launcher.jar files");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
String antLib = (new File(chooser.getSelectedFile().getPath())).getCanonicalPath();
if (Config.checkAntLib(antLib)) {
antTF.setText(antLib);
} else {
JOptionPane.showMessageDialog(null, "The selected directory doesn't have the files ant.jar and ant-launcher.jar!");
}
}
} catch (Exception e) {}
}
});
antHomePanel.add(setAnt);
pop.add(antHomePanel);
// infras
JPanel infraPanel = new JPanel();
infraPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(), "Available Insfrastructures", TitledBorder.LEFT, TitledBorder.TOP));
infraPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
infraTP = new JTextArea(5,45);
infraPanel.add(new JScrollPane(infraTP));
pop.add(infraPanel);
// jade home
jadeJarTF = new JTextField(25);
jadeArgsTF = new JTextField(30);
JPanel jadeHomePanel = new JPanel(new GridLayout(0,1));
jadeHomePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(), "JADE", TitledBorder.LEFT, TitledBorder.TOP));
JPanel jadeJarPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
jadeJarPanel.add(new JLabel("jade.jar location"));
jadeJarPanel.add(jadeJarTF);
jadeJarPanel.add(createBrowseButton("jade.jar", jadeJarTF));
jadeHomePanel.add(jadeJarPanel);
JPanel jadeArgsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
jadeArgsPanel.add(new JLabel("jade.Boot arguments"));
jadeArgsPanel.add(jadeArgsTF);
jadeHomePanel.add(jadeArgsPanel);
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
jadeRmaCB = new JCheckBox();
jadeRmaCB.setToolTipText("Should the JADE management agent be run at startup?");
p.add(jadeRmaCB);
p.add(new JLabel("Start management agent "));
jadeSnifferCB = new JCheckBox();
jadeSnifferCB.setToolTipText("Should the JADE sniffer agent be run at startup?");
p.add(jadeSnifferCB);
p.add(new JLabel("Start Sniffer"));
jadeHomePanel.add(p);
pop.add(jadeHomePanel);
// shell command
/*
JPanel shellPanel = new JPanel();
shellPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(), "Shell command", TitledBorder.LEFT, TitledBorder.TOP));
shellPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
shellTF = new JTextField(30);
shellTF.setToolTipText("This command will be used to run the scripts that run the MAS.");
shellPanel.add(shellTF);
pop.add(shellPanel);
*/
// run centralised inside jIDE
/*
JPanel insideJIDEPanel = new JPanel();
insideJIDEPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Centralised MAS execution mode", TitledBorder.LEFT, TitledBorder.TOP));
insideJIDEPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
insideJIDECBox = new JCheckBox("Run MAS as a JasonIDE internal thread instead of another process.");
insideJIDEPanel.add(insideJIDECBox);
pop.add(insideJIDEPanel);
*/
// close all before opening mas project
JPanel closeAllPanel = new JPanel();
closeAllPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "jEdit options", TitledBorder.LEFT, TitledBorder.TOP));
closeAllPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
closeAllCBox = new JCheckBox("Close all files before opening a new Jason Project.");
closeAllPanel.add(closeAllCBox);
pop.add(closeAllPanel);
jadeJarTF.setText(userProperties.getJadeJar());
jadeArgsTF.setText(userProperties.getJadeArgs());
jasonTF.setText(userProperties.getJasonJar());
javaTF.setText(userProperties.getJavaHome());
antTF.setText(userProperties.getAntLib());
//shellTF.setText(userProperties.getShellCommand());
//insideJIDECBox.setSelected(userProperties.runAsInternalTread());
closeAllCBox.setSelected(userProperties.getBoolean(Config.CLOSEALL));
checkVersionCBox.setSelected(userProperties.getBoolean(Config.CHECK_VERSION));
warnSingVarsCBox.setSelected(userProperties.getBoolean(Config.WARN_SING_VAR));
shortUnnamedVarCB.setSelected(userProperties.getBoolean(Config.SHORT_UNNAMED_VARS));
jadeSnifferCB.setSelected(userProperties.getBoolean(Config.JADE_SNIFFER));
jadeRmaCB.setSelected(userProperties.getBoolean(Config.JADE_RMA));
for (String i: userProperties.getAvailableInfrastructures()) {
infraTP.append(i+"="+userProperties.getInfrastructureFactoryClass(i)+"\n");
}
return pop;
}
protected JButton createBrowseButton(final String jarfile, final JTextField tf) {
JButton bt = new JButton("Browse");
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JFileChooser chooser = new JFileChooser(System.getProperty("user.dir"));
chooser.setDialogTitle("Select the "+jarfile+" file");
chooser.setFileFilter(new JarFileFilter(jarfile, "The "+jarfile+" file"));
//chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
String selJar = (new File(chooser.getSelectedFile().getPath())).getCanonicalPath();
if (Config.checkJar(selJar)) {
tf.setText(selJar);
} else {
JOptionPane.showMessageDialog(null, "The selected "+jarfile+" file was not ok!");
}
}
} catch (Exception e) {}
}
});
return bt;
}
public void save() {
if (Config.checkJar(jadeJarTF.getText())) {
userProperties.put(Config.JADE_JAR, jadeJarTF.getText().trim());
}
userProperties.put(Config.JADE_ARGS, jadeArgsTF.getText().trim());
if (Config.checkJar(jasonTF.getText())) {
userProperties.put(Config.JASON_JAR, jasonTF.getText().trim());
}
if (Config.checkJavaHomePath(javaTF.getText())) {
userProperties.setJavaHome(javaTF.getText().trim());
}
if (Config.checkAntLib(antTF.getText())) {
userProperties.setAntLib(antTF.getText().trim());
}
//userProperties.put(Config.SHELL_CMD, shellTF.getText().trim());
//userProperties.put(Config.RUN_AS_THREAD, insideJIDECBox.isSelected()+"");
userProperties.put(Config.CLOSEALL, closeAllCBox.isSelected()+"");
userProperties.put(Config.CHECK_VERSION, checkVersionCBox.isSelected()+"");
userProperties.put(Config.WARN_SING_VAR, warnSingVarsCBox.isSelected()+"");
userProperties.put(Config.SHORT_UNNAMED_VARS, shortUnnamedVarCB.isSelected()+"");
userProperties.put(Config.JADE_SNIFFER, jadeSnifferCB.isSelected()+"");
userProperties.put(Config.JADE_RMA, jadeRmaCB.isSelected()+"");
// infras
BufferedReader in = new BufferedReader(new StringReader(infraTP.getText()));
String i;
try {
for (String s: userProperties.getAvailableInfrastructures()) {
userProperties.removeInfrastructureFactoryClass(s);
}
while ( (i = in.readLine()) != null) {
int pos = i.indexOf("=");
if (pos > 0) {
String infra = i.substring(0,pos);
String factory = i.substring(pos+1);
userProperties.setInfrastructureFactoryClass(infra, factory);
}
}
} catch (IOException e) {
e.printStackTrace();
}
userProperties.store();
}
class JarFileFilter extends FileFilter {
String jar,ds;
public JarFileFilter(String jar, String ds) {
this.jar = jar;
this.ds = ds;
}
public boolean accept(File f) {
if (f.getName().endsWith(jar) || f.isDirectory()) {
return true;
} else {
return false;
}
}
public String getDescription() {
return ds;
}
}
}
| |
/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cxx;
import static com.facebook.buck.file.ProjectFilesystemMatchers.pathExists;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import com.facebook.buck.cli.FakeBuckConfig;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.TestExecutionContext;
import com.facebook.buck.testutil.TestConsole;
import com.facebook.buck.testutil.integration.TemporaryPaths;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
public class CxxCompileStepIntegrationTest {
@Rule
public TemporaryPaths tmp = new TemporaryPaths();
private void assertCompDir(Path compDir, Optional<String> failure) throws Exception {
ProjectFilesystem filesystem = new ProjectFilesystem(tmp.getRoot());
CxxPlatform platform = CxxPlatformUtils.build(
new CxxBuckConfig(FakeBuckConfig.builder().build()));
// Build up the paths to various files the archive step will use.
BuildRuleResolver resolver =
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
SourcePathResolver pathResolver = new SourcePathResolver(resolver);
Compiler compiler = platform.getCc().resolve(resolver);
ImmutableList<String> compilerCommandPrefix = compiler.getCommandPrefix(pathResolver);
Path output = filesystem.resolve(Paths.get("output.o"));
Path depFile = filesystem.resolve(Paths.get("output.dep"));
Path relativeInput = Paths.get("input.c");
Path input = filesystem.resolve(relativeInput);
filesystem.writeContentsToPath("int main() {}", relativeInput);
Path scratchDir = filesystem.getRootPath().getFileSystem().getPath("scratchDir");
filesystem.mkdirs(scratchDir);
ImmutableList.Builder<String> preprocessorArguments = ImmutableList.builder();
ImmutableList.Builder<String> compilerArguments = ImmutableList.builder();
compilerArguments.add("-g");
DebugPathSanitizer sanitizer = new MungingDebugPathSanitizer(
200,
File.separatorChar,
compDir,
ImmutableBiMap.of());
// Build an archive step.
CxxPreprocessAndCompileStep step =
new CxxPreprocessAndCompileStep(
filesystem,
CxxPreprocessAndCompileStep.Operation.COMPILE_MUNGE_DEBUGINFO,
output,
depFile,
relativeInput,
CxxSource.Type.C,
Optional.of(
new CxxPreprocessAndCompileStep.ToolCommand(
compilerCommandPrefix,
preprocessorArguments.build(),
ImmutableMap.of(),
Optional.empty())),
Optional.of(
new CxxPreprocessAndCompileStep.ToolCommand(
compilerCommandPrefix,
compilerArguments.build(),
ImmutableMap.of(),
Optional.empty())),
/* pch */ Optional.empty(),
HeaderPathNormalizer.empty(pathResolver),
sanitizer,
CxxPlatformUtils.DEFAULT_ASSEMBLER_DEBUG_PATH_SANITIZER,
CxxPlatformUtils.DEFAULT_CONFIG.getHeaderVerification(),
scratchDir,
true,
compiler);
// Execute the archive step and verify it ran successfully.
ExecutionContext executionContext = TestExecutionContext.newInstance();
TestConsole console = (TestConsole) executionContext.getConsole();
int exitCode = step.execute(executionContext).getExitCode();
if (failure.isPresent()) {
assertNotEquals("compile step succeeded", 0, exitCode);
assertThat(
console.getTextWrittenToStdErr(),
console.getTextWrittenToStdErr(),
Matchers.containsString(failure.get()));
} else {
assertEquals("compile step failed: " + console.getTextWrittenToStdErr(), 0, exitCode);
// Verify that we find the expected compilation dir embedded in the file.
String contents = new String(Files.readAllBytes(output));
assertThat(
contents,
Matchers.containsString(sanitizer.getCompilationDirectory()));
}
// Cleanup.
Files.delete(input);
Files.deleteIfExists(output);
}
@Test
public void updateCompilationDir() throws Exception {
assertCompDir(Paths.get("."), Optional.empty());
assertCompDir(Paths.get("blah"), Optional.empty());
}
@Test
public void createsAnArgfile() throws Exception {
ProjectFilesystem filesystem = new ProjectFilesystem(tmp.getRoot());
CxxPlatform platform = CxxPlatformUtils.build(
new CxxBuckConfig(FakeBuckConfig.builder().build()));
// Build up the paths to various files the archive step will use.
BuildRuleResolver resolver =
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
SourcePathResolver pathResolver = new SourcePathResolver(resolver);
Compiler compiler = platform.getCc().resolve(resolver);
ImmutableList<String> compilerCommandPrefix = compiler.getCommandPrefix(pathResolver);
Path output = filesystem.resolve(Paths.get("output.o"));
Path depFile = filesystem.resolve(Paths.get("output.dep"));
Path relativeInput = Paths.get("input.c");
Path input = filesystem.resolve(relativeInput);
filesystem.writeContentsToPath("int main() {}", relativeInput);
Path scratchDir = filesystem.getRootPath().getFileSystem().getPath("scratchDir");
filesystem.mkdirs(scratchDir);
ImmutableList.Builder<String> preprocessorArguments = ImmutableList.builder();
ImmutableList.Builder<String> compilerArguments = ImmutableList.builder();
compilerArguments.add("-g");
// Build an archive step.
CxxPreprocessAndCompileStep step =
new CxxPreprocessAndCompileStep(
filesystem,
CxxPreprocessAndCompileStep.Operation.COMPILE_MUNGE_DEBUGINFO,
output,
depFile,
relativeInput,
CxxSource.Type.C,
Optional.of(
new CxxPreprocessAndCompileStep.ToolCommand(
compilerCommandPrefix,
preprocessorArguments.build(),
ImmutableMap.of(),
Optional.empty())),
Optional.of(
new CxxPreprocessAndCompileStep.ToolCommand(
compilerCommandPrefix,
compilerArguments.build(),
ImmutableMap.of(),
Optional.empty())),
/* pch */ Optional.empty(),
HeaderPathNormalizer.empty(pathResolver),
CxxPlatformUtils.DEFAULT_COMPILER_DEBUG_PATH_SANITIZER,
CxxPlatformUtils.DEFAULT_ASSEMBLER_DEBUG_PATH_SANITIZER,
CxxPlatformUtils.DEFAULT_CONFIG.getHeaderVerification(),
scratchDir,
true,
compiler);
// Execute the archive step and verify it ran successfully.
ExecutionContext executionContext = TestExecutionContext.newInstance();
TestConsole console = (TestConsole) executionContext.getConsole();
int exitCode = step.execute(executionContext).getExitCode();
assertEquals("compile step failed: " + console.getTextWrittenToStdErr(), 0, exitCode);
Path argfile = filesystem.resolve(scratchDir.resolve("ppandcompile.argsfile"));
assertThat(filesystem, pathExists(argfile));
assertThat(
Files.readAllLines(argfile, StandardCharsets.UTF_8),
hasItem(
equalTo("-g")));
// Cleanup.
Files.delete(input);
Files.deleteIfExists(output);
}
}
| |
/*
* Copyright 2021 Danilo Reinert
*
* 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.reinert.requestor.gwtjackson;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.google.gwt.junit.client.GWTTestCase;
import io.reinert.requestor.core.SerializationModule;
import io.reinert.requestor.core.Session;
import io.reinert.requestor.core.annotations.MediaType;
import io.reinert.requestor.core.payload.SerializedPayload;
import io.reinert.requestor.core.serialization.Deserializer;
import io.reinert.requestor.core.serialization.Serializer;
import io.reinert.requestor.gwtjackson.annotations.JsonSerializationModule;
/**
* Integration tests for requestor gwt-jackson processor.
*
* @author Danilo Reinert
*/
public class JsonSessionGwtTest extends GWTTestCase {
static final String APP_JSON = "app*/json*";
static final String JAVASCRIPT = "*/javascript*";
@MediaType({APP_JSON, JAVASCRIPT})
@JsonSerializationModule(Animal.class)
interface TestSerializationModule extends SerializationModule { }
private Session session;
@Override
public String getModuleName() {
return "io.reinert.requestor.gwtjackson.RequestorGwtJacksonTest";
}
@Override
public void gwtSetUp() throws Exception {
session = new JsonSession();
}
public void testSerializerShouldBeAvailableBySerializerManager() {
final Serializer<Animal> serializer = session.getSerializer(Animal.class, "application/json");
assertNotNull(serializer);
}
public void testDeserializerShouldBeAvailableBySerializerManager() {
final Deserializer<Animal> deserializer = session.getDeserializer(Animal.class, "application/json");
assertNotNull(deserializer);
}
// This test will prevent us to every time test the same behaviour for both Serializer and Deserializer
// (since they are the same)
public void testSerializerAndDeserializerShouldBeTheSameInstance() {
final Serializer<Animal> serializer = session.getSerializer(Animal.class, "application/json");
final Deserializer<Animal> deserializer = session.getDeserializer(Animal.class, "application/json");
assertSame(serializer, deserializer);
}
public void testSerializerShouldSupportMediaTypeValuesFromMediaTypeAnnotation() {
final Serializer<Animal> serializer = session.getSerializer(Animal.class, "application/json");
assertTrue(Arrays.equals(new String[]{APP_JSON, JAVASCRIPT}, serializer.mediaType()));
}
public void testSerializerShouldHandleAnnotatedType() {
final Serializer<Animal> serializer = session.getSerializer(Animal.class, "application/json");
assertEquals(Animal.class, serializer.handledType());
}
@SuppressWarnings("null")
public void testSingleDeserialization() {
// Given
final Deserializer<Animal> deserializer = session.getDeserializer(Animal.class, "application/json");
final Animal expected = new Animal("Stuart", 3);
final String input = "{\"name\":\"Stuart\",\"age\":3}";
// When
final Animal output = deserializer.deserialize(new SerializedPayload(input), null);
// Then
assertEquals(expected, output);
}
@SuppressWarnings({"null", "unchecked"})
public void testDeserializationAsList() {
// Given
final Deserializer<Animal> deserializer = session.getDeserializer(Animal.class, "application/json");
final List<Animal> expected = Arrays.asList(new Animal("Stuart", 3), new Animal("March", 5));
final String input = "[{\"name\":\"Stuart\",\"age\":3},{\"name\":\"March\",\"age\":5}]";
// When
List<Animal> output = (List<Animal>) deserializer.deserialize(List.class, new SerializedPayload(input), null);
// Then
assertEquals(expected, output);
}
@SuppressWarnings({"null", "unchecked"})
public void testEmptyArrayDeserializationAsList() {
// Given
final Deserializer<Animal> deserializer = session.getDeserializer(Animal.class, "application/json");
final List<Animal> expected = Collections.emptyList();
final String input = "[]";
// When
List<Animal> output = (List<Animal>) deserializer.deserialize(List.class, new SerializedPayload(input), null);
// Then
assertEquals(expected, output);
}
@SuppressWarnings("null")
public void testSingleSerialization() {
// Given
final Serializer<Animal> serializer = session.getSerializer(Animal.class, "application/json");
final String expected = "{\"name\":\"Stuart\",\"age\":3}";
final Animal input = new Animal("Stuart", 3);
// When
final String output = serializer.serialize(input, null).asString();
// Then
assertEquals(expected, output);
}
@SuppressWarnings({"null", "unchecked"})
public void testSerializationAsList() {
// Given
final Serializer<Animal> serializer = session.getSerializer(Animal.class, "application/json");
final String expected = "[{\"name\":\"Stuart\",\"age\":3},{\"name\":\"March\",\"age\":5}]";
List<Animal> input = Arrays.asList(new Animal("Stuart", 3), new Animal("March", 5));
// When
String output = serializer.serialize(input, null).asString();
// Then
assertEquals(expected, output);
}
public static class Animal {
private String name;
private Integer age;
public Animal() {
}
public Animal(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Animal)) {
return false;
}
final Animal animal = (Animal) o;
if (age != null ? !age.equals(animal.age) : animal.age != null) {
return false;
}
if (name != null ? !name.equals(animal.name) : animal.name != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (age != null ? age.hashCode() : 0);
return result;
}
}
}
| |
/*
* Copyright 2014 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit.tests;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.SocketAddress;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.util.EnumSet;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.config.keys.ClientIdentityLoader;
import org.apache.sshd.client.future.AuthFuture;
import org.apache.sshd.client.keyverifier.ServerKeyVerifier;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.config.keys.FilePasswordProvider;
import org.apache.sshd.common.util.SecurityUtils;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.SystemReader;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import com.gitblit.Constants.AccessPermission;
import com.gitblit.transport.ssh.IPublicKeyManager;
import com.gitblit.transport.ssh.MemoryKeyManager;
import com.gitblit.transport.ssh.SshKey;
/**
* Base class for SSH unit tests.
*/
public abstract class SshUnitTest extends GitblitUnitTest {
protected static final AtomicBoolean started = new AtomicBoolean(false);
protected static KeyPairGenerator generator;
protected KeyPair rwKeyPair;
protected KeyPair roKeyPair;
protected String username = "admin";
protected String password = "admin";
@BeforeClass
public static void startGitblit() throws Exception {
generator = SecurityUtils.getKeyPairGenerator("RSA");
started.set(GitBlitSuite.startGitblit());
final SystemReader dsr = SystemReader.getInstance();
SystemReader.setInstance(new SystemReader()
{
final SystemReader defaultsr = dsr;
@Override
public String getHostname()
{
return defaultsr.getHostname();
}
@Override
public String getenv(String variable)
{
if ("GIT_SSH".equalsIgnoreCase(variable)) {
return null;
}
return defaultsr.getenv(variable);
}
@Override
public String getProperty(String key)
{
return defaultsr.getProperty(key);
}
@Override
public FileBasedConfig openUserConfig(Config parent, FS fs)
{
return defaultsr.openUserConfig(parent, fs);
}
@Override
public FileBasedConfig openSystemConfig(Config parent, FS fs)
{
return defaultsr.openSystemConfig(parent, fs);
}
@Override
public long getCurrentTime()
{
return defaultsr.getCurrentTime();
}
@Override
public int getTimezone(long when)
{
return defaultsr.getTimezone(when);
}
});
}
@AfterClass
public static void stopGitblit() throws Exception {
if (started.get()) {
GitBlitSuite.stopGitblit();
}
}
protected MemoryKeyManager getKeyManager() {
IPublicKeyManager mgr = gitblit().getPublicKeyManager();
if (mgr instanceof MemoryKeyManager) {
return (MemoryKeyManager) gitblit().getPublicKeyManager();
} else {
throw new RuntimeException("unexpected key manager type " + mgr.getClass().getName());
}
}
@Before
public void prepare() {
rwKeyPair = generator.generateKeyPair();
MemoryKeyManager keyMgr = getKeyManager();
keyMgr.addKey(username, new SshKey(rwKeyPair.getPublic()));
roKeyPair = generator.generateKeyPair();
SshKey sshKey = new SshKey(roKeyPair.getPublic());
sshKey.setPermission(AccessPermission.CLONE);
keyMgr.addKey(username, sshKey);
}
@After
public void tearDown() {
MemoryKeyManager keyMgr = getKeyManager();
keyMgr.removeAllKeys(username);
}
protected SshClient getClient() {
SshClient client = SshClient.setUpDefaultClient();
client.setClientIdentityLoader(new ClientIdentityLoader() { // Ignore the files under ~/.ssh
@Override
public boolean isValidLocation(String location) throws IOException {
return true;
}
@Override
public KeyPair loadClientIdentity(String location, FilePasswordProvider provider) throws IOException, GeneralSecurityException {
return null;
}
});
client.setServerKeyVerifier(new ServerKeyVerifier() {
@Override
public boolean verifyServerKey(ClientSession sshClientSession, SocketAddress remoteAddress, PublicKey serverKey) {
return true;
}
});
client.start();
return client;
}
protected String testSshCommand(String cmd) throws IOException, InterruptedException {
return testSshCommand(cmd, null);
}
protected String testSshCommand(String cmd, String stdin) throws IOException, InterruptedException {
SshClient client = getClient();
ClientSession session = client.connect(username, "localhost", GitBlitSuite.sshPort).verify().getSession();
session.addPublicKeyIdentity(rwKeyPair);
AuthFuture authFuture = session.auth();
assertTrue(authFuture.await());
assertTrue(authFuture.isSuccess());
ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_EXEC, cmd);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (stdin != null) {
Writer w = new OutputStreamWriter(baos);
w.write(stdin);
w.close();
}
channel.setIn(new ByteArrayInputStream(baos.toByteArray()));
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
channel.setOut(out);
channel.setErr(err);
channel.open();
channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED, ClientChannelEvent.EOF), 0);
String result = out.toString().trim();
channel.close(false);
client.stop();
return result;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.