conflict_resolution
stringlengths 27
16k
|
---|
<<<<<<<
prefHandler.putString(HOME_CURRENCY, Utils.getHomeCurrency().code());
=======
getPrefHandler().putString(HOME_CURRENCY, Utils.getHomeCurrency().getCurrencyCode());
>>>>>>>
getPrefHandler().putString(HOME_CURRENCY, Utils.getHomeCurrency().code()); |
<<<<<<<
if (savedInstanceState == null) {
viewModel.loadAccount(getArguments().getLong(KEY_ACCOUNTID));
}
viewModel.getUpdateComplete().observe(this, new EventObserver<>(result -> {
switch (result.getFirst()) {
case TransactionListViewModel.TOKEN_REMAP_CATEGORY: {
((ProtectedFragmentActivity) TransactionList.this.getActivity()).showSnackbar(getString(R.string.remapping_result, result.getSecond()), Snackbar.LENGTH_LONG);
}
}
return Unit.INSTANCE;
})
);
=======
>>>>>>>
viewModel.getUpdateComplete().observe(this, new EventObserver<>(result -> {
switch (result.getFirst()) {
case TransactionListViewModel.TOKEN_REMAP_CATEGORY: {
((ProtectedFragmentActivity) TransactionList.this.getActivity()).showSnackbar(getString(R.string.remapping_result, result.getSecond()), Snackbar.LENGTH_LONG);
}
}
return Unit.INSTANCE;
})
); |
<<<<<<<
SpinnerHelper mColorSpinner;
private SpinnerHelper mCurrencySpinner, mAccountTypeSpinner, mSyncSpinner;
=======
private SpinnerHelper mCurrencySpinner, mAccountTypeSpinner, mSyncSpinner;
private View mColorIndicator;
>>>>>>>
private SpinnerHelper mCurrencySpinner, mAccountTypeSpinner, mSyncSpinner;
private View mColorIndicator;
<<<<<<<
mAccountTypeSpinner = new SpinnerHelper(DialogUtils.configureTypeSpinner(findViewById(R.id.AccountType)));
mColorSpinner = new SpinnerHelper(DialogUtils.configureColorSpinner(findViewById(R.id.Color), mAccount.color));
=======
mAccountTypeSpinner = new SpinnerHelper(DialogUtils.configureTypeSpinner(this));
mColorIndicator = findViewById(R.id.ColorIndicator);
mColorIndicator.setBackgroundColor(mAccount.color);
>>>>>>>
mAccountTypeSpinner = new SpinnerHelper(DialogUtils.configureTypeSpinner(findViewById(R.id.AccountType)));
mColorIndicator = findViewById(R.id.ColorIndicator);
mColorIndicator.setBackgroundColor(mAccount.color);
<<<<<<<
mColorSpinner.setSelection(((ColorAdapter) mColorSpinner.getAdapter()).getPosition(mAccount.color));
=======
mColorIndicator.setBackgroundColor(mAccount.color);
>>>>>>>
mColorIndicator.setBackgroundColor(mAccount.color);
<<<<<<<
case R.id.Color:
mAccount.color = (int) parent.getSelectedItem();
break;
=======
>>>>>>>
<<<<<<<
=======
public void editAccountColor(View view) {
SimpleColorDialog.build()
.allowCustom(true)
.colorPreset(mAccount.color)
.show(this, ACCOUNT_COLOR_DIALOG);
}
@Override
public boolean onResult(@NonNull String dialogTag, int which, @NonNull Bundle extras) {
if (ACCOUNT_COLOR_DIALOG.equals(dialogTag) && which == BUTTON_POSITIVE){
mAccount.color = extras.getInt(SimpleColorDialog.COLOR);
mColorIndicator.setBackgroundColor(mAccount.color);
return true;
}
return false;
}
>>>>>>>
public void editAccountColor(View view) {
SimpleColorDialog.build()
.allowCustom(true)
.colorPreset(mAccount.color)
.show(this, ACCOUNT_COLOR_DIALOG);
}
@Override
public boolean onResult(@NonNull String dialogTag, int which, @NonNull Bundle extras) {
if (ACCOUNT_COLOR_DIALOG.equals(dialogTag) && which == BUTTON_POSITIVE){
mAccount.color = extras.getInt(SimpleColorDialog.COLOR);
mColorIndicator.setBackgroundColor(mAccount.color);
return true;
}
return false;
} |
<<<<<<<
public static final boolean DEBUG = false;
=======
public static final boolean DEBUG = true;
public static final String DONATE_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=KWFGX7RNJ6LM8&lc=US&item_name=Donate%20SGit&item_number=sgit¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted";
>>>>>>>
public static final boolean DEBUG = false;
public static final String DONATE_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=KWFGX7RNJ6LM8&lc=US&item_name=Donate%20SGit&item_number=sgit¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted"; |
<<<<<<<
=======
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
>>>>>>>
import java.util.Arrays;
import java.util.Collection; |
<<<<<<<
private final OnlineTablets onlineTablets = new OnlineTablets();
private final SortedSet<KeyExtent> unopenedTablets = Collections
.synchronizedSortedSet(new TreeSet<KeyExtent>());
private final SortedSet<KeyExtent> openingTablets = Collections
.synchronizedSortedSet(new TreeSet<KeyExtent>());
=======
private final SortedMap<KeyExtent,Tablet> onlineTablets =
Collections.synchronizedSortedMap(new TreeMap<KeyExtent,Tablet>());
private final SortedSet<KeyExtent> unopenedTablets =
Collections.synchronizedSortedSet(new TreeSet<KeyExtent>());
private final SortedSet<KeyExtent> openingTablets =
Collections.synchronizedSortedSet(new TreeSet<KeyExtent>());
>>>>>>>
private final OnlineTablets onlineTablets = new OnlineTablets();
private final SortedSet<KeyExtent> unopenedTablets =
Collections.synchronizedSortedSet(new TreeSet<KeyExtent>());
private final SortedSet<KeyExtent> openingTablets =
Collections.synchronizedSortedSet(new TreeSet<KeyExtent>());
<<<<<<<
final long minBlockSize = context.getHadoopConf()
.getLong("dfs.namenode.fs-limits.min-block-size", 0);
=======
final long minBlockSize =
CachedConfiguration.getInstance().getLong("dfs.namenode.fs-limits.min-block-size", 0);
>>>>>>>
final long minBlockSize =
context.getHadoopConf().getLong("dfs.namenode.fs-limits.min-block-size", 0);
<<<<<<<
authKeyWatcher = new ZooAuthenticationKeyWatcher(context.getSecretManager(),
context.getZooReaderWriter(),
context.getZooKeeperRoot() + Constants.ZDELEGATION_TOKEN_KEYS);
=======
authKeyWatcher =
new ZooAuthenticationKeyWatcher(getSecretManager(), ZooReaderWriter.getInstance(),
ZooUtil.getRoot(instance) + Constants.ZDELEGATION_TOKEN_KEYS);
>>>>>>>
authKeyWatcher =
new ZooAuthenticationKeyWatcher(context.getSecretManager(), context.getZooReaderWriter(),
context.getZooKeeperRoot() + Constants.ZDELEGATION_TOKEN_KEYS);
<<<<<<<
scanSession.nextBatchTask = new NextBatchTask(TabletServer.this, scanID,
scanSession.interruptFlag);
resourceManager.executeReadAhead(scanSession.extent, getScanDispatcher(scanSession.extent),
scanSession, scanSession.nextBatchTask);
=======
scanSession.nextBatchTask =
new NextBatchTask(TabletServer.this, scanID, scanSession.interruptFlag);
resourceManager.executeReadAhead(scanSession.extent, scanSession.nextBatchTask);
>>>>>>>
scanSession.nextBatchTask =
new NextBatchTask(TabletServer.this, scanID, scanSession.interruptFlag);
resourceManager.executeReadAhead(scanSession.extent, getScanDispatcher(scanSession.extent),
scanSession, scanSession.nextBatchTask);
<<<<<<<
scanSession.nextBatchTask = new NextBatchTask(TabletServer.this, scanID,
scanSession.interruptFlag);
resourceManager.executeReadAhead(scanSession.extent, getScanDispatcher(scanSession.extent),
scanSession, scanSession.nextBatchTask);
=======
scanSession.nextBatchTask =
new NextBatchTask(TabletServer.this, scanID, scanSession.interruptFlag);
resourceManager.executeReadAhead(scanSession.extent, scanSession.nextBatchTask);
>>>>>>>
scanSession.nextBatchTask =
new NextBatchTask(TabletServer.this, scanID, scanSession.interruptFlag);
resourceManager.executeReadAhead(scanSession.extent, getScanDispatcher(scanSession.extent),
scanSession, scanSession.nextBatchTask);
<<<<<<<
UpdateSession us = new UpdateSession(new TservConstraintEnv(context, security, credentials),
credentials, durability);
return sessionManager.createSession(us, false);
=======
UpdateSession us =
new UpdateSession(new TservConstraintEnv(security, credentials), credentials, durability);
long sid = sessionManager.createSession(us, false);
return sid;
>>>>>>>
UpdateSession us = new UpdateSession(new TservConstraintEnv(context, security, credentials),
credentials, durability);
return sessionManager.createSession(us, false);
<<<<<<<
ConditionalSession cs = new ConditionalSession(credentials,
new Authorizations(authorizations), tableId, DurabilityImpl.fromThrift(tdurabilty));
=======
ConditionalSession cs =
new ConditionalSession(credentials, new Authorizations(authorizations), tableId,
DurabilityImpl.fromThrift(tdurabilty), classLoaderContext);
>>>>>>>
ConditionalSession cs = new ConditionalSession(credentials,
new Authorizations(authorizations), tableId, DurabilityImpl.fromThrift(tdurabilty));
<<<<<<<
ZooUtil.LockID lid = new ZooUtil.LockID(context.getZooKeeperRoot() + Constants.ZMASTER_LOCK,
lock);
=======
ZooUtil.LockID lid =
new ZooUtil.LockID(ZooUtil.getRoot(getInstance()) + Constants.ZMASTER_LOCK, lock);
>>>>>>>
ZooUtil.LockID lid =
new ZooUtil.LockID(context.getZooKeeperRoot() + Constants.ZMASTER_LOCK, lock);
<<<<<<<
Tablet tablet = getOnlineTablet(e2);
if (System.currentTimeMillis()
- tablet.getSplitCreationTime() < RECENTLY_SPLIT_MILLIES) {
=======
Tablet tablet = onlineTablets.get(e2);
if (System.currentTimeMillis() - tablet.getSplitCreationTime()
< RECENTLY_SPLIT_MILLIES) {
>>>>>>>
Tablet tablet = getOnlineTablet(e2);
if (System.currentTimeMillis() - tablet.getSplitCreationTime()
< RECENTLY_SPLIT_MILLIES) {
<<<<<<<
KeyExtent ke = new KeyExtent(TableId.of(tableId), ByteBufferUtil.toText(endRow),
ByteBufferUtil.toText(startRow));
=======
KeyExtent ke =
new KeyExtent(tableId, ByteBufferUtil.toText(endRow), ByteBufferUtil.toText(startRow));
>>>>>>>
KeyExtent ke = new KeyExtent(TableId.of(tableId), ByteBufferUtil.toText(endRow),
ByteBufferUtil.toText(startRow));
<<<<<<<
KeyExtent ke = new KeyExtent(TableId.of(tableId), ByteBufferUtil.toText(endRow),
ByteBufferUtil.toText(startRow));
=======
KeyExtent ke =
new KeyExtent(tableId, ByteBufferUtil.toText(endRow), ByteBufferUtil.toText(startRow));
>>>>>>>
KeyExtent ke = new KeyExtent(TableId.of(tableId), ByteBufferUtil.toText(endRow),
ByteBufferUtil.toText(startRow));
<<<<<<<
tablet.initiateMajorCompaction(MajorCompactionReason.NORMAL);
=======
if (tablet.initiateMajorCompaction(MajorCompactionReason.NORMAL)
|| tablet.isMajorCompactionQueued() || tablet.isMajorCompactionRunning()) {
numMajorCompactionsInProgress++;
continue;
}
}
}
int idleCompactionsToStart =
Math.max(1, getConfiguration().getCount(Property.TSERV_MAJC_MAXCONCURRENT) / 2);
if (numMajorCompactionsInProgress < idleCompactionsToStart) {
// system is not major compacting, can schedule some
// idle compactions
iter = copyOnlineTablets.entrySet().iterator();
while (iter.hasNext() && numMajorCompactionsInProgress < idleCompactionsToStart) {
Entry<KeyExtent,Tablet> entry = iter.next();
Tablet tablet = entry.getValue();
if (tablet.initiateMajorCompaction(MajorCompactionReason.IDLE)) {
numMajorCompactionsInProgress++;
}
>>>>>>>
tablet.initiateMajorCompaction(MajorCompactionReason.NORMAL);
<<<<<<<
Pair<Text,KeyExtent> pair = verifyTabletInformation(context, extent,
TabletServer.this.getTabletSession(), tabletsKeyValues, getClientAddressString(),
getLock());
=======
Pair<Text,
KeyExtent> pair = verifyTabletInformation(TabletServer.this, extent,
TabletServer.this.getTabletSession(), tabletsKeyValues, getClientAddressString(),
getLock());
>>>>>>>
Pair<Text,KeyExtent> pair =
verifyTabletInformation(context, extent, TabletServer.this.getTabletSession(),
tabletsKeyValues, getClientAddressString(), getLock());
<<<<<<<
? Property.TSERV_MAX_MESSAGE_SIZE
: Property.GENERAL_MAX_MESSAGE_SIZE);
ServerAddress sp = TServerUtils.startServer(context, address, portHint, processor,
=======
? Property.TSERV_MAX_MESSAGE_SIZE : Property.GENERAL_MAX_MESSAGE_SIZE);
ServerAddress sp = TServerUtils.startServer(this, address, portHint, processor,
>>>>>>>
? Property.TSERV_MAX_MESSAGE_SIZE : Property.GENERAL_MAX_MESSAGE_SIZE);
ServerAddress sp = TServerUtils.startServer(context, address, portHint, processor,
<<<<<<<
=======
MasterClientService.Client client =
ThriftUtil.getClient(new MasterClientService.Client.Factory(), address, this);
>>>>>>>
<<<<<<<
ReplicationServicer.Iface rpcProxy = TraceUtil.wrapService(handler);
ReplicationServicer.Iface repl = TCredentialsUpdatingWrapper.service(rpcProxy,
handler.getClass(), getConfiguration());
// @formatter:off
=======
ReplicationServicer.Iface rpcProxy = RpcWrapper.service(handler,
new ReplicationServicer.Processor<ReplicationServicer.Iface>(handler));
ReplicationServicer.Iface repl =
TCredentialsUpdatingWrapper.service(rpcProxy, handler.getClass(), getConfiguration());
>>>>>>>
ReplicationServicer.Iface rpcProxy = TraceUtil.wrapService(handler);
ReplicationServicer.Iface repl =
TCredentialsUpdatingWrapper.service(rpcProxy, handler.getClass(), getConfiguration());
<<<<<<<
String zPath = context.getZooKeeperRoot() + Constants.ZTSERVERS + "/"
+ getClientAddressString();
=======
String zPath =
ZooUtil.getRoot(getInstance()) + Constants.ZTSERVERS + "/" + getClientAddressString();
>>>>>>>
String zPath =
context.getZooKeeperRoot() + Constants.ZTSERVERS + "/" + getClientAddressString();
<<<<<<<
List<ColumnFQ> columnsToFetch = Arrays.asList(
TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN,
TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN,
TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN,
TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN,
TabletsSection.ServerColumnFamily.TIME_COLUMN);
=======
List<ColumnFQ> columnsToFetch =
Arrays.asList(new ColumnFQ[] {TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN,
TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN,
TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN,
TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN,
TabletsSection.ServerColumnFamily.TIME_COLUMN});
>>>>>>>
List<ColumnFQ> columnsToFetch =
Arrays.asList(TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN,
TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN,
TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN,
TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN,
TabletsSection.ServerColumnFamily.TIME_COLUMN);
<<<<<<<
private void config() {
log.info("Tablet server starting on {}", context.getHostname());
majorCompactorThread = new Daemon(
new LoggingRunnable(log, new MajorCompactor(getConfiguration())));
=======
public void config(String hostname) {
log.info("Tablet server starting on " + hostname);
majorCompactorThread =
new Daemon(new LoggingRunnable(log, new MajorCompactor(getConfiguration())));
>>>>>>>
private void config() {
log.info("Tablet server starting on {}", context.getHostname());
majorCompactorThread =
new Daemon(new LoggingRunnable(log, new MajorCompactor(getConfiguration())));
<<<<<<<
final TabletServer server = new TabletServer(context);
=======
final String app = "tserver";
Accumulo.setupLogging(app);
SecurityUtil.serverLogin(SiteConfiguration.getInstance());
ServerOpts opts = new ServerOpts();
opts.parseArgs(app, args);
String hostname = opts.getAddress();
ServerConfigurationFactory conf =
new ServerConfigurationFactory(HdfsZooInstance.getInstance());
VolumeManager fs = VolumeManagerImpl.get();
MetricsSystemHelper.configure(TabletServer.class.getSimpleName());
Accumulo.init(fs, conf, app);
final TabletServer server = new TabletServer(conf, fs);
server.config(hostname);
DistributedTrace.enable(hostname, app, conf.getConfiguration());
>>>>>>>
final TabletServer server = new TabletServer(context);
<<<<<<<
Path finished = RecoveryPath.getRecoveryPath(fs.getFullPath(FileType.WAL, entry.filename));
=======
Path finished =
RecoveryPath.getRecoveryPath(fs, fs.getFullPath(FileType.WAL, entry.filename));
>>>>>>>
Path finished = RecoveryPath.getRecoveryPath(fs.getFullPath(FileType.WAL, entry.filename));
<<<<<<<
final ConcurrentHashMap<DfsLogger,EnumSet<TabletLevel>> metadataTableLogs = new ConcurrentHashMap<>();
=======
final ConcurrentHashMap<DfsLogger,EnumSet<TabletLevel>> metadataTableLogs =
new ConcurrentHashMap<>();
final Object levelLocks[] = new Object[TabletLevel.values().length];
{
for (int i = 0; i < levelLocks.length; i++) {
levelLocks[i] = new Object();
}
}
>>>>>>>
final ConcurrentHashMap<DfsLogger,EnumSet<TabletLevel>> metadataTableLogs =
new ConcurrentHashMap<>(); |
<<<<<<<
=======
readUsedUsernames();
>>>>>>> |
<<<<<<<
String type = config.getString(ElasticsearchSinkConnectorConfig.TYPE_NAME_CONFIG);
boolean ignoreKey =
config.getBoolean(ElasticsearchSinkConnectorConfig.KEY_IGNORE_CONFIG);
boolean ignoreSchema =
config.getBoolean(ElasticsearchSinkConnectorConfig.SCHEMA_IGNORE_CONFIG);
boolean useCompactMapEntries =
config.getBoolean(ElasticsearchSinkConnectorConfig.COMPACT_MAP_ENTRIES_CONFIG);
Map<String, String> topicToIndexMap =
parseMapConfig(config.getList(ElasticsearchSinkConnectorConfig.TOPIC_INDEX_MAP_CONFIG));
Set<String> topicIgnoreKey =
new HashSet<>(config.getList(ElasticsearchSinkConnectorConfig.TOPIC_KEY_IGNORE_CONFIG));
Set<String> topicIgnoreSchema = new HashSet<>(
config.getList(ElasticsearchSinkConnectorConfig.TOPIC_SCHEMA_IGNORE_CONFIG)
);
long flushTimeoutMs =
config.getLong(ElasticsearchSinkConnectorConfig.FLUSH_TIMEOUT_MS_CONFIG);
int maxBufferedRecords =
config.getInt(ElasticsearchSinkConnectorConfig.MAX_BUFFERED_RECORDS_CONFIG);
int batchSize =
config.getInt(ElasticsearchSinkConnectorConfig.BATCH_SIZE_CONFIG);
long lingerMs =
config.getLong(ElasticsearchSinkConnectorConfig.LINGER_MS_CONFIG);
int maxInFlightRequests =
config.getInt(ElasticsearchSinkConnectorConfig.MAX_IN_FLIGHT_REQUESTS_CONFIG);
long retryBackoffMs =
config.getLong(ElasticsearchSinkConnectorConfig.RETRY_BACKOFF_MS_CONFIG);
int maxRetry =
config.getInt(ElasticsearchSinkConnectorConfig.MAX_RETRIES_CONFIG);
boolean dropInvalidMessage =
config.getBoolean(ElasticsearchSinkConnectorConfig.DROP_INVALID_MESSAGE_CONFIG);
final boolean createIndicesAtStartTime =
config.getBoolean(ElasticsearchSinkConnectorConfig.AUTO_CREATE_INDICES_AT_START_CONFIG);
DataConverter.BehaviorOnNullValues behaviorOnNullValues =
DataConverter.BehaviorOnNullValues.forValue(
config.getString(ElasticsearchSinkConnectorConfig.BEHAVIOR_ON_NULL_VALUES_CONFIG)
);
BulkProcessor.BehaviorOnMalformedDoc behaviorOnMalformedDoc =
BulkProcessor.BehaviorOnMalformedDoc.forValue(
config.getString(ElasticsearchSinkConnectorConfig.BEHAVIOR_ON_MALFORMED_DOCS_CONFIG)
);
=======
>>>>>>>
<<<<<<<
.setType(type)
.setIgnoreKey(ignoreKey, topicIgnoreKey)
.setIgnoreSchema(ignoreSchema, topicIgnoreSchema)
.setCompactMapEntries(useCompactMapEntries)
.setTopicToIndexMap(topicToIndexMap)
.setFlushTimoutMs(flushTimeoutMs)
.setMaxBufferedRecords(maxBufferedRecords)
.setMaxInFlightRequests(maxInFlightRequests)
.setBatchSize(batchSize)
.setLingerMs(lingerMs)
.setRetryBackoffMs(retryBackoffMs)
.setMaxRetry(maxRetry)
.setDropInvalidMessage(dropInvalidMessage)
.setBehaviorOnNullValues(behaviorOnNullValues)
.setBehaviorOnMalformedDoc(behaviorOnMalformedDoc);
try {
if (context.errantRecordReporter() == null) {
log.info("Errant record reporter not configured.");
}
// may be null if DLQ not enabled
builder.setErrantRecordReporter(context.errantRecordReporter());
} catch (NoClassDefFoundError | NoSuchMethodError e) {
// Will occur in Connect runtimes earlier than 2.6
log.warn("AK versions prior to 2.6 do not support the errant record reporter");
}
this.createIndicesAtStartTime = createIndicesAtStartTime;
=======
.setType(config.type())
.setIgnoreKey(config.ignoreKey(), config.ignoreKeyTopics())
.setIgnoreSchema(config.ignoreSchema(), config.ignoreSchemaTopics())
.setCompactMapEntries(config.useCompactMapEntries())
.setTopicToIndexMap(config.topicToIndexMap())
.setFlushTimoutMs(config.flushTimeoutMs())
.setMaxBufferedRecords(config.maxBufferedRecords())
.setMaxInFlightRequests(config.maxInFlightRequests())
.setBatchSize(config.batchSize())
.setLingerMs(config.lingerMs())
.setRetryBackoffMs(config.retryBackoffMs())
.setMaxRetry(config.maxRetries())
.setDropInvalidMessage(config.dropInvalidMessage())
.setBehaviorOnNullValues(config.behaviorOnNullValues())
.setBehaviorOnMalformedDoc(config.behaviorOnMalformedDoc());
this.createIndicesAtStartTime = config.createIndicesAtStart();
>>>>>>>
.setType(config.type())
.setIgnoreKey(config.ignoreKey(), config.ignoreKeyTopics())
.setIgnoreSchema(config.ignoreSchema(), config.ignoreSchemaTopics())
.setCompactMapEntries(config.useCompactMapEntries())
.setTopicToIndexMap(config.topicToIndexMap())
.setFlushTimoutMs(config.flushTimeoutMs())
.setMaxBufferedRecords(config.maxBufferedRecords())
.setMaxInFlightRequests(config.maxInFlightRequests())
.setBatchSize(config.batchSize())
.setLingerMs(config.lingerMs())
.setRetryBackoffMs(config.retryBackoffMs())
.setMaxRetry(config.maxRetries())
.setDropInvalidMessage(config.dropInvalidMessage())
.setBehaviorOnNullValues(config.behaviorOnNullValues())
.setBehaviorOnMalformedDoc(config.behaviorOnMalformedDoc());
try {
if (context.errantRecordReporter() == null) {
log.info("Errant record reporter not configured.");
}
// may be null if DLQ not enabled
builder.setErrantRecordReporter(context.errantRecordReporter());
} catch (NoClassDefFoundError | NoSuchMethodError e) {
// Will occur in Connect runtimes earlier than 2.6
log.warn("AK versions prior to 2.6 do not support the errant record reporter");
}
this.createIndicesAtStartTime = config.createIndicesAtStart(); |
<<<<<<<
private final boolean dropInvalidMessage;
=======
private final DataConverter converter;
>>>>>>>
private final boolean dropInvalidMessage;
private final DataConverter converter;
<<<<<<<
this.dropInvalidMessage = dropInvalidMessage;
=======
this.converter = new DataConverter(useCompactMapEntries);
>>>>>>>
this.dropInvalidMessage = dropInvalidMessage;
this.converter = new DataConverter(useCompactMapEntries);
<<<<<<<
final IndexableRecord indexableRecord = tryGetIndexableRecord(
sinkRecord,
index,
ignoreKey,
ignoreSchema);
=======
final IndexableRecord indexableRecord = converter.convertRecord(sinkRecord, index, type,
ignoreKey, ignoreSchema);
>>>>>>>
final IndexableRecord indexableRecord = tryGetIndexableRecord(
sinkRecord,
index,
ignoreKey,
ignoreSchema); |
<<<<<<<
// Proxy group
public static final String PROXY_HOST_CONFIG = "proxy.host";
private static final String PROXY_HOST_DISPLAY = "Proxy Host";
private static final String PROXY_HOST_DOC = "The address of the proxy host to connect through. "
+ "Supports the basic authentication scheme only.";
private static final String PROXY_HOST_DEFAULT = "";
public static final String PROXY_PORT_CONFIG = "proxy.port";
private static final String PROXY_PORT_DISPLAY = "Proxy Port";
private static final String PROXY_PORT_DOC = "The port of the proxy host to connect through.";
private static final Integer PROXY_PORT_DEFAULT = 8080;
public static final String PROXY_USERNAME_CONFIG = "proxy.username";
private static final String PROXY_USERNAME_DISPLAY = "Proxy Username";
private static final String PROXY_USERNAME_DOC = "The username for the proxy host.";
private static final String PROXY_USERNAME_DEFAULT = "";
public static final String PROXY_PASSWORD_CONFIG = "proxy.password";
private static final String PROXY_PASSWORD_DISPLAY = "Proxy Password";
private static final String PROXY_PASSWORD_DOC = "The password for the proxy host.";
private static final Password PROXY_PASSWORD_DEFAULT = null;
private static final String CONNECTOR_GROUP = "Connector";
private static final String DATA_CONVERSION_GROUP = "Data Conversion";
private static final String PROXY_GROUP = "Proxy";
private static final String SSL_GROUP = "Security";
=======
// Ssl configs
public static final String SSL_CONFIG_PREFIX = "elastic.https.";
>>>>>>>
// Proxy group
public static final String PROXY_HOST_CONFIG = "proxy.host";
private static final String PROXY_HOST_DISPLAY = "Proxy Host";
private static final String PROXY_HOST_DOC = "The address of the proxy host to connect through. "
+ "Supports the basic authentication scheme only.";
private static final String PROXY_HOST_DEFAULT = "";
public static final String PROXY_PORT_CONFIG = "proxy.port";
private static final String PROXY_PORT_DISPLAY = "Proxy Port";
private static final String PROXY_PORT_DOC = "The port of the proxy host to connect through.";
private static final Integer PROXY_PORT_DEFAULT = 8080;
public static final String PROXY_USERNAME_CONFIG = "proxy.username";
private static final String PROXY_USERNAME_DISPLAY = "Proxy Username";
private static final String PROXY_USERNAME_DOC = "The username for the proxy host.";
private static final String PROXY_USERNAME_DEFAULT = "";
public static final String PROXY_PASSWORD_CONFIG = "proxy.password";
private static final String PROXY_PASSWORD_DISPLAY = "Proxy Password";
private static final String PROXY_PASSWORD_DOC = "The password for the proxy host.";
private static final Password PROXY_PASSWORD_DEFAULT = null;
// Ssl configs
public static final String SSL_CONFIG_PREFIX = "elastic.https.";
<<<<<<<
private static void addProxyConfigs(ConfigDef configDef) {
int orderInGroup = 0;
configDef
.define(
PROXY_HOST_CONFIG,
Type.STRING,
PROXY_HOST_DEFAULT,
Importance.LOW,
PROXY_HOST_DOC,
PROXY_GROUP,
orderInGroup++,
Width.LONG,
PROXY_HOST_DISPLAY
).define(
PROXY_PORT_CONFIG,
Type.INT,
PROXY_PORT_DEFAULT,
between(1, 65535),
Importance.LOW,
PROXY_PORT_DOC,
PROXY_GROUP,
orderInGroup++,
Width.LONG,
PROXY_PORT_DISPLAY
).define(
PROXY_USERNAME_CONFIG,
Type.STRING,
PROXY_USERNAME_DEFAULT,
Importance.LOW,
PROXY_USERNAME_DOC,
PROXY_GROUP,
orderInGroup++,
Width.LONG,
PROXY_USERNAME_DISPLAY
).define(
PROXY_PASSWORD_CONFIG,
Type.PASSWORD,
PROXY_PASSWORD_DEFAULT,
Importance.LOW,
PROXY_PASSWORD_DOC,
PROXY_GROUP,
orderInGroup++,
Width.LONG,
PROXY_PASSWORD_DISPLAY
);
}
private static void addSecurityConfigs(ConfigDef configDef) {
ConfigDef sslConfigDef = new ConfigDef();
addClientSslSupport(sslConfigDef);
int order = 0;
configDef.define(
ELASTICSEARCH_SECURITY_PROTOCOL_CONFIG,
Type.STRING,
SecurityProtocol.PLAINTEXT.name(),
Importance.MEDIUM,
ELASTICSEARCH_SECURITY_PROTOCOL_DOC,
SSL_GROUP,
++order,
Width.SHORT,
"Security protocol"
);
configDef.embed(
CONNECTION_SSL_CONFIG_PREFIX, SSL_GROUP,
configDef.configKeys().size() + 2, sslConfigDef
);
}
=======
private static void addSecurityConfigs(ConfigDef configDef) {
ConfigDef sslConfigDef = new ConfigDef();
addClientSslSupport(sslConfigDef);
int order = 0;
configDef.define(
SECURITY_PROTOCOL_CONFIG,
Type.STRING,
SECURITY_PROTOCOL_DEFAULT,
Importance.MEDIUM,
SECURITY_PROTOCOL_DOC,
SSL_GROUP,
++order,
Width.SHORT,
SECURITY_PROTOCOL_DISPLAY
);
configDef.embed(
SSL_CONFIG_PREFIX, SSL_GROUP, configDef.configKeys().size() + 2, sslConfigDef
);
}
>>>>>>>
private static void addProxyConfigs(ConfigDef configDef) {
int orderInGroup = 0;
configDef
.define(
PROXY_HOST_CONFIG,
Type.STRING,
PROXY_HOST_DEFAULT,
Importance.LOW,
PROXY_HOST_DOC,
PROXY_GROUP,
orderInGroup++,
Width.LONG,
PROXY_HOST_DISPLAY
).define(
PROXY_PORT_CONFIG,
Type.INT,
PROXY_PORT_DEFAULT,
between(1, 65535),
Importance.LOW,
PROXY_PORT_DOC,
PROXY_GROUP,
orderInGroup++,
Width.LONG,
PROXY_PORT_DISPLAY
).define(
PROXY_USERNAME_CONFIG,
Type.STRING,
PROXY_USERNAME_DEFAULT,
Importance.LOW,
PROXY_USERNAME_DOC,
PROXY_GROUP,
orderInGroup++,
Width.LONG,
PROXY_USERNAME_DISPLAY
).define(
PROXY_PASSWORD_CONFIG,
Type.PASSWORD,
PROXY_PASSWORD_DEFAULT,
Importance.LOW,
PROXY_PASSWORD_DOC,
PROXY_GROUP,
orderInGroup++,
Width.LONG,
PROXY_PASSWORD_DISPLAY
);
}
private static void addSecurityConfigs(ConfigDef configDef) {
ConfigDef sslConfigDef = new ConfigDef();
addClientSslSupport(sslConfigDef);
int order = 0;
configDef.define(
SECURITY_PROTOCOL_CONFIG,
Type.STRING,
SECURITY_PROTOCOL_DEFAULT,
Importance.MEDIUM,
SECURITY_PROTOCOL_DOC,
SSL_GROUP,
++order,
Width.SHORT,
SECURITY_PROTOCOL_DISPLAY
);
configDef.embed(
SSL_CONFIG_PREFIX, SSL_GROUP, configDef.configKeys().size() + 2, sslConfigDef
);
} |
<<<<<<<
props.put(ElasticsearchSinkConnectorConfig.KEY_IGNORE_CONFIG, "true");
props.put(ElasticsearchSinkConnectorConfig.READ_TIMEOUT_MS_CONFIG, "3000");
=======
props.put(ElasticsearchSinkConnectorConfig.IGNORE_KEY_CONFIG, "true");
>>>>>>>
props.put(ElasticsearchSinkConnectorConfig.IGNORE_KEY_CONFIG, "true");
props.put(ElasticsearchSinkConnectorConfig.READ_TIMEOUT_MS_CONFIG, "3000"); |
<<<<<<<
long retryBackoffMs,
boolean dropInvalidMessage
=======
long retryBackoffMs,
BehaviorOnNullValues behaviorOnNullValues
>>>>>>>
long retryBackoffMs,
boolean dropInvalidMessage,
BehaviorOnNullValues behaviorOnNullValues
<<<<<<<
this.dropInvalidMessage = dropInvalidMessage;
this.converter = new DataConverter(useCompactMapEntries);
=======
this.behaviorOnNullValues = behaviorOnNullValues;
this.converter = new DataConverter(useCompactMapEntries, behaviorOnNullValues);
>>>>>>>
this.dropInvalidMessage = dropInvalidMessage;
this.behaviorOnNullValues = behaviorOnNullValues;
this.converter = new DataConverter(useCompactMapEntries, behaviorOnNullValues);
<<<<<<<
private boolean dropInvalidMessage;
=======
private BehaviorOnNullValues behaviorOnNullValues = BehaviorOnNullValues.DEFAULT;
>>>>>>>
private boolean dropInvalidMessage;
private BehaviorOnNullValues behaviorOnNullValues = BehaviorOnNullValues.DEFAULT;
<<<<<<<
public Builder setDropInvalidMessage(boolean dropInvalidMessage) {
this.dropInvalidMessage = dropInvalidMessage;
return this;
}
=======
/**
* Change the behavior that the resulting {@link ElasticsearchWriter} will have when it
* encounters records with null values.
* @param behaviorOnNullValues Cannot be null. If in doubt, {@link BehaviorOnNullValues#DEFAULT}
* can be used.
*/
public Builder setBehaviorOnNullValues(BehaviorOnNullValues behaviorOnNullValues) {
this.behaviorOnNullValues =
Objects.requireNonNull(behaviorOnNullValues, "behaviorOnNullValues cannot be null");
return this;
}
>>>>>>>
public Builder setDropInvalidMessage(boolean dropInvalidMessage) {
this.dropInvalidMessage = dropInvalidMessage;
return this;
}
/**
* Change the behavior that the resulting {@link ElasticsearchWriter} will have when it
* encounters records with null values.
* @param behaviorOnNullValues Cannot be null. If in doubt, {@link BehaviorOnNullValues#DEFAULT}
* can be used.
*/
public Builder setBehaviorOnNullValues(BehaviorOnNullValues behaviorOnNullValues) {
this.behaviorOnNullValues =
Objects.requireNonNull(behaviorOnNullValues, "behaviorOnNullValues cannot be null");
return this;
}
<<<<<<<
retryBackoffMs,
dropInvalidMessage
=======
retryBackoffMs,
behaviorOnNullValues
>>>>>>>
retryBackoffMs,
dropInvalidMessage,
behaviorOnNullValues |
<<<<<<<
// Preemptively skip records with null values if they're going to be ignored anyways
if (sinkRecord.value() == null && behaviorOnNullValues == BehaviorOnNullValues.IGNORE) {
continue;
}
final String indexOverride = topicToIndexMap.get(sinkRecord.topic());
final String index = indexOverride != null ? indexOverride : sinkRecord.topic();
=======
final String index = convertTopicToIndexName(sinkRecord.topic());
>>>>>>>
// Preemptively skip records with null values if they're going to be ignored anyways
if (sinkRecord.value() == null && behaviorOnNullValues == BehaviorOnNullValues.IGNORE) {
continue;
}
final String index = convertTopicToIndexName(sinkRecord.topic()); |
<<<<<<<
boolean ignoreKey =
config.getBoolean(ElasticsearchSinkConnectorConfig.KEY_IGNORE_CONFIG);
boolean ignoreSchema =
config.getBoolean(ElasticsearchSinkConnectorConfig.SCHEMA_IGNORE_CONFIG);
Map<String, String> topicToIndexMap =
parseMapConfig(config.getList(ElasticsearchSinkConnectorConfig.TOPIC_INDEX_MAP_CONFIG));
Set<String> topicIgnoreKey =
new HashSet<>(config.getList(ElasticsearchSinkConnectorConfig.TOPIC_KEY_IGNORE_CONFIG));
Set<String> topicIgnoreSchema = new HashSet<>(
config.getList(ElasticsearchSinkConnectorConfig.TOPIC_SCHEMA_IGNORE_CONFIG)
);
long flushTimeoutMs =
config.getLong(ElasticsearchSinkConnectorConfig.FLUSH_TIMEOUT_MS_CONFIG);
int maxBufferedRecords =
config.getInt(ElasticsearchSinkConnectorConfig.MAX_BUFFERED_RECORDS_CONFIG);
int batchSize =
config.getInt(ElasticsearchSinkConnectorConfig.BATCH_SIZE_CONFIG);
long lingerMs =
config.getLong(ElasticsearchSinkConnectorConfig.LINGER_MS_CONFIG);
int maxInFlightRequests =
config.getInt(ElasticsearchSinkConnectorConfig.MAX_IN_FLIGHT_REQUESTS_CONFIG);
long retryBackoffMs =
config.getLong(ElasticsearchSinkConnectorConfig.RETRY_BACKOFF_MS_CONFIG);
int maxRetry =
config.getInt(ElasticsearchSinkConnectorConfig.MAX_RETRIES_CONFIG);
boolean dropInvalidMessage =
config.getBoolean(ElasticsearchSinkConnectorConfig.DROP_INVALID_MESSAGE_CONFIG);
=======
boolean ignoreKey = config.getBoolean(ElasticsearchSinkConnectorConfig.KEY_IGNORE_CONFIG);
boolean ignoreSchema = config.getBoolean(ElasticsearchSinkConnectorConfig.SCHEMA_IGNORE_CONFIG);
boolean useCompactMapEntries = config.getBoolean(ElasticsearchSinkConnectorConfig.COMPACT_MAP_ENTRIES_CONFIG);
Map<String, String> topicToIndexMap = parseMapConfig(config.getList(ElasticsearchSinkConnectorConfig.TOPIC_INDEX_MAP_CONFIG));
Set<String> topicIgnoreKey = new HashSet<>(config.getList(ElasticsearchSinkConnectorConfig.TOPIC_KEY_IGNORE_CONFIG));
Set<String> topicIgnoreSchema = new HashSet<>(config.getList(ElasticsearchSinkConnectorConfig.TOPIC_SCHEMA_IGNORE_CONFIG));
long flushTimeoutMs = config.getLong(ElasticsearchSinkConnectorConfig.FLUSH_TIMEOUT_MS_CONFIG);
int maxBufferedRecords = config.getInt(ElasticsearchSinkConnectorConfig.MAX_BUFFERED_RECORDS_CONFIG);
int batchSize = config.getInt(ElasticsearchSinkConnectorConfig.BATCH_SIZE_CONFIG);
long lingerMs = config.getLong(ElasticsearchSinkConnectorConfig.LINGER_MS_CONFIG);
int maxInFlightRequests = config.getInt(ElasticsearchSinkConnectorConfig.MAX_IN_FLIGHT_REQUESTS_CONFIG);
long retryBackoffMs = config.getLong(ElasticsearchSinkConnectorConfig.RETRY_BACKOFF_MS_CONFIG);
int maxRetry = config.getInt(ElasticsearchSinkConnectorConfig.MAX_RETRIES_CONFIG);
>>>>>>>
boolean ignoreKey =
config.getBoolean(ElasticsearchSinkConnectorConfig.KEY_IGNORE_CONFIG);
boolean ignoreSchema =
config.getBoolean(ElasticsearchSinkConnectorConfig.SCHEMA_IGNORE_CONFIG);
boolean useCompactMapEntries =
config.getBoolean(ElasticsearchSinkConnectorConfig.COMPACT_MAP_ENTRIES_CONFIG);
Map<String, String> topicToIndexMap =
parseMapConfig(config.getList(ElasticsearchSinkConnectorConfig.TOPIC_INDEX_MAP_CONFIG));
Set<String> topicIgnoreKey =
new HashSet<>(config.getList(ElasticsearchSinkConnectorConfig.TOPIC_KEY_IGNORE_CONFIG));
Set<String> topicIgnoreSchema = new HashSet<>(
config.getList(ElasticsearchSinkConnectorConfig.TOPIC_SCHEMA_IGNORE_CONFIG)
);
long flushTimeoutMs =
config.getLong(ElasticsearchSinkConnectorConfig.FLUSH_TIMEOUT_MS_CONFIG);
int maxBufferedRecords =
config.getInt(ElasticsearchSinkConnectorConfig.MAX_BUFFERED_RECORDS_CONFIG);
int batchSize =
config.getInt(ElasticsearchSinkConnectorConfig.BATCH_SIZE_CONFIG);
long lingerMs =
config.getLong(ElasticsearchSinkConnectorConfig.LINGER_MS_CONFIG);
int maxInFlightRequests =
config.getInt(ElasticsearchSinkConnectorConfig.MAX_IN_FLIGHT_REQUESTS_CONFIG);
long retryBackoffMs =
config.getLong(ElasticsearchSinkConnectorConfig.RETRY_BACKOFF_MS_CONFIG);
int maxRetry =
config.getInt(ElasticsearchSinkConnectorConfig.MAX_RETRIES_CONFIG);
boolean dropInvalidMessage =
config.getBoolean(ElasticsearchSinkConnectorConfig.DROP_INVALID_MESSAGE_CONFIG); |
<<<<<<<
import org.apache.kafka.common.config.types.Password;
import org.apache.kafka.common.network.Mode;
import org.apache.kafka.common.security.ssl.SslFactory;
=======
>>>>>>>
import org.apache.kafka.common.network.Mode;
import org.apache.kafka.common.security.ssl.SslFactory;
<<<<<<<
factory.setHttpClientConfig(getClientConfig(props));
=======
ElasticsearchSinkConnectorConfig config = new ElasticsearchSinkConnectorConfig(props);
Set<String> addresses = config.connectionUrls();
HttpClientConfig.Builder builder = new HttpClientConfig.Builder(addresses)
.connTimeout(config.connectionTimeoutMs())
.readTimeout(config.readTimeoutMs())
.multiThreaded(true);
if (config.isAuthenticatedConnection()) {
builder
.defaultCredentials(config.username(), config.password().value())
.preemptiveAuthTargetHosts(
addresses.stream().map(addr -> HttpHost.create(addr)).collect(Collectors.toSet())
);
}
HttpClientConfig httpClientConfig = builder.build();
factory.setHttpClientConfig(httpClientConfig);
>>>>>>>
factory.setHttpClientConfig(getClientConfig(props)); |
<<<<<<<
public IndexableRecord convertRecord(
SinkRecord record,
String index,
String type,
boolean ignoreKey,
boolean ignoreSchema
) {
=======
public IndexableRecord convertRecord(SinkRecord record, String index, String type, boolean ignoreKey, boolean ignoreSchema) {
if (record.value() == null) {
switch (behaviorOnNullValues) {
case IGNORE:
return null;
case DELETE:
if (record.key() == null) {
// Since the record key is used as the ID of the index to delete and we don't have a key
// for this record, we can't delete anything anyways, so we ignore the record.
// We can also disregard the value of the ignoreKey parameter, since even if it's true
// the resulting index we'd try to delete would be based solely off topic/partition/
// offset information for the SinkRecord. Since that information is guaranteed to be
// unique per message, we can be confident that there wouldn't be any corresponding
// index present in ES to delete anyways.
return null;
}
// Will proceed as normal, ultimately creating an IndexableRecord with a null payload
break;
case FAIL:
throw new DataException(String.format(
"Sink record with key of %s and null value encountered for topic/partition/offset "
+ "%s/%s/%s (to ignore future records like this change the configuration property "
+ "'%s' from '%s' to '%s')",
record.key(),
record.topic(),
record.kafkaPartition(),
record.kafkaOffset(),
ElasticsearchSinkConnectorConfig.BEHAVIOR_ON_NULL_VALUES_CONFIG,
BehaviorOnNullValues.FAIL,
BehaviorOnNullValues.IGNORE
));
default:
throw new RuntimeException(String.format(
"Unknown value for %s enum: %s",
BehaviorOnNullValues.class.getSimpleName(),
behaviorOnNullValues
));
}
}
>>>>>>>
public IndexableRecord convertRecord(
SinkRecord record,
String index,
String type,
boolean ignoreKey,
boolean ignoreSchema
) {
if (record.value() == null) {
switch (behaviorOnNullValues) {
case IGNORE:
return null;
case DELETE:
if (record.key() == null) {
// Since the record key is used as the ID of the index to delete and we don't have a key
// for this record, we can't delete anything anyways, so we ignore the record.
// We can also disregard the value of the ignoreKey parameter, since even if it's true
// the resulting index we'd try to delete would be based solely off topic/partition/
// offset information for the SinkRecord. Since that information is guaranteed to be
// unique per message, we can be confident that there wouldn't be any corresponding
// index present in ES to delete anyways.
return null;
}
// Will proceed as normal, ultimately creating an IndexableRecord with a null payload
break;
case FAIL:
throw new DataException(String.format(
"Sink record with key of %s and null value encountered for topic/partition/offset "
+ "%s/%s/%s (to ignore future records like this change the configuration property "
+ "'%s' from '%s' to '%s')",
record.key(),
record.topic(),
record.kafkaPartition(),
record.kafkaOffset(),
ElasticsearchSinkConnectorConfig.BEHAVIOR_ON_NULL_VALUES_CONFIG,
BehaviorOnNullValues.FAIL,
BehaviorOnNullValues.IGNORE
));
default:
throw new RuntimeException(String.format(
"Unknown value for %s enum: %s",
BehaviorOnNullValues.class.getSimpleName(),
behaviorOnNullValues
));
}
}
<<<<<<<
private Object preProcessNullValue(Schema schema) {
if (schema.defaultValue() != null) {
return schema.defaultValue();
}
if (schema.isOptional()) {
return null;
}
throw new DataException("null value for field that is required and has no default value");
}
// @returns the decoded logical value or null if this isn't a known logical type
private Object preProcessLogicalValue(String schemaName, Object value) {
switch (schemaName) {
case Decimal.LOGICAL_NAME:
return ((BigDecimal) value).doubleValue();
case Date.LOGICAL_NAME:
case Time.LOGICAL_NAME:
case Timestamp.LOGICAL_NAME:
return value;
default:
// User-defined type or unknown built-in
return null;
}
}
private Object preProcessArrayValue(Object value, Schema schema, Schema newSchema) {
Collection collection = (Collection) value;
List<Object> result = new ArrayList<>();
for (Object element: collection) {
result.add(preProcessValue(element, schema.valueSchema(), newSchema.valueSchema()));
}
return result;
}
private Object preProcessMapValue(Object value, Schema schema, Schema newSchema) {
Schema keySchema = schema.keySchema();
Schema valueSchema = schema.valueSchema();
Schema newValueSchema = newSchema.valueSchema();
Map<?, ?> map = (Map<?, ?>) value;
if (useCompactMapEntries && keySchema.type() == Schema.Type.STRING) {
Map<Object, Object> processedMap = new HashMap<>();
for (Map.Entry<?, ?> entry: map.entrySet()) {
processedMap.put(
preProcessValue(entry.getKey(), keySchema, newSchema.keySchema()),
preProcessValue(entry.getValue(), valueSchema, newValueSchema)
);
}
return processedMap;
}
List<Struct> mapStructs = new ArrayList<>();
for (Map.Entry<?, ?> entry: map.entrySet()) {
Struct mapStruct = new Struct(newValueSchema);
Schema mapKeySchema = newValueSchema.field(MAP_KEY).schema();
Schema mapValueSchema = newValueSchema.field(MAP_VALUE).schema();
mapStruct.put(MAP_KEY, preProcessValue(entry.getKey(), keySchema, mapKeySchema));
mapStruct.put(MAP_VALUE, preProcessValue(entry.getValue(), valueSchema, mapValueSchema));
mapStructs.add(mapStruct);
}
return mapStructs;
}
private Object preProcessStructValue(Object value, Schema schema, Schema newSchema) {
Struct struct = (Struct) value;
Struct newStruct = new Struct(newSchema);
for (Field field : schema.fields()) {
Schema newFieldSchema = newSchema.field(field.name()).schema();
Object converted = preProcessValue(struct.get(field), field.schema(), newFieldSchema);
newStruct.put(field.name(), converted);
}
return newStruct;
}
=======
public enum BehaviorOnNullValues {
IGNORE,
DELETE,
FAIL;
public static final BehaviorOnNullValues DEFAULT = IGNORE;
// Want values for "behavior.on.null.values" property to be case-insensitive
public static final ConfigDef.Validator VALIDATOR = new ConfigDef.Validator() {
private final ConfigDef.ValidString validator = ConfigDef.ValidString.in(names());
@Override
public void ensureValid(String name, Object value) {
if (value instanceof String) {
value = ((String) value).toLowerCase(Locale.ROOT);
}
validator.ensureValid(name, value);
}
// Overridden here so that ConfigDef.toEnrichedRst shows possible values correctly
@Override
public String toString() {
return validator.toString();
}
};
public static String[] names() {
BehaviorOnNullValues[] behaviors = values();
String[] result = new String[behaviors.length];
for (int i = 0; i < behaviors.length; i++) {
result[i] = behaviors[i].toString();
}
return result;
}
public static BehaviorOnNullValues forValue(String value) {
return valueOf(value.toUpperCase(Locale.ROOT));
}
@Override
public String toString() {
return name().toLowerCase(Locale.ROOT);
}
}
>>>>>>>
private Object preProcessNullValue(Schema schema) {
if (schema.defaultValue() != null) {
return schema.defaultValue();
}
if (schema.isOptional()) {
return null;
}
throw new DataException("null value for field that is required and has no default value");
}
// @returns the decoded logical value or null if this isn't a known logical type
private Object preProcessLogicalValue(String schemaName, Object value) {
switch (schemaName) {
case Decimal.LOGICAL_NAME:
return ((BigDecimal) value).doubleValue();
case Date.LOGICAL_NAME:
case Time.LOGICAL_NAME:
case Timestamp.LOGICAL_NAME:
return value;
default:
// User-defined type or unknown built-in
return null;
}
}
private Object preProcessArrayValue(Object value, Schema schema, Schema newSchema) {
Collection collection = (Collection) value;
List<Object> result = new ArrayList<>();
for (Object element: collection) {
result.add(preProcessValue(element, schema.valueSchema(), newSchema.valueSchema()));
}
return result;
}
private Object preProcessMapValue(Object value, Schema schema, Schema newSchema) {
Schema keySchema = schema.keySchema();
Schema valueSchema = schema.valueSchema();
Schema newValueSchema = newSchema.valueSchema();
Map<?, ?> map = (Map<?, ?>) value;
if (useCompactMapEntries && keySchema.type() == Schema.Type.STRING) {
Map<Object, Object> processedMap = new HashMap<>();
for (Map.Entry<?, ?> entry: map.entrySet()) {
processedMap.put(
preProcessValue(entry.getKey(), keySchema, newSchema.keySchema()),
preProcessValue(entry.getValue(), valueSchema, newValueSchema)
);
}
return processedMap;
}
List<Struct> mapStructs = new ArrayList<>();
for (Map.Entry<?, ?> entry: map.entrySet()) {
Struct mapStruct = new Struct(newValueSchema);
Schema mapKeySchema = newValueSchema.field(MAP_KEY).schema();
Schema mapValueSchema = newValueSchema.field(MAP_VALUE).schema();
mapStruct.put(MAP_KEY, preProcessValue(entry.getKey(), keySchema, mapKeySchema));
mapStruct.put(MAP_VALUE, preProcessValue(entry.getValue(), valueSchema, mapValueSchema));
mapStructs.add(mapStruct);
}
return mapStructs;
}
private Object preProcessStructValue(Object value, Schema schema, Schema newSchema) {
Struct struct = (Struct) value;
Struct newStruct = new Struct(newSchema);
for (Field field : schema.fields()) {
Schema newFieldSchema = newSchema.field(field.name()).schema();
Object converted = preProcessValue(struct.get(field), field.schema(), newFieldSchema);
newStruct.put(field.name(), converted);
}
return newStruct;
}
public enum BehaviorOnNullValues {
IGNORE,
DELETE,
FAIL;
public static final BehaviorOnNullValues DEFAULT = IGNORE;
// Want values for "behavior.on.null.values" property to be case-insensitive
public static final ConfigDef.Validator VALIDATOR = new ConfigDef.Validator() {
private final ConfigDef.ValidString validator = ConfigDef.ValidString.in(names());
@Override
public void ensureValid(String name, Object value) {
if (value instanceof String) {
value = ((String) value).toLowerCase(Locale.ROOT);
}
validator.ensureValid(name, value);
}
// Overridden here so that ConfigDef.toEnrichedRst shows possible values correctly
@Override
public String toString() {
return validator.toString();
}
};
public static String[] names() {
BehaviorOnNullValues[] behaviors = values();
String[] result = new String[behaviors.length];
for (int i = 0; i < behaviors.length; i++) {
result[i] = behaviors[i].toString();
}
return result;
}
public static BehaviorOnNullValues forValue(String value) {
return valueOf(value.toUpperCase(Locale.ROOT));
}
@Override
public String toString() {
return name().toLowerCase(Locale.ROOT);
}
} |
<<<<<<<
final int connTimeout = config.getInt(
ElasticsearchSinkConnectorConfig.CONNECTION_TIMEOUT_MS_CONFIG);
final int readTimeout = config.getInt(
ElasticsearchSinkConnectorConfig.READ_TIMEOUT_MS_CONFIG);
final String username = config.getString(
ElasticsearchSinkConnectorConfig.CONNECTION_USERNAME_CONFIG);
final Password password = config.getPassword(
ElasticsearchSinkConnectorConfig.CONNECTION_PASSWORD_CONFIG);
List<String> address = config.getList(
ElasticsearchSinkConnectorConfig.CONNECTION_URL_CONFIG);
final boolean compressionEnabled = config.getBoolean(
ElasticsearchSinkConnectorConfig.CONNECTION_COMPRESSION_CONFIG);
final int maxInFlightRequests = config.getInt(
ElasticsearchSinkConnectorConfig.MAX_IN_FLIGHT_REQUESTS_CONFIG);
=======
>>>>>>>
<<<<<<<
new HttpClientConfig.Builder(address)
.connTimeout(connTimeout)
.readTimeout(readTimeout)
.requestCompressionEnabled(compressionEnabled)
.defaultMaxTotalConnectionPerRoute(maxInFlightRequests)
=======
new HttpClientConfig.Builder(addresses)
.connTimeout(config.connectionTimeoutMs())
.readTimeout(config.readTimeoutMs())
.defaultMaxTotalConnectionPerRoute(config.maxInFlightRequests())
>>>>>>>
new HttpClientConfig.Builder(addresses)
.connTimeout(config.connectionTimeoutMs())
.readTimeout(config.readTimeoutMs())
.requestCompressionEnabled(config.compression())
.defaultMaxTotalConnectionPerRoute(config.maxInFlightRequests()) |
<<<<<<<
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.common.config.SslConfigs;
import org.apache.kafka.common.config.types.Password;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.CONNECTION_URL_CONFIG;
=======
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.CONNECTION_TIMEOUT_MS_CONFIG;
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.CONNECTION_URL_CONFIG;
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.IGNORE_KEY_CONFIG;
>>>>>>>
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.CONNECTION_TIMEOUT_MS_CONFIG;
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.CONNECTION_URL_CONFIG;
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.IGNORE_KEY_CONFIG;
<<<<<<<
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.SECURITY_PROTOCOL_CONFIG;
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.SSL_CONFIG_PREFIX;
import static junit.framework.TestCase.assertTrue;
=======
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.READ_TIMEOUT_MS_CONFIG;
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.TYPE_NAME_CONFIG;
>>>>>>>
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.READ_TIMEOUT_MS_CONFIG;
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.SECURITY_PROTOCOL_CONFIG;
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.SSL_CONFIG_PREFIX;
import static io.confluent.connect.elasticsearch.ElasticsearchSinkConnectorConfig.TYPE_NAME_CONFIG;
<<<<<<<
props.put(ElasticsearchSinkConnectorConfig.TYPE_NAME_CONFIG, ElasticsearchSinkTestBase.TYPE);
props.put(CONNECTION_URL_CONFIG, "localhost");
props.put(ElasticsearchSinkConnectorConfig.IGNORE_KEY_CONFIG, "true");
=======
props.put(TYPE_NAME_CONFIG, ElasticsearchSinkTestBase.TYPE);
props.put(CONNECTION_URL_CONFIG, "localhost");
props.put(IGNORE_KEY_CONFIG, "true");
>>>>>>>
props.put(TYPE_NAME_CONFIG, ElasticsearchSinkTestBase.TYPE);
props.put(CONNECTION_URL_CONFIG, "localhost");
props.put(IGNORE_KEY_CONFIG, "true");
<<<<<<<
new ElasticsearchSinkConnectorConfig(props);
}
@Test(expected = ConfigException.class)
public void shouldNotAllowInvalidUrl() {
props.put(CONNECTION_URL_CONFIG, ".com:/bbb/dfs,http://valid.com");
new ElasticsearchSinkConnectorConfig(props);
}
@Test(expected = ConfigException.class)
public void shouldNotAllowInvalidSecurityProtocol() {
props.put(SECURITY_PROTOCOL_CONFIG, "unsecure");
new ElasticsearchSinkConnectorConfig(props);
=======
new ElasticsearchSinkConnectorConfig(props);
>>>>>>>
new ElasticsearchSinkConnectorConfig(props);
}
@Test(expected = ConfigException.class)
public void shouldNotAllowInvalidUrl() {
props.put(CONNECTION_URL_CONFIG, ".com:/bbb/dfs,http://valid.com");
new ElasticsearchSinkConnectorConfig(props);
}
@Test(expected = ConfigException.class)
public void shouldNotAllowInvalidSecurityProtocol() {
props.put(SECURITY_PROTOCOL_CONFIG, "unsecure");
new ElasticsearchSinkConnectorConfig(props); |
<<<<<<<
import org.apache.commons.io.input.BoundedInputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
=======
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
>>>>>>>
import org.apache.commons.io.input.BoundedInputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
<<<<<<<
private TikaExtractor tika = new TikaExtractor();
private DroidDetector dd = null;
private boolean runDroid = true;
private MessageDigest md5 = null;
private AggressiveUrlCanonicalizer canon = new AggressiveUrlCanonicalizer();
/** */
private LanguageDetector ld = new LanguageDetector();
/** */
private HtmlFeatureParser hfp = new HtmlFeatureParser();
/** */
private SentimentalJ sentij = new SentimentalJ();
/** */
private PostcodeGeomapper pcg = new PostcodeGeomapper();
=======
TikaExtractor tika = null;
MessageDigest md5 = null;
AggressiveUrlCanonicalizer canon = new AggressiveUrlCanonicalizer();
SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'" );
>>>>>>>
private TikaExtractor tika = null;
private DroidDetector dd = null;
private boolean runDroid = true;
private MessageDigest md5 = null;
private AggressiveUrlCanonicalizer canon = new AggressiveUrlCanonicalizer();
/** */
private LanguageDetector ld = new LanguageDetector();
/** */
private HtmlFeatureParser hfp = new HtmlFeatureParser();
/** */
private SentimentalJ sentij = new SentimentalJ();
/** */
private PostcodeGeomapper pcg = new PostcodeGeomapper();
<<<<<<<
// Attempt to set up Droid:
try {
dd = new DroidDetector();
dd.setBinarySignaturesOnly(true);
dd.setMaxBytesToScan(512*1024l);
} catch (CommandExecutionException e) {
e.printStackTrace();
dd = null;
}
=======
tika = new TikaExtractor( conf );
>>>>>>>
// Attempt to set up Droid:
try {
dd = new DroidDetector();
dd.setBinarySignaturesOnly(true);
dd.setMaxBytesToScan(512*1024l);
} catch (CommandExecutionException e) {
e.printStackTrace();
dd = null;
}
tika = new TikaExtractor( conf );
<<<<<<<
// Spot 'slash pages':
if( urlParts.length == 1 || (urlParts.length == 2 && urlParts[1].matches("^index\\.[a-z]+$") ) )
=======
if( urlParts.length == 1 || (urlParts.length == 2 && urlParts[1].matches("^index\\.[a-z]+$") ) )
>>>>>>>
// Spot 'slash pages':
if( urlParts.length == 1 || (urlParts.length == 2 && urlParts[1].matches("^index\\.[a-z]+$") ) )
<<<<<<<
// There are not always headers! The code should check first.
String firstLine[] = HttpParser.readLine(record, "UTF-8").split(" ");
statusCode = firstLine[1].trim();
this.processHeaders(solr, statusCode, HttpParser.parseHeaders(record, "UTF-8"));
// No need for this, as the headers have already been read from the InputStream:
// WARCRecordUtils.getPayload(record);
tikainput = record;
=======
// try {
// String firstLine[] = HttpParser.readLine(record, "UTF-8").split(" ");
// statusCode = firstLine[1];
// Header[] headers = HttpParser.parseHeaders(record, "UTF-8");
// for( Header h : headers ) {
// //System.out.println("HttpHeader: "+h.getName()+" -> "+h.getValue());
// // FIXME This can't work, because the Referer is in the Request, not the Response.
// // TODO Generally, need to think about ensuring the request and response are brought together.
// if( h.getName().equals(HttpHeaders.REFERER))
// referrer = h.getValue();
// if( h.getName().equals(HttpHeaders.CONTENT_TYPE))
// serverType = h.getValue();
// }
// // No need for this, as the headers have already been read from the InputStream:
// // WARCRecordUtils.getPayload(record);
tikainput = record;
// } catch( Exception e ) {
// log.warn( e.getMessage() + "; " + fullUrl );
// }
>>>>>>>
// There are not always headers! The code should check first.
String firstLine[] = HttpParser.readLine(record, "UTF-8").split(" ");
statusCode = firstLine[1].trim();
this.processHeaders(solr, statusCode, HttpParser.parseHeaders(record, "UTF-8"));
// No need for this, as the headers have already been read from the InputStream:
// WARCRecordUtils.getPayload(record);
tikainput = record;
<<<<<<<
tikainput = new BufferedInputStream( new BoundedInputStream( tikainput, BUFFER_SIZE ), (int) BUFFER_SIZE );
tikainput.mark((int) header.getLength());
solr = tika.extract( solr, tikainput, header.getUrl() );
// Pull out the first few bytes, to hunt for new format by magic:
int MAX_FIRST_BYTES = 32;
try {
tikainput.reset();
byte[] ffb = new byte[MAX_FIRST_BYTES];
int read = tikainput.read(ffb);
if( read >= 4 ) {
String hexBytes = Hex.encodeHexString(ffb);
solr.addField(SolrFields.CONTENT_FFB, hexBytes.substring(0,2*4));
StringBuilder separatedHexBytes = new StringBuilder();
for( String hexByte : Splitter.fixedLength(2).split(hexBytes) ) {
separatedHexBytes.append(hexByte);
separatedHexBytes.append(" ");
}
solr.addField(SolrFields.CONTENT_FIRST_BYTES, separatedHexBytes.toString().trim());
}
} catch( IOException i ) {
log.error( i + ": " +i.getMessage() + ";ffb; " + header.getUrl() + "@" + header.getOffset() );
}
// Also run DROID (restricted range):
if( dd != null && runDroid == true ) {
try {
tikainput.reset();
Metadata metadata = new Metadata();
// Note that DROID complains about some URLs with an IllegalArgumentException.
//metadata.set(Metadata.RESOURCE_NAME_KEY, header.getUrl());
MediaType mt = dd.detect(tikainput, metadata);
solr.addField( SolrFields.CONTENT_TYPE_DROID, mt.toString() );
} catch( Exception i ) {
log.error( i + ": " +i.getMessage() + ";dd; " + header.getUrl() + "@" + header.getOffset() );
}
=======
try {
tikainput = new BufferedInputStream( tikainput );
tikainput.mark((int) header.getLength());
solr = tika.extract( solr, tikainput, header.getUrl() );
// Derive normalised/simplified content type:
processContentType(solr, header, serverType);
// Remove the Text Field if required
if( !isTextIncluded){
solr.doc.removeField(SolrFields.SOLR_EXTRACTED_TEXT);
}
} catch( Exception e ) {
log.warn( e.getMessage() + "; " + fullUrl );
>>>>>>>
tikainput = new BufferedInputStream( new BoundedInputStream( tikainput, BUFFER_SIZE ), (int) BUFFER_SIZE );
tikainput.mark((int) header.getLength());
solr = tika.extract( solr, tikainput, header.getUrl() );
// Pull out the first few bytes, to hunt for new format by magic:
int MAX_FIRST_BYTES = 32;
try {
tikainput.reset();
byte[] ffb = new byte[MAX_FIRST_BYTES];
int read = tikainput.read(ffb);
if( read >= 4 ) {
String hexBytes = Hex.encodeHexString(ffb);
solr.addField(SolrFields.CONTENT_FFB, hexBytes.substring(0,2*4));
StringBuilder separatedHexBytes = new StringBuilder();
for( String hexByte : Splitter.fixedLength(2).split(hexBytes) ) {
separatedHexBytes.append(hexByte);
separatedHexBytes.append(" ");
}
solr.addField(SolrFields.CONTENT_FIRST_BYTES, separatedHexBytes.toString().trim());
}
} catch( IOException i ) {
log.error( i + ": " +i.getMessage() + ";ffb; " + header.getUrl() + "@" + header.getOffset() );
}
// Also run DROID (restricted range):
if( dd != null && runDroid == true ) {
try {
tikainput.reset();
Metadata metadata = new Metadata();
// Note that DROID complains about some URLs with an IllegalArgumentException.
//metadata.set(Metadata.RESOURCE_NAME_KEY, header.getUrl());
MediaType mt = dd.detect(tikainput, metadata);
solr.addField( SolrFields.CONTENT_TYPE_DROID, mt.toString() );
} catch( Exception i ) {
log.error( i + ": " +i.getMessage() + ";dd; " + header.getUrl() + "@" + header.getOffset() );
} |
<<<<<<<
private static Log log = LogFactory.getLog( WARCIndexer.class );
private static final String CLI_USAGE = "[-o <output dir>] [-s <Solr instance>] [-t] [WARC File List]";
private static final String CLI_HEADER = "WARCIndexer - Extracts metadata and text from Archive Records";
private static final String CLI_FOOTER = "";
private static final long BUFFER_SIZE = 1024 * 1024l; // 10485760 bytes = 10MB.
private static final Pattern postcodePattern = Pattern.compile( "[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}" );
=======
private static Log log = LogFactory.getLog(WARCIndexer.class);
private static final long BUFFER_SIZE = 1024*1024l; // 10485760 bytes = 10MB.
private List<String> url_excludes;
private List<String> protocol_includes;
private List<String> response_includes;
private static final Pattern postcodePattern = Pattern.compile("[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}");
>>>>>>>
private static Log log = LogFactory.getLog(WARCIndexer.class);
private static final long BUFFER_SIZE = 1024*1024l; // 10485760 bytes = 10MB.
private List<String> url_excludes;
private List<String> protocol_includes;
private List<String> response_includes;
private static final Pattern postcodePattern = Pattern.compile("[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}");
<<<<<<<
=======
private boolean extractContentFirstBytes = true;
private int firstBytesLength = 32;
>>>>>>>
private boolean extractContentFirstBytes = true;
private int firstBytesLength = 32;
<<<<<<<
this.extractLinks = conf.getBoolean( "warc.index.extract.linked.resources" );
this.extractLinkHosts = conf.getBoolean( "warc.index.extract.linked.hosts" );
this.extractLinkDomains = conf.getBoolean( "warc.index.extract.linked.domains" );
this.runDroid = conf.getBoolean( "warc.index.id.droid.enabled" );
this.passUriToFormatTools = conf.getBoolean( "warc.index.id.useResourceURI" );
this.droidUseBinarySignaturesOnly = conf.getBoolean( "warc.index.id.droid.useBinarySignaturesOnly" );
=======
this.extractLinks = conf.getBoolean("warc.index.extract.linked.resources" );
this.extractLinkHosts = conf.getBoolean("warc.index.extract.linked.hosts" );
this.extractLinkDomains = conf.getBoolean("warc.index.extract.linked.domains" );
this.extractText = conf.getBoolean("warc.index.extract.content.text" );
this.extractElementsUsed = conf.getBoolean("warc.index.extract.content.elements_used" );
this.extractContentFirstBytes = conf.getBoolean("warc.index.extract.content.first_bytes.enabled" );
this.firstBytesLength = conf.getInt("warc.index.extract.content.first_bytes.num_bytes" );
this.runDroid = conf.getBoolean("warc.index.id.droid.enabled" );
this.passUriToFormatTools = conf.getBoolean("warc.index.id.useResourceURI");
this.droidUseBinarySignaturesOnly = conf.getBoolean("warc.index.id.droid.useBinarySignaturesOnly" );
// URLs to exclude:
this.url_excludes = conf.getStringList("warc.index.extract.url_exclude");
// Protocols to include:
this.protocol_includes = conf.getStringList("warc.index.extract.protocol_include");
// Response codes to include:
this.response_includes = conf.getStringList("warc.index.extract.response_include");
// URL Filtering options:
if( conf.getBoolean("warc.index.exclusions.enabled")) {
smef = new StaticMapExclusionFilterFactory();
smef.setFile(conf.getString("warc.index.exclusions.file"));
smef.setCheckInterval(conf.getInt("warc.index.exclusions.check_interval"));
try {
smef.init();
} catch (IOException e) {
log.error("Failed to load exclusions file.");
throw new RuntimeException("StaticMapExclusionFilterFactory failed with IOException when loading "+smef.getFile());
}
}
>>>>>>>
this.extractLinks = conf.getBoolean("warc.index.extract.linked.resources" );
this.extractLinkHosts = conf.getBoolean("warc.index.extract.linked.hosts" );
this.extractLinkDomains = conf.getBoolean("warc.index.extract.linked.domains" );
this.extractText = conf.getBoolean("warc.index.extract.content.text" );
this.extractElementsUsed = conf.getBoolean("warc.index.extract.content.elements_used" );
this.extractContentFirstBytes = conf.getBoolean("warc.index.extract.content.first_bytes.enabled" );
this.firstBytesLength = conf.getInt("warc.index.extract.content.first_bytes.num_bytes" );
this.runDroid = conf.getBoolean("warc.index.id.droid.enabled" );
this.passUriToFormatTools = conf.getBoolean("warc.index.id.useResourceURI");
this.droidUseBinarySignaturesOnly = conf.getBoolean("warc.index.id.droid.useBinarySignaturesOnly" );
// URLs to exclude:
this.url_excludes = conf.getStringList("warc.index.extract.url_exclude");
// Protocols to include:
this.protocol_includes = conf.getStringList("warc.index.extract.protocol_include");
// Response codes to include:
this.response_includes = conf.getStringList("warc.index.extract.response_include");
// URL Filtering options:
if( conf.getBoolean("warc.index.exclusions.enabled")) {
smef = new StaticMapExclusionFilterFactory();
smef.setFile(conf.getString("warc.index.exclusions.file"));
smef.setCheckInterval(conf.getInt("warc.index.exclusions.check_interval"));
try {
smef.init();
} catch (IOException e) {
log.error("Failed to load exclusions file.");
throw new RuntimeException("StaticMapExclusionFilterFactory failed with IOException when loading "+smef.getFile());
}
}
<<<<<<<
public WritableSolrRecord extract( String archiveName, ArchiveRecord record ) throws IOException {
return extract( archiveName, record, true );
=======
public SolrRecord extract( String archiveName, ArchiveRecord record ) throws IOException {
return this.extract(archiveName, record, this.extractText );
>>>>>>>
public SolrRecord extract( String archiveName, ArchiveRecord record ) throws IOException {
return this.extract(archiveName, record, this.extractText );
<<<<<<<
WritableSolrRecord solr = new WritableSolrRecord();
=======
SolrRecord solr = new SolrRecord();
>>>>>>>
SolrRecord solr = new SolrRecord();
<<<<<<<
if( header.getUrl() == null )
return null;
=======
if( header.getUrl() == null ) return null;
String fullUrl = header.getUrl();
// Check the filters:
if( this.checkProtocol(fullUrl) == false ) return null;
if( this.checkUrl(fullUrl) == false ) return null;
if( this.checkExclusionFilter(fullUrl) == false) return null;
>>>>>>>
if( header.getUrl() == null ) return null;
String fullUrl = header.getUrl();
// Check the filters:
if( this.checkProtocol(fullUrl) == false ) return null;
if( this.checkUrl(fullUrl) == false ) return null;
if( this.checkExclusionFilter(fullUrl) == false) return null;
<<<<<<<
solr.doc.setField( SolrFields.CRAWL_YEAR, extractYear( header.getDate() ) );
solr.doc.setField( SolrFields.CRAWL_DATE, parseCrawlDate( waybackDate ) );
//
byte[] md5digest = md5.digest( header.getUrl().getBytes( "UTF-8" ) );
=======
solr.doc.setField( SolrFields.CRAWL_YEAR, extractYear(header.getDate()) );
solr.doc.setField(SolrFields.CRAWL_DATE, parseCrawlDate(waybackDate));
// Basic metadata:
byte[] md5digest = md5.digest( fullUrl.getBytes( "UTF-8" ) );
>>>>>>>
solr.doc.setField( SolrFields.CRAWL_YEAR, extractYear(header.getDate()) );
solr.doc.setField(SolrFields.CRAWL_DATE, parseCrawlDate(waybackDate));
// Basic metadata:
byte[] md5digest = md5.digest( fullUrl.getBytes( "UTF-8" ) );
<<<<<<<
solr.doc.setField( SolrFields.ID, waybackDate + "/" + md5hex );
solr.doc.setField( SolrFields.ID_LONG, Long.parseLong( waybackDate + "00" ) + ( ( md5digest[ 1 ] << 8 ) + md5digest[ 0 ] ) );
solr.doc.setField( SolrFields.SOLR_DIGEST, header.getHeaderValue( WARCConstants.HEADER_KEY_PAYLOAD_DIGEST ) );
solr.doc.setField( SolrFields.SOLR_URL, header.getUrl() );
String fullUrl = header.getUrl();
=======
solr.doc.setField( SolrFields.ID, waybackDate + "/" + md5hex);
solr.doc.setField( SolrFields.ID_LONG, Long.parseLong(waybackDate + "00") + ( (md5digest[1] << 8) + md5digest[0] ) );
solr.doc.setField( SolrFields.HASH, header.getHeaderValue(WARCConstants.HEADER_KEY_PAYLOAD_DIGEST) );
solr.doc.setField( SolrFields.SOLR_URL, fullUrl);
solr.doc.setField( SolrFields.HASH_AND_URL,
header.getHeaderValue(WARCConstants.HEADER_KEY_PAYLOAD_DIGEST) + "_" + fullUrl );
>>>>>>>
solr.doc.setField( SolrFields.ID, waybackDate + "/" + md5hex);
solr.doc.setField( SolrFields.ID_LONG, Long.parseLong(waybackDate + "00") + ( (md5digest[1] << 8) + md5digest[0] ) );
solr.doc.setField( SolrFields.HASH, header.getHeaderValue(WARCConstants.HEADER_KEY_PAYLOAD_DIGEST) );
solr.doc.setField( SolrFields.SOLR_URL, fullUrl);
solr.doc.setField( SolrFields.HASH_AND_URL,
header.getHeaderValue(WARCConstants.HEADER_KEY_PAYLOAD_DIGEST) + "_" + fullUrl );
<<<<<<<
=======
// No need for this, as the headers have already been read from the InputStream (above):
// WARCRecordUtils.getPayload(record);
tikainput = record;
} else if ( record instanceof ARCRecord ) {
ARCRecord arcr = (ARCRecord) record;
statusCode = ""+arcr.getStatusCode();
this.processHeaders(solr, statusCode, arcr.getHttpHeaders());
arcr.skipHttpHeader();
tikainput = arcr;
} else {
log.error("FAIL! Unsupported archive record type.");
return solr;
}
// Skip recording non-content URLs (i.e. 2xx responses only please):
if( this.checkResponseCode(statusCode) == false ) {
log.error("Skipping this record based on status code "+statusCode+": "+header.getUrl());
return null;
>>>>>>>
// No need for this, as the headers have already been read from the InputStream (above):
// WARCRecordUtils.getPayload(record);
tikainput = record;
// Skip recording non-content URLs (i.e. 2xx responses only please):
if( this.checkResponseCode(statusCode) == false ) {
log.error("Skipping this record based on status code "+statusCode+": "+header.getUrl());
return null;
}
<<<<<<<
byte[] ffb = new byte[ MAX_FIRST_BYTES ];
int read = tikainput.read( ffb );
=======
byte[] ffb = new byte[this.firstBytesLength];
int read = tikainput.read(ffb);
>>>>>>>
byte[] ffb = new byte[this.firstBytesLength];
int read = tikainput.read(ffb);
<<<<<<<
solr.addField( SolrFields.CONTENT_FIRST_BYTES, separatedHexBytes.toString().trim() );
=======
if( this.extractContentFirstBytes ) {
solr.addField(SolrFields.CONTENT_FIRST_BYTES, separatedHexBytes.toString().trim());
}
>>>>>>>
if( this.extractContentFirstBytes ) {
solr.addField(SolrFields.CONTENT_FIRST_BYTES, separatedHexBytes.toString().trim());
}
<<<<<<<
// TODO ACT/WctEnricher, currently invoked in the reduce stage to lower query hits.
=======
// TODO ACT/WctEnricher, currently invoked in the reduce stage to lower query hits, but should shift here.
>>>>>>>
// TODO ACT/WctEnricher, currently invoked in the reduce stage to lower query hits, but should shift here.
<<<<<<<
if( !isTextIncluded ) {
solr.doc.removeField( SolrFields.SOLR_EXTRACTED_TEXT );
=======
if( !isTextIncluded ){
solr.doc.removeField(SolrFields.SOLR_EXTRACTED_TEXT);
>>>>>>>
if( !isTextIncluded ){
solr.doc.removeField(SolrFields.SOLR_EXTRACTED_TEXT);
<<<<<<<
private void processHeaders( WritableSolrRecord solr, String statusCode, Header[] httpHeaders ) {
=======
private void processHeaders(SolrRecord solr, String statusCode, Header[] httpHeaders) {
>>>>>>>
private void processHeaders(SolrRecord solr, String statusCode, Header[] httpHeaders) {
<<<<<<<
private void processContentType( WritableSolrRecord solr, ArchiveRecordHeader header ) {
=======
private void processContentType( SolrRecord solr, ArchiveRecordHeader header) {
>>>>>>>
private void processContentType( SolrRecord solr, ArchiveRecordHeader header) { |
<<<<<<<
@SuppressWarnings("deprecation")
Property generalClasspaths = Property.GENERAL_CLASSPATHS;
mergeProp(generalClasspaths.getKey(), libDir.getAbsolutePath() + "/[^.].*[.]jar");
mergeProp(Property.GENERAL_DYNAMIC_CLASSPATHS.getKey(), libExtDir.getAbsolutePath() + "/[^.].*[.]jar");
=======
mergeProp(Property.GENERAL_CLASSPATHS.getKey(), libDir.getAbsolutePath() + "/[^.].*[.]jar");
mergeProp(Property.GENERAL_DYNAMIC_CLASSPATHS.getKey(),
libExtDir.getAbsolutePath() + "/[^.].*[.]jar");
>>>>>>>
@SuppressWarnings("deprecation")
Property generalClasspaths = Property.GENERAL_CLASSPATHS;
mergeProp(generalClasspaths.getKey(), libDir.getAbsolutePath() + "/[^.].*[.]jar");
mergeProp(Property.GENERAL_DYNAMIC_CLASSPATHS.getKey(),
libExtDir.getAbsolutePath() + "/[^.].*[.]jar");
<<<<<<<
if (existingInstance != null && existingInstance)
throw new UnsupportedOperationException("Cannot set set config info when using an existing instance.");
=======
if (existingInstance != null && existingInstance.booleanValue())
throw new UnsupportedOperationException(
"Cannot set set config info when using an existing instance.");
>>>>>>>
if (existingInstance != null && existingInstance)
throw new UnsupportedOperationException(
"Cannot set set config info when using an existing instance.");
<<<<<<<
if (existingInstance != null && existingInstance)
throw new UnsupportedOperationException("Cannot set zookeeper info when using an existing instance.");
=======
if (existingInstance != null && existingInstance.booleanValue())
throw new UnsupportedOperationException(
"Cannot set zookeeper info when using an existing instance.");
>>>>>>>
if (existingInstance != null && existingInstance)
throw new UnsupportedOperationException(
"Cannot set zookeeper info when using an existing instance.");
<<<<<<<
if (existingInstance != null && existingInstance)
throw new UnsupportedOperationException("Cannot set zookeeper info when using an existing instance.");
=======
if (existingInstance != null && existingInstance.booleanValue())
throw new UnsupportedOperationException(
"Cannot set zookeeper info when using an existing instance.");
>>>>>>>
if (existingInstance != null && existingInstance)
throw new UnsupportedOperationException(
"Cannot set zookeeper info when using an existing instance.");
<<<<<<<
public MiniAccumuloConfigImpl useExistingInstance(File accumuloSite, File hadoopConfDir) throws IOException {
if (existingInstance != null && !existingInstance)
throw new UnsupportedOperationException("Cannot set to useExistingInstance after specifying config/zookeeper");
=======
public MiniAccumuloConfigImpl useExistingInstance(File accumuloSite, File hadoopConfDir)
throws IOException {
if (existingInstance != null && !existingInstance.booleanValue())
throw new UnsupportedOperationException(
"Cannot set to useExistingInstance after specifying config/zookeeper");
>>>>>>>
public MiniAccumuloConfigImpl useExistingInstance(File accumuloSite, File hadoopConfDir)
throws IOException {
if (existingInstance != null && !existingInstance)
throw new UnsupportedOperationException(
"Cannot set to useExistingInstance after specifying config/zookeeper"); |
<<<<<<<
String apiBaseUri = settings.getString("hasor.dataway.baseApiUrl", "/api/");
=======
String apiBaseUri = environment.getVariable("HASOR_DATAQL_DATAWAY_API_URL");
if (StringUtils.isBlank(apiBaseUri)) {
apiBaseUri = "/api/";
}
//
// .UI
String uiBaseUri = environment.getVariable("HASOR_DATAQL_DATAWAY_UI_URL");
if (StringUtils.isBlank(uiBaseUri)) {
uiBaseUri = "/interface-ui/";
}
if (!uiBaseUri.endsWith("/")) {
uiBaseUri = uiBaseUri + "/";
}
>>>>>>>
String apiBaseUri = settings.getString("hasor.dataway.baseApiUrl", "/api/");
if (StringUtils.isBlank(apiBaseUri)) {
apiBaseUri = "/api/";
}
if (!apiBaseUri.endsWith("/")) {
apiBaseUri = apiBaseUri + "/";
}
String adminBaseUri = settings.getString("hasor.dataway.baseAdminUrl", "/interface-ui/");
if (StringUtils.isBlank(adminBaseUri)) {
adminBaseUri = "/interface-ui/";
}
if (!adminBaseUri.endsWith("/")) {
adminBaseUri = adminBaseUri + "/";
}
//
<<<<<<<
apiBinder.filter(fixUrl(apiBaseUri + "/*")).through(Integer.MAX_VALUE, new InterfaceApiFilter(apiBaseUri));
=======
//
environment.addVariable("HASOR_DATAQL_DATAWAY_API_URL", apiBaseUri);
apiBinder.filter(fixUrl(apiBaseUri + "/*")).through(Integer.MAX_VALUE, new InterfaceApiFilter(apiBaseUri, uiBaseUri));
>>>>>>>
apiBinder.filter(fixUrl(apiBaseUri + "/*")).through(Integer.MAX_VALUE, new InterfaceApiFilter(apiBaseUri));
<<<<<<<
String uiBaseUri = settings.getString("hasor.dataway.baseAdminUrl", "/interface-ui/");
if (!uiBaseUri.endsWith("/")) {
uiBaseUri = uiBaseUri + "/";
}
=======
>>>>>>>
String uiBaseUri = settings.getString("hasor.dataway.baseAdminUrl", "/interface-ui/");
if (!uiBaseUri.endsWith("/")) {
uiBaseUri = uiBaseUri + "/";
} |
<<<<<<<
/**
* This is a potentially unsafe method for generating liner combinations, where if the linear combination is known,
* it maybe possible to find subspace kernels that reaveal information about the remaining variables. It is fine
* for the purposes for generating the hash function for indexing.
* @param inputLength
* @param outputLength
* @return
*/
public static SimplePolynomialFunction unsafeRandomManyToOneLinearCombination( int inputLength, int outputLength ) {
return EnhancedBitMatrix.randomMatrix( outputLength , inputLength ).multiply( PolynomialFunctions.identity( inputLength ) );
}
public static SimplePolynomialFunction linearCombination( EnhancedBitMatrix c1 , EnhancedBitMatrix c2 ) {
return c1.multiply( lowerIdentity( c1.cols() << 1) )
.xor( c2.multiply( upperIdentity( c2.cols() << 1 ) ) );
=======
public static Pair<SimplePolynomialFunction, SimplePolynomialFunction> randomlyPartitionMVQ(
SimplePolynomialFunction f) {
Preconditions.checkArgument(f.getMaximumMonomialOrder() == 2);
SimplePolynomialFunction g = denseRandomMultivariateQuadratic(f.getInputLength(), f.getOutputLength());
SimplePolynomialFunction h = f.xor(g);
return Pair.of(g, h);
>>>>>>>
/**
* This is a potentially unsafe method for generating liner combinations, where if the linear combination is known,
* it maybe possible to find subspace kernels that reaveal information about the remaining variables. It is fine
* for the purposes for generating the hash function for indexing.
* @param inputLength
* @param outputLength
* @return
*/
public static SimplePolynomialFunction unsafeRandomManyToOneLinearCombination( int inputLength, int outputLength ) {
return EnhancedBitMatrix.randomMatrix( outputLength , inputLength ).multiply( PolynomialFunctions.identity( inputLength ) );
}
public static SimplePolynomialFunction linearCombination( EnhancedBitMatrix c1 , EnhancedBitMatrix c2 ) {
return c1.multiply( lowerIdentity( c1.cols() << 1) )
.xor( c2.multiply( upperIdentity( c2.cols() << 1 ) ) );
}
public static Pair<SimplePolynomialFunction, SimplePolynomialFunction> randomlyPartitionMVQ(
SimplePolynomialFunction f) {
Preconditions.checkArgument(f.getMaximumMonomialOrder() == 2);
SimplePolynomialFunction g = denseRandomMultivariateQuadratic(f.getInputLength(), f.getOutputLength());
SimplePolynomialFunction h = f.xor(g);
return Pair.of(g, h); |
<<<<<<<
=======
// SimplePolynomialFunction composedRight = outer.partialComposeRight(inner);
>>>>>>>
<<<<<<<
=======
BitVector rightInnerResult = inner.apply(innerInput);
BitVector composedRightExpected = outer.apply(remainderInput, rightInnerResult);
// BitVector composedRightFound = composedRight.apply(remainderInput, innerInput);
// Assert.assertEquals(composedRightExpected, composedRightFound);
>>>>>>> |
<<<<<<<
player.getRoot().addWindow(new Window("Testwindow"));
=======
addComponent(new Button("Remove pdf", new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
removeComponent(player);
}
}));
player.getWindow().addWindow(new Window("Testwindow"));
>>>>>>>
addComponent(new Button("Remove pdf", new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
removeComponent(player);
}
}));
player.getRoot().addWindow(new Window("Testwindow")); |
<<<<<<<
=======
import com.vaadin.flow.router.RouteParameters;
>>>>>>>
import com.vaadin.flow.router.RouteParameters;
<<<<<<<
=======
import elemental.json.JsonValue;
>>>>>>>
import elemental.json.JsonValue;
<<<<<<<
=======
>>>>>>>
<<<<<<<
// Change the UI according to the navigation Component chain.
ui.getInternals().showRouteTarget(event.getLocation(),
navigationState.getResolvedPath(), componentInstance,
routerLayouts);
=======
// Change the UI according to the navigation Component chain.
ui.getInternals().showRouteTarget(event.getLocation(),
componentInstance, routerLayouts);
>>>>>>>
// Change the UI according to the navigation Component chain.
ui.getInternals().showRouteTarget(event.getLocation(),
componentInstance, routerLayouts);
<<<<<<<
=======
private void pushHistoryStateIfNeeded(NavigationEvent event, UI ui) {
if (event instanceof ErrorNavigationEvent) {
return;
}
if (NavigationTrigger.ROUTER_LINK.equals(event.getTrigger())) {
/*
* When the event trigger is a RouterLink, pushing history state
* should be done in client-side. See
* ScrollPositionHandler#afterNavigation(JsonObject).
*/
JsonValue state = event.getState()
.orElseThrow(() -> new IllegalStateException(
"When the navigation trigger is ROUTER_LINK, event state should not be null."));
ui.getPage().executeJs(
"this.scrollPositionHandlerAfterServerNavigation($0);",
state);
} else if (!event.isForwardTo()
&& (!ui.getInternals().hasLastHandledLocation()
|| !event.getLocation().getPathWithQueryParameters()
.equals(ui.getInternals()
.getLastHandledLocation()
.getPathWithQueryParameters()))) {
if (shouldPushHistoryState(event)) {
pushHistoryState(event);
}
ui.getInternals().setLastHandledNavigation(event.getLocation());
}
}
protected void pushHistoryState(NavigationEvent event) {
// Enable navigating back
event.getUI().getPage().getHistory().pushState(null, event.getLocation());
}
protected boolean shouldPushHistoryState(NavigationEvent event) {
return NavigationTrigger.UI_NAVIGATE.equals(event.getTrigger());
}
>>>>>>>
private void pushHistoryStateIfNeeded(NavigationEvent event, UI ui) {
if (event instanceof ErrorNavigationEvent) {
return;
}
if (NavigationTrigger.ROUTER_LINK.equals(event.getTrigger())) {
/*
* When the event trigger is a RouterLink, pushing history state
* should be done in client-side. See
* ScrollPositionHandler#afterNavigation(JsonObject).
*/
JsonValue state = event.getState()
.orElseThrow(() -> new IllegalStateException(
"When the navigation trigger is ROUTER_LINK, event state should not be null."));
ui.getPage().executeJs(
"this.scrollPositionHandlerAfterServerNavigation($0);",
state);
} else if (!event.isForwardTo()
&& (!ui.getInternals().hasLastHandledLocation()
|| !event.getLocation().getPathWithQueryParameters()
.equals(ui.getInternals()
.getLastHandledLocation()
.getPathWithQueryParameters()))) {
if (shouldPushHistoryState(event)) {
pushHistoryState(event);
}
ui.getInternals().setLastHandledNavigation(event.getLocation());
}
}
protected void pushHistoryState(NavigationEvent event) {
// Enable navigating back
event.getUI().getPage().getHistory().pushState(null, event.getLocation());
}
protected boolean shouldPushHistoryState(NavigationEvent event) {
return NavigationTrigger.UI_NAVIGATE.equals(event.getTrigger());
}
<<<<<<<
private Optional<Integer> executeBeforeLeaveNavigation(NavigationEvent event,
BeforeLeaveEvent beforeNavigation) {
Deque<BeforeLeaveHandler> leaveHandlers = getBeforeLeaveHandlers(
beforeNavigation.getUI());
while (!leaveHandlers.isEmpty()) {
=======
private Optional<Integer> executeBeforeLeaveNavigation(
NavigationEvent event, BeforeLeaveEvent beforeNavigation) {
Deque<BeforeLeaveHandler> leaveHandlers = getBeforeLeaveHandlers(
beforeNavigation.getUI());
while (!leaveHandlers.isEmpty()) {
>>>>>>>
private Optional<Integer> executeBeforeLeaveNavigation(
NavigationEvent event, BeforeLeaveEvent beforeNavigation) {
Deque<BeforeLeaveHandler> leaveHandlers = getBeforeLeaveHandlers(
beforeNavigation.getUI());
while (!leaveHandlers.isEmpty()) {
<<<<<<<
Optional<Integer> result = sendBeforeEnterEvent(
registeredEnterHandlers, event, beforeNavigation, null);
if (result.isPresent()) {
return result;
=======
Optional<Integer> result = sendBeforeEnterEvent(registeredEnterHandlers,
event, beforeNavigation, null);
if (result.isPresent()) {
return result;
>>>>>>>
Optional<Integer> result = sendBeforeEnterEvent(registeredEnterHandlers,
event, beforeNavigation, null);
if (result.isPresent()) {
return result;
<<<<<<<
Optional<Integer> result = sendBeforeEnterEvent(chainEnterHandlers,
event, beforeNavigation, lastElement ? chain : null);
if (result.isPresent()) {
return result;
=======
Optional<Integer> result = sendBeforeEnterEvent(
chainEnterHandlers, event, beforeNavigation,
lastElement ? chain : null);
if (result.isPresent()) {
return result;
>>>>>>>
Optional<Integer> result = sendBeforeEnterEvent(
chainEnterHandlers, event, beforeNavigation,
lastElement ? chain : null);
if (result.isPresent()) {
return result;
<<<<<<<
Optional<Integer> result = notifyNavigationTarget(
event, beforeNavigation, locationChangeEvent,
=======
Optional<Integer> result = notifyNavigationTarget(event,
beforeNavigation, locationChangeEvent,
>>>>>>>
Optional<Integer> result = notifyNavigationTarget(event,
beforeNavigation, locationChangeEvent,
<<<<<<<
Optional<Integer> result = notifyNavigationTarget(
event, beforeNavigation, locationChangeEvent,
componentInstance);
if (result.isPresent()) {
return result;
=======
Optional<Integer> result = notifyNavigationTarget(event,
beforeNavigation, locationChangeEvent, componentInstance);
if (result.isPresent()) {
return result;
>>>>>>>
Optional<Integer> result = notifyNavigationTarget(event,
beforeNavigation, locationChangeEvent, componentInstance);
if (result.isPresent()) {
return result;
<<<<<<<
private Optional<Integer> notifyNavigationTarget(
NavigationEvent event, BeforeEnterEvent beforeNavigation,
=======
private Optional<Integer> notifyNavigationTarget(NavigationEvent event,
BeforeEnterEvent beforeNavigation,
>>>>>>>
private Optional<Integer> notifyNavigationTarget(NavigationEvent event,
BeforeEnterEvent beforeNavigation,
<<<<<<<
/**
* Handle a {@link BeforeEvent} after if has been triggered to an observer.
*
* @param event
* the navigation event being handled.
* @param beforeEvent
* the {@link BeforeLeaveEvent} or {@link BeforeEnterEvent} being
* triggered to an observer.
* @return a HTTP status code wrapped as an {@link Optional}. If the
* {@link Optional} is empty, the process will proceed with next
* observer or just move forward, otherwise the process will return
* immediately with the provided http code.
* @see HttpServletResponse
*/
protected Optional<Integer> handleTriggeredBeforeEvent(
NavigationEvent event, BeforeEvent beforeEvent) {
=======
/**
* Handle a {@link BeforeEvent} after if has been triggered to an observer.
*
* @param event
* the navigation event being handled.
* @param beforeEvent
* the {@link BeforeLeaveEvent} or {@link BeforeEnterEvent} being
* triggered to an observer.
* @return a HTTP status code wrapped as an {@link Optional}. If the
* {@link Optional} is empty, the process will proceed with next
* observer or just move forward, otherwise the process will return
* immediately with the provided http code.
* @see HttpServletResponse
*/
protected Optional<Integer> handleTriggeredBeforeEvent(
NavigationEvent event, BeforeEvent beforeEvent) {
>>>>>>>
/**
* Handle a {@link BeforeEvent} after if has been triggered to an observer.
*
* @param event
* the navigation event being handled.
* @param beforeEvent
* the {@link BeforeLeaveEvent} or {@link BeforeEnterEvent} being
* triggered to an observer.
* @return a HTTP status code wrapped as an {@link Optional}. If the
* {@link Optional} is empty, the process will proceed with next
* observer or just move forward, otherwise the process will return
* immediately with the provided http code.
* @see HttpServletResponse
*/
protected Optional<Integer> handleTriggeredBeforeEvent(
NavigationEvent event, BeforeEvent beforeEvent) {
<<<<<<<
beforeEvent.getForwardTargetRouteParameters())) {
return Optional.of(forward(event, beforeEvent));
=======
beforeEvent.getForwardTargetRouteParameters())) {
return Optional.of(forward(event, beforeEvent));
>>>>>>>
beforeEvent.getForwardTargetRouteParameters())) {
return Optional.of(forward(event, beforeEvent));
<<<<<<<
final boolean sameParameters = targetParameters.equals(navigationState
.getRouteParameters());
=======
final boolean sameParameters = targetParameters
.equals(navigationState.getRouteParameters());
>>>>>>>
final boolean sameParameters = targetParameters
.equals(navigationState.getRouteParameters());
<<<<<<<
if (url == null) {
final String redirectType;
final Class<? extends Component> redirectTarget;
final RouteParameters redirectParameters;
if (isForward) {
redirectType = "forward";
redirectTarget = beforeNavigation.getForwardTargetType();
redirectParameters = beforeNavigation.getForwardTargetRouteParameters();
} else {
redirectType = "reroute";
redirectTarget = beforeNavigation.getRerouteTargetType();
redirectParameters = beforeNavigation.getRerouteTargetRouteParameters();
}
=======
if (url == null) {
final String redirectType;
final Class<? extends Component> redirectTarget;
final RouteParameters redirectParameters;
if (isForward) {
redirectType = "forward";
redirectTarget = beforeNavigation.getForwardTargetType();
redirectParameters = beforeNavigation
.getForwardTargetRouteParameters();
} else {
redirectType = "reroute";
redirectTarget = beforeNavigation.getRerouteTargetType();
redirectParameters = beforeNavigation
.getRerouteTargetRouteParameters();
}
>>>>>>>
if (url == null) {
final String redirectType;
final Class<? extends Component> redirectTarget;
final RouteParameters redirectParameters;
if (isForward) {
redirectType = "forward";
redirectTarget = beforeNavigation.getForwardTargetType();
redirectParameters = beforeNavigation
.getForwardTargetRouteParameters();
} else {
redirectType = "reroute";
redirectTarget = beforeNavigation.getRerouteTargetType();
redirectParameters = beforeNavigation
.getRerouteTargetRouteParameters();
} |
<<<<<<<
service(createWrappedRequest(request), createWrappedResponse(response));
}
private void service(WrappedHttpServletRequest request,
WrappedHttpServletResponse response) throws ServletException,
IOException {
AbstractApplicationServletWrapper servletWrapper = new AbstractApplicationServletWrapper(
this);
RequestTimer requestTimer = RequestTimer.get(request);
requestTimer.start(request);
=======
RequestTimer requestTimer = new RequestTimer();
requestTimer.start();
>>>>>>>
service(createWrappedRequest(request), createWrappedResponse(response));
}
private void service(WrappedHttpServletRequest request,
WrappedHttpServletResponse response) throws ServletException,
IOException {
RequestTimer requestTimer = new RequestTimer();
requestTimer.start();
AbstractApplicationServletWrapper servletWrapper = new AbstractApplicationServletWrapper(
this); |
<<<<<<<
private File defaultJavaSource;
private File generatedTsFolder;
=======
private MavenProject project;
>>>>>>>
private File defaultJavaSource;
private File generatedTsFolder;
private MavenProject project;
<<<<<<<
=======
project = Mockito.mock(MavenProject.class);
Mockito.when(project.getBasedir()).thenReturn(projectBase);
>>>>>>>
project = Mockito.mock(MavenProject.class);
Mockito.when(project.getBasedir()).thenReturn(projectBase); |
<<<<<<<
=======
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Optional;
>>>>>>>
<<<<<<<
private static class StubServletConfig implements ServletConfig {
=======
/**
* Default ServletConfig implementation.
*/
public static class StubServletConfig
implements ServletConfig {
>>>>>>>
/**
* Default ServletConfig implementation.
*/
public static class StubServletConfig
implements ServletConfig {
<<<<<<<
private DeploymentConfiguration createDeploymentConfiguration(
ServletConfig servletConfig, Class<?> servletClass) {
try {
return DeploymentConfigurationFactory
.createPropertyDeploymentConfiguration(servletClass,
servletConfig);
} catch (ServletException e) {
throw new IllegalStateException(String.format(
"Failed to get deployment configuration data for servlet with name '%s' and class '%s'",
servletConfig.getServletName(), servletClass), e);
}
}
=======
>>>>>>>
private DeploymentConfiguration createDeploymentConfiguration(
ServletConfig servletConfig, Class<?> servletClass) {
try {
return DeploymentConfigurationFactory
.createPropertyDeploymentConfiguration(servletClass,
servletConfig);
} catch (ServletException e) {
throw new IllegalStateException(String.format(
"Failed to get deployment configuration data for servlet with name '%s' and class '%s'",
servletConfig.getServletName(), servletClass), e);
}
}
<<<<<<<
boolean createServlet = ApplicationRouteRegistry.getInstance(context)
.hasNavigationTargets();
createServlet = createServlet || WebComponentConfigurationRegistry
.getInstance(context).hasConfigurations();
if (!createServlet) {
=======
boolean createServlet = ApplicationRouteRegistry.getInstance(context)
.hasNavigationTargets();
createServlet = createServlet || WebComponentConfigurationRegistry
.getInstance(context).hasExporters();
if (!createServlet) {
>>>>>>>
boolean createServlet = ApplicationRouteRegistry.getInstance(context)
.hasNavigationTargets();
createServlet = createServlet || WebComponentConfigurationRegistry
.getInstance(context).hasConfigurations();
if (!createServlet) { |
<<<<<<<
=======
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.VConsole;
>>>>>>>
import com.vaadin.terminal.gwt.client.BrowserInfo; |
<<<<<<<
private boolean rowCacheInvalidated;
private RowGenerator rowGenerator = null;
=======
private final Map<Field, Property> associatedProperties = new HashMap<Field, Property>();
>>>>>>>
private boolean rowCacheInvalidated;
private RowGenerator rowGenerator = null;
private final Map<Field, Property> associatedProperties = new HashMap<Field, Property>(); |
<<<<<<<
=======
String contentType = response.getHeader("Content-Type");
if (contentType == null
|| !contentType.startsWith("application/json")) {
/*
* A servlet filter or equivalent may have intercepted
* the request and served non-UIDL content (for
* instance, a login page if the session has expired.)
* If the response contains a magic substring, do a
* synchronous refresh. See #8241.
*/
MatchResult refreshToken = RegExp.compile(
UIDL_REFRESH_TOKEN + "(:\\s*(.*?))?(\\s|$)")
.exec(response.getText());
if (refreshToken != null) {
redirect(refreshToken.getGroup(2));
return;
}
}
final Date start = new Date();
>>>>>>>
String contentType = response.getHeader("Content-Type");
if (contentType == null
|| !contentType.startsWith("application/json")) {
/*
* A servlet filter or equivalent may have intercepted
* the request and served non-UIDL content (for
* instance, a login page if the session has expired.)
* If the response contains a magic substring, do a
* synchronous refresh. See #8241.
*/
MatchResult refreshToken = RegExp.compile(
UIDL_REFRESH_TOKEN + "(:\\s*(.*?))?(\\s|$)")
.exec(response.getText());
if (refreshToken != null) {
redirect(refreshToken.getGroup(2));
return;
}
}
<<<<<<<
TooltipInfo tooltipInfo = paintableMap.getTooltipInfo(paintable, null);
// Update tooltip
if (uidl.hasAttribute(ATTRIBUTE_DESCRIPTION)) {
tooltipInfo
.setTitle(uidl.getStringAttribute(ATTRIBUTE_DESCRIPTION));
} else {
tooltipInfo.setTitle(null);
}
// add error classname to components w/ error
=======
>>>>>>>
// add error classname to components w/ error
<<<<<<<
// Styles + disabled & readonly
component.setStyleName(styleBuf.toString());
// Set captions
if (manageCaption) {
final Container parent = Util.getLayout(component);
if (parent != null) {
parent.updateCaption(paintable, uidl);
}
}
/*
* updateComponentSize need to be after caption update so caption can be
* taken into account
*/
updateComponentSize(paintable, uidl);
=======
return styleBuf.toString();
>>>>>>>
return styleBuf.toString(); |
<<<<<<<
columnsUpdatedFromState = true;
=======
>>>>>>>
columnsUpdatedFromState = true;
<<<<<<<
columnsUpdatedFromState = false;
if (columnState.rendererConnector != column.getRendererConnector()) {
throw new UnsupportedOperationException(
"Changing column renderer after initialization is currently unsupported");
}
=======
>>>>>>>
columnsUpdatedFromState = false; |
<<<<<<<
import static com.vaadin.flow.server.frontend.FrontendUtils.DEAULT_FLOW_RESOURCES_FOLDER;
=======
import static com.vaadin.flow.server.Constants.CONNECT_JAVA_SOURCE_FOLDER_TOKEN;
import static com.vaadin.flow.server.Constants.CONNECT_APPLICATION_PROPERTIES_TOKEN;
import static com.vaadin.flow.server.Constants.CONNECT_OPEN_API_FILE_TOKEN;
import static com.vaadin.flow.server.Constants.CONNECT_GENERATED_TS_DIR_TOKEN;
import static com.vaadin.flow.server.frontend.FrontendUtils.DEFAULT_FLOW_RESOURCES_FOLDER;
>>>>>>>
import static com.vaadin.flow.server.frontend.FrontendUtils.DEFAULT_FLOW_RESOURCES_FOLDER; |
<<<<<<<
this.pwaConfiguration = pwaConfiguration;
this.resourceFolder = new File(webpackOutputDirectory.getParentFile(), "resources").toPath();
=======
this.resourceFolder = new File(webpackOutputDirectory.getParentFile(),
VAADIN_STATIC_FILES_PATH).toPath();
>>>>>>>
this.pwaConfiguration = pwaConfiguration;
this.resourceFolder = new File(webpackOutputDirectory.getParentFile(),
VAADIN_STATIC_FILES_PATH).toPath(); |
<<<<<<<
* @param T
* type of the underlying property (a PropertyFormatter is always a
* Property<String>)
*
* @author IT Mill Ltd.
=======
* @author Vaadin Ltd.
>>>>>>>
* @param T
* type of the underlying property (a PropertyFormatter is always a
* Property<String>)
*
* @author Vaadin Ltd. |
<<<<<<<
builder.tokenFileData, builder.disablePnpm));
=======
builder.tokenFileData));
}
}
private void addBootstrapTasks(Builder builder) {
File outputDirectory = new File(builder.npmFolder,
FrontendUtils.TARGET);
TaskGenerateIndexHtml taskGenerateIndexHtml = new TaskGenerateIndexHtml(
builder.frontendDirectory, outputDirectory);
commands.add(taskGenerateIndexHtml);
TaskGenerateIndexTs taskGenerateIndexTs = new TaskGenerateIndexTs(
builder.frontendDirectory,
new File(builder.generatedFolder, IMPORTS_NAME),
outputDirectory);
commands.add(taskGenerateIndexTs);
TaskGenerateTsConfig taskGenerateTsConfig = new TaskGenerateTsConfig(
builder.frontendDirectory, builder.npmFolder, outputDirectory);
commands.add(taskGenerateTsConfig);
}
>>>>>>>
builder.tokenFileData, builder.disablePnpm));
}
}
private void addBootstrapTasks(Builder builder) {
File outputDirectory = new File(builder.npmFolder,
FrontendUtils.TARGET);
TaskGenerateIndexHtml taskGenerateIndexHtml = new TaskGenerateIndexHtml(
builder.frontendDirectory, outputDirectory);
commands.add(taskGenerateIndexHtml);
TaskGenerateIndexTs taskGenerateIndexTs = new TaskGenerateIndexTs(
builder.frontendDirectory,
new File(builder.generatedFolder, IMPORTS_NAME),
outputDirectory);
commands.add(taskGenerateIndexTs);
TaskGenerateTsConfig taskGenerateTsConfig = new TaskGenerateTsConfig(
builder.frontendDirectory, builder.npmFolder, outputDirectory);
commands.add(taskGenerateTsConfig);
} |
<<<<<<<
import com.vaadin.flow.server.connect.Endpoint;
import com.vaadin.flow.server.frontend.FrontendTools;
import com.vaadin.flow.server.frontend.installer.NodeInstaller;
=======
>>>>>>>
import com.vaadin.flow.server.frontend.FrontendTools;
import com.vaadin.flow.server.frontend.installer.NodeInstaller; |
<<<<<<<
getScanner(classFinder), baseDir, generatedDir, resourcesDir, false);
=======
getScanner(classFinder), baseDir, generatedDir, false, true);
>>>>>>>
getScanner(classFinder), baseDir, generatedDir, resourcesDir, false, true);
<<<<<<<
public void versionsDoNotMatch_inMainJson_cleanUp() throws IOException {
FrontendDependencies frontendDependencies = Mockito
.mock(FrontendDependencies.class);
Map<String, String> packages = new HashMap<>();
packages.put("@polymer/iron-list", "3.0.2");
packages.put("@vaadin/vaadin-confirm-dialog", "1.1.4");
packages.put("@vaadin/vaadin-checkbox", "2.2.10");
packages.put("@polymer/iron-icon", "3.0.1");
packages.put("@vaadin/vaadin-time-picker", "2.0.2");
packages.put(SHRINKWRAP, "1.2.3");
Mockito.when(frontendDependencies.getPackages()).thenReturn(packages);
packageUpdater = new TaskUpdatePackages(null, frontendDependencies,
baseDir, generatedDir, null, false);
// Generate package json in a proper format first
packageCreator.execute();
makeNodeModulesAndPackageLock();
JsonObject packageJson = getPackageJson(this.packageJson);
packageJson.put(SHRINKWRAP, "1.1.1");
Files.write(packageLock.toPath(),
Collections.singletonList(stringify(packageJson)));
=======
public void versionsDoNotMatch_inMainJson_npm_cleanUp() throws IOException {
versionsDoNotMatch_inMainJson_cleanUp(true);
assertVersionAndCleanUp();
}
>>>>>>>
public void versionsDoNotMatch_inMainJson_npm_cleanUp() throws IOException {
versionsDoNotMatch_inMainJson_cleanUp(true);
assertVersionAndCleanUp();
}
<<<<<<<
baseDir, generatedDir, null, false);
=======
baseDir, generatedDir, false, true);
>>>>>>>
baseDir, generatedDir, null, false, true);
<<<<<<<
getScanner(classFinder), baseDir, generatedDir, null, true);
=======
getScanner(classFinder), baseDir, generatedDir, true, true);
>>>>>>>
getScanner(classFinder), baseDir, generatedDir, null, true, true);
<<<<<<<
baseDir, generatedDir, null, false);
=======
baseDir, generatedDir, false, true);
>>>>>>>
baseDir, generatedDir, null, false, true);
<<<<<<<
baseDir, generatedDir, null, false);
=======
baseDir, generatedDir, false, true);
>>>>>>>
baseDir, generatedDir, null, false, true);
<<<<<<<
baseDir, generatedDir, null, false);
=======
baseDir, generatedDir, false, true);
>>>>>>>
baseDir, generatedDir, null, false, true);
<<<<<<<
baseDir, generatedDir, null, false);
=======
baseDir, generatedDir, false, true);
>>>>>>>
baseDir, generatedDir, null, false, true);
<<<<<<<
baseDir, generatedDir, null, false);
=======
baseDir, generatedDir, false, true);
>>>>>>>
baseDir, generatedDir, null, false, true);
<<<<<<<
baseDir, generatedDir, null, false);
=======
baseDir, generatedDir, false, true);
>>>>>>>
baseDir, generatedDir, null, false, true);
<<<<<<<
baseDir, generatedDir, null, false);
=======
baseDir, generatedDir, false, true);
>>>>>>>
baseDir, generatedDir, null, false, true);
<<<<<<<
baseDir, generatedDir, null, false);
=======
baseDir, generatedDir, false, true);
>>>>>>>
baseDir, generatedDir, null, false, true);
<<<<<<<
baseDir, generatedDir, null, false);
=======
baseDir, generatedDir, false, true);
>>>>>>>
baseDir, generatedDir, null, false, true);
<<<<<<<
Assert.assertTrue("Missing @webcomponents/webcomponentsjs package",
dependencies.hasKey("@webcomponents/webcomponentsjs"));
JsonObject devDependencies = json.getObject("devDependencies");
Assert.assertTrue("Missing webpack dev package",
devDependencies.hasKey("webpack"));
Assert.assertTrue("Missing webpack-cli dev package",
devDependencies.hasKey("webpack-cli"));
Assert.assertTrue("Missing webpack-dev-server dev package",
devDependencies.hasKey("webpack-dev-server"));
Assert.assertTrue(
"Missing webpack-babel-multi-target-plugin dev package",
devDependencies.hasKey("webpack-babel-multi-target-plugin"));
Assert.assertTrue("Missing copy-webpack-plugin dev package",
devDependencies.hasKey("copy-webpack-plugin"));
Assert.assertTrue("Missing html-webpack-plugin dev package",
devDependencies.hasKey("html-webpack-plugin"));
=======
for (Map.Entry<String, String> entry : NodeUpdater
.getDefaultDependencies().entrySet()) {
Assert.assertTrue("Missing '" + entry.getKey() + "' package",
dependencies.hasKey(entry.getKey()));
}
JsonObject devDependencies = json.getObject(DEV_DEPENDENCIES);
for (Map.Entry<String, String> entry : NodeUpdater
.getDefaultDevDependencies().entrySet()) {
Assert.assertTrue("Missing '" + entry.getKey() + "' package",
devDependencies.hasKey(entry.getKey()));
}
>>>>>>>
for (Map.Entry<String, String> entry : NodeUpdater
.getDefaultDependencies().entrySet()) {
Assert.assertTrue("Missing '" + entry.getKey() + "' package",
dependencies.hasKey(entry.getKey()));
}
JsonObject devDependencies = json.getObject(DEV_DEPENDENCIES);
for (Map.Entry<String, String> entry : NodeUpdater
.getDefaultDevDependencies().entrySet()) {
Assert.assertTrue("Missing '" + entry.getKey() + "' package",
devDependencies.hasKey(entry.getKey()));
} |
<<<<<<<
private static final Logger logger = Logger
.getLogger(AbstractCommunicationManager.class.getName());
private static final RequestHandler APP_RESOURCE_HANDLER = new ApplicationResourceHandler();
=======
/**
* Generic interface of a (HTTP or Portlet) request to the application.
*
* This is a wrapper interface that allows
* {@link AbstractCommunicationManager} to use a unified API.
*
* @see javax.servlet.ServletRequest
* @see javax.portlet.PortletRequest
*
* @author peholmst
*/
public interface Request {
/**
* Gets a {@link Session} wrapper implementation representing the
* session for which this request was sent.
*
* Multiple Vaadin applications can be associated with a single session.
*
* @return Session
*/
public Session getSession();
/**
* Are the applications in this session running in a portlet or directly
* as servlets.
*
* @return true if in a portlet
*/
public boolean isRunningInPortlet();
/**
* Get the named HTTP or portlet request parameter.
*
* @see javax.servlet.ServletRequest#getParameter(String)
* @see javax.portlet.PortletRequest#getParameter(String)
*
* @param name
* @return
*/
public String getParameter(String name);
/**
* Returns the length of the request content that can be read from the
* input stream returned by {@link #getInputStream()}.
*
* @return content length in bytes
*/
public int getContentLength();
/**
* Returns an input stream from which the request content can be read.
* The request content length can be obtained with
* {@link #getContentLength()} without reading the full stream contents.
*
* @return
* @throws IOException
*/
public InputStream getInputStream() throws IOException;
/**
* Returns the request identifier that identifies the target Vaadin
* window for the request.
*
* @return String identifier for the request target window
*/
public String getRequestID();
/**
* @see javax.servlet.ServletRequest#getAttribute(String)
* @see javax.portlet.PortletRequest#getAttribute(String)
*/
public Object getAttribute(String name);
/**
* @see javax.servlet.ServletRequest#setAttribute(String, Object)
* @see javax.portlet.PortletRequest#setAttribute(String, Object)
*/
public void setAttribute(String name, Object value);
/**
* Gets the underlying request object. The request is typically either a
* {@link ServletRequest} or a {@link PortletRequest}.
*
* @return wrapped request object
*/
public Object getWrappedRequest();
}
/**
* Generic interface of a (HTTP or Portlet) response from the application.
*
* This is a wrapper interface that allows
* {@link AbstractCommunicationManager} to use a unified API.
*
* @see javax.servlet.ServletResponse
* @see javax.portlet.PortletResponse
*
* @author peholmst
*/
public interface Response {
/**
* Gets the output stream to which the response can be written.
*
* @return
* @throws IOException
*/
public OutputStream getOutputStream() throws IOException;
/**
* Sets the MIME content type for the response to be communicated to the
* browser.
*
* @param type
*/
public void setContentType(String type);
/**
* Gets the wrapped response object, usually a class implementing either
* {@link ServletResponse} or {@link PortletResponse}.
*
* @return wrapped request object
*/
public Object getWrappedResponse();
}
/**
* Generic wrapper interface for a (HTTP or Portlet) session.
*
* Several applications can be associated with a single session.
*
* TODO Document me!
*
* @see javax.servlet.http.HttpSession
* @see javax.portlet.PortletSession
*
* @author peholmst
*/
protected interface Session {
public boolean isNew();
public Object getAttribute(String name);
public void setAttribute(String name, Object o);
>>>>>>>
private static final RequestHandler APP_RESOURCE_HANDLER = new ApplicationResourceHandler();
<<<<<<<
logger.warning("Could not get root for application");
=======
getLogger().warning(
"Could not get window for application with request ID "
+ request.getRequestID());
>>>>>>>
getLogger().warning("Could not get root for application");
<<<<<<<
=======
private static final Logger getLogger() {
return Logger.getLogger(AbstractCommunicationManager.class.getName());
}
>>>>>>>
private static final Logger getLogger() {
return Logger.getLogger(AbstractCommunicationManager.class.getName());
} |
<<<<<<<
@Override
protected String getImportsNotFoundMessage() {
return getAbsentPackagesMessage();
}
=======
protected List<String> getDefinitionLines() {
List<String> lines = new ArrayList<>();
addLines(lines, EXPORT_MODULES_DEF);
return lines;
}
>>>>>>>
@Override
protected String getImportsNotFoundMessage() {
return getAbsentPackagesMessage();
}
protected List<String> getDefinitionLines() {
List<String> lines = new ArrayList<>();
addLines(lines, EXPORT_MODULES_DEF);
return lines;
}
<<<<<<<
File tokenFile, JsonObject tokenFileData, boolean disablePnpm) {
super(finder, frontendDepScanner, npmFolder, generatedPath);
=======
File tokenFile, JsonObject tokenFileData) {
super(finder, frontendDepScanner, npmFolder, generatedPath, null);
>>>>>>>
File tokenFile, JsonObject tokenFileData, boolean disablePnpm) {
super(finder, frontendDepScanner, npmFolder, generatedPath, null); |
<<<<<<<
import com.vaadin.terminal.gwt.client.MeasureManager.MeasuredSize;
=======
import com.vaadin.terminal.gwt.client.TooltipInfo;
import com.vaadin.terminal.gwt.client.UIDL;
>>>>>>>
import com.vaadin.terminal.gwt.client.MeasureManager.MeasuredSize;
import com.vaadin.terminal.gwt.client.TooltipInfo;
import com.vaadin.terminal.gwt.client.UIDL;
<<<<<<<
private VPaintableWidgetContainer parent;
private final MeasuredSize measuredSize = new MeasuredSize();
=======
>>>>>>>
private final MeasuredSize measuredSize = new MeasuredSize();
<<<<<<<
if (parent != null) {
return parent;
}
=======
>>>>>>> |
<<<<<<<
import com.vaadin.flow.server.VaadinRequest;
import com.vaadin.flow.server.VaadinServletRequest;
import com.vaadin.flow.uitest.servlet.ViewTestLayout;
import com.vaadin.flow.router.Route;
=======
>>>>>>> |
<<<<<<<
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
=======
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
>>>>>>>
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
<<<<<<<
=======
>>>>>>>
<<<<<<<
WebComponentConfigurationRegistry registry = WebComponentConfigurationRegistry
.getInstance(this.getContext());
return registry.hasConfigurations();
=======
WebComponentConfigurationRegistry registry = WebComponentConfigurationRegistry
.getInstance(getContext());
return registry.hasConfigurations();
>>>>>>>
WebComponentConfigurationRegistry registry = WebComponentConfigurationRegistry
.getInstance(getContext());
return registry.hasConfigurations(); |
<<<<<<<
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
=======
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
>>>>>>>
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
<<<<<<<
public class VTwinColSelect extends VOptionGroupBase implements KeyDownHandler {
=======
public class VTwinColSelect extends VOptionGroupBase implements
MouseDownHandler {
>>>>>>>
public class VTwinColSelect extends VOptionGroupBase implements KeyDownHandler, MouseDownHandler {
<<<<<<<
options.addKeyDownHandler(this);
selections.addKeyDownHandler(this);
=======
options.addMouseDownHandler(this);
selections.addMouseDownHandler(this);
>>>>>>>
options.addKeyDownHandler(this);
options.addMouseDownHandler(this);
selections.addMouseDownHandler(this);
selections.addKeyDownHandler(this);
<<<<<<<
/**
* Get the key that selects an item in the table. By default it is the Enter
* key but by overriding this you can change the key to whatever you want.
*
* @return
*/
protected int getNavigationSelectKey() {
return KeyCodes.KEY_ENTER;
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
* .event.dom.client.KeyDownEvent)
*/
public void onKeyDown(KeyDownEvent event) {
int keycode = event.getNativeKeyCode();
// Catch tab and move between select:s
if (keycode == KeyCodes.KEY_TAB && event.getSource() == options) {
// Prevent default behavior
event.preventDefault();
// Remove current selections
for (int i = 0; i < options.getItemCount(); i++) {
options.setItemSelected(i, false);
}
// Focus selections
selections.setFocus(true);
}
if (keycode == KeyCodes.KEY_TAB && event.isShiftKeyDown()
&& event.getSource() == selections) {
// Prevent default behavior
event.preventDefault();
// Remove current selections
for (int i = 0; i < selections.getItemCount(); i++) {
selections.setItemSelected(i, false);
}
// Focus options
options.setFocus(true);
}
if (keycode == getNavigationSelectKey()) {
// Prevent default behavior
event.preventDefault();
// Decide which select the selection was made in
if (event.getSource() == options) {
// Prevents the selection to become a single selection when
// using Enter key
// as the selection key (default)
options.setFocus(false);
addItem();
} else if (event.getSource() == selections) {
// Prevents the selection to become a single selection when
// using Enter key
// as the selection key (default)
selections.setFocus(false);
removeItem();
}
}
}
=======
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.MouseDownHandler#onMouseDown(com.google
* .gwt.event.dom.client.MouseDownEvent)
*/
public void onMouseDown(MouseDownEvent event) {
// Ensure that items are deselected when selecting
// from a different source. See #3699 for details.
if (event.getSource() == options) {
for (int i = 0; i < selections.getItemCount(); i++) {
selections.setItemSelected(i, false);
}
} else if (event.getSource() == selections) {
for (int i = 0; i < options.getItemCount(); i++) {
options.setItemSelected(i, false);
}
}
}
>>>>>>>
/**
* Get the key that selects an item in the table. By default it is the Enter
* key but by overriding this you can change the key to whatever you want.
*
* @return
*/
protected int getNavigationSelectKey() {
return KeyCodes.KEY_ENTER;
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
* .event.dom.client.KeyDownEvent)
*/
public void onKeyDown(KeyDownEvent event) {
int keycode = event.getNativeKeyCode();
// Catch tab and move between select:s
if (keycode == KeyCodes.KEY_TAB && event.getSource() == options) {
// Prevent default behavior
event.preventDefault();
// Remove current selections
for (int i = 0; i < options.getItemCount(); i++) {
options.setItemSelected(i, false);
}
// Focus selections
selections.setFocus(true);
}
if (keycode == KeyCodes.KEY_TAB && event.isShiftKeyDown()
&& event.getSource() == selections) {
// Prevent default behavior
event.preventDefault();
// Remove current selections
for (int i = 0; i < selections.getItemCount(); i++) {
selections.setItemSelected(i, false);
}
// Focus options
options.setFocus(true);
}
if (keycode == getNavigationSelectKey()) {
// Prevent default behavior
event.preventDefault();
// Decide which select the selection was made in
if (event.getSource() == options) {
// Prevents the selection to become a single selection when
// using Enter key
// as the selection key (default)
options.setFocus(false);
addItem();
} else if (event.getSource() == selections) {
// Prevents the selection to become a single selection when
// using Enter key
// as the selection key (default)
selections.setFocus(false);
removeItem();
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.MouseDownHandler#onMouseDown(com.google
* .gwt.event.dom.client.MouseDownEvent)
*/
public void onMouseDown(MouseDownEvent event) {
// Ensure that items are deselected when selecting
// from a different source. See #3699 for details.
if (event.getSource() == options) {
for (int i = 0; i < selections.getItemCount(); i++) {
selections.setItemSelected(i, false);
}
} else if (event.getSource() == selections) {
for (int i = 0; i < options.getItemCount(); i++) {
options.setItemSelected(i, false);
}
}
} |
<<<<<<<
=======
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.communication.RpcProxy;
>>>>>>>
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.communication.RpcProxy;
<<<<<<<
implements BeforeShortcutActionListener, SimpleManagedLayout,
PostLayoutListener, RequiresOverflowAutoFix {
=======
implements Paintable, BeforeShortcutActionListener,
SimpleManagedLayout, PostLayoutListener {
>>>>>>>
implements Paintable, BeforeShortcutActionListener, SimpleManagedLayout,
PostLayoutListener, RequiresOverflowAutoFix { |
<<<<<<<
log.trace(String.format("Using cipher suite \"%s\" with key length %d with RNG \"%s\" and RNG provider \"%s\" and key encryption strategy \"%s\"",
params.getCipherSuite(), params.getKeyLength(), params.getRandomNumberGenerator(), params.getRandomNumberGeneratorProvider(),
params.getKeyEncryptionStrategyClass()));
=======
log.trace(String.format(
"Using cipher suite \"%s\" with key length %d with RNG \"%s\" and RNG provider \"%s\" and key encryption strategy \"%s\"",
cipherTransformation, params.getKeyLength(), params.getRandomNumberGenerator(),
params.getRandomNumberGeneratorProvider(), params.getKeyEncryptionStrategyClass()));
>>>>>>>
log.trace(String.format(
"Using cipher suite \"%s\" with key length %d with RNG \"%s\" and RNG provider \"%s\" and key encryption strategy \"%s\"",
params.getCipherSuite(), params.getKeyLength(), params.getRandomNumberGenerator(),
params.getRandomNumberGeneratorProvider(), params.getKeyEncryptionStrategyClass()));
<<<<<<<
private boolean validateNotEmpty(String givenValue, boolean allIsWell, StringBuilder buf, String errorMessage) {
=======
private String getCipherTransformation(CryptoModuleParameters params) {
String cipherSuite = params.getAlgorithmName() + "/" + params.getEncryptionMode() + "/"
+ params.getPadding();
return cipherSuite;
}
private String[] parseCipherSuite(String cipherSuite) {
return cipherSuite.split("/");
}
private boolean validateNotEmpty(String givenValue, boolean allIsWell, StringBuilder buf,
String errorMessage) {
>>>>>>>
private boolean validateNotEmpty(String givenValue, boolean allIsWell, StringBuilder buf,
String errorMessage) {
<<<<<<<
allIsWell = validateNotEmpty(params.getCipherSuite(), allIsWell, errorBuf, "No cipher suite was specified.");
=======
allIsWell = validateNotEmpty(params.getAlgorithmName(), allIsWell, errorBuf,
"No algorithm name was specified.");
>>>>>>>
allIsWell = validateNotEmpty(params.getCipherSuite(), allIsWell, errorBuf,
"No cipher suite was specified.");
<<<<<<<
allIsWell = validateNotZero(params.getKeyLength(), allIsWell, errorBuf, "No key length was specified.");
allIsWell = validateNotEmpty(params.getKeyAlgorithmName(), allIsWell, errorBuf, "No key algorithm name was specified.");
allIsWell = validateNotEmpty(params.getRandomNumberGenerator(), allIsWell, errorBuf, "No random number generator was specified.");
allIsWell = validateNotEmpty(params.getRandomNumberGeneratorProvider(), allIsWell, errorBuf, "No random number generate provider was specified.");
allIsWell = validateNotNull(params.getPlaintextOutputStream(), allIsWell, errorBuf, "No plaintext output stream was specified.");
=======
allIsWell = validateNotEmpty(params.getPadding(), allIsWell, errorBuf,
"No padding was specified.");
allIsWell = validateNotZero(params.getKeyLength(), allIsWell, errorBuf,
"No key length was specified.");
allIsWell = validateNotEmpty(params.getEncryptionMode(), allIsWell, errorBuf,
"No encryption mode was specified.");
allIsWell = validateNotEmpty(params.getRandomNumberGenerator(), allIsWell, errorBuf,
"No random number generator was specified.");
allIsWell = validateNotEmpty(params.getRandomNumberGeneratorProvider(), allIsWell, errorBuf,
"No random number generate provider was specified.");
allIsWell = validateNotNull(params.getPlaintextOutputStream(), allIsWell, errorBuf,
"No plaintext output stream was specified.");
>>>>>>>
allIsWell = validateNotZero(params.getKeyLength(), allIsWell, errorBuf,
"No key length was specified.");
allIsWell = validateNotEmpty(params.getKeyAlgorithmName(), allIsWell, errorBuf,
"No key algorithm name was specified.");
allIsWell = validateNotEmpty(params.getRandomNumberGenerator(), allIsWell, errorBuf,
"No random number generator was specified.");
allIsWell = validateNotEmpty(params.getRandomNumberGeneratorProvider(), allIsWell, errorBuf,
"No random number generate provider was specified.");
allIsWell = validateNotNull(params.getPlaintextOutputStream(), allIsWell, errorBuf,
"No plaintext output stream was specified.");
<<<<<<<
allIsWell = validateNotZero(params.getKeyLength(), allIsWell, errorBuf, "No key length was specified.");
allIsWell = validateNotEmpty(params.getRandomNumberGenerator(), allIsWell, errorBuf, "No random number generator was specified.");
allIsWell = validateNotEmpty(params.getRandomNumberGeneratorProvider(), allIsWell, errorBuf, "No random number generate provider was specified.");
allIsWell = validateNotNull(params.getEncryptedInputStream(), allIsWell, errorBuf, "No encrypted input stream was specified.");
allIsWell = validateNotNull(params.getInitializationVector(), allIsWell, errorBuf, "No initialization vector was specified.");
allIsWell = validateNotNull(params.getEncryptedKey(), allIsWell, errorBuf, "No encrypted key was specified.");
if (params.getKeyEncryptionStrategyClass() != null && !params.getKeyEncryptionStrategyClass().equals("NullSecretKeyEncryptionStrategy")) {
allIsWell = validateNotEmpty(params.getOpaqueKeyEncryptionKeyID(), allIsWell, errorBuf, "No opqaue key encryption ID was specified.");
=======
allIsWell = validateNotEmpty(params.getPadding(), allIsWell, errorBuf,
"No padding was specified.");
allIsWell = validateNotZero(params.getKeyLength(), allIsWell, errorBuf,
"No key length was specified.");
allIsWell = validateNotEmpty(params.getEncryptionMode(), allIsWell, errorBuf,
"No encryption mode was specified.");
allIsWell = validateNotEmpty(params.getRandomNumberGenerator(), allIsWell, errorBuf,
"No random number generator was specified.");
allIsWell = validateNotEmpty(params.getRandomNumberGeneratorProvider(), allIsWell, errorBuf,
"No random number generate provider was specified.");
allIsWell = validateNotNull(params.getEncryptedInputStream(), allIsWell, errorBuf,
"No encrypted input stream was specified.");
allIsWell = validateNotNull(params.getInitializationVector(), allIsWell, errorBuf,
"No initialization vector was specified.");
allIsWell = validateNotNull(params.getEncryptedKey(), allIsWell, errorBuf,
"No encrypted key was specified.");
if (params.getKeyEncryptionStrategyClass() != null
&& !params.getKeyEncryptionStrategyClass().equals("NullSecretKeyEncryptionStrategy")) {
allIsWell = validateNotEmpty(params.getOpaqueKeyEncryptionKeyID(), allIsWell, errorBuf,
"No opqaue key encryption ID was specified.");
>>>>>>>
allIsWell = validateNotZero(params.getKeyLength(), allIsWell, errorBuf,
"No key length was specified.");
allIsWell = validateNotEmpty(params.getRandomNumberGenerator(), allIsWell, errorBuf,
"No random number generator was specified.");
allIsWell = validateNotEmpty(params.getRandomNumberGeneratorProvider(), allIsWell, errorBuf,
"No random number generate provider was specified.");
allIsWell = validateNotNull(params.getEncryptedInputStream(), allIsWell, errorBuf,
"No encrypted input stream was specified.");
allIsWell = validateNotNull(params.getInitializationVector(), allIsWell, errorBuf,
"No initialization vector was specified.");
allIsWell = validateNotNull(params.getEncryptedKey(), allIsWell, errorBuf,
"No encrypted key was specified.");
if (params.getKeyEncryptionStrategyClass() != null
&& !params.getKeyEncryptionStrategyClass().equals("NullSecretKeyEncryptionStrategy")) {
allIsWell = validateNotEmpty(params.getOpaqueKeyEncryptionKeyID(), allIsWell, errorBuf,
"No opqaue key encryption ID was specified.");
<<<<<<<
=======
SecureRandom secureRandom = DefaultCryptoModuleUtils.getSecureRandom(
params.getRandomNumberGenerator(), params.getRandomNumberGeneratorProvider());
>>>>>>>
<<<<<<<
RFileCipherOutputStream cipherOutputStream = new RFileCipherOutputStream(params.getPlaintextOutputStream(), cipher);
BlockedOutputStream blockedOutputStream = new BlockedOutputStream(cipherOutputStream, cipher.getBlockSize(), params.getBlockStreamSize());
=======
CipherOutputStream cipherOutputStream = new CipherOutputStream(
params.getPlaintextOutputStream(), cipher);
BlockedOutputStream blockedOutputStream = new BlockedOutputStream(cipherOutputStream,
cipher.getBlockSize(), params.getBlockStreamSize());
>>>>>>>
RFileCipherOutputStream cipherOutputStream = new RFileCipherOutputStream(
params.getPlaintextOutputStream(), cipher);
BlockedOutputStream blockedOutputStream = new BlockedOutputStream(cipherOutputStream,
cipher.getBlockSize(), params.getBlockStreamSize());
<<<<<<<
initCipher(params, cipher, Cipher.DECRYPT_MODE);
=======
cipher.init(Cipher.DECRYPT_MODE,
new SecretKeySpec(params.getPlaintextKey(), params.getAlgorithmName()),
new IvParameterSpec(params.getInitializationVector()));
>>>>>>>
initCipher(params, cipher, Cipher.DECRYPT_MODE);
<<<<<<<
log.trace("Initialized cipher input stream with transformation [{}]", params.getCipherSuite());
=======
log.trace("Initialized cipher input stream with transformation ["
+ getCipherTransformation(params) + "]");
>>>>>>>
log.trace("Initialized cipher input stream with transformation [{}]", params.getCipherSuite()); |
<<<<<<<
=======
private class SubpixelBrowserBugDetector {
private static final double SUBPIXEL_ADJUSTMENT = .1;
private boolean hasAlreadyBeenFixed = false;
/**
* This is a fix essentially for Firefox and how it handles subpixels.
* <p>
* Even if an element has {@code style="width: 1000.12px"}, the bounding
* box's width in Firefox is usually nothing of that sort. It's actually
* 1000.11669921875 (in version 35.0.1). That's not even close, when
* talking about floating point precision. Other browsers handle the
* subpixels way better
* <p>
* In any case, we need to fix that. And that's fixed by simply checking
* if the sum of the width of all the cells is larger than the width of
* the row. If it is, we <i>hack</i> the last column
* {@value #SUBPIXEL_ADJUSTMENT}px narrower.
*/
public void checkAndFix() {
if (!hasAlreadyBeenFixed && hasSubpixelBrowserBug()) {
fixSubpixelBrowserBug();
hasAlreadyBeenFixed = true;
}
}
public void invalidateFix() {
adjustBookkeepingPixels(SUBPIXEL_ADJUSTMENT);
hasAlreadyBeenFixed = false;
}
private boolean hasSubpixelBrowserBug() {
final RowContainer rowContainer;
if (header.getRowCount() > 0) {
rowContainer = header;
} else if (body.getRowCount() > 0) {
rowContainer = body;
} else if (footer.getRowCount() > 0) {
rowContainer = footer;
} else {
return false;
}
double sumOfCellWidths = 0;
TableRowElement tr = rowContainer.getElement().getRows().getItem(0);
if (tr == null) {
/*
* for some weird reason, the row might be null at this point in
* (some?) webkit browsers.
*/
return false;
}
NodeList<TableCellElement> cells = tr.getCells();
assert cells != null : "cells was null, why is it null?";
for (int i = 0; i < cells.getLength(); i++) {
TableCellElement cell = cells.getItem(i);
if (!cell.getStyle().getDisplay()
.equals(Display.NONE.getCssName())) {
sumOfCellWidths += WidgetUtil.getBoundingClientRect(cell)
.getWidth();
}
}
double rowWidth = WidgetUtil.getBoundingClientRect(tr).getWidth();
return sumOfCellWidths >= rowWidth;
}
private void fixSubpixelBrowserBug() {
assert columnConfiguration.getColumnCount() > 0 : "Why are we running this code if there are no columns?";
adjustBookkeepingPixels(-SUBPIXEL_ADJUSTMENT);
fixSubpixelBrowserBugFor(header);
fixSubpixelBrowserBugFor(body);
fixSubpixelBrowserBugFor(footer);
}
private void adjustBookkeepingPixels(double adjustment) {
int lastColumnIndex = columnConfiguration.columns.size() - 1;
if (lastColumnIndex < 0) {
return;
}
columnConfiguration.columns.get(lastColumnIndex).calculatedWidth += adjustment;
if (columnConfiguration.widthsArray != null) {
columnConfiguration.widthsArray[lastColumnIndex] += adjustment;
}
}
/**
* Adjust the last non-spanned cell by {@link #SUBPIXEL_ADJUSTMENT} (
* {@value #SUBPIXEL_ADJUSTMENT}px).
* <p>
* We'll do this brute-force, by individually measuring and shrinking
* the last non-spanned cell. Brute-force, since each row might be
* spanned differently - we can't simply pick one index and one width,
* and mass-apply that to everything :(
*/
private void fixSubpixelBrowserBugFor(RowContainer rowContainer) {
if (rowContainer.getRowCount() == 0) {
return;
}
NodeList<TableRowElement> rows = rowContainer.getElement()
.getRows();
for (int i = 0; i < rows.getLength(); i++) {
NodeList<TableCellElement> cells = rows.getItem(i).getCells();
TableCellElement lastNonspannedCell = null;
for (int j = cells.getLength() - 1; j >= 0; j--) {
TableCellElement cell = cells.getItem(j);
if (!cell.getStyle().getDisplay()
.equals(Display.NONE.getCssName())) {
lastNonspannedCell = cell;
break;
}
}
assert lastNonspannedCell != null : "all cells were \"display: none\" on row "
+ i + " in " + rowContainer.getElement().getTagName();
double cellWidth = WidgetUtil.getBoundingClientRect(
lastNonspannedCell).getWidth();
double newWidth = cellWidth - SUBPIXEL_ADJUSTMENT;
lastNonspannedCell.getStyle().setWidth(newWidth, Unit.PX);
}
}
}
// abs(atan(y/x))*(180/PI) = n deg, x = 1, solve y
/**
* The solution to
* <code>|tan<sup>-1</sup>(<i>x</i>)|×(180/π) = 30</code>
* .
* <p>
* This constant is placed in the Escalator class, instead of an inner
* class, since even mathematical expressions aren't allowed in non-static
* inner classes for constants.
*/
private static final double RATIO_OF_30_DEGREES = 1 / Math.sqrt(3);
>>>>>>>
private class SubpixelBrowserBugDetector {
private static final double SUBPIXEL_ADJUSTMENT = .1;
private boolean hasAlreadyBeenFixed = false;
/**
* This is a fix essentially for Firefox and how it handles subpixels.
* <p>
* Even if an element has {@code style="width: 1000.12px"}, the bounding
* box's width in Firefox is usually nothing of that sort. It's actually
* 1000.11669921875 (in version 35.0.1). That's not even close, when
* talking about floating point precision. Other browsers handle the
* subpixels way better
* <p>
* In any case, we need to fix that. And that's fixed by simply checking
* if the sum of the width of all the cells is larger than the width of
* the row. If it is, we <i>hack</i> the last column
* {@value #SUBPIXEL_ADJUSTMENT}px narrower.
*/
public void checkAndFix() {
if (!hasAlreadyBeenFixed && hasSubpixelBrowserBug()) {
fixSubpixelBrowserBug();
hasAlreadyBeenFixed = true;
}
}
public void invalidateFix() {
adjustBookkeepingPixels(SUBPIXEL_ADJUSTMENT);
hasAlreadyBeenFixed = false;
}
private boolean hasSubpixelBrowserBug() {
final RowContainer rowContainer;
if (header.getRowCount() > 0) {
rowContainer = header;
} else if (body.getRowCount() > 0) {
rowContainer = body;
} else if (footer.getRowCount() > 0) {
rowContainer = footer;
} else {
return false;
}
double sumOfCellWidths = 0;
TableRowElement tr = rowContainer.getElement().getRows().getItem(0);
if (tr == null) {
/*
* for some weird reason, the row might be null at this point in
* (some?) webkit browsers.
*/
return false;
}
NodeList<TableCellElement> cells = tr.getCells();
assert cells != null : "cells was null, why is it null?";
for (int i = 0; i < cells.getLength(); i++) {
TableCellElement cell = cells.getItem(i);
if (!cell.getStyle().getDisplay()
.equals(Display.NONE.getCssName())) {
sumOfCellWidths += WidgetUtil.getBoundingClientRect(cell)
.getWidth();
}
}
double rowWidth = WidgetUtil.getBoundingClientRect(tr).getWidth();
return sumOfCellWidths >= rowWidth;
}
private void fixSubpixelBrowserBug() {
assert columnConfiguration.getColumnCount() > 0 : "Why are we running this code if there are no columns?";
adjustBookkeepingPixels(-SUBPIXEL_ADJUSTMENT);
fixSubpixelBrowserBugFor(header);
fixSubpixelBrowserBugFor(body);
fixSubpixelBrowserBugFor(footer);
}
private void adjustBookkeepingPixels(double adjustment) {
int lastColumnIndex = columnConfiguration.columns.size() - 1;
if (lastColumnIndex < 0) {
return;
}
columnConfiguration.columns.get(lastColumnIndex).calculatedWidth += adjustment;
if (columnConfiguration.widthsArray != null) {
columnConfiguration.widthsArray[lastColumnIndex] += adjustment;
}
}
/**
* Adjust the last non-spanned cell by {@link #SUBPIXEL_ADJUSTMENT} (
* {@value #SUBPIXEL_ADJUSTMENT}px).
* <p>
* We'll do this brute-force, by individually measuring and shrinking
* the last non-spanned cell. Brute-force, since each row might be
* spanned differently - we can't simply pick one index and one width,
* and mass-apply that to everything :(
*/
private void fixSubpixelBrowserBugFor(RowContainer rowContainer) {
if (rowContainer.getRowCount() == 0) {
return;
}
NodeList<TableRowElement> rows = rowContainer.getElement()
.getRows();
for (int i = 0; i < rows.getLength(); i++) {
NodeList<TableCellElement> cells = rows.getItem(i).getCells();
TableCellElement lastNonspannedCell = null;
for (int j = cells.getLength() - 1; j >= 0; j--) {
TableCellElement cell = cells.getItem(j);
if (!cell.getStyle().getDisplay()
.equals(Display.NONE.getCssName())) {
lastNonspannedCell = cell;
break;
}
}
assert lastNonspannedCell != null : "all cells were \"display: none\" on row "
+ i + " in " + rowContainer.getElement().getTagName();
double cellWidth = WidgetUtil.getBoundingClientRect(
lastNonspannedCell).getWidth();
double newWidth = cellWidth - SUBPIXEL_ADJUSTMENT;
lastNonspannedCell.getStyle().setWidth(newWidth, Unit.PX);
}
}
}
<<<<<<<
private final ElementPositionBookkeeper positions = new ElementPositionBookkeeper();
=======
private final SubpixelBrowserBugDetector subpixelBrowserBugDetector = new SubpixelBrowserBugDetector();
>>>>>>>
private final SubpixelBrowserBugDetector subpixelBrowserBugDetector = new SubpixelBrowserBugDetector();
private final ElementPositionBookkeeper positions = new ElementPositionBookkeeper(); |
<<<<<<<
"com\\.vaadin\\.flow\\.server\\.frontend\\.TaskGenerateServiceWorker",
=======
"com\\.vaadin\\.flow\\.server\\.frontend\\.TaskInstallWebpackPlugins",
"com\\.vaadin\\.flow\\.server\\.frontend\\.TaskUpdateThemeImport",
>>>>>>>
"com\\.vaadin\\.flow\\.server\\.frontend\\.TaskGenerateServiceWorker",
"com\\.vaadin\\.flow\\.server\\.frontend\\.TaskInstallWebpackPlugins",
"com\\.vaadin\\.flow\\.server\\.frontend\\.TaskUpdateThemeImport", |
<<<<<<<
import elemental.json.JsonObject;
=======
import com.vaadin.shared.util.SharedUtil;
>>>>>>>
import com.vaadin.shared.util.SharedUtil;
import elemental.json.JsonObject; |
<<<<<<<
import com.vaadin.ui.Grid.ColumnReorderEvent;
import com.vaadin.ui.Grid.ColumnReorderListener;
import com.vaadin.ui.Grid.ColumnVisibilityChangeEvent;
import com.vaadin.ui.Grid.ColumnVisibilityChangeListener;
=======
import com.vaadin.ui.Grid.DetailsGenerator;
>>>>>>>
import com.vaadin.ui.Grid.ColumnReorderEvent;
import com.vaadin.ui.Grid.ColumnReorderListener;
import com.vaadin.ui.Grid.ColumnVisibilityChangeEvent;
import com.vaadin.ui.Grid.ColumnVisibilityChangeListener;
import com.vaadin.ui.Grid.DetailsGenerator;
<<<<<<<
private ColumnReorderListener columnReorderListener = new ColumnReorderListener() {
@Override
public void columnReorder(ColumnReorderEvent event) {
log("Columns reordered, userOriginated: "
+ event.isUserOriginated());
}
};
private ColumnVisibilityChangeListener columnVisibilityListener = new ColumnVisibilityChangeListener() {
@Override
public void columnVisibilityChanged(ColumnVisibilityChangeEvent event) {
log("Visibility changed: "//
+ "propertyId: " + event.getColumn().getPropertyId() //
+ ", isHidden: " + event.getColumn().isHidden() //
+ ", userOriginated: " + event.isUserOriginated());
}
};
=======
private Panel detailsPanel;
private final DetailsGenerator detailedDetailsGenerator = new DetailsGenerator() {
@Override
public Component getDetails(final RowReference rowReference) {
CssLayout cssLayout = new CssLayout();
cssLayout.setHeight("200px");
cssLayout.setWidth("100%");
Item item = rowReference.getItem();
for (Object propertyId : item.getItemPropertyIds()) {
Property<?> prop = item.getItemProperty(propertyId);
String string = prop.getValue().toString();
cssLayout.addComponent(new Label(string));
}
final int rowIndex = grid.getContainerDataSource().indexOfId(
rowReference.getItemId());
ClickListener clickListener = new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
Notification.show("You clicked on the "
+ "button in the details for " + "row " + rowIndex);
}
};
cssLayout.addComponent(new Button("Press me", clickListener));
return cssLayout;
}
};
private final DetailsGenerator watchingDetailsGenerator = new DetailsGenerator() {
private int id = 0;
@Override
public Component getDetails(RowReference rowReference) {
return new Label("You are watching item id "
+ rowReference.getItemId() + " (" + (id++) + ")");
}
};
private final DetailsGenerator hierarchicalDetailsGenerator = new DetailsGenerator() {
@Override
public Component getDetails(RowReference rowReference) {
detailsPanel = new Panel();
detailsPanel.setContent(new Label("One"));
return detailsPanel;
}
};
>>>>>>>
private ColumnReorderListener columnReorderListener = new ColumnReorderListener() {
@Override
public void columnReorder(ColumnReorderEvent event) {
log("Columns reordered, userOriginated: "
+ event.isUserOriginated());
}
};
private ColumnVisibilityChangeListener columnVisibilityListener = new ColumnVisibilityChangeListener() {
@Override
public void columnVisibilityChanged(ColumnVisibilityChangeEvent event) {
log("Visibility changed: "//
+ "propertyId: " + event.getColumn().getPropertyId() //
+ ", isHidden: " + event.getColumn().isHidden() //
+ ", userOriginated: " + event.isUserOriginated());
}
};
private Panel detailsPanel;
private final DetailsGenerator detailedDetailsGenerator = new DetailsGenerator() {
@Override
public Component getDetails(final RowReference rowReference) {
CssLayout cssLayout = new CssLayout();
cssLayout.setHeight("200px");
cssLayout.setWidth("100%");
Item item = rowReference.getItem();
for (Object propertyId : item.getItemPropertyIds()) {
Property<?> prop = item.getItemProperty(propertyId);
String string = prop.getValue().toString();
cssLayout.addComponent(new Label(string));
}
final int rowIndex = grid.getContainerDataSource().indexOfId(
rowReference.getItemId());
ClickListener clickListener = new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
Notification.show("You clicked on the "
+ "button in the details for " + "row " + rowIndex);
}
};
cssLayout.addComponent(new Button("Press me", clickListener));
return cssLayout;
}
};
private final DetailsGenerator watchingDetailsGenerator = new DetailsGenerator() {
private int id = 0;
@Override
public Component getDetails(RowReference rowReference) {
return new Label("You are watching item id "
+ rowReference.getItemId() + " (" + (id++) + ")");
}
};
private final DetailsGenerator hierarchicalDetailsGenerator = new DetailsGenerator() {
@Override
public Component getDetails(RowReference rowReference) {
detailsPanel = new Panel();
detailsPanel.setContent(new Label("One"));
return detailsPanel;
}
};
<<<<<<<
addInternalActions();
=======
createDetailsActions();
>>>>>>>
addInternalActions();
createDetailsActions(); |
<<<<<<<
@Override
public void splitterClick(MouseEventDetails mouseDetails) {
fireEvent(new SplitterClickEvent(AbstractSplitPanel.this,
mouseDetails));
}
=======
private float pos = 50;
private int posUnit = UNITS_PERCENTAGE;
private boolean posReversed = false;
private float posMin = 0;
private int posMinUnit = UNITS_PERCENTAGE;
private float posMax = 100;
private int posMaxUnit = UNITS_PERCENTAGE;
>>>>>>>
@Override
public void splitterClick(MouseEventDetails mouseDetails) {
fireEvent(new SplitterClickEvent(AbstractSplitPanel.this,
mouseDetails));
}
<<<<<<<
=======
/**
* Paints the content of this component.
*
* @param target
* the Paint Event.
* @throws PaintException
* if the paint operation failed.
*/
@Override
public void paintContent(PaintTarget target) throws PaintException {
super.paintContent(target);
final String position = pos + UNIT_SYMBOLS[posUnit];
final String minimumPosition = posMin + UNIT_SYMBOLS[posMinUnit];
final String maximumPosition = posMax + UNIT_SYMBOLS[posMaxUnit];
target.addAttribute("position", position);
if (!minimumPosition.equals("0%")) {
target.addAttribute("minimumPosition", minimumPosition);
}
if (!maximumPosition.equals("100%")) {
target.addAttribute("maximumPosition", maximumPosition);
}
if (isLocked()) {
target.addAttribute("locked", true);
}
target.addAttribute("reversed", posReversed);
if (firstComponent != null) {
firstComponent.paint(target);
} else {
VerticalLayout temporaryComponent = new VerticalLayout();
temporaryComponent.setParent(this);
temporaryComponent.paint(target);
}
if (secondComponent != null) {
secondComponent.paint(target);
} else {
VerticalLayout temporaryComponent = new VerticalLayout();
temporaryComponent.setParent(this);
temporaryComponent.paint(target);
}
}
>>>>>>>
<<<<<<<
public void setMinimumSplitPosition(int pos, Unit unit) {
setSplitPositionLimits(pos, unit, getSplitterState().getMaxPosition(),
posMaxUnit);
=======
public void setMinSplitPosition(float pos, int unit) {
setSplitPositionLimits(pos, unit, posMax, posMaxUnit);
>>>>>>>
public void setMinSplitPosition(int pos, Unit unit) {
setSplitPositionLimits(pos, unit, getSplitterState().getMaxPosition(),
posMaxUnit);
<<<<<<<
public float getMinSplitPosition() {
return getSplitterState().getMinPosition();
=======
public float getMinSplitPosition() {
return posMin;
>>>>>>>
public float getMinSplitPosition() {
return getSplitterState().getMinPosition();
<<<<<<<
public void setMaxSplitPosition(int pos, Unit unit) {
setSplitPositionLimits(getSplitterState().getMinPosition(), posMinUnit,
pos, unit);
=======
public void setMaxSplitPosition(float pos, int unit) {
setSplitPositionLimits(posMin, posMinUnit, pos, unit);
>>>>>>>
public void setMaxSplitPosition(float pos, Unit unit) {
setSplitPositionLimits(getSplitterState().getMinPosition(), posMinUnit,
pos, unit);
<<<<<<<
public float getMaxSplitPosition() {
return getSplitterState().getMaxPosition();
=======
public float getMaxSplitPosition() {
return posMax;
>>>>>>>
public float getMaxSplitPosition() {
return getSplitterState().getMaxPosition();
<<<<<<<
private void setSplitPositionLimits(float minPos, Unit minPosUnit,
float maxPos, Unit maxPosUnit) {
if ((minPosUnit != Unit.PERCENTAGE && minPosUnit != Unit.PIXELS)
|| (maxPosUnit != Unit.PERCENTAGE && maxPosUnit != Unit.PIXELS)) {
=======
private void setSplitPositionLimits(float minPos, int minPosUnit,
float maxPos, int maxPosUnit) {
if ((minPosUnit != UNITS_PERCENTAGE && minPosUnit != UNITS_PIXELS)
|| (maxPosUnit != UNITS_PERCENTAGE && maxPosUnit != UNITS_PIXELS)) {
>>>>>>>
private void setSplitPositionLimits(float minPos, Unit minPosUnit,
float maxPos, Unit maxPosUnit) {
if ((minPosUnit != Unit.PERCENTAGE && minPosUnit != Unit.PIXELS)
|| (maxPosUnit != Unit.PERCENTAGE && maxPosUnit != Unit.PIXELS)) { |
<<<<<<<
ui.getInternals().moveElementsFrom(prevUi));
} else {
// Instantiate new chain for the route
chain = createChain(event);
setPreservedChain(session, windowName, location, chain);
=======
moveElementsToNewUI(prevUi, ui));
return Optional.of(chain);
>>>>>>>
ui.getInternals().moveElementsFrom(prevUi));
return Optional.of(chain); |
<<<<<<<
@Test
public void parseManifestJson_returnsValidPaths() {
String manifestJson = "{\"index.html\": \"index.html\", \"sw.js\": " +
"\"sw.js\", \"favicon.ico\": \"favicon.ico\", \"index.ts\": " +
"\"VAADIN/build/vaadin-bundle-index.js\"}";
List<String> manifestPaths =
FrontendUtils.parseManifestPaths(manifestJson);
Assert.assertTrue("Should list bundle path",
manifestPaths.contains("/VAADIN/build/vaadin-bundle-index.js"));
Assert.assertTrue("Should list /sw.js",
manifestPaths.contains("/sw.js"));
Assert.assertTrue("Should list /favicon.ico",
manifestPaths.contains("/favicon.ico"));
Assert.assertFalse("Should not list /index.html",
manifestPaths.contains("/index.html"));
}
private VaadinService setupStatsAssetMocks(String statsFile)
=======
@Test
public void getStatsContent_getStatsFromClassPath_delegateToGetApplicationResource()
>>>>>>>
@Test
public void parseManifestJson_returnsValidPaths() {
String manifestJson = "{\"index.html\": \"index.html\", \"sw.js\": " +
"\"sw.js\", \"favicon.ico\": \"favicon.ico\", \"index.ts\": " +
"\"VAADIN/build/vaadin-bundle-index.js\"}";
List<String> manifestPaths =
FrontendUtils.parseManifestPaths(manifestJson);
Assert.assertTrue("Should list bundle path",
manifestPaths.contains("/VAADIN/build/vaadin-bundle-index.js"));
Assert.assertTrue("Should list /sw.js",
manifestPaths.contains("/sw.js"));
Assert.assertTrue("Should list /favicon.ico",
manifestPaths.contains("/favicon.ico"));
Assert.assertFalse("Should not list /index.html",
manifestPaths.contains("/index.html"));
}
public void getStatsContent_getStatsFromClassPath_delegateToGetApplicationResource() |
<<<<<<<
/**
* Sets the error handler for the editor.
*
* The error handler is called whenever there is an exception in the editor.
*
* @param editorErrorHandler
* The editor error handler to use
* @throws IllegalArgumentException
* if the error handler is null
*/
public void setEditorErrorHandler(EditorErrorHandler editorErrorHandler)
throws IllegalArgumentException {
if (editorErrorHandler == null) {
throw new IllegalArgumentException(
"The error handler cannot be null");
}
this.editorErrorHandler = editorErrorHandler;
}
/**
* Gets the error handler used for the editor
*
* @see #setErrorHandler(com.vaadin.server.ErrorHandler)
* @return the editor error handler, never null
*/
public EditorErrorHandler getEditorErrorHandler() {
return editorErrorHandler;
}
=======
/**
* Gets the field factory for the {@link FieldGroup}. The field factory is
* only used when {@link FieldGroup} creates a new field.
* <p>
* <em>Note:</em> This is a pass-through call to the backing field group.
*
* @return The field factory in use
*/
public FieldGroupFieldFactory getEditorFieldFactory() {
return editorFieldGroup.getFieldFactory();
}
>>>>>>>
/**
* Sets the error handler for the editor.
*
* The error handler is called whenever there is an exception in the editor.
*
* @param editorErrorHandler
* The editor error handler to use
* @throws IllegalArgumentException
* if the error handler is null
*/
public void setEditorErrorHandler(EditorErrorHandler editorErrorHandler)
throws IllegalArgumentException {
if (editorErrorHandler == null) {
throw new IllegalArgumentException(
"The error handler cannot be null");
}
this.editorErrorHandler = editorErrorHandler;
}
/**
* Gets the error handler used for the editor
*
* @see #setErrorHandler(com.vaadin.server.ErrorHandler)
* @return the editor error handler, never null
*/
public EditorErrorHandler getEditorErrorHandler() {
return editorErrorHandler;
}
/**
* Gets the field factory for the {@link FieldGroup}. The field factory is
* only used when {@link FieldGroup} creates a new field.
* <p>
* <em>Note:</em> This is a pass-through call to the backing field group.
*
* @return The field factory in use
*/
public FieldGroupFieldFactory getEditorFieldFactory() {
return editorFieldGroup.getFieldFactory();
} |
<<<<<<<
private ColumnReorderHandler<JsonObject> columnReorderHandler = new ColumnReorderHandler<JsonObject>() {
@Override
public void onColumnReorder(ColumnReorderEvent<JsonObject> event) {
if (!columnsUpdatedFromState) {
List<Column<?, JsonObject>> columns = getWidget().getColumns();
final List<String> newColumnOrder = new ArrayList<String>();
for (Column<?, JsonObject> column : columns) {
if (column instanceof CustomGridColumn) {
newColumnOrder.add(((CustomGridColumn) column).id);
} // the other case would be the multi selection column
}
getRpcProxy(GridServerRpc.class).columnsReordered(
newColumnOrder, columnOrder);
columnOrder = newColumnOrder;
getState().columnOrder = newColumnOrder;
}
}
};
=======
private static class CustomDetailsGenerator implements DetailsGenerator {
private final Map<Integer, ComponentConnector> indexToDetailsMap = new HashMap<Integer, ComponentConnector>();
@Override
@SuppressWarnings("boxing")
public Widget getDetails(int rowIndex) {
ComponentConnector componentConnector = indexToDetailsMap
.get(rowIndex);
if (componentConnector != null) {
return componentConnector.getWidget();
} else {
return null;
}
}
public void setDetailsConnectorChanges(
Set<DetailsConnectorChange> changes) {
/*
* To avoid overwriting connectors while moving them about, we'll
* take all the affected connectors, first all remove those that are
* removed or moved, then we add back those that are moved or added.
*/
/* Remove moved/removed connectors from bookkeeping */
for (DetailsConnectorChange change : changes) {
Integer oldIndex = change.getOldIndex();
Connector removedConnector = indexToDetailsMap.remove(oldIndex);
Connector connector = change.getConnector();
assert removedConnector == null || connector == null
|| removedConnector.equals(connector) : "Index "
+ oldIndex + " points to " + removedConnector
+ " while " + connector + " was expected";
}
/* Add moved/added connectors to bookkeeping */
for (DetailsConnectorChange change : changes) {
Integer newIndex = change.getNewIndex();
ComponentConnector connector = (ComponentConnector) change
.getConnector();
if (connector != null) {
assert newIndex != null : "An existing connector has a missing new index.";
ComponentConnector prevConnector = indexToDetailsMap.put(
newIndex, connector);
assert prevConnector == null : "Connector collision at index "
+ newIndex
+ " between old "
+ prevConnector
+ " and new " + connector;
}
}
}
}
@SuppressWarnings("boxing")
private class DetailsConnectorFetcher implements DeferredWorker {
/** A flag making sure that we don't call scheduleFinally many times. */
private boolean fetcherHasBeenCalled = false;
/** A rolling counter for unique values. */
private int detailsFetchCounter = 0;
/** A collection that tracks the amount of requests currently underway. */
private Set<Integer> pendingFetches = new HashSet<Integer>(5);
private final ScheduledCommand lazyDetailsFetcher = new ScheduledCommand() {
@Override
public void execute() {
int currentFetchId = detailsFetchCounter++;
pendingFetches.add(currentFetchId);
getRpcProxy(GridServerRpc.class).sendDetailsComponents(
currentFetchId);
fetcherHasBeenCalled = false;
assert assertRequestDoesNotTimeout(currentFetchId);
}
};
public void schedule() {
if (!fetcherHasBeenCalled) {
Scheduler.get().scheduleFinally(lazyDetailsFetcher);
fetcherHasBeenCalled = true;
}
}
public void responseReceived(int fetchId) {
/* Ignore negative fetchIds (they're pushed, not fetched) */
if (fetchId >= 0) {
boolean success = pendingFetches.remove(fetchId);
assert success : "Received a response with an unidentified fetch id";
}
}
@Override
public boolean isWorkPending() {
return fetcherHasBeenCalled || !pendingFetches.isEmpty();
}
private boolean assertRequestDoesNotTimeout(final int fetchId) {
/*
* This method will not be compiled without asserts enabled. This
* only makes sure that any request does not time out.
*
* TODO Should this be an explicit check? Is it worth the overhead?
*/
new Timer() {
@Override
public void run() {
assert !pendingFetches.contains(fetchId);
}
}.schedule(1000);
return true;
}
}
>>>>>>>
private ColumnReorderHandler<JsonObject> columnReorderHandler = new ColumnReorderHandler<JsonObject>() {
@Override
public void onColumnReorder(ColumnReorderEvent<JsonObject> event) {
if (!columnsUpdatedFromState) {
List<Column<?, JsonObject>> columns = getWidget().getColumns();
final List<String> newColumnOrder = new ArrayList<String>();
for (Column<?, JsonObject> column : columns) {
if (column instanceof CustomGridColumn) {
newColumnOrder.add(((CustomGridColumn) column).id);
} // the other case would be the multi selection column
}
getRpcProxy(GridServerRpc.class).columnsReordered(
newColumnOrder, columnOrder);
columnOrder = newColumnOrder;
getState().columnOrder = newColumnOrder;
}
}
};
private static class CustomDetailsGenerator implements DetailsGenerator {
private final Map<Integer, ComponentConnector> indexToDetailsMap = new HashMap<Integer, ComponentConnector>();
@Override
@SuppressWarnings("boxing")
public Widget getDetails(int rowIndex) {
ComponentConnector componentConnector = indexToDetailsMap
.get(rowIndex);
if (componentConnector != null) {
return componentConnector.getWidget();
} else {
return null;
}
}
public void setDetailsConnectorChanges(
Set<DetailsConnectorChange> changes) {
/*
* To avoid overwriting connectors while moving them about, we'll
* take all the affected connectors, first all remove those that are
* removed or moved, then we add back those that are moved or added.
*/
/* Remove moved/removed connectors from bookkeeping */
for (DetailsConnectorChange change : changes) {
Integer oldIndex = change.getOldIndex();
Connector removedConnector = indexToDetailsMap.remove(oldIndex);
Connector connector = change.getConnector();
assert removedConnector == null || connector == null
|| removedConnector.equals(connector) : "Index "
+ oldIndex + " points to " + removedConnector
+ " while " + connector + " was expected";
}
/* Add moved/added connectors to bookkeeping */
for (DetailsConnectorChange change : changes) {
Integer newIndex = change.getNewIndex();
ComponentConnector connector = (ComponentConnector) change
.getConnector();
if (connector != null) {
assert newIndex != null : "An existing connector has a missing new index.";
ComponentConnector prevConnector = indexToDetailsMap.put(
newIndex, connector);
assert prevConnector == null : "Connector collision at index "
+ newIndex
+ " between old "
+ prevConnector
+ " and new " + connector;
}
}
}
}
@SuppressWarnings("boxing")
private class DetailsConnectorFetcher implements DeferredWorker {
/** A flag making sure that we don't call scheduleFinally many times. */
private boolean fetcherHasBeenCalled = false;
/** A rolling counter for unique values. */
private int detailsFetchCounter = 0;
/** A collection that tracks the amount of requests currently underway. */
private Set<Integer> pendingFetches = new HashSet<Integer>(5);
private final ScheduledCommand lazyDetailsFetcher = new ScheduledCommand() {
@Override
public void execute() {
int currentFetchId = detailsFetchCounter++;
pendingFetches.add(currentFetchId);
getRpcProxy(GridServerRpc.class).sendDetailsComponents(
currentFetchId);
fetcherHasBeenCalled = false;
assert assertRequestDoesNotTimeout(currentFetchId);
}
};
public void schedule() {
if (!fetcherHasBeenCalled) {
Scheduler.get().scheduleFinally(lazyDetailsFetcher);
fetcherHasBeenCalled = true;
}
}
public void responseReceived(int fetchId) {
/* Ignore negative fetchIds (they're pushed, not fetched) */
if (fetchId >= 0) {
boolean success = pendingFetches.remove(fetchId);
assert success : "Received a response with an unidentified fetch id";
}
}
@Override
public boolean isWorkPending() {
return fetcherHasBeenCalled || !pendingFetches.isEmpty();
}
private boolean assertRequestDoesNotTimeout(final int fetchId) {
/*
* This method will not be compiled without asserts enabled. This
* only makes sure that any request does not time out.
*
* TODO Should this be an explicit check? Is it worth the overhead?
*/
new Timer() {
@Override
public void run() {
assert !pendingFetches.contains(fetchId) : "Fetch id "
+ fetchId + " timed out.";
}
}.schedule(1000);
return true;
}
}
<<<<<<<
getWidget().addColumnReorderHandler(columnReorderHandler);
=======
getWidget().setDetailsGenerator(customDetailsGenerator);
>>>>>>>
getWidget().addColumnReorderHandler(columnReorderHandler);
getWidget().setDetailsGenerator(customDetailsGenerator); |
<<<<<<<
import com.vaadin.terminal.gwt.client.ui.layout.RequiresOverflowAutoFix;
=======
import com.vaadin.ui.Accordion;
>>>>>>>
import com.vaadin.terminal.gwt.client.ui.layout.RequiresOverflowAutoFix;
import com.vaadin.ui.Accordion; |
<<<<<<<
added = addDependency(packageJson, DEPENDENCIES, "@polymer/polymer",
polymerDepVersion) || added;
added = addDependency(packageJson, DEPENDENCIES,
"@webcomponents/webcomponentsjs", "^2.2.10") || added;
=======
added += addDependency(packageJson, DEPENDENCIES, "@polymer/polymer",
polymerDepVersion);
added += addDependency(packageJson, DEPENDENCIES,
"@webcomponents/webcomponentsjs", "^2.2.10");
// dependency for the custom package.json placed in the generated
// folder.
>>>>>>>
added += addDependency(packageJson, DEPENDENCIES, "@polymer/polymer",
polymerDepVersion);
added += addDependency(packageJson, DEPENDENCIES,
"@webcomponents/webcomponentsjs", "^2.2.10");
<<<<<<<
// dependency for the custom package.json placed in the generated
// folder.
String customPkg = "./" + FrontendUtils.getUnixRelativePath(
npmFolder.getAbsoluteFile().toPath(),
generatedFolder.getAbsoluteFile().toPath());
added = addDependency(packageJson, DEPENDENCIES, DEP_NAME_FLOW_DEPS,
customPkg) || added;
// dependency for the package.json in the folder where frontend
// dependencies are copied
if (flowResourcesFolder != null
// Skip if deps are copied directly to `node_modules` folder
&& !flowResourcesFolder.toString().contains(NODE_MODULES)) {
String depsPkg = "./" + FrontendUtils.getUnixRelativePath(
npmFolder.getAbsoluteFile().toPath(),
flowResourcesFolder.getAbsoluteFile().toPath());
added = addDependency(packageJson, DEPENDENCIES, DEP_NAME_FLOW_JARS,
depsPkg) || added;
}
=======
String customPkg = "./" + npmFolder.getAbsoluteFile().toPath()
.relativize(generatedFolder.getAbsoluteFile().toPath())
.toString();
added += addDependency(packageJson, DEPENDENCIES, DEP_NAME_FLOW_DEPS,
customPkg.replaceAll("\\\\", "/"));
>>>>>>>
// dependency for the custom package.json placed in the generated
// folder.
String customPkg = "./" + npmFolder.getAbsoluteFile().toPath()
.relativize(generatedFolder.getAbsoluteFile().toPath())
.toString();
added += addDependency(packageJson, DEPENDENCIES, DEP_NAME_FLOW_DEPS,
customPkg.replaceAll("\\\\", "/"));
// dependency for the package.json in the folder where frontend
// dependencies are copied
if (flowResourcesFolder != null
// Skip if deps are copied directly to `node_modules` folder
&& !flowResourcesFolder.toString().contains(NODE_MODULES)) {
String depsPkg = "./" + FrontendUtils.getUnixRelativePath(
npmFolder.getAbsoluteFile().toPath(),
flowResourcesFolder.getAbsoluteFile().toPath());
added += addDependency(packageJson, DEPENDENCIES,
DEP_NAME_FLOW_JARS, depsPkg);
}
<<<<<<<
log().info("Added dependency \"{}\": \"{}\".", pkg, vers);
return true;
=======
log().debug("Added \"{}\": \"{}\" line.", pkg, vers);
return 1;
>>>>>>>
log().debug("Added \"{}\": \"{}\" line.", pkg, vers);
return 1; |
<<<<<<<
private boolean enablePnpm;
=======
private File connectJavaSourceFolder;
private File connectGeneratedOpenApiFile;
private File connectApplicationProperties;
private File connectClientTsApiFolder;
private boolean disablePnpm;
>>>>>>>
private boolean enablePnpm;
private File connectJavaSourceFolder;
private File connectGeneratedOpenApiFile;
private File connectApplicationProperties;
private File connectClientTsApiFolder;
<<<<<<<
builder.generatedFolder, builder.cleanNpmFiles,
builder.enablePnpm);
=======
builder.generatedFolder, builder.flowResourcesFolder,
builder.cleanNpmFiles,
builder.disablePnpm);
>>>>>>>
builder.generatedFolder, builder.flowResourcesFolder,
builder.cleanNpmFiles,
builder.enablePnpm);
<<<<<<<
builder.tokenFileData, builder.enablePnpm));
=======
builder.tokenFileData, builder.disablePnpm));
}
}
private void addBootstrapTasks(Builder builder) {
File outputDirectory = new File(builder.npmFolder,
FrontendUtils.TARGET);
TaskGenerateIndexHtml taskGenerateIndexHtml = new TaskGenerateIndexHtml(
builder.frontendDirectory, outputDirectory);
commands.add(taskGenerateIndexHtml);
TaskGenerateIndexTs taskGenerateIndexTs = new TaskGenerateIndexTs(
builder.frontendDirectory,
new File(builder.generatedFolder, IMPORTS_NAME),
outputDirectory);
commands.add(taskGenerateIndexTs);
TaskGenerateTsConfig taskGenerateTsConfig = new TaskGenerateTsConfig(
builder.frontendDirectory, builder.npmFolder, outputDirectory);
commands.add(taskGenerateTsConfig);
}
>>>>>>>
builder.tokenFileData, builder.enablePnpm));
}
}
private void addBootstrapTasks(Builder builder) {
File outputDirectory = new File(builder.npmFolder,
FrontendUtils.TARGET);
TaskGenerateIndexHtml taskGenerateIndexHtml = new TaskGenerateIndexHtml(
builder.frontendDirectory, outputDirectory);
commands.add(taskGenerateIndexHtml);
TaskGenerateIndexTs taskGenerateIndexTs = new TaskGenerateIndexTs(
builder.frontendDirectory,
new File(builder.generatedFolder, IMPORTS_NAME),
outputDirectory);
commands.add(taskGenerateIndexTs);
TaskGenerateTsConfig taskGenerateTsConfig = new TaskGenerateTsConfig(
builder.frontendDirectory, builder.npmFolder, outputDirectory);
commands.add(taskGenerateTsConfig);
} |
<<<<<<<
public abstract class PropertyFormatter<T> extends AbstractProperty<String>
implements Property.ValueChangeListener,
Property.ReadOnlyStatusChangeListener {
=======
public abstract class PropertyFormatter extends AbstractProperty implements
Property.Viewer, Property.ValueChangeListener,
Property.ReadOnlyStatusChangeListener {
>>>>>>>
public abstract class PropertyFormatter<T> extends AbstractProperty<String>
implements Property.Viewer, Property.ValueChangeListener,
Property.ReadOnlyStatusChangeListener {
<<<<<<<
public String getStringValue() {
T value = dataSource == null ? null : dataSource.getValue();
=======
public String toString() {
if (dataSource == null) {
return null;
}
Object value = dataSource.getValue();
>>>>>>>
public String getStringValue() {
T value = dataSource == null ? null : dataSource.getValue();
<<<<<<<
dataSource.setValue(parse(newValue.toString()));
if (!newValue.equals(getStringValue())) {
=======
dataSource.setValue(parse(newValue.toString()));
if (!newValue.equals(toString())) {
>>>>>>>
dataSource.setValue(parse(newValue.toString()));
if (!newValue.equals(getStringValue())) { |
<<<<<<<
AbstractApplicationPortletWrapper portletWrapper = new AbstractApplicationPortletWrapper(
this);
WrappedPortletRequest wrappedRequest;
String portalInfo = request.getPortalContext().getPortalInfo()
.toLowerCase();
if (portalInfo.contains("liferay")) {
wrappedRequest = new WrappedLiferayRequest(request,
getDeploymentConfiguration());
} else if (portalInfo.contains("gatein")) {
wrappedRequest = new WrappedGateinRequest(request,
getDeploymentConfiguration());
} else {
wrappedRequest = new WrappedPortletRequest(request,
getDeploymentConfiguration());
}
WrappedPortletResponse wrappedResponse = new WrappedPortletResponse(
response, getDeploymentConfiguration());
RequestTimer requestTimer = RequestTimer.get(wrappedRequest);
requestTimer.start(wrappedRequest);
=======
RequestTimer requestTimer = new RequestTimer();
requestTimer.start();
>>>>>>>
RequestTimer requestTimer = new RequestTimer();
requestTimer.start();
AbstractApplicationPortletWrapper portletWrapper = new AbstractApplicationPortletWrapper(
this);
WrappedPortletRequest wrappedRequest;
String portalInfo = request.getPortalContext().getPortalInfo()
.toLowerCase();
if (portalInfo.contains("liferay")) {
wrappedRequest = new WrappedLiferayRequest(request,
getDeploymentConfiguration());
} else if (portalInfo.contains("gatein")) {
wrappedRequest = new WrappedGateinRequest(request,
getDeploymentConfiguration());
} else {
wrappedRequest = new WrappedPortletRequest(request,
getDeploymentConfiguration());
}
WrappedPortletResponse wrappedResponse = new WrappedPortletResponse(
response, getDeploymentConfiguration());
<<<<<<<
}
} finally {
Root.setCurrentRoot(null);
Application.setCurrentApplication(null);
=======
}
} finally {
requestTimer
.stop((AbstractWebApplicationContext) application
.getContext());
>>>>>>>
}
} finally {
Root.setCurrentRoot(null);
Application.setCurrentApplication(null);
requestTimer
.stop((AbstractWebApplicationContext) application
.getContext()); |
<<<<<<<
if (detailComponentManager.visibleDetails.contains(itemId)) {
detailComponentManager.createDetails(itemId,
indexOf(itemId));
}
=======
>>>>>>>
if (visibleDetails.contains(itemId)) {
detailComponentManager.createDetails(itemId);
}
<<<<<<<
for (DataGenerator dg : dataGenerators) {
dg.generateData(itemId, item, rowObject);
=======
rowObject.put(GridState.JSONKEY_DATA, rowData);
rowObject.put(GridState.JSONKEY_ROWKEY, keyMapper.getKey(itemId));
if (visibleDetails.contains(itemId)) {
// Double check to be sure details component exists.
detailComponentManager.createDetails(itemId);
Component detailsComponent = detailComponentManager.visibleDetailsComponents
.get(itemId);
rowObject.put(
GridState.JSONKEY_DETAILS_VISIBLE,
(detailsComponent != null ? detailsComponent
.getConnectorId() : ""));
}
rowReference.set(itemId);
CellStyleGenerator cellStyleGenerator = grid.getCellStyleGenerator();
if (cellStyleGenerator != null) {
setGeneratedCellStyles(cellStyleGenerator, rowObject, columns);
}
RowStyleGenerator rowStyleGenerator = grid.getRowStyleGenerator();
if (rowStyleGenerator != null) {
setGeneratedRowStyles(rowStyleGenerator, rowObject);
>>>>>>>
for (DataGenerator dg : dataGenerators) {
dg.generateData(itemId, item, rowObject);
<<<<<<<
modified = detailComponentManager.visibleDetails.add(itemId);
=======
visibleDetails.add(itemId);
>>>>>>>
visibleDetails.add(itemId);
<<<<<<<
modified = detailComponentManager.visibleDetails.remove(itemId);
=======
visibleDetails.remove(itemId);
>>>>>>>
visibleDetails.remove(itemId);
<<<<<<<
@Override
public void detach() {
for (Object itemId : ImmutableSet
.copyOf(detailComponentManager.visibleDetails)) {
detailComponentManager.destroyDetails(itemId);
}
super.detach();
}
=======
>>>>>>> |
<<<<<<<
public class VScrollTable extends FlowPanel implements Table, ScrollHandler,
VHasDropHandler {
=======
public class VScrollTable extends FlowPanel implements Table, ScrollHandler,
ValueChangeHandler<String> {
>>>>>>>
public class VScrollTable extends FlowPanel implements Table, ScrollHandler,
VHasDropHandler, ValueChangeHandler<String> {
<<<<<<<
public VScrollTableDropHandler getDropHandler() {
return dropHandler;
}
private static class TableDDDetails {
int overkey = -1;
VerticalDropLocation dropLocation;
String colkey;
@Override
public boolean equals(Object obj) {
if (obj instanceof TableDDDetails) {
TableDDDetails other = (TableDDDetails) obj;
return dropLocation == other.dropLocation
&& overkey == other.overkey
&& ((colkey != null && colkey.equals(other.colkey)) || (colkey == null && other.colkey == null));
}
return false;
}
// @Override
// public int hashCode() {
// return overkey;
// }
}
public class VScrollTableDropHandler extends VAbstractDropHandler {
private static final String ROWSTYLEBASE = "v-table-row-drag-";
private TableDDDetails dropDetails;
private TableDDDetails lastEmphasized;
@Override
public void dragEnter(VDragEvent drag) {
updateDropDetails(drag);
super.dragEnter(drag);
}
private void updateDropDetails(VDragEvent drag) {
dropDetails = new TableDDDetails();
Element elementOver = drag.getElementOver();
VScrollTableRow row = Util.findWidget(elementOver,
VScrollTableRow.class);
if (row != null) {
dropDetails.overkey = row.rowKey;
Element tr = row.getElement();
Element element = elementOver;
while (element != null && element.getParentElement() != tr) {
element = (Element) element.getParentElement();
}
int childIndex = DOM.getChildIndex(tr, element);
dropDetails.colkey = tHead.getHeaderCell(childIndex)
.getColKey();
dropDetails.dropLocation = VerticalDropLocation.get(row
.getElement(), drag.getCurrentGwtEvent().getClientY(),
0.2);
}
drag.getDropDetails().put("itemIdOver", dropDetails.overkey + "");
drag.getDropDetails().put(
"detail",
dropDetails.dropLocation != null ? dropDetails.dropLocation
.toString() : null);
}
@Override
public void dragOver(VDragEvent drag) {
TableDDDetails oldDetails = dropDetails;
updateDropDetails(drag);
if (!oldDetails.equals(dropDetails)) {
deEmphasis();
VAcceptCallback cb = new VAcceptCallback() {
public void accepted(VDragEvent event) {
dragAccepted(event);
}
};
validate(cb, drag);
}
}
@Override
public void dragLeave(VDragEvent drag) {
deEmphasis();
super.dragLeave(drag);
}
@Override
public boolean drop(VDragEvent drag) {
deEmphasis();
return super.drop(drag);
}
private void deEmphasis() {
if (lastEmphasized == null) {
return;
}
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (lastEmphasized != null
&& row.rowKey == lastEmphasized.overkey) {
if (row != null) {
String stylename = ROWSTYLEBASE
+ lastEmphasized.dropLocation.toString()
.toLowerCase();
VScrollTableRow.setStyleName(row.getElement(),
stylename, false);
}
lastEmphasized = null;
return;
}
}
}
/**
* TODO needs different drop modes ?? (on cells, on rows), now only
* supports rows
*/
private void emphasis(TableDDDetails details) {
deEmphasis();
// iterate old and new emphasized row
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (details != null && details.overkey == row.rowKey) {
if (row != null) {
String stylename = ROWSTYLEBASE
+ details.dropLocation.toString().toLowerCase();
VScrollTableRow.setStyleName(row.getElement(),
stylename, true);
}
lastEmphasized = details;
return;
}
}
}
@Override
protected void dragAccepted(VDragEvent drag) {
emphasis(dropDetails);
}
@Override
public Paintable getPaintable() {
return VScrollTable.this;
}
public ApplicationConnection getApplicationConnection() {
return client;
}
}
=======
public void onValueChange(ValueChangeEvent<String> arg0) {
client.getContextMenu().hide();
}
>>>>>>>
public VScrollTableDropHandler getDropHandler() {
return dropHandler;
}
private static class TableDDDetails {
int overkey = -1;
VerticalDropLocation dropLocation;
String colkey;
@Override
public boolean equals(Object obj) {
if (obj instanceof TableDDDetails) {
TableDDDetails other = (TableDDDetails) obj;
return dropLocation == other.dropLocation
&& overkey == other.overkey
&& ((colkey != null && colkey.equals(other.colkey)) || (colkey == null && other.colkey == null));
}
return false;
}
// @Override
// public int hashCode() {
// return overkey;
// }
}
public class VScrollTableDropHandler extends VAbstractDropHandler {
private static final String ROWSTYLEBASE = "v-table-row-drag-";
private TableDDDetails dropDetails;
private TableDDDetails lastEmphasized;
@Override
public void dragEnter(VDragEvent drag) {
updateDropDetails(drag);
super.dragEnter(drag);
}
private void updateDropDetails(VDragEvent drag) {
dropDetails = new TableDDDetails();
Element elementOver = drag.getElementOver();
VScrollTableRow row = Util.findWidget(elementOver,
VScrollTableRow.class);
if (row != null) {
dropDetails.overkey = row.rowKey;
Element tr = row.getElement();
Element element = elementOver;
while (element != null && element.getParentElement() != tr) {
element = (Element) element.getParentElement();
}
int childIndex = DOM.getChildIndex(tr, element);
dropDetails.colkey = tHead.getHeaderCell(childIndex)
.getColKey();
dropDetails.dropLocation = VerticalDropLocation.get(row
.getElement(), drag.getCurrentGwtEvent().getClientY(),
0.2);
}
drag.getDropDetails().put("itemIdOver", dropDetails.overkey + "");
drag.getDropDetails().put(
"detail",
dropDetails.dropLocation != null ? dropDetails.dropLocation
.toString() : null);
}
@Override
public void dragOver(VDragEvent drag) {
TableDDDetails oldDetails = dropDetails;
updateDropDetails(drag);
if (!oldDetails.equals(dropDetails)) {
deEmphasis();
VAcceptCallback cb = new VAcceptCallback() {
public void accepted(VDragEvent event) {
dragAccepted(event);
}
};
validate(cb, drag);
}
}
@Override
public void dragLeave(VDragEvent drag) {
deEmphasis();
super.dragLeave(drag);
}
@Override
public boolean drop(VDragEvent drag) {
deEmphasis();
return super.drop(drag);
}
private void deEmphasis() {
if (lastEmphasized == null) {
return;
}
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (lastEmphasized != null
&& row.rowKey == lastEmphasized.overkey) {
if (row != null) {
String stylename = ROWSTYLEBASE
+ lastEmphasized.dropLocation.toString()
.toLowerCase();
VScrollTableRow.setStyleName(row.getElement(),
stylename, false);
}
lastEmphasized = null;
return;
}
}
}
/**
* TODO needs different drop modes ?? (on cells, on rows), now only
* supports rows
*/
private void emphasis(TableDDDetails details) {
deEmphasis();
// iterate old and new emphasized row
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (details != null && details.overkey == row.rowKey) {
if (row != null) {
String stylename = ROWSTYLEBASE
+ details.dropLocation.toString().toLowerCase();
VScrollTableRow.setStyleName(row.getElement(),
stylename, true);
}
lastEmphasized = details;
return;
}
}
}
@Override
protected void dragAccepted(VDragEvent drag) {
emphasis(dropDetails);
}
@Override
public Paintable getPaintable() {
return VScrollTable.this;
}
public ApplicationConnection getApplicationConnection() {
return client;
}
}
public void onValueChange(ValueChangeEvent<String> arg0) {
client.getContextMenu().hide();
} |
<<<<<<<
=======
private Object decodeVariable(String[] variable) {
try {
return convertVariableValue(variable[VAR_TYPE].charAt(0),
variable[VAR_VALUE]);
} catch (Exception e) {
String pid = variable[VAR_PID];
VariableOwner variableOwner = getVariableOwner(pid);
throw new RuntimeException("Could not convert variable \""
+ variable[VAR_NAME] + "\" for "
+ variableOwner.getClass().getName() + " (" + pid + ")", e);
}
}
private Object convertVariableValue(char variableType, String strValue) {
Object val = null;
switch (variableType) {
case VTYPE_ARRAY:
val = convertArray(strValue);
break;
case VTYPE_MAP:
val = convertMap(strValue);
break;
case VTYPE_STRINGARRAY:
val = convertStringArray(strValue);
break;
case VTYPE_STRING:
// decode encoded separators
val = decodeVariableValue(strValue);
break;
case VTYPE_INTEGER:
val = Integer.valueOf(strValue);
break;
case VTYPE_LONG:
val = Long.valueOf(strValue);
break;
case VTYPE_FLOAT:
val = Float.valueOf(strValue);
break;
case VTYPE_DOUBLE:
val = Double.valueOf(strValue);
break;
case VTYPE_BOOLEAN:
val = Boolean.valueOf(strValue);
break;
case VTYPE_PAINTABLE:
val = idPaintableMap.get(strValue);
break;
}
return val;
}
private Object convertMap(String strValue) {
String[] parts = strValue
.split(String.valueOf(VAR_ARRAYITEM_SEPARATOR));
HashMap<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < parts.length; i += 2) {
String key = parts[i];
if (key.length() > 0) {
char variabletype = key.charAt(0);
// decode encoded separators
String decodedValue = decodeVariableValue(parts[i + 1]);
String decodedKey = decodeVariableValue(key.substring(1));
Object value = convertVariableValue(variabletype, decodedValue);
map.put(decodedKey, value);
}
}
return map;
}
private String[] convertStringArray(String strValue) {
// need to return delimiters and filter them out; otherwise empty
// strings are lost
// an extra empty delimiter at the end is automatically eliminated
final String arrayItemSeparator = String
.valueOf(VAR_ARRAYITEM_SEPARATOR);
StringTokenizer tokenizer = new StringTokenizer(strValue,
arrayItemSeparator, true);
List<String> tokens = new ArrayList<String>();
String prevToken = arrayItemSeparator;
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (!arrayItemSeparator.equals(token)) {
// decode encoded separators
tokens.add(decodeVariableValue(token));
} else if (arrayItemSeparator.equals(prevToken)) {
tokens.add("");
}
prevToken = token;
}
return tokens.toArray(new String[tokens.size()]);
}
private Object convertArray(String strValue) {
String[] val = strValue.split(String.valueOf(VAR_ARRAYITEM_SEPARATOR));
if (val.length == 0 || (val.length == 1 && val[0].length() == 0)) {
return new Object[0];
}
Object[] values = new Object[val.length];
for (int i = 0; i < values.length; i++) {
String string = val[i];
// first char of string is type
char variableType = string.charAt(0);
values[i] = convertVariableValue(variableType, string.substring(1));
}
return values;
}
>>>>>>> |
<<<<<<<
/**
* Enable clientSideMode which uses `frontend/index` as the entry
* point.
*
* @param clientSideMode
* <code>true</code> to enable the mode, false otherwise.
* @return the builder, for chaining
*/
public Builder enableClientSideMode(boolean clientSideMode) {
this.clientSideMode = clientSideMode;
return this;
}
=======
/**
* Sets frontend scanner strategy: byte code scanning strategy is used
* if {@code byteCodeScanner} is {@code true}, full classpath scanner
* strategy is used otherwise (by default).
*
* @param byteCodeScanner
* if {@code true} then byte code scanner is used, full
* scanner is used otherwise (by default).
* @return the builder, for chaining
*/
public Builder useByteCodeScanner(boolean byteCodeScanner) {
this.useByteCodeScanner = byteCodeScanner;
return this;
}
/**
* Fill token file data into the provided {@code object}.
*
* @param object
* the object to fill with token file data
* @return the builder, for chaining
*/
public Builder populateTokenFileData(JsonObject object) {
tokenFileData = object;
return this;
}
>>>>>>>
/**
* Enable clientSideMode which uses `frontend/index` as the entry
* point.
*
* @param clientSideMode
* <code>true</code> to enable the mode, false otherwise.
* @return the builder, for chaining
*/
public Builder enableClientSideMode(boolean clientSideMode) {
this.clientSideMode = clientSideMode;
return this;
}
/**
* Sets frontend scanner strategy: byte code scanning strategy is used
* if {@code byteCodeScanner} is {@code true}, full classpath scanner
* strategy is used otherwise (by default).
*
* @param byteCodeScanner
* if {@code true} then byte code scanner is used, full
* scanner is used otherwise (by default).
* @return the builder, for chaining
*/
public Builder useByteCodeScanner(boolean byteCodeScanner) {
this.useByteCodeScanner = byteCodeScanner;
return this;
}
/**
* Fill token file data into the provided {@code object}.
*
* @param object
* the object to fill with token file data
* @return the builder, for chaining
*/
public Builder populateTokenFileData(JsonObject object) {
tokenFileData = object;
return this;
}
<<<<<<<
private void generateClientBootstrapFiles(Builder builder) {
if (builder.clientSideMode) {
File outputDirectory = new File(builder.npmFolder,
FrontendUtils.TARGET);
TaskGenerateIndexHtml taskGenerateIndexHtml = new TaskGenerateIndexHtml(
builder.frontendDirectory,
outputDirectory);
commands.add(taskGenerateIndexHtml);
TaskGenerateIndexJs taskGenerateIndexJs = new TaskGenerateIndexJs(
builder.frontendDirectory,
new File(builder.generatedFolder, IMPORTS_NAME), outputDirectory);
commands.add(taskGenerateIndexJs);
TaskGenerateTsConfig taskGenerateTsConfig = new TaskGenerateTsConfig(
builder.frontendDirectory,
builder.npmFolder);
commands.add(taskGenerateTsConfig);
}
}
=======
private FrontendDependenciesScanner getFallbackScanner(Builder builder,
ClassFinder finder) {
if (builder.useByteCodeScanner) {
return new FrontendDependenciesScanner.FrontendDependenciesScannerFactory()
.createScanner(true, finder,
builder.generateEmbeddableWebComponents);
} else {
return null;
}
}
>>>>>>>
private void generateClientBootstrapFiles(Builder builder) {
if (builder.clientSideMode) {
File outputDirectory = new File(builder.npmFolder,
FrontendUtils.TARGET);
TaskGenerateIndexHtml taskGenerateIndexHtml = new TaskGenerateIndexHtml(
builder.frontendDirectory, outputDirectory);
commands.add(taskGenerateIndexHtml);
TaskGenerateIndexJs taskGenerateIndexJs = new TaskGenerateIndexJs(
builder.frontendDirectory,
new File(builder.generatedFolder, IMPORTS_NAME),
outputDirectory);
commands.add(taskGenerateIndexJs);
TaskGenerateTsConfig taskGenerateTsConfig = new TaskGenerateTsConfig(
builder.frontendDirectory, builder.npmFolder);
commands.add(taskGenerateTsConfig);
}
}
private FrontendDependenciesScanner getFallbackScanner(Builder builder,
ClassFinder finder) {
if (builder.useByteCodeScanner) {
return new FrontendDependenciesScanner.FrontendDependenciesScannerFactory()
.createScanner(true, finder,
builder.generateEmbeddableWebComponents);
} else {
return null;
}
} |
<<<<<<<
private final boolean isClientSideMode;
=======
private final transient Path frontendDirectory;
>>>>>>>
private final transient Path frontendDirectory;
private final boolean isClientSideMode;
<<<<<<<
=======
if (lines.get(i).startsWith("const frontendFolder")) {
lines.set(i, frontendLine);
}
}
>>>>>>>
if (lines.get(i).startsWith("const frontendFolder")) {
lines.set(i, frontendLine);
} |
<<<<<<<
Assert.assertEquals(Pattern.compile("r02.*").pattern(), patterns.get(BAR.getTableName()).pattern());
Map<Table.ID,String> tids = this.getTableIdToTableName();
=======
Assert.assertEquals(Pattern.compile("r02.*").pattern(),
patterns.get(BAR.getTableName()).pattern());
Map<String,String> tids = this.getTableIdToTableName();
>>>>>>>
Assert.assertEquals(Pattern.compile("r02.*").pattern(),
patterns.get(BAR.getTableName()).pattern());
Map<Table.ID,String> tids = this.getTableIdToTableName();
<<<<<<<
init(new AccumuloServerContext(instance, factory));
// lets say we already have migrations ongoing for the FOO and BAR table extends (should be 5 of each of them) for a total of 10
=======
init(factory);
// lets say we already have migrations ongoing for the FOO and BAR table extends (should be 5 of
// each of them) for a total of 10
>>>>>>>
init(new AccumuloServerContext(instance, factory));
// lets say we already have migrations ongoing for the FOO and BAR table extends (should be 5 of
// each of them) for a total of 10
<<<<<<<
init(new AccumuloServerContext(instance, factory));
Map<String,SortedMap<TServerInstance,TabletServerStatus>> groups = this.splitCurrentByRegex(createCurrent(15));
=======
init(factory);
Map<String,SortedMap<TServerInstance,TabletServerStatus>> groups = this
.splitCurrentByRegex(createCurrent(15));
>>>>>>>
init(new AccumuloServerContext(instance, factory));
Map<String,SortedMap<TServerInstance,TabletServerStatus>> groups = this
.splitCurrentByRegex(createCurrent(15));
<<<<<<<
}));
Map<String,SortedMap<TServerInstance,TabletServerStatus>> groups = this.splitCurrentByRegex(createCurrent(15));
=======
});
Map<String,SortedMap<TServerInstance,TabletServerStatus>> groups = this
.splitCurrentByRegex(createCurrent(15));
>>>>>>>
}));
Map<String,SortedMap<TServerInstance,TabletServerStatus>> groups = this
.splitCurrentByRegex(createCurrent(15));
<<<<<<<
init(new AccumuloServerContext(instance, factory));
// Wait to trigger the out of bounds check which will call our version of getOnlineTabletsForTable
=======
init(factory);
// Wait to trigger the out of bounds check which will call our version of
// getOnlineTabletsForTable
>>>>>>>
init(new AccumuloServerContext(instance, factory));
// Wait to trigger the out of bounds check which will call our version of
// getOnlineTabletsForTable
<<<<<<<
public List<TabletStats> getOnlineTabletsForTable(TServerInstance tserver, Table.ID tableId) throws TException {
=======
public List<TabletStats> getOnlineTabletsForTable(TServerInstance tserver, String tableId)
throws ThriftSecurityException, TException {
>>>>>>>
public List<TabletStats> getOnlineTabletsForTable(TServerInstance tserver, Table.ID tableId)
throws TException { |
<<<<<<<
public void setSplitPosition(int pos) {
setSplitPosition(pos, posUnit, false);
=======
public void setSplitPosition(float pos) {
setSplitPosition(pos, posUnit, true, false);
>>>>>>>
public void setSplitPosition(float pos) {
setSplitPosition(pos, posUnit, false);
<<<<<<<
public void setSplitPosition(int pos, boolean reverse) {
setSplitPosition(pos, posUnit, reverse);
=======
public void setSplitPosition(float pos, boolean reverse) {
setSplitPosition(pos, posUnit, true, reverse);
>>>>>>>
public void setSplitPosition(float pos, boolean reverse) {
setSplitPosition(pos, posUnit, reverse);
<<<<<<<
public void setSplitPosition(int pos, Unit unit) {
setSplitPosition(pos, unit, false);
=======
public void setSplitPosition(float pos, int unit) {
setSplitPosition(pos, unit, true, false);
>>>>>>>
public void setSplitPosition(float pos, Unit unit) {
setSplitPosition(pos, unit, false);
<<<<<<<
public void setSplitPosition(int pos, Unit unit, boolean reverse) {
if (unit != Unit.PERCENTAGE && unit != Unit.PIXELS) {
throw new IllegalArgumentException(
"Only percentage and pixel units are allowed");
}
SplitterState splitterState = getState().getSplitterState();
splitterState.setPosition(pos);
splitterState.setPositionUnit(unit.getSymbol());
splitterState.setPositionReversed(reverse);
posUnit = unit;
requestRepaint();
=======
public void setSplitPosition(float pos, int unit, boolean reverse) {
setSplitPosition(pos, unit, true, reverse);
>>>>>>>
public void setSplitPosition(float pos, Unit unit, boolean reverse) {
if (unit != Unit.PERCENTAGE && unit != Unit.PIXELS) {
throw new IllegalArgumentException(
"Only percentage and pixel units are allowed");
}
if (unit != Unit.PERCENTAGE) {
pos = Math.round(pos);
}
SplitterState splitterState = getState().getSplitterState();
splitterState.setPosition(pos);
splitterState.setPositionUnit(unit.getSymbol());
splitterState.setPositionReversed(reverse);
posUnit = unit;
requestRepaint();
<<<<<<<
public int getSplitPosition() {
return getState().getSplitterState().getPosition();
=======
public float getSplitPosition() {
return pos;
>>>>>>>
public float getSplitPosition() {
return getState().getSplitterState().getPosition();
<<<<<<<
=======
* Moves the position of the splitter.
*
* @param pos
* the new size of the first region. Fractions are only allowed
* when unit is percentage.
* @param unit
* the unit (from {@link Sizeable}) in which the size is given.
* @param repaintNotNeeded
* true if client side needs to be updated. Use false if the
* position info has come from the client side, thus it already
* knows the position.
*/
private void setSplitPosition(float pos, int unit, boolean repaintNeeded,
boolean reverse) {
if (unit != UNITS_PERCENTAGE && unit != UNITS_PIXELS) {
throw new IllegalArgumentException(
"Only percentage and pixel units are allowed");
}
if (unit != UNITS_PERCENTAGE) {
pos = Math.round(pos);
}
this.pos = pos;
posUnit = unit;
posReversed = reverse;
if (repaintNeeded) {
requestRepaint();
}
}
/**
>>>>>>>
<<<<<<<
return getState().getSplitterState().isLocked();
=======
return locked;
}
/*
* Invoked when a variable of the component changes. Don't add a JavaDoc
* comment here, we use the default documentation from implemented
* interface.
*/
@SuppressWarnings("unchecked")
@Override
public void changeVariables(Object source, Map<String, Object> variables) {
super.changeVariables(source, variables);
if (variables.containsKey("position") && !isLocked()) {
Float newPos = (Float) variables.get("position");
setSplitPosition(newPos, posUnit, posReversed);
}
if (variables.containsKey(SPLITTER_CLICK_EVENT)) {
fireClick((Map<String, Object>) variables.get(SPLITTER_CLICK_EVENT));
}
}
@Override
protected void fireClick(Map<String, Object> parameters) {
MouseEventDetails mouseDetails = MouseEventDetails
.deSerialize((String) parameters.get("mouseDetails"));
fireEvent(new SplitterClickEvent(this, mouseDetails));
>>>>>>>
return getState().getSplitterState().isLocked(); |
<<<<<<<
import com.vaadin.annotations.RootInitRequiresBrowserDetals;
import com.vaadin.annotations.RootTheme;
import com.vaadin.annotations.RootWidgetset;
=======
import com.vaadin.data.util.converter.Converter;
import com.vaadin.data.util.converter.ConverterFactory;
import com.vaadin.data.util.converter.DefaultConverterFactory;
>>>>>>>
import com.vaadin.annotations.RootInitRequiresBrowserDetals;
import com.vaadin.annotations.RootTheme;
import com.vaadin.annotations.RootWidgetset;
import com.vaadin.data.util.converter.Converter;
import com.vaadin.data.util.converter.ConverterFactory;
import com.vaadin.data.util.converter.DefaultConverterFactory;
<<<<<<<
import com.vaadin.ui.Root;
=======
import com.vaadin.ui.AbstractField;
>>>>>>>
import com.vaadin.ui.AbstractField;
import com.vaadin.ui.Root;
<<<<<<<
private LinkedList<RequestHandler> requestHandlers = new LinkedList<RequestHandler>();
=======
/**
* The converter factory that is used for all fields in the application.
*/
// private ConverterFactory converterFactory = new
// DefaultConverterFactory();
private static ConverterFactory converterFactory = new DefaultConverterFactory();
/**
* <p>
* Gets a window by name. Returns <code>null</code> if the application is
* not running or it does not contain a window corresponding to the name.
* </p>
*
* <p>
* All windows can be referenced by their names in url
* <code>http://host:port/foo/bar/</code> where
* <code>http://host:port/foo/</code> is the application url as returned by
* getURL() and <code>bar</code> is the name of the window.
* </p>
*
* <p>
* One should note that this method can, as a side effect create new windows
* if needed by the application. This can be achieved by overriding the
* default implementation.
* </p>
*
* <p>
* If for some reason user opens another window with same url that is
* already open, name is modified by adding "_12345678" postfix to the name,
* where 12345678 is a random number. One can decide to create another
* window-object for those windows (recommended) or to discard the postfix.
* If the user has two browser windows pointing to the same window-object on
* server, synchronization errors are likely to occur.
* </p>
*
* <p>
* If no browser-level windowing is used, all defaults are fine and this
* method can be left as is. In case browser-level windows are needed, it is
* recommended to create new window-objects on this method from their names
* if the super.getWindow() does not find existing windows. See below for
* implementation example: <code><pre>
// If we already have the requested window, use it
Window w = super.getWindow(name);
if (w == null) {
// If no window found, create it
w = new Window(name);
// set windows name to the one requested
w.setName(name);
// add it to this application
addWindow(w);
// ensure use of window specific url
w.open(new ExternalResource(w.getURL().toString()));
// add some content
w.addComponent(new Label("Test window"));
}
return w;</pre></code>
* </p>
*
* <p>
* <strong>Note</strong> that all returned Window objects must be added to
* this application instance.
*
* <p>
* The method should return null if the window does not exists (and is not
* created as a side-effect) or if the application is not running anymore.
* </p>
*
* @param name
* the name of the window.
* @return the window associated with the given URI or <code>null</code>
*/
public Window getWindow(String name) {
// For closed app, do not give any windows
if (!isRunning()) {
return null;
}
>>>>>>>
/**
* The converter factory that is used for all fields in the application.
*/
// private ConverterFactory converterFactory = new
// DefaultConverterFactory();
private static ConverterFactory converterFactory = new DefaultConverterFactory();
private LinkedList<RequestHandler> requestHandlers = new LinkedList<RequestHandler>(); |
<<<<<<<
for (final Iterator<File> i = ll.iterator(); i.hasNext();) {
final File lf = i.next();
=======
for (final Iterator i = ll.iterator(); i.hasNext();) {
final File lf = (File) i.next();
col.add(lf);
>>>>>>>
for (final Iterator<File> i = ll.iterator(); i.hasNext();) {
final File lf = i.next();
col.add(lf); |
<<<<<<<
getScanner(classFinder), baseDir, generatedDir, false, false);
=======
getScanner(classFinder), baseDir, generatedDir, resourcesDir, false, true);
>>>>>>>
getScanner(classFinder), baseDir, generatedDir, resourcesDir, false, false);
<<<<<<<
getScanner(classFinder), baseDir, generatedDir, false, false);
=======
getScanner(classFinder), baseDir, generatedDir, null, false, true);
>>>>>>>
getScanner(classFinder), baseDir, generatedDir, null, false, false);
<<<<<<<
getScanner(classFinder), baseDir, generatedDir, false, true);
=======
getScanner(classFinder), baseDir, generatedDir, null, false, false);
>>>>>>>
getScanner(classFinder), baseDir, generatedDir, null, false, true);
<<<<<<<
getScanner(classFinder), baseDir, generatedDir, false, false);
=======
getScanner(classFinder), baseDir, generatedDir, null, false, true);
>>>>>>>
getScanner(classFinder), baseDir, generatedDir, null, false, false);
<<<<<<<
getScanner(classFinder), baseDir, generatedDir, false, true);
=======
getScanner(classFinder), baseDir, generatedDir, null, false, false);
>>>>>>>
getScanner(classFinder), baseDir, generatedDir, null, false, true);
<<<<<<<
baseDir, generatedDir, false, false);
=======
baseDir, generatedDir, null, false, true);
>>>>>>>
baseDir, generatedDir, null, false, false);
<<<<<<<
getScanner(classFinder), baseDir, generatedDir, true, false);
=======
getScanner(classFinder), baseDir, generatedDir, null, true, true);
>>>>>>>
getScanner(classFinder), baseDir, generatedDir, null, true, false);
<<<<<<<
baseDir, generatedDir, false, false);
=======
baseDir, generatedDir, null, false, true);
>>>>>>>
baseDir, generatedDir, null, false, false);
<<<<<<<
baseDir, generatedDir, false, false);
=======
baseDir, generatedDir, null, false, true);
>>>>>>>
baseDir, generatedDir, null, false, false);
<<<<<<<
baseDir, generatedDir, false, false);
=======
baseDir, generatedDir, null, false, true);
>>>>>>>
baseDir, generatedDir, null, false, false);
<<<<<<<
baseDir, generatedDir, false, false);
=======
baseDir, generatedDir, null, false, true);
>>>>>>>
baseDir, generatedDir, null, false, false);
<<<<<<<
baseDir, generatedDir, false, false);
=======
baseDir, generatedDir, null, false, true);
>>>>>>>
baseDir, generatedDir, null, false, false);
<<<<<<<
baseDir, generatedDir, false, false);
=======
baseDir, generatedDir, null, false, true);
>>>>>>>
baseDir, generatedDir, null, false, false);
<<<<<<<
baseDir, generatedDir, false, false);
=======
baseDir, generatedDir, null, false, true);
>>>>>>>
baseDir, generatedDir, null, false, false);
<<<<<<<
baseDir, generatedDir, false, false);
=======
baseDir, generatedDir, null, false, true);
>>>>>>>
baseDir, generatedDir, null, false, false);
<<<<<<<
baseDir, generatedDir, false, false);
=======
baseDir, generatedDir, null, false, true);
>>>>>>>
baseDir, generatedDir, null, false, false);
<<<<<<<
baseDir, generatedDir, false, isPnpm);
=======
baseDir, generatedDir, null, false, isNpm);
>>>>>>>
baseDir, generatedDir, null, false, isPnpm); |
<<<<<<<
=======
* Checks the validity of the the given value. The value is valid, if:
* <ul>
* <li>{@link CombinationMode.AND}: All of the sub-validators are valid
* <li>{@link CombinationMode.OR}: Any of the sub-validators are valid
* </ul>
*
* @param value
* the value to check.
*/
public boolean isValid(Object value) {
switch (mode) {
case AND:
for (Validator v : validators) {
if (!v.isValid(value)) {
return false;
}
}
return true;
case OR:
for (Validator v : validators) {
if (v.isValid(value)) {
return true;
}
}
return false;
}
throw new IllegalStateException(
"The validator is in unsupported operation mode");
}
/**
>>>>>>> |
<<<<<<<
import com.vaadin.ui.Root;
=======
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Window;
>>>>>>>
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Root; |
<<<<<<<
@Override
public void removeExtension(Extension feature) {
=======
public void removeExtension(Extension extension) {
>>>>>>>
@Override
public void removeExtension(Extension extension) { |
<<<<<<<
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import junit.framework.Assert;
=======
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
>>>>>>>
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import junit.framework.Assert;
<<<<<<<
import org.jongo.util.ErrorObject;
=======
import org.jongo.model.LinkedFriend;
>>>>>>>
import org.jongo.model.LinkedFriend;
import org.jongo.util.ErrorObject;
<<<<<<<
@Test
=======
@Test(expected = IllegalArgumentException.class)
public void shouldFailWhenMarshalledJsonIsInvalid() throws Exception {
Marshaller marshaller = mock(Marshaller.class);
Unmarshaller unmarshaller = mock(Unmarshaller.class);
when(marshaller.marshall(anyObject())).thenReturn("invalid");
Save save = new Save(collection.getDBCollection(), marshaller, unmarshaller, new Object());
save.execute();
}
@Test(expected = IllegalArgumentException.class)
>>>>>>>
@Test
<<<<<<<
try {
collection.save(new ErrorObject());
Assert.fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage()).contains("Unable to save object");
}
=======
Marshaller marshaller = mock(Marshaller.class);
Unmarshaller unmarshaller = mock(Unmarshaller.class);
when(marshaller.marshall(anyObject())).thenThrow(new RuntimeException());
Save save = new Save(collection.getDBCollection(), marshaller, unmarshaller, new Object());
save.execute();
>>>>>>>
try {
collection.save(new ErrorObject());
Assert.fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage()).contains("Unable to save object");
} |
<<<<<<<
import com.mongodb.MongoCommandException;
=======
import com.mongodb.AggregationOptions;
import com.mongodb.CommandFailureException;
>>>>>>>
import com.mongodb.AggregationOptions;
import com.mongodb.MongoCommandException; |
<<<<<<<
<T> T unmarshall(byte[] data, int offset, Class<T> clazz) throws MarshallingException;
=======
<T> T unmarshall(String json, Class<T> clazz) throws MarshallingException;
void setDocumentGeneratedId(Object document, String id);
>>>>>>>
<T> T unmarshall(byte[] data, int offset, Class<T> clazz) throws MarshallingException;
void setDocumentGeneratedId(Object document, String id); |
<<<<<<<
import com.luck.picture.lib.instagram.InstagramSelectionConfig;
import com.luck.picture.lib.listener.OnPictureSelectorInterfaceListener;
=======
import com.luck.picture.lib.listener.OnCustomCameraInterfaceListener;
>>>>>>>
import com.luck.picture.lib.instagram.InstagramSelectionConfig;
import com.luck.picture.lib.listener.OnCustomCameraInterfaceListener;
<<<<<<<
instagramSelectionConfig = null;
=======
cameraMimeType = -1;
pageSize = PictureConfig.MAX_PAGE_SIZE;
isPageStrategy = true;
isFilterInvalidFile = false;
isMaxSelectEnabledMask = false;
animationMode = -1;
isAutomaticTitleRecyclerTop = true;
isCallbackMode = false;
isAndroidQChangeWH = true;
isAndroidQChangeVideoWH = false;
isQuickCapture = true;
>>>>>>>
instagramSelectionConfig = null;
cameraMimeType = -1;
pageSize = PictureConfig.MAX_PAGE_SIZE;
isPageStrategy = true;
isFilterInvalidFile = false;
isMaxSelectEnabledMask = false;
animationMode = -1;
isAutomaticTitleRecyclerTop = true;
isCallbackMode = false;
isAndroidQChangeWH = true;
isAndroidQChangeVideoWH = false;
isQuickCapture = true; |
<<<<<<<
import com.falcon.suitagent.util.OSUtil;
=======
import com.falcon.suitagent.util.StringUtils;
>>>>>>>
import com.falcon.suitagent.util.OSUtil;
import com.falcon.suitagent.util.StringUtils;
<<<<<<<
DockerMetrics dockerMetrics = new DockerMetrics("0.0.0.0",Integer.parseInt(address));
List<DockerMetrics.CollectObject> collectObjectList = dockerMetrics.getMetrics();
List<DetectResult.Metric> metrics = new ArrayList<>();
for (DockerMetrics.CollectObject collectObject : collectObjectList) {
DetectResult.Metric metric = new DetectResult.Metric(collectObject.getMetric(),
collectObject.getValue(),
CounterType.GAUGE,
"containerName=" + collectObject.getContainerName() + collectObject.getTags());
metrics.add(metric);
=======
CommandUtilForUnix.ExecuteResult executeResult = CommandUtilForUnix.execWithReadTimeLimit("docker ps",false,7);
if(executeResult.isSuccess){
DockerMetrics dockerMetrics = new DockerMetrics("0.0.0.0",Integer.parseInt(address));
List<DockerMetrics.CollectObject> collectObjectList = dockerMetrics.getMetrics();
List<DetectResult.Metric> metrics = new ArrayList<>();
for (DockerMetrics.CollectObject collectObject : collectObjectList) {
DetectResult.Metric metric = new DetectResult.Metric(collectObject.getMetric(),
collectObject.getValue(),
CounterType.GAUGE,
"containerName=" + collectObject.getContainerName() + (StringUtils.isEmpty(collectObject.getTags()) ? "" : ("," + collectObject.getTags())));
metrics.add(metric);
}
detectResult.setMetricsList(metrics);
detectResult.setSuccess(true);
}else{
log.error("Docker daemon failed : {}",executeResult.msg);
detectResult.setSuccess(false);
>>>>>>>
DockerMetrics dockerMetrics = new DockerMetrics("0.0.0.0",Integer.parseInt(address));
List<DockerMetrics.CollectObject> collectObjectList = dockerMetrics.getMetrics();
List<DetectResult.Metric> metrics = new ArrayList<>();
for (DockerMetrics.CollectObject collectObject : collectObjectList) {
DetectResult.Metric metric = new DetectResult.Metric(collectObject.getMetric(),
collectObject.getValue(),
CounterType.GAUGE,
"containerName=" + collectObject.getContainerName() + collectObject.getTags());
metrics.add(metric); |
<<<<<<<
import com.tinkerpop.rexster.protocol.msg.MessageType;
=======
import com.tinkerpop.rexster.protocol.msg.MsgPackScriptResponseMessage;
>>>>>>>
import com.tinkerpop.rexster.protocol.msg.MessageType;
import com.tinkerpop.rexster.protocol.msg.MsgPackScriptResponseMessage;
<<<<<<<
byte messageType = unpacker.readByte();
=======
>>>>>>>
unpacker.setArraySizeLimit(Integer.MAX_VALUE);
unpacker.setMapSizeLimit(Integer.MAX_VALUE);
unpacker.setRawSizeLimit(Integer.MAX_VALUE);
<<<<<<<
ByteArrayOutputStream out = new ByteArrayOutputStream();
Packer packer = msgpack.createPacker(out);
=======
ByteArrayOutputStream rexProMessageStream = new ByteArrayOutputStream();
Packer packer = msgpack.createPacker(rexProMessageStream);
packer.write(message);
byte[] rexProMessageAsBytes = rexProMessageStream.toByteArray();
rexProMessageStream.close();
ByteBuffer bb = ByteBuffer.allocate(5 + rexProMessageAsBytes.length);
>>>>>>>
ByteArrayOutputStream rexProMessageStream = new ByteArrayOutputStream();
Packer packer = msgpack.createPacker(rexProMessageStream);
packer.write(message);
byte[] rexProMessageAsBytes = rexProMessageStream.toByteArray();
rexProMessageStream.close();
ByteBuffer bb = ByteBuffer.allocate(5 + rexProMessageAsBytes.length);
<<<<<<<
packer.write(message);
byte[] messageAsBytes = out.toByteArray();
out.close();
=======
bb.putInt(rexProMessageAsBytes.length);
bb.put(rexProMessageAsBytes);
byte[] messageAsBytes = bb.array();
>>>>>>>
bb.putInt(rexProMessageAsBytes.length);
bb.put(rexProMessageAsBytes);
byte[] messageAsBytes = bb.array(); |
<<<<<<<
@Test
public void testRemoteUrlWithQueryString() throws IOException {
final String expectedUrl = "http://some-http-server.com/image/with/query/parameters/image.png?a=b&c=d";
String code = "background : url(/image/with/query/parameters/image.png?a=b&c=d)";
StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), CSSURLEmbedder.DATAURI_OPTION, true, 0, 200) {
/*
* Override method to prevent a network call during unit tests
*/
@Override
String getImageURIString(String url, String originalUrl) throws IOException {
if(url.equals("")) {
throw new IllegalArgumentException("Expected URL " + expectedUrl + ", but found " + url);
}
return "data:image/gif;base64,AAAABBBBCCCCDDDD";
}
};
embedder.embedImages(writer, "http://some-http-server.com/");
String result = writer.toString();
assertEquals("background : url(data:image/gif;base64,AAAABBBBCCCCDDDD)", result);
}
@Test
public void testImageDetection() {
String tests[] = {
"file://path/to/image.png",
"http://some.server.com/image.png",
"http://some.server.com/image.png?param=legalvalue&anotherparam=anothervalue",
"http://some.server.com/image.png?param=illegal.value.with.period"
};
boolean expectedImage[] = {
true, true, true, false
};
for(int i=0; i<tests.length; i++) {
if(expectedImage[i]) {
assertTrue("Expected " + tests[i] + " to resolve to an image", CSSURLEmbedder.isImage(tests[i]));
}
else {
assertFalse("Did NOT expect " + tests[i] + " to resolve as an image", CSSURLEmbedder.isImage(tests[i]));
}
}
}
=======
@Test
public void testRegularUrlWithSkipComment() throws IOException {
String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png); /* CssEmbed: SKIP */";
StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));
String result = writer.toString();
//assert that nothing changed
assertEquals(code, result);
}
>>>>>>>
@Test
public void testRemoteUrlWithQueryString() throws IOException {
final String expectedUrl = "http://some-http-server.com/image/with/query/parameters/image.png?a=b&c=d";
String code = "background : url(/image/with/query/parameters/image.png?a=b&c=d)";
StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), CSSURLEmbedder.DATAURI_OPTION, true, 0, 200) {
/*
* Override method to prevent a network call during unit tests
*/
@Override
String getImageURIString(String url, String originalUrl) throws IOException {
if(url.equals("")) {
throw new IllegalArgumentException("Expected URL " + expectedUrl + ", but found " + url);
}
return "data:image/gif;base64,AAAABBBBCCCCDDDD";
}
};
embedder.embedImages(writer, "http://some-http-server.com/");
String result = writer.toString();
assertEquals("background : url(data:image/gif;base64,AAAABBBBCCCCDDDD)", result);
}
@Test
public void testImageDetection() {
String tests[] = {
"file://path/to/image.png",
"http://some.server.com/image.png",
"http://some.server.com/image.png?param=legalvalue&anotherparam=anothervalue",
"http://some.server.com/image.png?param=illegal.value.with.period"
};
boolean expectedImage[] = {
true, true, true, false
};
for(int i=0; i<tests.length; i++) {
if(expectedImage[i]) {
assertTrue("Expected " + tests[i] + " to resolve to an image", CSSURLEmbedder.isImage(tests[i]));
}
else {
assertFalse("Did NOT expect " + tests[i] + " to resolve as an image", CSSURLEmbedder.isImage(tests[i]));
}
}
}
@Test
public void testRegularUrlWithSkipComment() throws IOException {
String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png); /* CssEmbed: SKIP */";
StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));
String result = writer.toString();
//assert that nothing changed
assertEquals(code, result);
} |
<<<<<<<
player.equipItem("rightHand", itemRepo.getItem((json.get("weapon").getAsString())));
=======
player.equipItem("rightHand", new Item(json.get("weapon").getAsString()));
>>>>>>>
player.equipItem("rightHand", itemRepo.getItem((json.get("weapon").getAsString())));
<<<<<<<
location.removePublicItem(itemToPickUp.getId());
QueueProvider.offer("\n" + item.getName()+ " picked up");
=======
location.removePublicItem(itemToPickUp.getItemID());
QueueProvider.offer(item.getName()+ " picked up");
>>>>>>>
location.removePublicItem(itemToPickUp.getId());
QueueProvider.offer(item.getName()+ " picked up");
<<<<<<<
location.addPublicItem(itemToDrop.getId());
QueueProvider.offer("\n" + item.getName()+ " dropped");
=======
location.addPublicItem(itemToDrop.getItemID());
QueueProvider.offer(item.getName() + " dropped");
>>>>>>>
location.addPublicItem(itemToDrop.getId());
QueueProvider.offer(item.getName() + " dropped"); |
<<<<<<<
else if (command.equals("exit")) {
continuePrompt = false;
}
else if (command.startsWith("e")) {
=======
else if (command.startsWith("e")) { // equip
>>>>>>>
else if (command.equals("exit")) {
continuePrompt = false;
}
else if (command.startsWith("e")) {
<<<<<<<
else if (command.equals("debug")) {
new DebugMenu(player);
=======
else if (command.startsWith("p")) { // pick
String itemName = command.substring(1);
player.pickUpItem(itemName);
}
else if (command.startsWith("d")){ // drop
String itemName = command.substring(1);
player.dropItem(itemName);
}
else if (command.equals("exit")) {
continuePrompt = false;
>>>>>>>
else if (command.startsWith("p")) { // pick
String itemName = command.substring(1);
player.pickUpItem(itemName);
}
else if (command.startsWith("d")){ // drop
String itemName = command.substring(1);
player.dropItem(itemName); |
<<<<<<<
=======
player.setWeapon(json.get("weapon").getAsString());
if (json.has("items")) {
HashMap<String, Integer> items = new Gson().fromJson(json.get("items"), new TypeToken<HashMap<String, Integer>>(){}.getType());
ArrayList<ItemStack> itemList = new ArrayList<ItemStack>();
for (Map.Entry<String, Integer> entry : items.entrySet()) {
String itemID = entry.getKey();
int amount = entry.getValue();
Item item = new Item(itemID);
ItemStack itemStack = new ItemStack(amount, item);
itemList.add(itemStack);
}
player.setStorage(new Backpack(MAX_BACKPACK_WEIGHT, itemList));
}
>>>>>>>
player.setWeapon(json.get("weapon").getAsString());
if (json.has("items")) {
HashMap<String, Integer> items = new Gson().fromJson(json.get("items"), new TypeToken<HashMap<String, Integer>>(){}.getType());
ArrayList<ItemStack> itemList = new ArrayList<ItemStack>();
for (Map.Entry<String, Integer> entry : items.entrySet()) {
String itemID = entry.getKey();
int amount = entry.getValue();
Item item = new Item(itemID);
ItemStack itemStack = new ItemStack(amount, item);
itemList.add(itemStack);
}
player.setStorage(new Backpack(MAX_BACKPACK_WEIGHT, itemList));
}
<<<<<<<
jsonObject.addProperty("level", getWeapon());
=======
jsonObject.addProperty("weapon", getWeapon());
HashMap<String, Integer> items = new HashMap<String, Integer>();
JsonArray itemList = new JsonArray();
for (ItemStack item : getStorage().getItems()) {
items.put(item.getItem().getItemID(), item.getAmount());
JsonPrimitive itemJson = new JsonPrimitive(item.getItem().getItemID());
itemList.add(itemJson);
}
JsonElement itemsJsonObj = gson.toJsonTree(items);
jsonObject.add("items", itemsJsonObj);
>>>>>>>
jsonObject.addProperty("level", getWeapon());
jsonObject.addProperty("weapon", getWeapon());
HashMap<String, Integer> items = new HashMap<String, Integer>();
JsonArray itemList = new JsonArray();
for (ItemStack item : getStorage().getItems()) {
items.put(item.getItem().getItemID(), item.getAmount());
JsonPrimitive itemJson = new JsonPrimitive(item.getItem().getItemID());
itemList.add(itemJson);
}
JsonElement itemsJsonObj = gson.toJsonTree(items);
jsonObject.add("items", itemsJsonObj); |
<<<<<<<
@Issue("JENKINS-46391")
@Test
public void tildePattern() throws Exception {
WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "p");
job.setDefinition(new CpsFlowDefinition("def f = ~/f.*/; f.matcher('foo').matches()", true));
jenkins.buildAndAssertSuccess(job);
}
=======
@Issue("JENKINS-46088")
@Test
public void matcherTypeAssignment() throws Exception {
logging.record(CpsTransformer.class, Level.FINEST);
WorkflowJob p = jenkins.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition("@NonCPS\n" +
"def nonCPSMatcherMethod(String x) {\n" +
" java.util.regex.Matcher m = x =~ /bla/\n" +
" return m.matches()\n" +
"}\n" +
"def cpsMatcherMethod(String x) {\n" +
" java.util.regex.Matcher m = x =~ /bla/\n" +
" return m.matches()\n" +
"}\n" +
"assert !nonCPSMatcherMethod('foo')\n" +
"assert !cpsMatcherMethod('foo')\n", true));
jenkins.buildAndAssertSuccess(p);
}
@Issue("JENKINS-46088")
@Test
public void rhsOfDeclarationTransformedInNonCPS() throws Exception {
logging.record(CpsTransformer.class, Level.FINEST);
WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "p");
job.setDefinition(new CpsFlowDefinition("@NonCPS\n" +
"def willFail() {\n" +
" jenkins.model.Jenkins x = jenkins.model.Jenkins.getInstance()\n" +
"}\n" +
"willFail()\n", true));
WorkflowRun b = job.scheduleBuild2(0).get();
jenkins.assertBuildStatus(Result.FAILURE, b);
jenkins.assertLogContains("org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance", b);
}
@Issue("JENKINS-46088")
@Test
public void rhsOfDeclarationSandboxedInCPS() throws Exception {
logging.record(CpsTransformer.class, Level.FINEST);
WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "p");
job.setDefinition(new CpsFlowDefinition("jenkins.model.Jenkins x = jenkins.model.Jenkins.getInstance()\n", true));
WorkflowRun b = job.scheduleBuild2(0).get();
jenkins.assertBuildStatus(Result.FAILURE, b);
jenkins.assertLogContains("org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance", b);
}
>>>>>>>
@Issue("JENKINS-46391")
@Test
public void tildePattern() throws Exception {
WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "p");
job.setDefinition(new CpsFlowDefinition("def f = ~/f.*/; f.matcher('foo').matches()", true));
jenkins.buildAndAssertSuccess(job);
}
@Issue("JENKINS-46088")
@Test
public void matcherTypeAssignment() throws Exception {
logging.record(CpsTransformer.class, Level.FINEST);
WorkflowJob p = jenkins.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition("@NonCPS\n" +
"def nonCPSMatcherMethod(String x) {\n" +
" java.util.regex.Matcher m = x =~ /bla/\n" +
" return m.matches()\n" +
"}\n" +
"def cpsMatcherMethod(String x) {\n" +
" java.util.regex.Matcher m = x =~ /bla/\n" +
" return m.matches()\n" +
"}\n" +
"assert !nonCPSMatcherMethod('foo')\n" +
"assert !cpsMatcherMethod('foo')\n", true));
jenkins.buildAndAssertSuccess(p);
}
@Issue("JENKINS-46088")
@Test
public void rhsOfDeclarationTransformedInNonCPS() throws Exception {
logging.record(CpsTransformer.class, Level.FINEST);
WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "p");
job.setDefinition(new CpsFlowDefinition("@NonCPS\n" +
"def willFail() {\n" +
" jenkins.model.Jenkins x = jenkins.model.Jenkins.getInstance()\n" +
"}\n" +
"willFail()\n", true));
WorkflowRun b = job.scheduleBuild2(0).get();
jenkins.assertBuildStatus(Result.FAILURE, b);
jenkins.assertLogContains("org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance", b);
}
@Issue("JENKINS-46088")
@Test
public void rhsOfDeclarationSandboxedInCPS() throws Exception {
logging.record(CpsTransformer.class, Level.FINEST);
WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "p");
job.setDefinition(new CpsFlowDefinition("jenkins.model.Jenkins x = jenkins.model.Jenkins.getInstance()\n", true));
WorkflowRun b = job.scheduleBuild2(0).get();
jenkins.assertBuildStatus(Result.FAILURE, b);
jenkins.assertLogContains("org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance", b);
} |
<<<<<<<
liveness();
FileUtils.write(new File(jenkins().getRootDir(), "touch"), "I'm here");
watchDescriptor.watchUpdate();
=======
assertFalse(jenkins().toComputer().isIdle());
SemaphoreStep.success("wait/1", null);
>>>>>>>
liveness();
SemaphoreStep.success("wait/1", null); |
<<<<<<<
Accumulo.init(fs, instance, config, app);
=======
MetricsSystemHelper.configure(Monitor.class.getSimpleName());
Accumulo.init(fs, config, app);
>>>>>>>
MetricsSystemHelper.configure(Monitor.class.getSimpleName());
Accumulo.init(fs, instance, config, app); |
<<<<<<<
=======
for (Entry<Key,Value> entry : s) {
actual.put(Maps.immutableEntry(entry.getKey().getRow().toString(),
entry.getKey().getColumnFamily().toString()), entry.getValue().toString());
}
assertEquals("Differing results for " + table1, table1Expectations, actual);
>>>>>>>
<<<<<<<
try (Scanner s = connector.createScanner(table2, new Authorizations())) {
s.setRange(new Range());
actual = new HashMap<>();
for (Entry<Key,Value> entry : s) {
actual.put(Maps.immutableEntry(entry.getKey().getRow().toString(),
entry.getKey().getColumnFamily().toString()), entry.getValue().toString());
}
Assert.assertEquals("Differing results for " + table2, table2Expectations, actual);
}
=======
assertEquals("Differing results for " + table2, table2Expectations, actual);
>>>>>>>
try (Scanner s = connector.createScanner(table2, new Authorizations())) {
s.setRange(new Range());
actual = new HashMap<>();
for (Entry<Key,Value> entry : s) {
actual.put(Maps.immutableEntry(entry.getKey().getRow().toString(),
entry.getKey().getColumnFamily().toString()), entry.getValue().toString());
}
assertEquals("Differing results for " + table2, table2Expectations, actual);
} |
<<<<<<<
=======
import com.velocitypowered.proxy.protocol.util.DeferredByteBufHolder;
>>>>>>>
import com.velocitypowered.proxy.protocol.util.DeferredByteBufHolder;
<<<<<<<
=======
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
>>>>>>>
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
<<<<<<<
if (version.compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
this.data = new byte[buf.readableBytes()];
buf.readBytes(data);
} else {
data = ProtocolUtils.readByteArray17(buf);
}
=======
this.replace(buf.readRetainedSlice(buf.readableBytes()));
>>>>>>>
if (version.compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
this.replace(buf.readRetainedSlice(buf.readableBytes()));
} else {
this.replace(ProtocolUtils.readRetainedByteBufSlice17(buf));
}
<<<<<<<
if (version.compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
buf.writeBytes(data);
} else {
ProtocolUtils.writeByteArray17(data, buf, true); // True for Forge support
}
=======
buf.writeBytes(content());
>>>>>>>
if (version.compareTo(ProtocolVersion.MINECRAFT_1_8) >= 0) {
buf.writeBytes(content());
} else {
ProtocolUtils.writeByteBuf17(content(), buf, true); // True for Forge support
} |
<<<<<<<
public long getPing() {
return this.ping;
}
public void setPing(long ping) {
this.ping = ping;
}
@Override
=======
public PlayerSettings getPlayerSettings() {
return settings == null ? ClientSettingsWrapper.DEFAULT : this.settings;
}
public void setPlayerSettings(ClientSettings settings) {
this.settings = new ClientSettingsWrapper(settings);
VelocityServer.getServer().getEventManager().fireAndForget(new PlayerSettingsChangedEvent(this, this.settings));
}
@Override
>>>>>>>
public long getPing() {
return this.ping;
}
public void setPing(long ping) {
this.ping = ping;
}
public PlayerSettings getPlayerSettings() {
return settings == null ? ClientSettingsWrapper.DEFAULT : this.settings;
}
public void setPlayerSettings(ClientSettings settings) {
this.settings = new ClientSettingsWrapper(settings);
VelocityServer.getServer().getEventManager().fireAndForget(new PlayerSettingsChangedEvent(this, this.settings));
}
@Override |
<<<<<<<
GOOGLE_ANALYTICS_KEY("Google Analytics tracking ID", false),
OFFLINE_PAYMENT_DAYS("Maximum number of days allowed to pay an offline ticket", false),
BANK_ACCOUNT_NR("Bank Account number", false);
=======
//
//mailgun configuration related info
MAILGUN_KEY("Mailgun key", false),
MAILGUN_DOMAIN("Mailgun domain", false),
MAILGUN_FROM("Mailgun E-Mail sender", false),
//
GOOGLE_ANALYTICS_KEY("Google Analytics tracking ID", false);
>>>>>>>
GOOGLE_ANALYTICS_KEY("Google Analytics tracking ID", false),
OFFLINE_PAYMENT_DAYS("Maximum number of days allowed to pay an offline ticket", false),
BANK_ACCOUNT_NR("Bank Account number", false),
//
//mailgun configuration related info
MAILGUN_KEY("Mailgun key", false),
MAILGUN_DOMAIN("Mailgun domain", false),
MAILGUN_FROM("Mailgun E-Mail sender", false),
//
GOOGLE_ANALYTICS_KEY("Google Analytics tracking ID", false); |
<<<<<<<
=======
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
>>>>>>>
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
<<<<<<<
import static alfio.util.ImageUtil.createQRCode;
=======
import lombok.extern.log4j.Log4j2;
import static alfio.util.TicketUtil.createQRCode;
>>>>>>>
import lombok.extern.log4j.Log4j2;
import static alfio.util.ImageUtil.createQRCode; |
<<<<<<<
import com.json.generators.JSONGenerator;
import com.json.generators.JsonGeneratorFactory;
import com.json.parsers.JSONParser;
import com.json.parsers.JsonParserFactory;
import cz.cuni.lf1.lge.ThunderSTORM.results.TripleStateTableModel;
=======
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import cz.cuni.lf1.lge.ThunderSTORM.results.IJResultsTable;
>>>>>>>
import cz.cuni.lf1.lge.ThunderSTORM.results.TripleStateTableModel;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import cz.cuni.lf1.lge.ThunderSTORM.results.IJResultsTable;
<<<<<<<
Iterator it = ((Map)item).entrySet().iterator();
while(it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
rt.addValue(Double.parseDouble((String)pairs.getValue()), (String)pairs.getKey());
=======
for(Entry<String,Double> entry : mol.entrySet()) {
if(IJResultsTable.COLUMN_ID.equals(entry.getKey())) continue;
rt.addValue(entry.getKey(), entry.getValue().doubleValue());
>>>>>>>
for(Entry<String,Double> entry : mol.entrySet()) {
if(IJResultsTable.COLUMN_ID.equals(entry.getKey())) continue;
rt.addValue(entry.getValue(), entry.getKey());
<<<<<<<
public void exportToFile(String fp, TripleStateTableModel rt) throws IOException {
int ncols = rt.getColumnCount(), nrows = rt.getRowCount();
String [] headers = rt.getColumnNames();
=======
public void exportToFile(String fp, IJResultsTable.View rt, Vector<String> columns) throws IOException {
assert(rt != null);
assert(fp != null);
assert(!fp.isEmpty());
assert(columns != null);
int ncols = columns.size(), nrows = rt.getRowCount();
String [] headers = new String[ncols];
columns.toArray(headers);
>>>>>>>
public void exportToFile(String fp, TripleStateTableModel rt, Vector<String> columns) throws IOException {
assert(rt != null);
assert(fp != null);
assert(!fp.isEmpty());
assert(columns != null);
int ncols = rt.getColumnCount(), nrows = rt.getRowCount();
String [] headers = rt.getColumnNames();
<<<<<<<
molecule.put(headers[c], (Double)rt.getValueAt(c,r));
results[r] = molecule;
=======
molecule.put(headers[c], rt.getValue(headers[c],r));
results.add(molecule);
>>>>>>>
molecule.put(headers[c], (Double)rt.getValueAt(c,r));
results.add(molecule); |
<<<<<<<
import cz.cuni.lf1.lge.ThunderSTORM.thresholding.ThresholdFormulaException;
=======
import cz.cuni.lf1.lge.ThunderSTORM.IModule;
>>>>>>>
import cz.cuni.lf1.lge.ThunderSTORM.thresholding.ThresholdFormulaException;
import cz.cuni.lf1.lge.ThunderSTORM.IModule; |
<<<<<<<
import cz.cuni.lf1.lge.ThunderSTORM.rendering.ScatterRenderingWrapper;
import cz.cuni.lf1.lge.ThunderSTORM.thresholding.ThresholdFormulaException;
import cz.cuni.lf1.lge.ThunderSTORM.thresholding.Thresholder;
import cz.cuni.lf1.lge.ThunderSTORM.util.Graph;
=======
>>>>>>>
import cz.cuni.lf1.lge.ThunderSTORM.thresholding.ThresholdFormulaException;
import cz.cuni.lf1.lge.ThunderSTORM.thresholding.Thresholder; |
<<<<<<<
private RenderingQueue renderingQueue;
private ImagePlus renderedImage;
private Runnable repaintTask = new Runnable() {
@Override
public void run() {
renderedImage.show();
if (renderedImage.isVisible()) {
IJ.run(renderedImage, "Enhance Contrast", "saturated=0.05");
}
}
};
=======
private IRenderer renderingQueue;
private ImagePlus imgPlus;
>>>>>>>
private RenderingQueue renderingQueue;
private ImagePlus renderedImage;
private Runnable repaintTask = new Runnable() {
@Override
public void run() {
renderedImage.show();
if (renderedImage.isVisible()) {
IJ.run(renderedImage, "Enhance Contrast", "saturated=0.05");
}
}
};
<<<<<<<
RenderingOverlay.showPointsInImageSlice(imp,
PSFInstance.extractParamToArray(results[frame], PSFInstance.X),
PSFInstance.extractParamToArray(results[frame], PSFInstance.Y),
frame, Color.red, RenderingOverlay.MARKER_CROSS);
=======
RenderingOverlay.showPointsInImageSlice(imp, offset(imp.getRoi().getBounds().x, extractX(results[frame])), offset(imp.getRoi().getBounds().y, extractY(results[frame])), frame, Color.red, RenderingOverlay.MARKER_CROSS);
>>>>>>>
RenderingOverlay.showPointsInImageSlice(imp,
offset(imp.getRoi().getBounds().x,PSFInstance.extractParamToArray(results[frame], PSFInstance.X)),
offset(imp.getRoi().getBounds().y,PSFInstance.extractParamToArray(results[frame], PSFInstance.Y)),
frame, Color.red, RenderingOverlay.MARKER_CROSS);
<<<<<<<
rendererPanel.setSize(imp.getWidth(), imp.getHeight());
IncrementalRenderingMethod method = rendererPanel.getImplementation();
renderedImage = method.getRenderedImage();
renderingQueue = new RenderingQueue(method, repaintTask, rendererPanel.getRepaintFrequency());
=======
rendererPanel.setSize(imp.getRoi().getBounds().width, imp.getRoi().getBounds().height);
renderingQueue = rendererPanel.getImplementation();
>>>>>>>
rendererPanel.setSize(imp.getRoi().getBounds().width, imp.getRoi().getBounds().height);
IncrementalRenderingMethod method = rendererPanel.getImplementation();
renderedImage = method.getRenderedImage();
renderingQueue = new RenderingQueue(method, repaintTask, rendererPanel.getRepaintFrequency());
<<<<<<<
IRendererUI selectedRenderer = dialog.getRenderer();
selectedRenderer.setSize(imp.getWidth(), imp.getHeight());
IncrementalRenderingMethod method = selectedRenderer.getImplementation();
renderedImage = method.getRenderedImage();
renderingQueue = new RenderingQueue(method, repaintTask, selectedRenderer.getRepaintFrequency());
=======
IRendererUI rendererPanel = dialog.getRenderer();
rendererPanel.setSize(imp.getRoi().getBounds().width, imp.getRoi().getBounds().height);
renderingQueue = rendererPanel.getImplementation();
>>>>>>>
IRendererUI selectedRenderer = dialog.getRenderer();
selectedRenderer.setSize(imp.getRoi().getBounds().width, imp.getRoi().getBounds().height);
IncrementalRenderingMethod method = selectedRenderer.getImplementation();
renderedImage = method.getRenderedImage();
renderingQueue = new RenderingQueue(method, repaintTask, selectedRenderer.getRepaintFrequency());
<<<<<<<
FloatProcessor fp = (FloatProcessor) ip.convertToFloat();
Vector<PSFInstance> fits;
=======
FloatProcessor fp = (FloatProcessor) ip.crop().convertToFloat();
Vector<PSFInstance> fits = null;
>>>>>>>
FloatProcessor fp = (FloatProcessor) ip.crop().convertToFloat();
Vector<PSFInstance> fits; |
<<<<<<<
public void fireStructureChanged() {
model.fireTableStructureChanged();
}
ResultsFilter getFilter() {
return tableWindow.getFilter();
}
ResultsGrouping getGrouping() {
return tableWindow.getGrouping();
}
ResultsDriftCorrection getDriftCorrection() {
return tableWindow.getDriftCorrection();
}
=======
>>>>>>>
ResultsFilter getFilter() {
return tableWindow.getFilter();
}
ResultsGrouping getGrouping() {
return tableWindow.getGrouping();
}
ResultsDriftCorrection getDriftCorrection() {
return tableWindow.getDriftCorrection();
} |
<<<<<<<
import cz.cuni.lf1.lge.ThunderSTORM.IModule;
import cz.cuni.lf1.lge.ThunderSTORM.thresholding.ThresholdFormulaException;
import cz.cuni.lf1.lge.ThunderSTORM.thresholding.Thresholder;
=======
>>>>>>>
import cz.cuni.lf1.lge.ThunderSTORM.thresholding.ThresholdFormulaException;
import cz.cuni.lf1.lge.ThunderSTORM.thresholding.Thresholder;
<<<<<<<
try {
threshold = thrTextField.getText();
radius = Integer.parseInt(radiusTextField.getText());
} catch(NumberFormatException ex) {
IJ.showMessage("Error!", ex.getMessage());
}
=======
threshold = Double.parseDouble(thrTextField.getText());
radius = Integer.parseInt(radiusTextField.getText());
>>>>>>>
threshold = thrTextField.getText();
radius = Integer.parseInt(radiusTextField.getText()); |
<<<<<<<
import com.microsoft.tooling.msservices.serviceexplorer.listener.Telemetrable;
import org.apache.commons.lang3.StringUtils;
import java.util.Objects;
=======
>>>>>>>
import com.microsoft.tooling.msservices.serviceexplorer.listener.Telemetrable;
<<<<<<<
public class CreateMySQLAction extends NodeActionListener implements Backgroundable, Basicable, Telemetrable {
=======
public class CreateMySQLAction extends NodeActionListener implements Basicable {
>>>>>>>
public class CreateMySQLAction extends NodeActionListener implements Basicable, Telemetrable {
<<<<<<<
public String getProgressMessage() {
return Node.getProgressMessage(AzureActionEnum.CREATE.getDoingName(), MySQLModule.MODULE_NAME,
Objects.nonNull(config) ? config.getServerName() : StringUtils.EMPTY);
}
@Override
public TelemetryParameter getTelemetryParameter() {
return TelemetryParameter.MySQL.CREATE;
}
@Override
=======
>>>>>>>
public TelemetryParameter getTelemetryParameter() {
return TelemetryParameter.MySQL.CREATE;
}
@Override |
<<<<<<<
import com.microsoft.tooling.msservices.serviceexplorer.listener.ActionBasicable;
=======
import com.microsoft.tooling.msservices.serviceexplorer.listener.Basicable;
import rx.Single;
import java.util.Objects;
import java.util.function.Consumer;
>>>>>>>
import com.microsoft.tooling.msservices.serviceexplorer.listener.ActionBasicable;
import rx.Single;
import java.util.Objects;
import java.util.function.Consumer;
<<<<<<<
public class CreateFunctionAppAction extends NodeActionListener implements ActionBasicable {
=======
@Name("Create Function App")
public class CreateFunctionAppAction extends NodeActionListener implements Basicable {
private static final String NOTIFICATION_GROUP_ID = "Azure Plugin";
>>>>>>>
public class CreateFunctionAppAction extends NodeActionListener implements ActionBasicable {
private static final String NOTIFICATION_GROUP_ID = "Azure Plugin"; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.