gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.dynamicconfig.search;
import com.hazelcast.config.AtomicLongConfig;
import com.hazelcast.config.AtomicReferenceConfig;
import com.hazelcast.config.CacheSimpleConfig;
import com.hazelcast.config.CardinalityEstimatorConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.ConfigPatternMatcher;
import com.hazelcast.config.CountDownLatchConfig;
import com.hazelcast.config.DurableExecutorConfig;
import com.hazelcast.config.ExecutorConfig;
import com.hazelcast.config.FlakeIdGeneratorConfig;
import com.hazelcast.config.ListConfig;
import com.hazelcast.config.LockConfig;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MultiMapConfig;
import com.hazelcast.config.PNCounterConfig;
import com.hazelcast.config.QueueConfig;
import com.hazelcast.config.ReliableTopicConfig;
import com.hazelcast.config.ReplicatedMapConfig;
import com.hazelcast.config.RingbufferConfig;
import com.hazelcast.config.ScheduledExecutorConfig;
import com.hazelcast.config.SemaphoreConfig;
import com.hazelcast.config.SetConfig;
import com.hazelcast.config.TopicConfig;
import com.hazelcast.internal.dynamicconfig.ConfigurationService;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Config search factory, which allows to build searchers for the given config types.
*
* @since 3.11
* @see Searcher
*/
@SuppressWarnings({"checkstyle:methodcount", "checkstyle:executablestatementcount"})
public final class ConfigSearch {
private static final Map<Class, ConfigSupplier> CONFIG_SUPPLIERS = new ConcurrentHashMap<Class, ConfigSupplier>();
private ConfigSearch() {
}
static {
CONFIG_SUPPLIERS.put(MapConfig.class, new ConfigSupplier<MapConfig>() {
@Override
public MapConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findMapConfig(name);
}
@Override
public MapConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getMapConfig(name);
}
@Override
public Map<String, MapConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getMapConfigs();
}
});
CONFIG_SUPPLIERS.put(CacheSimpleConfig.class, new ConfigSupplier<CacheSimpleConfig>() {
@Override
public CacheSimpleConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findCacheSimpleConfig(name);
}
@Override
public CacheSimpleConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getCacheConfig(name);
}
@Override
public Map<String, CacheSimpleConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getCacheConfigs();
}
});
CONFIG_SUPPLIERS.put(QueueConfig.class, new ConfigSupplier<QueueConfig>() {
@Override
public QueueConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findQueueConfig(name);
}
@Override
public QueueConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getQueueConfig(name);
}
@Override
public Map<String, QueueConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getQueueConfigs();
}
});
CONFIG_SUPPLIERS.put(LockConfig.class, new ConfigSupplier<LockConfig>() {
@Override
public LockConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findLockConfig(name);
}
@Override
public LockConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getLockConfig(name);
}
@Override
public Map<String, LockConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getLockConfigs();
}
});
CONFIG_SUPPLIERS.put(ListConfig.class, new ConfigSupplier<ListConfig>() {
@Override
public ListConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findListConfig(name);
}
@Override
public ListConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getListConfig(name);
}
@Override
public Map<String, ListConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getListConfigs();
}
});
CONFIG_SUPPLIERS.put(SetConfig.class, new ConfigSupplier<SetConfig>() {
@Override
public SetConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findSetConfig(name);
}
@Override
public SetConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getSetConfig(name);
}
@Override
public Map<String, SetConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getSetConfigs();
}
});
CONFIG_SUPPLIERS.put(MultiMapConfig.class, new ConfigSupplier<MultiMapConfig>() {
@Override
public MultiMapConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findMultiMapConfig(name);
}
@Override
public MultiMapConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getMultiMapConfig(name);
}
@Override
public Map<String, MultiMapConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getMultiMapConfigs();
}
});
CONFIG_SUPPLIERS.put(ReplicatedMapConfig.class, new ConfigSupplier<ReplicatedMapConfig>() {
@Override
public ReplicatedMapConfig getDynamicConfig(@Nonnull ConfigurationService configurationService,
@Nonnull String name) {
return configurationService.findReplicatedMapConfig(name);
}
@Override
public ReplicatedMapConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getReplicatedMapConfig(name);
}
@Override
public Map<String, ReplicatedMapConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getReplicatedMapConfigs();
}
});
CONFIG_SUPPLIERS.put(RingbufferConfig.class, new ConfigSupplier<RingbufferConfig>() {
@Override
public RingbufferConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findRingbufferConfig(name);
}
@Override
public RingbufferConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getRingbufferConfig(name);
}
@Override
public Map<String, RingbufferConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getRingbufferConfigs();
}
});
CONFIG_SUPPLIERS.put(AtomicLongConfig.class, new ConfigSupplier<AtomicLongConfig>() {
@Override
public AtomicLongConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findAtomicLongConfig(name);
}
@Override
public AtomicLongConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getAtomicLongConfig(name);
}
@Override
public Map<String, AtomicLongConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getAtomicLongConfigs();
}
});
CONFIG_SUPPLIERS.put(AtomicReferenceConfig.class, new ConfigSupplier<AtomicReferenceConfig>() {
@Override
public AtomicReferenceConfig getDynamicConfig(@Nonnull ConfigurationService configurationService,
@Nonnull String name) {
return configurationService.findAtomicReferenceConfig(name);
}
@Override
public AtomicReferenceConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getAtomicReferenceConfig(name);
}
@Override
public Map<String, AtomicReferenceConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getAtomicReferenceConfigs();
}
});
CONFIG_SUPPLIERS.put(CountDownLatchConfig.class, new ConfigSupplier<CountDownLatchConfig>() {
@Override
public CountDownLatchConfig getDynamicConfig(@Nonnull ConfigurationService configurationService,
@Nonnull String name) {
return configurationService.findCountDownLatchConfig(name);
}
@Override
public CountDownLatchConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getCountDownLatchConfig(name);
}
@Override
public Map<String, CountDownLatchConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getCountDownLatchConfigs();
}
});
CONFIG_SUPPLIERS.put(TopicConfig.class, new ConfigSupplier<TopicConfig>() {
@Override
public TopicConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findTopicConfig(name);
}
@Override
public TopicConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getTopicConfig(name);
}
@Override
public Map<String, TopicConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getTopicConfigs();
}
});
CONFIG_SUPPLIERS.put(ReliableTopicConfig.class, new ConfigSupplier<ReliableTopicConfig>() {
@Override
public ReliableTopicConfig getDynamicConfig(@Nonnull ConfigurationService configurationService,
@Nonnull String name) {
return configurationService.findReliableTopicConfig(name);
}
@Override
public ReliableTopicConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getReliableTopicConfig(name);
}
@Override
public Map<String, ReliableTopicConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getReliableTopicConfigs();
}
});
CONFIG_SUPPLIERS.put(ExecutorConfig.class, new ConfigSupplier<ExecutorConfig>() {
@Override
public ExecutorConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findExecutorConfig(name);
}
@Override
public ExecutorConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getExecutorConfig(name);
}
@Override
public Map<String, ExecutorConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getExecutorConfigs();
}
});
CONFIG_SUPPLIERS.put(DurableExecutorConfig.class, new ConfigSupplier<DurableExecutorConfig>() {
@Override
public DurableExecutorConfig getDynamicConfig(@Nonnull ConfigurationService configurationService,
@Nonnull String name) {
return configurationService.findDurableExecutorConfig(name);
}
@Override
public DurableExecutorConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getDurableExecutorConfig(name);
}
@Override
public Map<String, DurableExecutorConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getDurableExecutorConfigs();
}
});
CONFIG_SUPPLIERS.put(ScheduledExecutorConfig.class, new ConfigSupplier<ScheduledExecutorConfig>() {
@Override
public ScheduledExecutorConfig getDynamicConfig(@Nonnull ConfigurationService configurationService,
@Nonnull String name) {
return configurationService.findScheduledExecutorConfig(name);
}
@Override
public ScheduledExecutorConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getScheduledExecutorConfig(name);
}
@Override
public Map<String, ScheduledExecutorConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getScheduledExecutorConfigs();
}
});
CONFIG_SUPPLIERS.put(CardinalityEstimatorConfig.class, new ConfigSupplier<CardinalityEstimatorConfig>() {
@Override
public CardinalityEstimatorConfig getDynamicConfig(@Nonnull ConfigurationService configurationService,
@Nonnull String name) {
return configurationService.findCardinalityEstimatorConfig(name);
}
@Override
public CardinalityEstimatorConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getCardinalityEstimatorConfig(name);
}
@Override
public Map<String, CardinalityEstimatorConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getCardinalityEstimatorConfigs();
}
});
CONFIG_SUPPLIERS.put(SemaphoreConfig.class, new ConfigSupplier<SemaphoreConfig>() {
@Override
public SemaphoreConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findSemaphoreConfig(name);
}
@Override
public SemaphoreConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getSemaphoreConfig(name);
}
@Override
public Map<String, SemaphoreConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getSemaphoreConfigsAsMap();
}
});
CONFIG_SUPPLIERS.put(FlakeIdGeneratorConfig.class, new ConfigSupplier<FlakeIdGeneratorConfig>() {
@Override
public FlakeIdGeneratorConfig getDynamicConfig(@Nonnull ConfigurationService configurationService,
@Nonnull String name) {
return configurationService.findFlakeIdGeneratorConfig(name);
}
@Override
public FlakeIdGeneratorConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getFlakeIdGeneratorConfig(name);
}
@Override
public Map<String, FlakeIdGeneratorConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getFlakeIdGeneratorConfigs();
}
});
CONFIG_SUPPLIERS.put(PNCounterConfig.class, new ConfigSupplier<PNCounterConfig>() {
@Override
public PNCounterConfig getDynamicConfig(@Nonnull ConfigurationService configurationService, @Nonnull String name) {
return configurationService.findPNCounterConfig(name);
}
@Override
public PNCounterConfig getStaticConfig(@Nonnull Config staticConfig, @Nonnull String name) {
return staticConfig.getPNCounterConfig(name);
}
@Override
public Map<String, PNCounterConfig> getStaticConfigs(@Nonnull Config staticConfig) {
return staticConfig.getPNCounterConfigs();
}
});
}
/**
* Factory method for providing {@link ConfigSupplier} instances for the given config class
*
* @param cls class of the config we're looking for
* @param <T> type of config class
* @return {@link ConfigSupplier} config supplier for the given config type
* @see com.hazelcast.spi.properties.GroupProperty#SEARCH_DYNAMIC_CONFIG_FIRST
*/
@Nullable
public static <T extends IdentifiedDataSerializable> ConfigSupplier<T> supplierFor(@Nonnull Class<T> cls) {
return CONFIG_SUPPLIERS.get(cls);
}
/**
* Factory method for creating {@link Searcher} instances
*
* @param staticConfig hazelcast static config
* @param configurationService configuration service
* @param isStaticFirst <code>true</code> if {@link Searcher} should look into static config first, and
* <code>false</code> otherwise.
* @param <T> type of config class
* @return {@link Searcher} for the given config type and conditions
* @see com.hazelcast.spi.properties.GroupProperty#SEARCH_DYNAMIC_CONFIG_FIRST
* @see ConfigSupplier
*/
@Nonnull
public static <T extends IdentifiedDataSerializable>
Searcher<T> searcherFor(@Nonnull final Config staticConfig,
@Nonnull final ConfigurationService configurationService,
@Nonnull final ConfigPatternMatcher configPatternMatcher, boolean isStaticFirst) {
return isStaticFirst
? new StaticFirstSearcher<T>(configurationService, staticConfig, configPatternMatcher)
: new DynamicFirstSearcher<T>(configurationService, staticConfig, configPatternMatcher);
}
}
| |
/*
* Copyright 2015-2016 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.hal.core;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Provider;
import com.google.common.collect.Iterables;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.web.bindery.event.shared.EventBus;
import jsinterop.annotations.JsIgnore;
import org.jboss.hal.ballroom.dialog.DialogFactory;
import org.jboss.hal.ballroom.form.Form;
import org.jboss.hal.ballroom.form.FormItem;
import org.jboss.hal.core.mbui.dialog.AddResourceDialog;
import org.jboss.hal.core.mbui.form.ModelNodeForm;
import org.jboss.hal.dmr.Composite;
import org.jboss.hal.dmr.CompositeResult;
import org.jboss.hal.dmr.ModelNode;
import org.jboss.hal.dmr.Operation;
import org.jboss.hal.dmr.ResourceAddress;
import org.jboss.hal.dmr.dispatch.Dispatcher;
import org.jboss.hal.flow.Progress;
import org.jboss.hal.meta.AddressTemplate;
import org.jboss.hal.meta.Metadata;
import org.jboss.hal.meta.StatementContext;
import org.jboss.hal.meta.processing.MetadataProcessor;
import org.jboss.hal.meta.processing.SuccessfulMetadataCallback;
import org.jboss.hal.resources.Resources;
import org.jboss.hal.spi.Callback;
import org.jboss.hal.spi.Footer;
import org.jboss.hal.spi.Message;
import org.jboss.hal.spi.MessageEvent;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toSet;
import static java.util.stream.StreamSupport.stream;
import static org.jboss.hal.dmr.ModelDescriptionConstants.*;
/**
* Class to create, read, update and delete complex attributes. This class mirrors and delegates to methods from {@link
* CrudOperations}.
*/
public class ComplexAttributeOperations {
private final CrudOperations crud;
private final EventBus eventBus;
private final Dispatcher dispatcher;
private final MetadataProcessor metadataProcessor;
private final Provider<Progress> progress;
private final StatementContext statementContext;
private final Resources resources;
@Inject
public ComplexAttributeOperations(CrudOperations crud,
EventBus eventBus,
Dispatcher dispatcher,
MetadataProcessor metadataProcessor,
@Footer Provider<Progress> progress,
StatementContext statementContext,
Resources resources) {
this.crud = crud;
this.eventBus = eventBus;
this.dispatcher = dispatcher;
this.metadataProcessor = metadataProcessor;
this.progress = progress;
this.statementContext = statementContext;
this.resources = resources;
}
// ------------------------------------------------------ (c)reate with dialog
/**
* Opens an add-resource-dialog for the given complex attribute. The dialog contains fields for all required
* attributes. When clicking "Add", a new complex attribute is created and written to the specified resource.
* After the resource has been updated, a success message is fired and the specified callback is executed.
*
* @param id the id used for the add resource dialog
* @param resource the resource name
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param template the address template which is resolved against the current statement context and the
* resource name to get the resource address for the operation
* @param callback the callback executed after the resource has been added
*/
@JsIgnore
public void add(String id, String resource, String complexAttribute, String type, AddressTemplate template,
Callback callback) {
lookupAndAdd(id, complexAttribute, type, template, emptyList(),
(name, model) -> add(resource, complexAttribute, type, template, model, callback));
}
/**
* Opens an add-resource-dialog for the given complex attribute. The dialog contains fields for all required
* attributes. When clicking "Add", a new complex attribute is created and written to the specified resource.
* After the resource has been updated, a success message is fired and the specified callback is executed.
*
* @param id the id used for the add resource dialog
* @param resource the resource name
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param template the address template which is resolved against the current statement context and the
* resource name to get the resource address for the operation
* @param attributes additional attributes which should be part of the add resource dialog
* @param callback the callback executed after the resource has been added
*/
@JsIgnore
public void add(String id, String resource, String complexAttribute, String type, AddressTemplate template,
Iterable<String> attributes, Callback callback) {
lookupAndAdd(id, complexAttribute, type, template, attributes,
(name, model) -> add(resource, complexAttribute, type, template, model, callback));
}
/**
* Opens an add-resource-dialog for the given complex attribute. The dialog contains fields for all required
* attributes. When clicking "Add", a new model node is created and added to the complex attribute in the specified
* resource. After the resource has been updated, a success message is fired and the specified callback is executed.
*
* @param id the id used for the add resource dialog
* @param resource the resource name
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param template the address template which is resolved against the current statement context and the
* resource name to get the resource address for the operation
* @param callback the callback executed after the resource has been added
*/
@JsIgnore
public void listAdd(String id, String resource, String complexAttribute, String type, AddressTemplate template,
Callback callback) {
lookupAndAdd(id, complexAttribute, type, template, emptyList(),
(name, model) -> listAdd(resource, complexAttribute, type, template, model, callback));
}
/**
* Opens an add-resource-dialog for the given complex attribute. If the resource contains required attributes, they
* are displayed, otherwise all attributes are displayed.
* When clicking "Add", a new model node is created and added to the complex attribute in the specified
* resource. After the resource has been updated, a success message is fired and the specified callback is
* executed.
*
* @param id the id used for the add resource dialog
* @param resource the resource name
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param template the address template which is resolved against the current statement context and the
* resource name to get the resource address for the operation
* @param attributes additional attributes which should be part of the add resource dialog
* @param callback the callback executed after the resource has been added
*/
@JsIgnore
public void listAdd(String id, String resource, String complexAttribute, String type, AddressTemplate template,
Iterable<String> attributes, Callback callback) {
lookupAndAdd(id, complexAttribute, type, template, attributes,
(name, model) -> listAdd(resource, complexAttribute, type, template, model, callback));
}
private void lookupAndAdd(String id, String complexAttribute, String type, AddressTemplate template,
Iterable<String> attributes, AddResourceDialog.Callback callback) {
metadataProcessor.lookup(template, progress.get(), new SuccessfulMetadataCallback(eventBus, resources) {
@Override
public void onMetadata(Metadata metadata) {
Metadata caMetadata = metadata.forComplexAttribute(complexAttribute);
boolean requiredAttributes = !caMetadata.getDescription()
.getRequiredAttributes(ATTRIBUTE_GROUP)
.isEmpty();
ModelNodeForm.Builder<ModelNode> builder = new ModelNodeForm.Builder<>(id, caMetadata)
.addOnly();
if (requiredAttributes) {
builder.requiredOnly();
}
if (!Iterables.isEmpty(attributes)) {
builder.include(attributes).unsorted();
}
AddResourceDialog dialog = new AddResourceDialog(resources.messages().addResourceTitle(type),
builder.build(), callback);
dialog.show();
}
});
}
// ------------------------------------------------------ (c)reate operation
/**
* Writes the payload to the complex attribute in the specified resource. After the resource has been updated,
* a success message is fired and the specified callback is executed.
*
* @param resource the resource name
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param template the address template which is resolved against the current statement context and the
* resource name to get the resource address for the operation
* @param payload the optional payload for the complex attribute (may be null or undefined)
* @param callback the callback executed after the resource has been added
*/
@JsIgnore
public void add(String resource, String complexAttribute, String type, AddressTemplate template,
@Nullable ModelNode payload, Callback callback) {
ResourceAddress address = template.resolve(statementContext, resource);
add(complexAttribute, type, address, payload, callback);
}
/**
* Writes the payload to the complex attribute in the specified resource. After the resource has been updated,
* a success message is fired and the specified callback is executed.
*
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param address the fq address for the operation
* @param payload the optional payload for the complex attribute (may be null or undefined)
* @param callback the callback executed after the resource has been added
*/
@JsIgnore
public void add(String complexAttribute, String type, ResourceAddress address, @Nullable ModelNode payload,
Callback callback) {
Operation operation = new Operation.Builder(address, WRITE_ATTRIBUTE_OPERATION)
.param(NAME, complexAttribute)
.param(VALUE, payload == null ? new ModelNode().addEmptyObject() : payload)
.build();
dispatcher.execute(operation, result -> {
MessageEvent.fire(eventBus, Message.success(resources.messages().addSingleResourceSuccess(type)));
callback.execute();
});
}
/**
* Adds the payload to the complex attribute in the specified resource. After the resource has been updated,
* a success message is fired and the specified callback is executed.
*
* @param resource the resource name
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param template the address template which is resolved against the current statement context and the
* resource name to get the resource address for the operation
* @param payload the optional payload for the complex attribute (may be null or undefined)
* @param callback the callback executed after the resource has been added
*/
@JsIgnore
public void listAdd(String resource, String complexAttribute, String type, AddressTemplate template,
@Nullable ModelNode payload, Callback callback) {
ResourceAddress address = template.resolve(statementContext, resource);
Operation operation = new Operation.Builder(address, LIST_ADD_OPERATION)
.param(NAME, complexAttribute)
.param(VALUE, payload == null ? new ModelNode().addEmptyObject() : payload)
.build();
dispatcher.execute(operation, result -> {
MessageEvent.fire(eventBus, Message.success(resources.messages().addSingleResourceSuccess(type)));
callback.execute();
});
}
// ------------------------------------------------------ (u)pdate using template
/**
* Writes the changed values to the complex attribute. After the complex attribute has been saved a standard success
* message is fired and the specified callback is executed.
* <p>
* If the change set is empty, a warning message is fired and the specified callback is executed.
*
* @param resource the resource name
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param template the address template which is resolved against the current statement context and the
* resource name to get the resource address for the operation
* @param changedValues the changed values / payload for the operation
* @param callback the callback executed after the resource has been saved
*/
@JsIgnore
public void save(String resource, String complexAttribute, String type, AddressTemplate template,
Map<String, Object> changedValues, Callback callback) {
metadataProcessor.lookup(template, progress.get(), new SuccessfulMetadataCallback(eventBus, resources) {
@Override
public void onMetadata(Metadata metadata) {
ResourceAddress address = template.resolve(statementContext, resource);
Metadata caMetadata = metadata.forComplexAttribute(complexAttribute);
save(complexAttribute, type, address, changedValues, caMetadata, callback);
}
});
}
/**
* Writes the changed values to the list-type complex attribute. After the complex attribute has been saved a
* standard success message is fired and the specified callback is executed.
* <p>
* If the change set is empty, a warning message is fired and the specified callback is executed.
*
* @param resource the resource name
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param index the index for the list-type complex attribute
* @param template the address template which is resolved against the current statement context and the
* resource name to get the resource address for the operation
* @param changedValues the changed values / payload for the operation
* @param callback the callback executed after the resource has been saved
*/
@JsIgnore
public void save(String resource, String complexAttribute, String type, int index, AddressTemplate template,
Map<String, Object> changedValues, Callback callback) {
metadataProcessor.lookup(template, progress.get(), new SuccessfulMetadataCallback(eventBus, resources) {
@Override
public void onMetadata(Metadata metadata) {
ResourceAddress address = template.resolve(statementContext, resource);
Metadata caMetadata = metadata.forComplexAttribute(complexAttribute);
save(complexAttribute, type, index, address, changedValues, caMetadata, callback);
}
});
}
// ------------------------------------------------------ (u)pdate using address
/**
* Writes the changed values to the complex attribute. After the complex attribute has been saved a standard success
* message is fired and the specified callback is executed.
* <p>
* If the change set is empty, a warning message is fired and the specified callback is executed.
*
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param address the fq address for the operation
* @param changedValues the changed values / payload for the operation
* @param metadata the metadata for the complex attribute
* @param callback the callback executed after the resource has been saved
*/
@JsIgnore
public void save(String complexAttribute, String type, ResourceAddress address, Map<String, Object> changedValues,
Metadata metadata, Callback callback) {
Composite operations = operationFactory(complexAttribute).fromChangeSet(address, changedValues, metadata);
crud.save(operations, resources.messages().modifySingleResourceSuccess(type), callback);
}
/**
* Writes the changed values to the list-type complex attribute. After the complex attribute has been saved a
* standard success message is fired and the specified callback is executed.
* <p>
* If the change set is empty, a warning message is fired and the specified callback is executed.
*
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param index the index for the list-type complex attribute
* @param address the fq address for the operation
* @param changedValues the changed values / payload for the operation
* @param metadata the metadata for the complex attribute
* @param callback the callback executed after the resource has been saved
*/
@JsIgnore
public void save(String complexAttribute, String type, int index, ResourceAddress address,
Map<String, Object> changedValues, Metadata metadata, Callback callback) {
Composite operations = operationFactory(complexAttribute, index).fromChangeSet(address, changedValues,
metadata);
crud.save(operations, resources.messages().modifySingleResourceSuccess(type), callback);
}
// ------------------------------------------------------ (u) reset using template
/**
* Undefines all non required attributes in the specified form. After the attributes in the complex attribute have
* been undefined a standard success message is fired and the specified callback is executed.
* <p>
* If the form contains only required attributes, a warning message is fired and the specified callback is executed.
*
* @param resource the resource name
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param template the address template which is resolved against the current statement context and the
* resource name to get the resource address for the operation
* @param form the form which should be reset
* @param callback the callback executed after the resource has been saved
*/
@JsIgnore
public <T> void reset(String resource, String complexAttribute, String type, AddressTemplate template, Form<T> form,
Callback callback) {
metadataProcessor.lookup(template, progress.get(), new SuccessfulMetadataCallback(eventBus, resources) {
@Override
public void onMetadata(Metadata metadata) {
Metadata caMetadata = metadata.forComplexAttribute(complexAttribute);
reset(resource, complexAttribute, type, template, caMetadata, form, callback);
}
});
}
/**
* Undefines all non required attributes in the specified form. After the attributes in the complex attribute have
* been undefined a standard success message is fired and the specified callback is executed.
* <p>
* If the form contains only required attributes, a warning message is fired and the specified callback is executed.
*
* @param resource the resource name
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param template the address template which is resolved against the current statement context and the
* resource name to get the resource address for the operation
* @param form the form which should be reset
* @param callback the callback executed after the resource has been saved
*/
@JsIgnore
public <T> void reset(String resource, String complexAttribute, String type, AddressTemplate template,
Metadata metadata, Form<T> form, Callback callback) {
Set<String> attributes = stream(form.getBoundFormItems().spliterator(), false)
.map(FormItem::getName)
.collect(toSet());
ResourceAddress address = template.resolve(statementContext, resource);
Composite composite = operationFactory(complexAttribute).resetResource(address, attributes, metadata);
reset(type, composite, callback);
}
/**
* Undefines all non required attributes in the specified form. After the attributes in the complex attribute have
* been undefined a standard success message is fired and the specified callback is executed.
* <p>
* If the form contains only required attributes, a warning message is fired and the specified callback is executed.
*
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param address the fq address for the operation
* @param form the form which should be reset
* @param callback the callback executed after the resource has been saved
*/
@JsIgnore
public <T> void reset(String complexAttribute, String type, ResourceAddress address, Metadata metadata,
Form<T> form, Callback callback) {
Set<String> attributes = stream(form.getBoundFormItems().spliterator(), false)
.map(FormItem::getName)
.collect(toSet());
Composite composite = operationFactory(complexAttribute).resetResource(address, attributes, metadata);
reset(type, composite, callback);
}
private void reset(String type, Composite composite, Callback callback) {
if (composite.isEmpty()) {
MessageEvent.fire(eventBus, Message.warning(resources.messages().noReset()));
callback.execute();
} else {
DialogFactory.showConfirmation(
resources.messages().resetConfirmationTitle(type),
resources.messages().resetSingletonConfirmationQuestion(),
() -> dispatcher.execute(composite, (CompositeResult result) -> {
MessageEvent.fire(eventBus,
Message.success(resources.messages().resetSingletonSuccess(type)));
callback.execute();
}));
}
}
// ------------------------------------------------------ (d)elete using template
/**
* Undefines the complex attribute. After the attribute has been undefined a standard success message is fired and
* the specified callback is executed.
*
* @param resource the resource name
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param template the address template which is resolved against the current statement context and the
* resource name to get the resource address for the operation
* @param callback the callback executed after the complex attribute has been undefined
*/
@JsIgnore
public void remove(String resource, String complexAttribute, String type, AddressTemplate template,
Callback callback) {
ResourceAddress address = template.resolve(statementContext, resource);
remove(complexAttribute, type, address, callback);
}
/**
* Undefines the complex attribute. After the attribute has been undefined a standard success message is fired and
* the specified callback is executed.
*
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param address the fq address for the operation
* @param callback the callback executed after the complex attribute has been undefined
*/
@JsIgnore
public void remove(String complexAttribute, String type, ResourceAddress address, Callback callback) {
Operation operation = new Operation.Builder(address, UNDEFINE_ATTRIBUTE_OPERATION)
.param(NAME, complexAttribute)
.build();
SafeHtml question = resources.messages().removeSingletonConfirmationQuestion();
DialogFactory.showConfirmation(
resources.messages().removeConfirmationTitle(type), question,
() -> dispatcher.execute(operation, result -> {
MessageEvent.fire(eventBus,
Message.success(resources.messages().removeSingletonResourceSuccess(type)));
callback.execute();
}));
}
/**
* Undefines the complex attribute at the specified index. After the attribute has been undefined a standard success
* message is fired and the specified callback is executed.
*
* @param resource the resource name
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param index the index for the list-type complex attribute
* @param template the address template which is resolved against the current statement context and the
* resource name to get the resource address for the operation
* @param callback the callback executed after the complex attribute has been undefined
*/
@JsIgnore
public void remove(String resource, String complexAttribute, String type, int index, AddressTemplate template,
Callback callback) {
ResourceAddress address = template.resolve(statementContext, resource);
remove(complexAttribute, type, index, address, callback);
}
// ------------------------------------------------------ (d)elete using address
/**
* Undefines the complex attribute at the specified index. After the attribute has been undefined a standard success
* message is fired and the specified callback is executed.
*
* @param complexAttribute the name of the complex attribute
* @param type the human readable name of the complex attribute
* @param index the index for the list-type complex attribute
* @param address the fq address for the operation
* @param callback the callback executed after the complex attribute has been undefined
*/
@JsIgnore
public void remove(String complexAttribute, String type, int index, ResourceAddress address, Callback callback) {
Operation operation = new Operation.Builder(address, LIST_REMOVE_OPERATION)
.param(NAME, complexAttribute)
.param(INDEX, index)
.build();
SafeHtml question = resources.messages().removeSingletonConfirmationQuestion();
DialogFactory.showConfirmation(
resources.messages().removeConfirmationTitle(type), question,
() -> dispatcher.execute(operation, result -> {
MessageEvent.fire(eventBus,
Message.success(resources.messages().removeSingletonResourceSuccess(type)));
callback.execute();
}));
}
// ------------------------------------------------------ helper methods
private OperationFactory operationFactory(String complexAttribute) {
return new OperationFactory(name -> complexAttribute + "." + name);
}
private OperationFactory operationFactory(String complexAttribute, int index) {
return new OperationFactory(name -> complexAttribute + "[" + index + "]." + name);
}
}
| |
/*
*
* * Copyright 2013 dc-square GmbH
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.dcsquare.fileauthplugin.utility;
import com.dcsquare.fileauthplugin.utility.hashing.PasswordHasher;
import com.dcsquare.fileauthplugin.utility.properties.CredentialProperties;
import com.dcsquare.fileauthplugin.utility.properties.FileAuthConfiguration;
import com.google.common.base.Charsets;
import org.apache.commons.configuration.ConfigurationException;
import org.bouncycastle.util.encoders.Base64;
import org.jasypt.salt.RandomSaltGenerator;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* All available commands are defined in this class.
*
* @author Christian Goetz
*/
@Component
public class Commands implements CommandMarker {
FileAuthConfiguration fileAuthConfiguration;
CredentialProperties credentialProperties;
private static int DEFAULT_SALT_LENGTH = 50;
int saltLength = DEFAULT_SALT_LENGTH;
/**
* This method sets the path to the configuration file.
*
* @param path to configuration file
* @return message if loading of file was successful or not
*/
@CliCommand(value = "configure", help = "reads File Authentication Plugin Configuration File")
public String configure(
@CliOption(key = {"file"}, mandatory = true, help = "The absolute path to the fileAuthentication.properties file") final String path) {
try {
fileAuthConfiguration = new FileAuthConfiguration(path);
} catch (ConfigurationException e) {
return "Error reading configuration, try again";
} catch (FileNotFoundException e) {
return e.getMessage();
} catch (IOException e) {
return "Error did not find credential file and creation was not possible";
}
final File file = new File(new File(path).getParent(), fileAuthConfiguration.getCredentialFileName());
try {
credentialProperties = new CredentialProperties(file.getAbsolutePath());
} catch (ConfigurationException e) {
return "Error reading credentials, try again";
}
return "Configuration successfully read!";
}
/**
* This method ensures that it is only possible to add, update,
* delete or list users if the configuration file was found.
*
* @return true, if the configuration file is loaded, false if not.
*/
@CliAvailabilityIndicator({"addUser", "addOrUpdateUser", "listUsers", "deleteUser"})
public boolean checkAvailability() {
if (fileAuthConfiguration == null || credentialProperties == null) {
return false;
}
return true;
}
/**
* Add User Command
*
* @param username username
* @param password plaintext password
* @return message if adding the user was successful or not
*/
@CliCommand(value = "addUser", help = "adds a user in the credential file")
public String addUser(
@CliOption(key = {"username"}, mandatory = true, help = "The username") final String username,
@CliOption(key = {"password"}, mandatory = true, help = "The password to hash") final String password) {
String hashedString = getHashedString(password);
final boolean returnValue;
try {
returnValue = credentialProperties.addUser(username, hashedString);
} catch (ConfigurationException e) {
return "Error during saving of the configuration:" + e.getMessage();
}
String returnString;
if (returnValue) {
returnString = "User " + username + " added";
} else {
returnString = "Username " + username + " already taken";
}
return returnString;
}
/**
* Decides according to the configuration file how to hash the plaintext password.
*
* @param password plaintext password
* @return hashed string
*/
protected String getHashedString(String password) {
String hashedString;
final String salt;
if (fileAuthConfiguration.isHashed()) {
if (!fileAuthConfiguration.isSalted()) {
hashedString = PasswordHasher.hashPassword(fileAuthConfiguration.getAlgorithm(), password, fileAuthConfiguration.getIterations(), null);
} else {
salt = getSalt();
final String saltBase64 = encodeSalt(salt);
if (!fileAuthConfiguration.isFirst()) {
hashedString = PasswordHasher.hashPassword(fileAuthConfiguration.getAlgorithm(), password, fileAuthConfiguration.getIterations(), salt) + fileAuthConfiguration.getSeparationChar() + saltBase64;
} else {
hashedString = saltBase64 + fileAuthConfiguration.getSeparationChar() + PasswordHasher.hashPassword(fileAuthConfiguration.getAlgorithm(), password, fileAuthConfiguration.getIterations(), salt);
}
}
} else {
hashedString = password;
}
return hashedString;
}
/**
* Update User Command.
*
* @param username username
* @param password new plaintext password
* @return message if updating the user was successful or not
*/
@CliCommand(value = "updateUser", help = "changes the password of a user in the credential file")
public String updateUser(
@CliOption(key = {"username"}, mandatory = true, help = "The username") final String username,
@CliOption(key = {"password"}, mandatory = true, help = "The password to hash") final String password) {
String hashedString = getHashedString(password);
final boolean returnValue;
try {
returnValue = credentialProperties.updateUser(username, hashedString);
} catch (ConfigurationException e) {
return "Error during saving of the configuration:" + e.getMessage();
}
String returnString;
if (returnValue) {
returnString = "User " + username + " updated";
} else {
returnString = "User " + username + " not existent";
}
return returnString;
}
/**
* Add or Update User Command
*
* @param username username
* @param password plaintext password
* @return message if creating/updating of the user was successful or not
*/
@CliCommand(value = "addOrUpdateUser", help = "changes the password of a user or create a new user in the credential file")
public String addOrUpdateUser(
@CliOption(key = {"username"}, mandatory = true, help = "The username") final String username,
@CliOption(key = {"password"}, mandatory = true, help = "The password to hash") final String password) {
String hashedString = getHashedString(password);
final boolean returnValue;
try {
returnValue = credentialProperties.updateUser(username, hashedString);
} catch (ConfigurationException e) {
return "Error during saving of the configuration:" + e.getMessage();
}
String returnString;
if (returnValue) {
returnString = "User " + username + " updated";
} else {
final boolean returnValueNewUser;
try {
returnValueNewUser = credentialProperties.addUser(username, hashedString);
} catch (ConfigurationException e) {
return "Error during saving of the configuration:" + e.getMessage();
}
if (!returnValueNewUser) {
return "Could not save new user!";
}
returnString = "User " + username + " added";
}
return returnString;
}
/**
* Delete User Command
*
* @param username username
* @return message if deletion of user was successful or not
*/
@CliCommand(value = "deleteUser", help = "deletes a user in the credential file")
public String deleteUser(
@CliOption(key = {"username"}, mandatory = true, help = "The username") final String username) {
final boolean returnValue;
try {
returnValue = credentialProperties.deleteUser(username);
} catch (ConfigurationException e) {
return "Error during saving of the configuration:" + e.getMessage();
}
String returnString;
if (returnValue) {
returnString = "User " + username + " deleted";
} else {
returnString = "User " + username + " not existent";
}
return returnString;
}
/**
* List Users Command
*
* @return message of how many users are in the file
*/
@CliCommand(value = "listUsers", help = "shows all users in the credential file")
public String listUsers() {
final int count = credentialProperties.show();
return "Listed " + count + " users";
}
/**
* This command sets the salt length that should be used, when hashing a password.
*
* @param length length of salt
* @return message if setting the length accordingly was successful or not
*/
@CliCommand(value = "salt", help = "length of the salt applied")
public String setSaltLength(@CliOption(key = {"length"}, mandatory = true, help = "The absolute path to the fileAuthentication.properties file") final String length) {
int parsedInteger;
try {
parsedInteger = Integer.parseInt(length);
} catch (NumberFormatException e) {
saltLength = DEFAULT_SALT_LENGTH;
return "Error: The length should be an integer, using default salt length";
}
saltLength = parsedInteger;
return "Salt length set to " + saltLength;
}
/**
* Generates a random salt.
*
* @return salt
*/
private String getSalt() {
final RandomSaltGenerator randomSaltGenerator = new RandomSaltGenerator();
return new String(randomSaltGenerator.generateSalt(saltLength), Charsets.UTF_8);
}
/**
* Encodes a salt with base64
*
* @param salt raw salt
* @return base64 encoded salt
*/
private String encodeSalt(String salt) {
return new String(Base64.encode(salt.getBytes()), Charsets.UTF_8);
}
}
| |
/*
* Copyright 2010 Outerthought bvba
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lilyproject.indexer.batchbuild;
import net.iharder.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.solr.client.solrj.SolrServerException;
import org.lilyproject.client.LilyClient;
import org.lilyproject.indexer.engine.IndexLocker;
import org.lilyproject.indexer.engine.Indexer;
import org.lilyproject.indexer.engine.IndexerMetrics;
import org.lilyproject.indexer.model.indexerconf.IndexerConf;
import org.lilyproject.indexer.model.indexerconf.IndexerConfBuilder;
import org.lilyproject.indexer.engine.SolrServers;
import org.lilyproject.indexer.model.sharding.DefaultShardSelectorBuilder;
import org.lilyproject.indexer.model.sharding.JsonShardSelectorBuilder;
import org.lilyproject.indexer.model.sharding.ShardSelector;
import org.lilyproject.repository.api.*;
import org.lilyproject.repository.impl.*;
import org.lilyproject.rowlog.api.RowLog;
import org.lilyproject.util.hbase.HBaseTableFactory;
import org.lilyproject.util.hbase.HBaseTableFactoryImpl;
import org.lilyproject.util.io.Closer;
import org.lilyproject.util.zookeeper.ZkUtil;
import org.lilyproject.util.zookeeper.ZooKeeperItf;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class IndexingMapper extends TableMapper<ImmutableBytesWritable, Result> {
private IdGenerator idGenerator;
private Indexer indexer;
private MultiThreadedHttpConnectionManager connectionManager;
private IndexLocker indexLocker;
private ZooKeeperItf zk;
private Repository repository;
private ThreadPoolExecutor executor;
private Log log = LogFactory.getLog(getClass());
private HBaseTableFactory hbaseTableFactory;
@Override
protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
try {
Configuration jobConf = context.getConfiguration();
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", jobConf.get("hbase.zookeeper.quorum"));
conf.set("hbase.zookeeper.property.clientPort", jobConf.get("hbase.zookeeper.property.clientPort"));
idGenerator = new IdGeneratorImpl();
String zkConnectString = jobConf.get("org.lilyproject.indexer.batchbuild.zooKeeperConnectString");
int zkSessionTimeout = getIntProp("org.lilyproject.indexer.batchbuild.zooKeeperSessionTimeout", null, jobConf);
zk = ZkUtil.connect(zkConnectString, zkSessionTimeout);
hbaseTableFactory = new HBaseTableFactoryImpl(conf, null, null);
TypeManager typeManager = new HBaseTypeManager(idGenerator, conf, zk, hbaseTableFactory);
BlobStoreAccessFactory blobStoreAccessFactory = LilyClient.getBlobStoreAccess(zk);
RowLog wal = new DummyRowLog("The write ahead log should not be called from within MapReduce jobs.");
repository = new HBaseRepository(typeManager, idGenerator, blobStoreAccessFactory, wal, conf, hbaseTableFactory);
byte[] indexerConfBytes = Base64.decode(jobConf.get("org.lilyproject.indexer.batchbuild.indexerconf"));
IndexerConf indexerConf = IndexerConfBuilder.build(new ByteArrayInputStream(indexerConfBytes), repository);
Map<String, String> solrShards = new HashMap<String, String>();
for (int i = 1; true; i++) {
String shardName = jobConf.get("org.lilyproject.indexer.batchbuild.solrshard.name." + i);
String shardAddress = jobConf.get("org.lilyproject.indexer.batchbuild.solrshard.address." + i);
if (shardName == null)
break;
solrShards.put(shardName, shardAddress);
}
ShardSelector shardSelector;
String shardingConf = jobConf.get("org.lilyproject.indexer.batchbuild.shardingconf");
if (shardingConf != null) {
byte[] shardingConfBytes = Base64.decode(shardingConf);
shardSelector = JsonShardSelectorBuilder.build(shardingConfBytes);
} else {
shardSelector = DefaultShardSelectorBuilder.createDefaultSelector(solrShards);
}
connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(5);
connectionManager.getParams().setMaxTotalConnections(50);
HttpClient httpClient = new HttpClient(connectionManager);
SolrServers solrServers = new SolrServers(solrShards, shardSelector, httpClient);
indexLocker = new IndexLocker(zk);
indexer = new Indexer(indexerConf, repository, solrServers, indexLocker, new IndexerMetrics("dummy"));
int workers = getIntProp("org.lilyproject.indexer.batchbuild.threads", 5, jobConf);
executor = new ThreadPoolExecutor(workers, workers, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000));
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
} catch (Exception e) {
throw new IOException("Error in index build map task setup.", e);
}
}
private int getIntProp(String name, Integer defaultValue, Configuration conf) {
String value = conf.get(name);
if (value == null) {
if (defaultValue != null)
return defaultValue;
else
throw new RuntimeException("Missing property in jobconf: " + name);
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new RuntimeException("Invalid integer value in jobconf property. Property '" + name + "', value: " +
value);
}
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
executor.shutdown();
boolean successfulFinish = executor.awaitTermination(5, TimeUnit.MINUTES);
if (!successfulFinish) {
log.error("Executor did not finish outstanding work within the foreseen timeout.");
}
Closer.close(connectionManager);
Closer.close(repository);
super.cleanup(context);
Closer.close(zk);
}
public void map(ImmutableBytesWritable key, Result value, Context context)
throws IOException, InterruptedException {
executor.submit(new MappingTask(context.getCurrentKey().get(), context));
}
public class MappingTask implements Runnable {
private byte[] key;
private Context context;
private MappingTask(byte[] key, Context context) {
this.key = key;
this.context = context;
}
public void run() {
RecordId recordId = null;
boolean locked = false;
try {
recordId = idGenerator.fromBytes(key);
indexLocker.lock(recordId);
locked = true;
indexer.index(recordId);
} catch (Throwable t) {
context.getCounter(IndexBatchBuildCounters.NUM_FAILED_RECORDS).increment(1);
// Avoid printing a complete stack trace for common errors.
if (t instanceof SolrServerException && t.getMessage().equals("java.net.ConnectException: Connection refused")) {
log.error("Failure indexing record " + recordId + ": SOLR connection refused.");
} else {
log.error("Failure indexing record " + recordId, t);
}
} finally {
if (locked) {
indexLocker.unlockLogFailure(recordId);
}
}
}
}
}
| |
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.firebase.dynamiclinks;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.FirebaseApp;
import com.google.firebase.dynamiclinks.DynamicLink;
import com.google.firebase.dynamiclinks.FirebaseDynamicLinks;
import com.google.firebase.dynamiclinks.PendingDynamicLinkData;
import com.google.firebase.dynamiclinks.ShortDynamicLink;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.PluginRegistry.NewIntentListener;
import io.flutter.plugins.firebase.core.FlutterFirebasePlugin;
import io.flutter.plugins.firebase.core.FlutterFirebasePluginRegistry;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
public class FlutterFirebaseDynamicLinksPlugin
implements FlutterFirebasePlugin,
FlutterPlugin,
ActivityAware,
MethodCallHandler,
NewIntentListener {
private final AtomicReference<Activity> activity = new AtomicReference<>(null);
private MethodChannel channel;
@Nullable private BinaryMessenger messenger;
private static final String METHOD_CHANNEL_NAME = "plugins.flutter.io/firebase_dynamic_links";
private void initInstance(BinaryMessenger messenger) {
channel = new MethodChannel(messenger, METHOD_CHANNEL_NAME);
channel.setMethodCallHandler(this);
FlutterFirebasePluginRegistry.registerPlugin(METHOD_CHANNEL_NAME, this);
this.messenger = messenger;
}
@Override
public void onAttachedToEngine(FlutterPluginBinding binding) {
initInstance(binding.getBinaryMessenger());
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
channel = null;
messenger = null;
}
@Override
public void onAttachedToActivity(ActivityPluginBinding binding) {
activity.set(binding.getActivity());
binding.addOnNewIntentListener(this);
}
@Override
public void onDetachedFromActivityForConfigChanges() {
detachToActivity();
}
@Override
public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) {
activity.set(binding.getActivity());
binding.addOnNewIntentListener(this);
}
private void detachToActivity() {
activity.set(null);
}
@Override
public void onDetachedFromActivity() {
detachToActivity();
}
static FirebaseDynamicLinks getDynamicLinkInstance(@Nullable Map<String, Object> arguments) {
if (arguments != null) {
String appName = (String) arguments.get(Constants.APP_NAME);
if (appName != null) {
FirebaseApp app = FirebaseApp.getInstance(appName);
return FirebaseDynamicLinks.getInstance(app);
}
}
return FirebaseDynamicLinks.getInstance();
}
@Override
public boolean onNewIntent(Intent intent) {
getDynamicLinkInstance(null)
.getDynamicLink(intent)
.addOnSuccessListener(
pendingDynamicLinkData -> {
Map<String, Object> dynamicLink =
Utils.getMapFromPendingDynamicLinkData(pendingDynamicLinkData);
if (dynamicLink != null) {
channel.invokeMethod("FirebaseDynamicLink#onLinkSuccess", dynamicLink);
}
})
.addOnFailureListener(
exception ->
channel.invokeMethod(
"FirebaseDynamicLink#onLinkError", Utils.getExceptionDetails(exception)));
return false;
}
@Override
public void onMethodCall(MethodCall call, @NonNull final MethodChannel.Result result) {
Task<?> methodCallTask;
FirebaseDynamicLinks dynamicLinks = getDynamicLinkInstance(call.arguments());
switch (call.method) {
case "FirebaseDynamicLinks#buildLink":
String url = buildLink(call.arguments());
result.success(url);
return;
case "FirebaseDynamicLinks#buildShortLink":
DynamicLink.Builder urlBuilder = setupParameters(call.arguments());
methodCallTask = buildShortLink(urlBuilder, call.arguments());
break;
case "FirebaseDynamicLinks#getDynamicLink":
case "FirebaseDynamicLinks#getInitialLink":
methodCallTask = getDynamicLink(dynamicLinks, call.argument("url"));
break;
default:
result.notImplemented();
return;
}
methodCallTask.addOnCompleteListener(
task -> {
if (task.isSuccessful()) {
result.success(task.getResult());
} else {
Exception exception = task.getException();
result.error(
Constants.DEFAULT_ERROR_CODE,
exception != null ? exception.getMessage() : null,
io.flutter.plugins.firebase.dynamiclinks.Utils.getExceptionDetails(exception));
}
});
}
private String buildLink(Map<String, Object> arguments) {
DynamicLink.Builder urlBuilder = setupParameters(arguments);
return urlBuilder.buildDynamicLink().getUri().toString();
}
private Task<Map<String, Object>> buildShortLink(
DynamicLink.Builder urlBuilder, @Nullable Map<String, Object> arguments) {
return Tasks.call(
cachedThreadPool,
() -> {
Integer suffix = 1;
Integer shortDynamicLinkPathLength = (Integer) arguments.get("shortLinkType");
if (shortDynamicLinkPathLength != null) {
switch (shortDynamicLinkPathLength) {
case 0:
suffix = ShortDynamicLink.Suffix.UNGUESSABLE;
break;
case 1:
suffix = ShortDynamicLink.Suffix.SHORT;
break;
default:
break;
}
}
Map<String, Object> result = new HashMap<>();
ShortDynamicLink shortLink;
if (suffix != null) {
shortLink = Tasks.await(urlBuilder.buildShortDynamicLink(suffix));
} else {
shortLink = Tasks.await(urlBuilder.buildShortDynamicLink());
}
List<String> warnings = new ArrayList<>();
for (ShortDynamicLink.Warning warning : shortLink.getWarnings()) {
warnings.add(warning.getMessage());
}
result.put("url", shortLink.getShortLink().toString());
result.put("warnings", warnings);
result.put("previewLink", shortLink.getPreviewLink().toString());
return result;
});
}
private Task<Map<String, Object>> getDynamicLink(
FirebaseDynamicLinks dynamicLinks, @Nullable String url) {
return Tasks.call(
cachedThreadPool,
() -> {
PendingDynamicLinkData pendingDynamicLink;
if (url != null) {
pendingDynamicLink = Tasks.await(dynamicLinks.getDynamicLink(Uri.parse(url)));
} else {
// If there's no activity or initial Intent, then there's no initial dynamic link.
if (activity.get() == null
|| activity.get().getIntent() == null
|| activity.get().getIntent().getBooleanExtra("flutterfire-used-link", false)) {
return null;
}
pendingDynamicLink =
Tasks.await(dynamicLinks.getDynamicLink(activity.get().getIntent()));
activity.get().getIntent().putExtra("flutterfire-used-link", true);
}
return Utils.getMapFromPendingDynamicLinkData(pendingDynamicLink);
});
}
private DynamicLink.Builder setupParameters(Map<String, Object> arguments) {
DynamicLink.Builder dynamicLinkBuilder = getDynamicLinkInstance(arguments).createDynamicLink();
String uriPrefix = (String) arguments.get("uriPrefix");
String link = (String) arguments.get("link");
dynamicLinkBuilder.setDomainUriPrefix(uriPrefix);
dynamicLinkBuilder.setLink(Uri.parse(link));
Map<String, Object> androidParameters =
(Map<String, Object>) arguments.get("androidParameters");
if (androidParameters != null) {
String packageName = valueFor("packageName", androidParameters);
String fallbackUrl = valueFor("fallbackUrl", androidParameters);
Integer minimumVersion = valueFor("minimumVersion", androidParameters);
DynamicLink.AndroidParameters.Builder builder =
new DynamicLink.AndroidParameters.Builder(packageName);
if (fallbackUrl != null) builder.setFallbackUrl(Uri.parse(fallbackUrl));
if (minimumVersion != null) builder.setMinimumVersion(minimumVersion);
dynamicLinkBuilder.setAndroidParameters(builder.build());
}
Map<String, Object> googleAnalyticsParameters =
(Map<String, Object>) arguments.get("googleAnalyticsParameters");
if (googleAnalyticsParameters != null) {
String campaign = valueFor("campaign", googleAnalyticsParameters);
String content = valueFor("content", googleAnalyticsParameters);
String medium = valueFor("medium", googleAnalyticsParameters);
String source = valueFor("source", googleAnalyticsParameters);
String term = valueFor("term", googleAnalyticsParameters);
DynamicLink.GoogleAnalyticsParameters.Builder builder =
new DynamicLink.GoogleAnalyticsParameters.Builder();
if (campaign != null) builder.setCampaign(campaign);
if (content != null) builder.setContent(content);
if (medium != null) builder.setMedium(medium);
if (source != null) builder.setSource(source);
if (term != null) builder.setTerm(term);
dynamicLinkBuilder.setGoogleAnalyticsParameters(builder.build());
}
Map<String, Object> iosParameters = (Map<String, Object>) arguments.get("iosParameters");
if (iosParameters != null) {
String bundleId = valueFor("bundleId", iosParameters);
String appStoreId = valueFor("appStoreId", iosParameters);
String customScheme = valueFor("customScheme", iosParameters);
String fallbackUrl = valueFor("fallbackUrl", iosParameters);
String ipadBundleId = valueFor("ipadBundleId", iosParameters);
String ipadFallbackUrl = valueFor("ipadFallbackUrl", iosParameters);
String minimumVersion = valueFor("minimumVersion", iosParameters);
DynamicLink.IosParameters.Builder builder = new DynamicLink.IosParameters.Builder(bundleId);
if (appStoreId != null) builder.setAppStoreId(appStoreId);
if (customScheme != null) builder.setCustomScheme(customScheme);
if (fallbackUrl != null) builder.setFallbackUrl(Uri.parse(fallbackUrl));
if (ipadBundleId != null) builder.setIpadBundleId(ipadBundleId);
if (ipadFallbackUrl != null) builder.setIpadFallbackUrl(Uri.parse(ipadFallbackUrl));
if (minimumVersion != null) builder.setMinimumVersion(minimumVersion);
dynamicLinkBuilder.setIosParameters(builder.build());
}
Map<String, Object> itunesConnectAnalyticsParameters =
(Map<String, Object>) arguments.get("itunesConnectAnalyticsParameters");
if (itunesConnectAnalyticsParameters != null) {
String affiliateToken = valueFor("affiliateToken", itunesConnectAnalyticsParameters);
String campaignToken = valueFor("campaignToken", itunesConnectAnalyticsParameters);
String providerToken = valueFor("providerToken", itunesConnectAnalyticsParameters);
DynamicLink.ItunesConnectAnalyticsParameters.Builder builder =
new DynamicLink.ItunesConnectAnalyticsParameters.Builder();
if (affiliateToken != null) builder.setAffiliateToken(affiliateToken);
if (campaignToken != null) builder.setCampaignToken(campaignToken);
if (providerToken != null) builder.setProviderToken(providerToken);
dynamicLinkBuilder.setItunesConnectAnalyticsParameters(builder.build());
}
Map<String, Object> navigationInfoParameters =
(Map<String, Object>) arguments.get("navigationInfoParameters");
if (navigationInfoParameters != null) {
Boolean forcedRedirectEnabled = valueFor("forcedRedirectEnabled", navigationInfoParameters);
DynamicLink.NavigationInfoParameters.Builder builder =
new DynamicLink.NavigationInfoParameters.Builder();
if (forcedRedirectEnabled != null) builder.setForcedRedirectEnabled(forcedRedirectEnabled);
dynamicLinkBuilder.setNavigationInfoParameters(builder.build());
}
Map<String, Object> socialMetaTagParameters =
(Map<String, Object>) arguments.get("socialMetaTagParameters");
if (socialMetaTagParameters != null) {
String description = valueFor("description", socialMetaTagParameters);
String imageUrl = valueFor("imageUrl", socialMetaTagParameters);
String title = valueFor("title", socialMetaTagParameters);
DynamicLink.SocialMetaTagParameters.Builder builder =
new DynamicLink.SocialMetaTagParameters.Builder();
if (description != null) builder.setDescription(description);
if (imageUrl != null) builder.setImageUrl(Uri.parse(imageUrl));
if (title != null) builder.setTitle(title);
dynamicLinkBuilder.setSocialMetaTagParameters(builder.build());
}
return dynamicLinkBuilder;
}
private static <T> T valueFor(String key, Map<String, Object> map) {
@SuppressWarnings("unchecked")
T result = (T) map.get(key);
return result;
}
@Override
public Task<Map<String, Object>> getPluginConstantsForFirebaseApp(FirebaseApp firebaseApp) {
return Tasks.call(cachedThreadPool, () -> null);
}
@Override
public Task<Void> didReinitializeFirebaseCore() {
return Tasks.call(
cachedThreadPool,
() -> {
return null;
});
}
}
| |
/**
* Copyright 2005-2015 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kim.api.identity.personal;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.Years;
import org.kuali.rice.core.api.CoreConstants;
import org.kuali.rice.core.api.mo.AbstractDataTransferObject;
import org.kuali.rice.core.api.mo.ModelBuilder;
import org.kuali.rice.core.api.util.jaxb.PrimitiveBooleanDefaultToFalseAdapter;
import org.kuali.rice.kim.api.KimConstants;
import org.w3c.dom.Element;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
@XmlRootElement(name = EntityBioDemographics.Constants.ROOT_ELEMENT_NAME)
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = EntityBioDemographics.Constants.TYPE_NAME, propOrder = {
EntityBioDemographics.Elements.ENTITY_ID,
EntityBioDemographics.Elements.DECEASED_DATE,
EntityBioDemographics.Elements.BIRTH_DATE,
EntityBioDemographics.Elements.AGE,
EntityBioDemographics.Elements.GENDER_CODE,
EntityBioDemographics.Elements.GENDER_CHANGE_CODE,
EntityBioDemographics.Elements.MARITAL_STATUS_CODE,
EntityBioDemographics.Elements.PRIMARY_LANGUAGE_CODE,
EntityBioDemographics.Elements.SECONDARY_LANGUAGE_CODE,
EntityBioDemographics.Elements.BIRTH_COUNTRY,
EntityBioDemographics.Elements.BIRTH_STATE_PROVINCE_CODE,
EntityBioDemographics.Elements.BIRTH_CITY,
EntityBioDemographics.Elements.GEOGRAPHIC_ORIGIN,
EntityBioDemographics.Elements.BIRTH_DATE_UNMASKED,
EntityBioDemographics.Elements.GENDER_CODE_UNMASKED,
EntityBioDemographics.Elements.GENDER_CHANGE_CODE_UNMASKED,
EntityBioDemographics.Elements.MARITAL_STATUS_CODE_UNMASKED,
EntityBioDemographics.Elements.PRIMARY_LANGUAGE_CODE_UNMASKED,
EntityBioDemographics.Elements.SECONDARY_LANGUAGE_CODE_UNMASKED,
EntityBioDemographics.Elements.BIRTH_COUNTRY_UNMASKED,
EntityBioDemographics.Elements.BIRTH_STATE_PROVINCE_CODE_UNMASKED,
EntityBioDemographics.Elements.BIRTH_CITY_UNMASKED,
EntityBioDemographics.Elements.GEOGRAPHIC_ORIGIN_UNMASKED,
EntityBioDemographics.Elements.NOTE_MESSAGE,
EntityBioDemographics.Elements.SUPPRESS_PERSONAL,
CoreConstants.CommonElements.VERSION_NUMBER,
CoreConstants.CommonElements.OBJECT_ID,
CoreConstants.CommonElements.FUTURE_ELEMENTS
})
public final class EntityBioDemographics extends AbstractDataTransferObject
implements EntityBioDemographicsContract
{
private static final Logger LOG = Logger.getLogger(EntityBioDemographics.class);
@XmlElement(name = Elements.ENTITY_ID, required = false)
private final String entityId;
@XmlElement(name = Elements.DECEASED_DATE, required = false)
private final String deceasedDate;
@XmlElement(name = Elements.BIRTH_DATE, required = false)
private final String birthDate;
@XmlElement(name = Elements.GENDER_CODE, required = false)
private final String genderCode;
@XmlElement(name = Elements.GENDER_CHANGE_CODE, required = false)
private final String genderChangeCode;
@XmlElement(name = Elements.MARITAL_STATUS_CODE, required = false)
private final String maritalStatusCode;
@XmlElement(name = Elements.PRIMARY_LANGUAGE_CODE, required = false)
private final String primaryLanguageCode;
@XmlElement(name = Elements.SECONDARY_LANGUAGE_CODE, required = false)
private final String secondaryLanguageCode;
@XmlElement(name = Elements.BIRTH_COUNTRY, required = false)
private final String birthCountry;
@XmlElement(name = Elements.BIRTH_STATE_PROVINCE_CODE, required = false)
private final String birthStateProvinceCode;
@XmlElement(name = Elements.BIRTH_CITY, required = false)
private final String birthCity;
@XmlElement(name = Elements.GEOGRAPHIC_ORIGIN, required = false)
private final String geographicOrigin;
@XmlElement(name = Elements.BIRTH_DATE_UNMASKED, required = false)
private final String birthDateUnmasked;
@XmlElement(name = Elements.GENDER_CODE_UNMASKED, required = false)
private final String genderCodeUnmasked;
@XmlElement(name = Elements.GENDER_CHANGE_CODE_UNMASKED, required = false)
private final String genderChangeCodeUnmasked;
@XmlElement(name = Elements.MARITAL_STATUS_CODE_UNMASKED, required = false)
private final String maritalStatusCodeUnmasked;
@XmlElement(name = Elements.PRIMARY_LANGUAGE_CODE_UNMASKED, required = false)
private final String primaryLanguageCodeUnmasked;
@XmlElement(name = Elements.SECONDARY_LANGUAGE_CODE_UNMASKED, required = false)
private final String secondaryLanguageCodeUnmasked;
@XmlElement(name = Elements.BIRTH_COUNTRY_UNMASKED, required = false)
private final String birthCountryUnmasked;
@XmlElement(name = Elements.BIRTH_STATE_PROVINCE_CODE_UNMASKED, required = false)
private final String birthStateProvinceCodeUnmasked;
@XmlElement(name = Elements.BIRTH_CITY_UNMASKED, required = false)
private final String birthCityUnmasked;
@XmlElement(name = Elements.GEOGRAPHIC_ORIGIN_UNMASKED, required = false)
private final String geographicOriginUnmasked;
@XmlElement(name = Elements.NOTE_MESSAGE, required = false)
private final String noteMessage;
@XmlElement(name = Elements.SUPPRESS_PERSONAL, required = true)
private final boolean suppressPersonal;
@XmlElement(name = CoreConstants.CommonElements.VERSION_NUMBER, required = false)
private final Long versionNumber;
@XmlElement(name = CoreConstants.CommonElements.OBJECT_ID, required = false)
private final String objectId;
@SuppressWarnings("unused")
@XmlAnyElement
private final Collection<Element> _futureElements = null;
/**
* Private constructor used only by JAXB.
*
*/
private EntityBioDemographics() {
this.entityId = null;
this.deceasedDate = null;
this.birthDate = null;
this.genderCode = null;
this.genderChangeCode = null;
this.maritalStatusCode = null;
this.primaryLanguageCode = null;
this.secondaryLanguageCode = null;
this.birthCountry = null;
this.birthStateProvinceCode = null;
this.birthCity = null;
this.geographicOrigin = null;
this.birthDateUnmasked = null;
this.genderCodeUnmasked = null;
this.genderChangeCodeUnmasked = null;
this.maritalStatusCodeUnmasked = null;
this.primaryLanguageCodeUnmasked = null;
this.secondaryLanguageCodeUnmasked = null;
this.birthCountryUnmasked = null;
this.birthStateProvinceCodeUnmasked = null;
this.birthCityUnmasked = null;
this.geographicOriginUnmasked = null;
this.noteMessage = null;
this.suppressPersonal = false;
this.versionNumber = null;
this.objectId = null;
}
private EntityBioDemographics(Builder builder) {
this.entityId = builder.getEntityId();
this.deceasedDate = builder.getDeceasedDate();
this.birthDate = builder.getBirthDate();
this.genderCode = builder.getGenderCode();
this.genderChangeCode = builder.getGenderChangeCode();
this.maritalStatusCode = builder.getMaritalStatusCode();
this.primaryLanguageCode = builder.getPrimaryLanguageCode();
this.secondaryLanguageCode = builder.getSecondaryLanguageCode();
this.birthCountry = builder.getBirthCountry();
this.birthStateProvinceCode = builder.getBirthStateProvinceCode();
this.birthCity = builder.getBirthCity();
this.geographicOrigin = builder.getGeographicOrigin();
this.birthDateUnmasked = builder.getBirthDateUnmasked();
this.genderCodeUnmasked = builder.getGenderCodeUnmasked();
this.genderChangeCodeUnmasked = builder.getGenderChangeCodeUnmasked();
this.maritalStatusCodeUnmasked = builder.getMaritalStatusCodeUnmasked();
this.primaryLanguageCodeUnmasked = builder.getPrimaryLanguageCodeUnmasked();
this.secondaryLanguageCodeUnmasked = builder.getSecondaryLanguageCodeUnmasked();
this.birthCountryUnmasked = builder.getBirthCountryUnmasked();
this.birthStateProvinceCodeUnmasked = builder.getBirthStateProvinceCodeUnmasked();
this.birthCityUnmasked = builder.getBirthCityUnmasked();
this.geographicOriginUnmasked = builder.getGeographicOriginUnmasked();
this.noteMessage = builder.getNoteMessage();
this.suppressPersonal = builder.isSuppressPersonal();
this.versionNumber = builder.getVersionNumber();
this.objectId = builder.getObjectId();
}
@Override
public String getEntityId() {
return this.entityId;
}
@Override
public String getDeceasedDate() {
return this.deceasedDate;
}
@Override
public String getBirthDate() {
return this.birthDate;
}
@Override
@XmlElement(name = Elements.AGE, required = true)
public Integer getAge() {
return calculateAge(this.birthDate, this.deceasedDate, isSuppressPersonal());
}
@Override
public String getGenderCode() {
return this.genderCode;
}
@Override
public String getGenderChangeCode() {
return this.genderChangeCode;
}
@Override
public String getMaritalStatusCode() {
return this.maritalStatusCode;
}
@Override
public String getPrimaryLanguageCode() {
return this.primaryLanguageCode;
}
@Override
public String getSecondaryLanguageCode() {
return this.secondaryLanguageCode;
}
@Override
public String getBirthCountry() {
return this.birthCountry;
}
@Override
public String getBirthStateProvinceCode() {
return this.birthStateProvinceCode;
}
@Override
public String getBirthCity() {
return this.birthCity;
}
@Override
public String getGeographicOrigin() {
return this.geographicOrigin;
}
@Override
public String getBirthDateUnmasked() {
return this.birthDateUnmasked;
}
@Override
public String getGenderCodeUnmasked() {
return this.genderCodeUnmasked;
}
@Override
public String getGenderChangeCodeUnmasked() {
return this.genderChangeCodeUnmasked;
}
@Override
public String getMaritalStatusCodeUnmasked() {
return this.maritalStatusCodeUnmasked;
}
@Override
public String getPrimaryLanguageCodeUnmasked() {
return this.primaryLanguageCodeUnmasked;
}
@Override
public String getSecondaryLanguageCodeUnmasked() {
return this.secondaryLanguageCodeUnmasked;
}
@Override
public String getBirthCountryUnmasked() {
return this.birthCountryUnmasked;
}
@Override
public String getBirthStateProvinceCodeUnmasked() {
return this.birthStateProvinceCodeUnmasked;
}
@Override
public String getBirthCityUnmasked() {
return this.birthCityUnmasked;
}
@Override
public String getGeographicOriginUnmasked() {
return this.geographicOriginUnmasked;
}
@Override
public String getNoteMessage() {
return this.noteMessage;
}
@Override
public boolean isSuppressPersonal() {
return this.suppressPersonal;
}
@Override
public Long getVersionNumber() {
return this.versionNumber;
}
@Override
public String getObjectId() {
return this.objectId;
}
/**
* Helper to parse the birth date for age calculation
* @param birthDate the birth date in EntityBioDemographicsContract BIRTH_DATE_FORMAT format
* @param deceasedDate the deceased date in EntityBioDemographicsContract DECEASED_DATE_FORMAT format
* @param suppressPersonal whether personal information is being suppressed
* @return the age in years or null if unavailable, suppressed, or an error occurs during calculation
*/
private static Integer calculateAge(String birthDate, String deceasedDate, boolean suppressPersonal) {
if (birthDate != null && ! suppressPersonal) {
Date parsedBirthDate;
try {
parsedBirthDate = new SimpleDateFormat(BIRTH_DATE_FORMAT).parse(birthDate);
} catch (ParseException pe) {
LOG.error("Error parsing EntityBioDemographics birth date: '" + birthDate + "'", pe);
return null;
}
DateTime endDate;
if (deceasedDate != null) {
try {
endDate = new DateTime(new SimpleDateFormat(BIRTH_DATE_FORMAT).parse(deceasedDate));
} catch (ParseException pe) {
LOG.error("Error parsing EntityBioDemographics deceased date: '" + deceasedDate+ "'", pe);
return null;
}
} else {
endDate = new DateTime();
}
return Years.yearsBetween(new DateTime(parsedBirthDate), endDate).getYears();
}
return null;
}
/**
* A builder which can be used to construct {@link EntityBioDemographics} instances. Enforces the constraints of the {@link EntityBioDemographicsContract}.
*
*/
public final static class Builder
implements Serializable, ModelBuilder, EntityBioDemographicsContract
{
private String entityId;
private String deceasedDate;
private String birthDate;
private String genderCode;
private String maritalStatusCode;
private String primaryLanguageCode;
private String secondaryLanguageCode;
private String birthCountry;
private String birthStateProvinceCode;
private String birthCity;
private String geographicOrigin;
private String genderChangeCode;
private String noteMessage;
private boolean suppressPersonal;
private Long versionNumber;
private String objectId;
private Builder(String entityId, String genderCode) {
setEntityId(entityId);
setGenderCode(genderCode);
}
public static Builder create(String entityId, String genderCode) {
// TODO modify as needed to pass any required values and add them to the signature of the 'create' method
return new Builder(entityId, genderCode);
}
public static Builder create(EntityBioDemographicsContract contract) {
if (contract == null) {
throw new IllegalArgumentException("contract was null");
}
Builder builder = create(contract.getEntityId(), contract.getGenderCode());
builder.setDeceasedDate(contract.getDeceasedDate());
builder.setBirthDate(contract.getBirthDate());
builder.setMaritalStatusCode(contract.getMaritalStatusCode());
builder.setPrimaryLanguageCode(contract.getPrimaryLanguageCode());
builder.setSecondaryLanguageCode(contract.getSecondaryLanguageCode());
builder.setBirthCountry(contract.getBirthCountry());
builder.setBirthStateProvinceCode(contract.getBirthStateProvinceCode());
builder.setBirthCity(contract.getBirthCity());
builder.setGeographicOrigin(contract.getGeographicOrigin());
builder.setGenderChangeCode(contract.getGenderChangeCode());
builder.setNoteMessage(contract.getNoteMessage());
builder.setSuppressPersonal(contract.isSuppressPersonal());
builder.setVersionNumber(contract.getVersionNumber());
builder.setObjectId(contract.getObjectId());
return builder;
}
public EntityBioDemographics build() {
return new EntityBioDemographics(this);
}
@Override
public String getEntityId() {
return this.entityId;
}
@Override
public String getDeceasedDate() {
return this.deceasedDate;
}
@Override
public String getBirthDate() {
if (isSuppressPersonal()) {
return KimConstants.RESTRICTED_DATA_MASK;
}
return this.birthDate;
}
@Override
public Integer getAge() {
return calculateAge(this.birthDate, this.deceasedDate, isSuppressPersonal());
}
@Override
public String getGenderCode() {
if (isSuppressPersonal()) {
return KimConstants.RESTRICTED_DATA_MASK;
}
return this.genderCode;
}
@Override
public String getGenderChangeCode() {
if (isSuppressPersonal()) {
return KimConstants.RESTRICTED_DATA_MASK;
}
return this.genderChangeCode;
}
@Override
public String getMaritalStatusCode() {
if (isSuppressPersonal()) {
return KimConstants.RESTRICTED_DATA_MASK;
}
return this.maritalStatusCode;
}
@Override
public String getPrimaryLanguageCode() {
if (isSuppressPersonal()) {
return KimConstants.RESTRICTED_DATA_MASK;
}
return this.primaryLanguageCode;
}
@Override
public String getSecondaryLanguageCode() {
if (isSuppressPersonal()) {
return KimConstants.RESTRICTED_DATA_MASK;
}
return this.secondaryLanguageCode;
}
@Override
public String getBirthCountry() {
if (isSuppressPersonal()) {
return KimConstants.RESTRICTED_DATA_MASK;
}
return this.birthCountry;
}
@Override
public String getBirthStateProvinceCode() {
if (isSuppressPersonal()) {
return KimConstants.RESTRICTED_DATA_MASK;
}
return this.birthStateProvinceCode;
}
@Override
public String getBirthCity() {
if (isSuppressPersonal()) {
return KimConstants.RESTRICTED_DATA_MASK;
}
return this.birthCity;
}
@Override
public String getGeographicOrigin() {
if (isSuppressPersonal()) {
return KimConstants.RESTRICTED_DATA_MASK;
}
return this.geographicOrigin;
}
@Override
public String getBirthDateUnmasked() {
return this.birthDate;
}
@Override
public String getGenderCodeUnmasked() {
return this.genderCode;
}
@Override
public String getGenderChangeCodeUnmasked() {
return this.genderChangeCode;
}
@Override
public String getMaritalStatusCodeUnmasked() {
return this.maritalStatusCode;
}
@Override
public String getPrimaryLanguageCodeUnmasked() {
return this.primaryLanguageCode;
}
@Override
public String getSecondaryLanguageCodeUnmasked() {
return this.secondaryLanguageCode;
}
@Override
public String getBirthCountryUnmasked() {
return this.birthCountry;
}
@Override
public String getBirthStateProvinceCodeUnmasked() {
return this.birthStateProvinceCode;
}
@Override
public String getBirthCityUnmasked() {
return this.birthCity;
}
@Override
public String getGeographicOriginUnmasked() {
return this.geographicOrigin;
}
@Override
public String getNoteMessage() {
return this.noteMessage;
}
@Override
public boolean isSuppressPersonal() {
return this.suppressPersonal;
}
@Override
public Long getVersionNumber() {
return this.versionNumber;
}
@Override
public String getObjectId() {
return this.objectId;
}
public void setEntityId(String entityId) {
if (StringUtils.isEmpty(entityId)) {
throw new IllegalArgumentException("id is empty");
}
this.entityId = entityId;
}
public void setDeceasedDate(String deceasedDate) {
if (deceasedDate != null) {
SimpleDateFormat format = new SimpleDateFormat(DECEASED_DATE_FORMAT);
try{
format.parse(deceasedDate);
this.deceasedDate = deceasedDate;
}
catch(ParseException e) {
throw new IllegalArgumentException("deceasedDate is not of the format 'yyyy-MM-DD'");
}
}
}
public void setBirthDate(String birthDate) {
if (birthDate != null) {
SimpleDateFormat format = new SimpleDateFormat(BIRTH_DATE_FORMAT);
try{
format.parse(birthDate);
this.birthDate = birthDate;
}
catch(ParseException e) {
throw new IllegalArgumentException("birthDate is not of the format 'yyyy-MM-DD'");
}
}
}
public void setDeceasedDate(Date deceasedDate) {
this.deceasedDate = new SimpleDateFormat(DECEASED_DATE_FORMAT).format(deceasedDate);
}
public void setBirthDate(Date birthDate) {
this.birthDate = new SimpleDateFormat(BIRTH_DATE_FORMAT).format(birthDate);
}
public void setGenderCode(String genderCode) {
if (StringUtils.isEmpty(genderCode)) {
throw new IllegalArgumentException("genderCode is empty");
}
this.genderCode = genderCode;
}
public void setGenderChangeCode(String genderChangeCode) {
this.genderChangeCode = genderChangeCode;
}
public void setMaritalStatusCode(String maritalStatusCode) {
this.maritalStatusCode = maritalStatusCode;
}
public void setPrimaryLanguageCode(String primaryLanguageCode) {
this.primaryLanguageCode = primaryLanguageCode;
}
public void setSecondaryLanguageCode(String secondaryLanguageCode) {
this.secondaryLanguageCode = secondaryLanguageCode;
}
public void setBirthCountry(String birthCountry) {
this.birthCountry = birthCountry;
}
public void setBirthStateProvinceCode(String birthStateProvinceCode) {
this.birthStateProvinceCode = birthStateProvinceCode;
}
public void setBirthCity(String birthCity) {
this.birthCity = birthCity;
}
public void setGeographicOrigin(String geographicOrigin) {
this.geographicOrigin = geographicOrigin;
}
private void setNoteMessage(String noteMessage) {
this.noteMessage = noteMessage;
}
private void setSuppressPersonal(boolean suppressPersonal) {
this.suppressPersonal = suppressPersonal;
}
public void setVersionNumber(Long versionNumber) {
this.versionNumber = versionNumber;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
}
/**
* Defines some internal constants used on this class.
*
*/
static class Constants {
final static String ROOT_ELEMENT_NAME = "entityBioDemographics";
final static String TYPE_NAME = "EntityBioDemographicsType";
}
/**
* A private class which exposes constants which define the XML element names to use when this object is marshalled to XML.
*
*/
static class Elements {
final static String ENTITY_ID = "entityId";
final static String DECEASED_DATE = "deceasedDate";
final static String BIRTH_DATE = "birthDate";
final static String AGE = "age";
final static String GENDER_CODE = "genderCode";
final static String MARITAL_STATUS_CODE = "maritalStatusCode";
final static String PRIMARY_LANGUAGE_CODE = "primaryLanguageCode";
final static String SECONDARY_LANGUAGE_CODE = "secondaryLanguageCode";
final static String BIRTH_COUNTRY = "birthCountry";
final static String BIRTH_STATE_PROVINCE_CODE = "birthStateProvinceCode";
final static String BIRTH_CITY = "birthCity";
final static String GEOGRAPHIC_ORIGIN = "geographicOrigin";
final static String BIRTH_DATE_UNMASKED = "birthDateUnmasked";
final static String GENDER_CODE_UNMASKED = "genderCodeUnmasked";
final static String MARITAL_STATUS_CODE_UNMASKED = "maritalStatusCodeUnmasked";
final static String PRIMARY_LANGUAGE_CODE_UNMASKED = "primaryLanguageCodeUnmasked";
final static String SECONDARY_LANGUAGE_CODE_UNMASKED = "secondaryLanguageCodeUnmasked";
final static String BIRTH_COUNTRY_UNMASKED = "birthCountryUnmasked";
final static String BIRTH_STATE_PROVINCE_CODE_UNMASKED = "birthStateProvinceCodeUnmasked";
final static String BIRTH_CITY_UNMASKED = "birthCityUnmasked";
final static String GEOGRAPHIC_ORIGIN_UNMASKED = "geographicOriginUnmasked";
final static String GENDER_CHANGE_CODE = "genderChangeCode";
final static String GENDER_CHANGE_CODE_UNMASKED = "genderChangeCodeUnmasked";
final static String NOTE_MESSAGE = "noteMessage";
final static String SUPPRESS_PERSONAL = "suppressPersonal";
}
}
| |
/**
* Copyright (C) 2009-2015 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.dasein.cloud.test.compute;
import junit.framework.Assert;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.compute.ComputeServices;
import org.dasein.cloud.compute.VirtualMachineSupport;
import org.dasein.cloud.compute.VmStatistics;
import org.dasein.cloud.test.DaseinTestManager;
import org.dasein.util.CalendarWrapper;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import java.util.Date;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
/**
* Tests on {@link VirtualMachineSupport} that do not involve making any changes to the system.
* <p>Created by George Reese: 2/17/13 3:22 PM</p>
* @author George Reese
* @version 2013.04 initial version
* @since 2013.04
*/
public class StatelessVMMonitoringTests {
static private DaseinTestManager tm;
@BeforeClass
static public void configure() {
tm = new DaseinTestManager(StatelessVMMonitoringTests.class);
}
@AfterClass
static public void cleanUp() {
if( tm != null ) {
tm.close();
}
}
@Rule
public final TestName name = new TestName();
private String testVMId;
public StatelessVMMonitoringTests() { }
@Before
public void before() {
tm.begin(name.getMethodName());
assumeTrue(!tm.isTestSkipped());
testVMId = tm.getTestVMId(DaseinTestManager.STATELESS, null, false, null);
}
@After
public void after() {
testVMId = null;
tm.end();
}
@Test
public void checkMetaData() throws CloudException, InternalException {
assumeTrue(!tm.isTestSkipped());
ComputeServices services = tm.getProvider().getComputeServices();
if( services != null ) {
VirtualMachineSupport support = services.getVirtualMachineSupport();
if( support != null ) {
tm.out("Basic Analytics", support.getCapabilities().isBasicAnalyticsSupported());
tm.out("Extended Analytics", support.getCapabilities().isExtendedAnalyticsSupported());
}
else {
tm.ok("No virtual machine support in this cloud");
}
}
else {
tm.ok("No compute services in this cloud");
}
}
@Test
public void getConsoleOutput() throws CloudException, InternalException {
assumeTrue(!tm.isTestSkipped());
ComputeServices services = tm.getProvider().getComputeServices();
if( services != null ) {
VirtualMachineSupport support = services.getVirtualMachineSupport();
if( support != null ) {
if( testVMId != null ) {
String output = support.getConsoleOutput(testVMId);
tm.out("Console", output);
assertNotNull("Console output may be empty, but it cannot be null", output);
}
else if( support.isSubscribed() ) {
fail("No test virtual machine exists and thus no test could be run for "+name.getMethodName());
}
}
else {
tm.ok("No virtual machine support in this cloud");
}
}
else {
tm.ok("No compute services in this cloud");
}
}
@Test
public void getStatisticsForLastHour() throws CloudException, InternalException {
assumeTrue(!tm.isTestSkipped());
ComputeServices services = tm.getProvider().getComputeServices();
if( services != null ) {
VirtualMachineSupport support = services.getVirtualMachineSupport();
if( support != null ) {
if( testVMId != null ) {
VmStatistics stats = support.getVMStatistics(testVMId, System.currentTimeMillis() - CalendarWrapper.HOUR, System.currentTimeMillis());
tm.out("Statistics", stats);
assertNotNull("Statistics object may be empty, but it cannot be null", stats);
tm.out("Sample Count", stats.getSamples());
tm.out("Sample Start", new Date(stats.getStartTimestamp()));
tm.out("Sample End", new Date(stats.getEndTimestamp()));
tm.out("Min CPU", stats.getMinimumCpuUtilization());
tm.out("Max CPU", stats.getMaximumCpuUtilization());
tm.out("Avg CPU", stats.getAverageCpuUtilization());
tm.out("Min Disk Read Bytes", stats.getMinimumDiskReadBytes());
tm.out("Max Disk Read Bytes", stats.getMaximumDiskReadBytes());
tm.out("Avg Disk Read Bytes", stats.getAverageDiskReadBytes());
tm.out("Min Disk Read Ops", stats.getMinimumDiskReadOperations());
tm.out("Max Disk Read Ops", stats.getMaximumDiskReadOperations());
tm.out("Avg Disk Read Ops", stats.getAverageDiskReadOperations());
tm.out("Min Disk Write Bytes", stats.getMinimumDiskWriteBytes());
tm.out("Max Disk Write Bytes", stats.getMaximumDiskWriteBytes());
tm.out("Avg Disk Write Bytes", stats.getAverageDiskWriteBytes());
tm.out("Min Disk Write Ops", stats.getMinimumDiskWriteOperations());
tm.out("Max Disk Write Ops", stats.getMaximumDiskWriteOperations());
tm.out("Avg Disk Write Ops", stats.getAverageDiskWriteOperations());
tm.out("Min Network In", stats.getMinimumNetworkIn());
tm.out("Max Network In", stats.getMaximumNetworkIn());
tm.out("Avg Network In", stats.getAverageNetworkIn());
tm.out("Min Network Out", stats.getMinimumNetworkOut());
tm.out("Max Network Out", stats.getMaximumNetworkOut());
tm.out("Avg Network Out", stats.getAverageNetworkOut());
if( stats.getSamples() > 0 ) {
assertTrue("Sample start must be an hour ago", stats.getStartTimestamp() >= ( System.currentTimeMillis() - ( CalendarWrapper.MINUTE + CalendarWrapper.HOUR ) ));
assertTrue("Sample end must be greater than the sample start", stats.getEndTimestamp() >= stats.getStartTimestamp());
}
}
else if( support.isSubscribed() ) {
fail("No test virtual machine exists and thus no test could be run for "+name.getMethodName());
}
}
else {
tm.ok("No virtual machine support in this cloud");
}
}
else {
tm.ok("No compute services in this cloud");
}
}
@Test
public void getSamplesForLastHour() throws CloudException, InternalException {
assumeTrue(!tm.isTestSkipped());
ComputeServices services = tm.getProvider().getComputeServices();
if( services != null ) {
VirtualMachineSupport support = services.getVirtualMachineSupport();
if( support != null ) {
if( testVMId != null ) {
Iterable<VmStatistics> samples = support.getVMStatisticsForPeriod(testVMId, System.currentTimeMillis() - CalendarWrapper.HOUR, System.currentTimeMillis());
//noinspection ConstantConditions
tm.out("Has Samples", samples != null);
assertNotNull("Samples may be empty, but they may not be null", samples);
VmStatistics lastSample = null;
for( VmStatistics sample : samples ) {
tm.out(( new Date(sample.getStartTimestamp()) ).toString(), sample);
if( lastSample != null ) {
assertTrue("Samples must be ordered from oldest to newest", lastSample.getStartTimestamp() < sample.getStartTimestamp());
}
lastSample = sample;
}
}
else if( support.isSubscribed() ) {
fail("No test virtual machine exists and thus no test could be run for "+name.getMethodName());
}
}
else {
tm.ok("No virtual machine support in this cloud");
}
}
else {
tm.ok("No compute services in this cloud");
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.database.connection;
import com.google.firebase.database.connection.util.StringListReader;
import com.google.firebase.database.logging.LogWrapper;
import com.google.firebase.database.tubesock.WebSocket;
import com.google.firebase.database.tubesock.WebSocketEventHandler;
import com.google.firebase.database.tubesock.WebSocketException;
import com.google.firebase.database.tubesock.WebSocketMessage;
import com.google.firebase.database.util.JsonMapper;
import java.io.EOFException;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
class WebsocketConnection {
private static long connectionId = 0;
private static final long KEEP_ALIVE_TIMEOUT_MS = 45 * 1000; // 45 seconds
private static final long CONNECT_TIMEOUT_MS = 30 * 1000; // 30 seconds
private static final int MAX_FRAME_SIZE = 16384;
public interface Delegate {
public void onMessage(Map<String, Object> message);
public void onDisconnect(boolean wasEverConnected);
}
private interface WSClient {
public void connect();
public void close();
public void send(String msg);
}
private class WSClientTubesock implements WSClient, WebSocketEventHandler {
private WebSocket ws;
private WSClientTubesock(WebSocket ws) {
this.ws = ws;
this.ws.setEventHandler(this);
}
@Override
public void onOpen() {
executorService.execute(
new Runnable() {
@Override
public void run() {
connectTimeout.cancel(false);
everConnected = true;
if (logger.logsDebug()) logger.debug("websocket opened");
resetKeepAlive();
}
});
}
@Override
public void onMessage(WebSocketMessage msg) {
final String str = msg.getText();
if (logger.logsDebug()) logger.debug("ws message: " + str);
executorService.execute(
new Runnable() {
@Override
public void run() {
handleIncomingFrame(str);
}
});
}
@Override
public void onClose() {
final String logMessage = "closed";
executorService.execute(
new Runnable() {
@Override
public void run() {
if (logger.logsDebug()) logger.debug(logMessage);
onClosed();
}
});
}
@Override
public void onError(final WebSocketException e) {
executorService.execute(
new Runnable() {
@Override
public void run() {
if (e.getCause() != null && e.getCause() instanceof EOFException) {
logger.debug("WebSocket reached EOF.");
} else {
logger.debug("WebSocket error.", e);
}
onClosed();
}
});
}
@Override
public void onLogMessage(String msg) {
if (logger.logsDebug()) logger.debug("Tubesock: " + msg);
}
@Override
public void send(String msg) {
ws.send(msg);
}
@Override
public void close() {
ws.close();
}
private void shutdown() {
ws.close();
try {
ws.blockClose();
} catch (InterruptedException e) {
logger.error("Interrupted while shutting down websocket threads", e);
}
}
@Override
public void connect() {
try {
ws.connect();
} catch (WebSocketException e) {
if (logger.logsDebug()) logger.debug("Error connecting", e);
shutdown();
}
}
}
private WSClient conn;
private boolean everConnected = false;
private boolean isClosed = false;
private long totalFrames = 0;
private StringListReader frameReader;
private Delegate delegate;
private ScheduledFuture<?> keepAlive;
private ScheduledFuture<?> connectTimeout;
private final ConnectionContext connectionContext;
private final ScheduledExecutorService executorService;
private final LogWrapper logger;
public WebsocketConnection(
ConnectionContext connectionContext,
HostInfo hostInfo,
String optCachedHost,
String appCheckToken,
Delegate delegate,
String optLastSessionId) {
this.connectionContext = connectionContext;
this.executorService = connectionContext.getExecutorService();
this.delegate = delegate;
long connId = connectionId++;
logger = new LogWrapper(connectionContext.getLogger(), "WebSocket", "ws_" + connId);
conn = createConnection(hostInfo, optCachedHost, appCheckToken, optLastSessionId);
}
private WSClient createConnection(
HostInfo hostInfo, String optCachedHost, String appCheckToken, String optLastSessionId) {
String host = (optCachedHost != null) ? optCachedHost : hostInfo.getHost();
URI uri =
HostInfo.getConnectionUrl(
host, hostInfo.isSecure(), hostInfo.getNamespace(), optLastSessionId);
Map<String, String> extraHeaders = new HashMap<String, String>();
extraHeaders.put("User-Agent", connectionContext.getUserAgent());
extraHeaders.put("X-Firebase-GMPID", connectionContext.getApplicationId());
extraHeaders.put("X-Firebase-AppCheck", appCheckToken);
WebSocket ws = new WebSocket(connectionContext, uri, /*protocol=*/ null, extraHeaders);
WSClientTubesock client = new WSClientTubesock(ws);
return client;
}
public void open() {
conn.connect();
connectTimeout =
executorService.schedule(
new Runnable() {
@Override
public void run() {
closeIfNeverConnected();
}
},
CONNECT_TIMEOUT_MS,
TimeUnit.MILLISECONDS);
}
public void start() {
// No-op in java
}
public void close() {
if (logger.logsDebug()) logger.debug("websocket is being closed");
isClosed = true;
// Although true is passed for both of these, they each run on the same event loop, so they will
// never be
// running.
conn.close();
if (connectTimeout != null) {
connectTimeout.cancel(true);
}
if (keepAlive != null) {
keepAlive.cancel(true);
}
}
public void send(Map<String, Object> message) {
resetKeepAlive();
try {
String toSend = JsonMapper.serializeJson(message);
String[] segs = splitIntoFrames(toSend, MAX_FRAME_SIZE);
if (segs.length > 1) {
conn.send("" + segs.length);
}
for (int i = 0; i < segs.length; ++i) {
conn.send(segs[i]);
}
} catch (IOException e) {
logger.error("Failed to serialize message: " + message.toString(), e);
shutdown();
}
}
private void appendFrame(String message) {
frameReader.addString(message);
totalFrames -= 1;
if (totalFrames == 0) {
// Decode JSON
try {
frameReader.freeze();
Map<String, Object> decoded = JsonMapper.parseJson(frameReader.toString());
frameReader = null;
if (logger.logsDebug()) logger.debug("handleIncomingFrame complete frame: " + decoded);
delegate.onMessage(decoded);
} catch (IOException e) {
logger.error("Error parsing frame: " + frameReader.toString(), e);
close();
shutdown();
} catch (ClassCastException e) {
logger.error("Error parsing frame (cast error): " + frameReader.toString(), e);
close();
shutdown();
}
}
}
private void handleNewFrameCount(int numFrames) {
totalFrames = numFrames;
frameReader = new StringListReader();
if (logger.logsDebug()) logger.debug("HandleNewFrameCount: " + totalFrames);
}
private String extractFrameCount(String message) {
// TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that
// isn't being enforced
// currently. So allowing larger frame counts (length <= 6). See
// https://app.asana.com/0/search/8688598998380/8237608042508
if (message.length() <= 6) {
try {
int frameCount = Integer.parseInt(message);
if (frameCount > 0) {
handleNewFrameCount(frameCount);
}
return null;
} catch (NumberFormatException e) {
// not a number, default to framecount 1
}
}
handleNewFrameCount(1);
return message;
}
private void handleIncomingFrame(String message) {
if (!isClosed) {
resetKeepAlive();
if (isBuffering()) {
appendFrame(message);
} else {
String remaining = extractFrameCount(message);
if (remaining != null) {
appendFrame(remaining);
}
}
}
}
private void resetKeepAlive() {
if (!isClosed) {
if (keepAlive != null) {
keepAlive.cancel(false);
if (logger.logsDebug())
logger.debug("Reset keepAlive. Remaining: " + keepAlive.getDelay(TimeUnit.MILLISECONDS));
} else {
if (logger.logsDebug()) logger.debug("Reset keepAlive");
}
keepAlive = executorService.schedule(nop(), KEEP_ALIVE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
}
}
private Runnable nop() {
return new Runnable() {
@Override
public void run() {
if (conn != null) {
conn.send("0");
resetKeepAlive();
}
}
};
}
private boolean isBuffering() {
return frameReader != null;
}
// Close methods
private void onClosed() {
if (!isClosed) {
if (logger.logsDebug()) logger.debug("closing itself");
shutdown();
}
conn = null;
if (keepAlive != null) {
keepAlive.cancel(false);
}
}
private void shutdown() {
isClosed = true;
delegate.onDisconnect(everConnected);
}
private void closeIfNeverConnected() {
if (!everConnected && !isClosed) {
if (logger.logsDebug()) logger.debug("timed out on connect");
conn.close();
}
}
private static String[] splitIntoFrames(String src, int maxFrameSize) {
if (src.length() <= maxFrameSize) {
return new String[] {src};
} else {
ArrayList<String> segs = new ArrayList<String>();
for (int i = 0; i < src.length(); i += maxFrameSize) {
int end = Math.min(i + maxFrameSize, src.length());
String seg = src.substring(i, end);
segs.add(seg);
}
return segs.toArray(new String[segs.size()]);
}
}
}
| |
/*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.server;
import java.io.Serializable;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.vaadin.shared.VBrowserDetails;
/**
* Class that provides information about the web browser the user is using.
* Provides information such as browser name and version, screen resolution and
* IP address.
*
* @author Vaadin Ltd.
*/
public class WebBrowser implements Serializable {
private int screenHeight = -1;
private int screenWidth = -1;
private String browserApplication = null;
private Locale locale;
private String address;
private boolean secureConnection;
private int timezoneOffset = 0;
private int rawTimezoneOffset = 0;
private int dstSavings;
private boolean dstInEffect;
private boolean touchDevice;
private VBrowserDetails browserDetails;
private long clientServerTimeDelta;
/**
* Gets the height of the screen in pixels. This is the full screen
* resolution and not the height available for the application.
*
* @return the height of the screen in pixels.
*/
public int getScreenHeight() {
return screenHeight;
}
/**
* Gets the width of the screen in pixels. This is the full screen
* resolution and not the width available for the application.
*
* @return the width of the screen in pixels.
*/
public int getScreenWidth() {
return screenWidth;
}
/**
* Get the browser user-agent string.
*
* @return The raw browser userAgent string
*/
public String getBrowserApplication() {
return browserApplication;
}
/**
* Gets the IP-address of the web browser. If the application is running
* inside a portlet, this method will return null.
*
* @return IP-address in 1.12.123.123 -format
*/
public String getAddress() {
return address;
}
/** Get the default locate of the browser. */
public Locale getLocale() {
return locale;
}
/** Is the connection made using HTTPS? */
public boolean isSecureConnection() {
return secureConnection;
}
/**
* Tests whether the user is using Firefox.
*
* @return true if the user is using Firefox, false if the user is not using
* Firefox or if no information on the browser is present
*/
public boolean isFirefox() {
if (browserDetails == null) {
return false;
}
return browserDetails.isFirefox();
}
/**
* Tests whether the user is using Internet Explorer.
*
* @return true if the user is using Internet Explorer, false if the user is
* not using Internet Explorer or if no information on the browser
* is present
*/
public boolean isIE() {
if (browserDetails == null) {
return false;
}
return browserDetails.isIE();
}
/**
* Tests whether the user is using Edge.
*
* @return true if the user is using Edge, false if the user is not using
* Edge or if no information on the browser is present
*/
public boolean isEdge() {
if (browserDetails == null) {
return false;
}
return browserDetails.isEdge();
}
/**
* Tests whether the user is using Safari.
*
* @return true if the user is using Safari, false if the user is not using
* Safari or if no information on the browser is present
*/
public boolean isSafari() {
if (browserDetails == null) {
return false;
}
return browserDetails.isSafari();
}
/**
* Tests whether the user is using Opera.
*
* @return true if the user is using Opera, false if the user is not using
* Opera or if no information on the browser is present
*/
public boolean isOpera() {
if (browserDetails == null) {
return false;
}
return browserDetails.isOpera();
}
/**
* Tests whether the user is using Chrome.
*
* @return true if the user is using Chrome, false if the user is not using
* Chrome or if no information on the browser is present
*/
public boolean isChrome() {
if (browserDetails == null) {
return false;
}
return browserDetails.isChrome();
}
/**
* Tests whether the user is using Chrome Frame.
*
* @return true if the user is using Chrome Frame, false if the user is not
* using Chrome or if no information on the browser is present
*/
public boolean isChromeFrame() {
if (browserDetails == null) {
return false;
}
return browserDetails.isChromeFrame();
}
/**
* Tests whether the user's browser is Chrome Frame capable.
*
* @return true if the user can use Chrome Frame, false if the user can not
* or if no information on the browser is present
*/
public boolean isChromeFrameCapable() {
if (browserDetails == null) {
return false;
}
return browserDetails.isChromeFrameCapable();
}
/**
* Gets the major version of the browser the user is using.
*
* <p>
* Note that Internet Explorer in IE7 compatibility mode might return 8 in
* some cases even though it should return 7.
* </p>
*
* @return The major version of the browser or -1 if not known.
*/
public int getBrowserMajorVersion() {
if (browserDetails == null) {
return -1;
}
return browserDetails.getBrowserMajorVersion();
}
/**
* Gets the minor version of the browser the user is using.
*
* @see #getBrowserMajorVersion()
*
* @return The minor version of the browser or -1 if not known.
*/
public int getBrowserMinorVersion() {
if (browserDetails == null) {
return -1;
}
return browserDetails.getBrowserMinorVersion();
}
/**
* Tests whether the user is using Linux.
*
* @return true if the user is using Linux, false if the user is not using
* Linux or if no information on the browser is present
*/
public boolean isLinux() {
return browserDetails.isLinux();
}
/**
* Tests whether the user is using Mac OS X.
*
* @return true if the user is using Mac OS X, false if the user is not
* using Mac OS X or if no information on the browser is present
*/
public boolean isMacOSX() {
return browserDetails.isMacOSX();
}
/**
* Tests whether the user is using Windows.
*
* @return true if the user is using Windows, false if the user is not using
* Windows or if no information on the browser is present
*/
public boolean isWindows() {
return browserDetails.isWindows();
}
/**
* Tests whether the user is using Windows Phone.
*
* @return true if the user is using Windows Phone, false if the user is not
* using Windows Phone or if no information on the browser is
* present
* @since 7.3.2
*/
public boolean isWindowsPhone() {
return browserDetails.isWindowsPhone();
}
/**
* Tests if the browser is run on Android.
*
* @return true if run on Android false if the user is not using Android or
* if no information on the browser is present
*/
public boolean isAndroid() {
return browserDetails.isAndroid();
}
/**
* Tests if the browser is run in iOS.
*
* @return true if run in iOS false if the user is not using iOS or if no
* information on the browser is present
*/
public boolean isIOS() {
return browserDetails.isIOS();
}
/**
* Tests if the browser is run on IPhone.
*
* @return true if run on IPhone false if the user is not using IPhone or if
* no information on the browser is present
* @since 7.3.3
*/
public boolean isIPhone() {
return browserDetails.isIPhone();
}
/**
* Tests if the browser is run on IPad.
*
* @return true if run on IPad false if the user is not using IPad or if no
* information on the browser is present
* @since 7.3.3
*/
public boolean isIPad() {
return browserDetails.isIPad();
}
/**
* Returns the browser-reported TimeZone offset in milliseconds from GMT.
* This includes possible daylight saving adjustments, to figure out which
* TimeZone the user actually might be in, see
* {@link #getRawTimezoneOffset()}.
*
* @see WebBrowser#getRawTimezoneOffset()
* @return timezone offset in milliseconds, 0 if not available
*/
public int getTimezoneOffset() {
return timezoneOffset;
}
/**
* Returns the browser-reported TimeZone offset in milliseconds from GMT
* ignoring possible daylight saving adjustments that may be in effect in
* the browser.
* <p>
* You can use this to figure out which TimeZones the user could actually be
* in by calling {@link TimeZone#getAvailableIDs(int)}.
* </p>
* <p>
* If {@link #getRawTimezoneOffset()} and {@link #getTimezoneOffset()}
* returns the same value, the browser is either in a zone that does not
* currently have daylight saving time, or in a zone that never has daylight
* saving time.
* </p>
*
* @return timezone offset in milliseconds excluding DST, 0 if not available
*/
public int getRawTimezoneOffset() {
return rawTimezoneOffset;
}
/**
* Returns the offset in milliseconds between the browser's GMT TimeZone and
* DST.
*
* @return the number of milliseconds that the TimeZone shifts when DST is
* in effect
*/
public int getDSTSavings() {
return dstSavings;
}
/**
* Returns whether daylight saving time (DST) is currently in effect in the
* region of the browser or not.
*
* @return true if the browser resides at a location that currently is in
* DST
*/
public boolean isDSTInEffect() {
return dstInEffect;
}
/**
* Returns the current date and time of the browser. This will not be
* entirely accurate due to varying network latencies, but should provide a
* close-enough value for most cases. Also note that the returned Date
* object uses servers default time zone, not the clients.
* <p>
* To get the actual date and time shown in the end users computer, you can
* do something like:
*
* <pre>
* WebBrowser browser = ...;
* SimpleTimeZone timeZone = new SimpleTimeZone(browser.getTimezoneOffset(), "Fake client time zone");
* DateFormat format = DateFormat.getDateTimeInstance();
* format.setTimeZone(timeZone);
* myLabel.setValue(format.format(browser.getCurrentDate()));
* </pre>
*
* @return the current date and time of the browser.
* @see #isDSTInEffect()
* @see #getDSTSavings()
* @see #getTimezoneOffset()
*/
public Date getCurrentDate() {
return new Date(new Date().getTime() + clientServerTimeDelta);
}
/**
* @return true if the browser is detected to support touch events
*/
public boolean isTouchDevice() {
return touchDevice;
}
/**
* For internal use by VaadinServlet/VaadinPortlet only. Updates all
* properties in the class according to the given information.
*
* @param sw
* Screen width
* @param sh
* Screen height
* @param tzo
* TimeZone offset in minutes from GMT
* @param rtzo
* raw TimeZone offset in minutes from GMT (w/o DST adjustment)
* @param dstSavings
* the difference between the raw TimeZone and DST in minutes
* @param dstInEffect
* is DST currently active in the region or not?
* @param curDate
* the current date in milliseconds since the epoch
* @param touchDevice
*/
void updateClientSideDetails(String sw, String sh, String tzo, String rtzo,
String dstSavings, String dstInEffect, String curDate,
boolean touchDevice) {
if (sw != null) {
try {
screenHeight = Integer.parseInt(sh);
screenWidth = Integer.parseInt(sw);
} catch (final NumberFormatException e) {
screenHeight = screenWidth = -1;
}
}
if (tzo != null) {
try {
// browser->java conversion: min->ms, reverse sign
timezoneOffset = -Integer.parseInt(tzo) * 60 * 1000;
} catch (final NumberFormatException e) {
timezoneOffset = 0; // default gmt+0
}
}
if (rtzo != null) {
try {
// browser->java conversion: min->ms, reverse sign
rawTimezoneOffset = -Integer.parseInt(rtzo) * 60 * 1000;
} catch (final NumberFormatException e) {
rawTimezoneOffset = 0; // default gmt+0
}
}
if (dstSavings != null) {
try {
// browser->java conversion: min->ms
this.dstSavings = Integer.parseInt(dstSavings) * 60 * 1000;
} catch (final NumberFormatException e) {
this.dstSavings = 0; // default no savings
}
}
if (dstInEffect != null) {
this.dstInEffect = Boolean.parseBoolean(dstInEffect);
}
if (curDate != null) {
try {
long curTime = Long.parseLong(curDate);
clientServerTimeDelta = curTime - new Date().getTime();
} catch (final NumberFormatException e) {
clientServerTimeDelta = 0;
}
}
this.touchDevice = touchDevice;
}
/**
* For internal use by VaadinServlet/VaadinPortlet only. Updates all
* properties in the class according to the given information.
*
* @param request
* the Vaadin request to read the information from
*/
public void updateRequestDetails(VaadinRequest request) {
locale = request.getLocale();
address = request.getRemoteAddr();
secureConnection = request.isSecure();
String agent = request.getHeader("user-agent");
if (agent != null) {
browserApplication = agent;
browserDetails = new VBrowserDetails(agent);
}
if (request.getParameter("v-sw") != null) {
updateClientSideDetails(request.getParameter("v-sw"),
request.getParameter("v-sh"),
request.getParameter("v-tzo"),
request.getParameter("v-rtzo"),
request.getParameter("v-dstd"),
request.getParameter("v-dston"),
request.getParameter("v-curdate"),
request.getParameter("v-td") != null);
}
}
/**
* Checks if the browser is so old that it simply won't work with a Vaadin
* application. Can be used to redirect to an alternative page, show
* alternative content or similar.
*
* When this method returns true chances are very high that the browser
* won't work and it does not make sense to direct the user to the Vaadin
* application.
*
* @return true if the browser won't work, false if not the browser is
* supported or might work
*/
public boolean isTooOldToFunctionProperly() {
if (browserDetails == null) {
// Don't know, so assume it will work
return false;
}
return browserDetails.isTooOldToFunctionProperly();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.util;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Streaming XML output.
*
* <p>Use this class to write XML to any streaming source.
* While the class itself is unstructured and doesn't enforce any DTD
* specification, use of the class
* does ensure that the output is syntactically valid XML.</p>
*/
public class XmlOutput {
// This Writer is the underlying output stream to which all XML is
// written.
private final PrintWriter out;
// The tagStack is maintained to check that tags are balanced.
private final List<String> tagStack = new ArrayList<String>();
// The class maintains an indentation level to improve output quality.
private int indent;
// The class also maintains the total number of tags written. This
// is used to monitor changes to the output
private int tagsWritten;
// This flag is set to true if the output should be compacted.
// Compacted output is free of extraneous whitespace and is designed
// for easier transport.
private boolean compact;
/** @see #setIndentString */
private String indentString = "\t";
/** @see #setGlob */
private boolean glob;
/**
* Whether we have started but not finished a start tag. This only happens
* if <code>glob</code> is true. The start tag is automatically closed
* when we start a child node. If there are no child nodes, {@link #endTag}
* creates an empty tag.
*/
private boolean inTag;
/** @see #setAlwaysQuoteCData */
private boolean alwaysQuoteCData;
/** @see #setIgnorePcdata */
private boolean ignorePcdata;
/**
* Private helper function to display a degree of indentation
* @param out the PrintWriter to which to display output.
* @param indent the degree of indentation.
*/
private void displayIndent(PrintWriter out, int indent) {
if (!compact) {
for (int i = 0; i < indent; i++) {
out.print(indentString);
}
}
}
/**
* Constructs a new XmlOutput based on any {@link Writer}.
*
* @param out the writer to which this XmlOutput generates results.
*/
public XmlOutput(Writer out) {
this(new PrintWriter(out, true));
}
/**
* Constructs a new XmlOutput based on a {@link PrintWriter}.
*
* @param out the writer to which this XmlOutput generates results.
*/
public XmlOutput(PrintWriter out) {
this.out = out;
indent = 0;
tagsWritten = 0;
}
/**
* Sets or unsets the compact mode. Compact mode causes the generated
* XML to be free of extraneous whitespace and other unnecessary
* characters.
*
* @param compact true to turn on compact mode, or false to turn it off.
*/
public void setCompact(boolean compact) {
this.compact = compact;
}
public boolean getCompact() {
return compact;
}
/**
* Sets the string to print for each level of indentation. The default is a
* tab. The value must not be <code>null</code>. Set this to the empty
* string to achieve no indentation (note that
* <code>{@link #setCompact}(true)</code> removes indentation <em>and</em>
* newlines).
*/
public void setIndentString(String indentString) {
this.indentString = indentString;
}
/**
* Sets whether to detect that tags are empty.
*/
public void setGlob(boolean glob) {
this.glob = glob;
}
/**
* Sets whether to always quote cdata segments (even if they don't contain
* special characters).
*/
public void setAlwaysQuoteCData(boolean alwaysQuoteCData) {
this.alwaysQuoteCData = alwaysQuoteCData;
}
/**
* Sets whether to ignore unquoted text, such as whitespace.
*/
public void setIgnorePcdata(boolean ignorePcdata) {
this.ignorePcdata = ignorePcdata;
}
public boolean getIgnorePcdata() {
return ignorePcdata;
}
/**
* Sends a string directly to the output stream, without escaping any
* characters. Use with caution!
*/
public void print(String s) {
out.print(s);
}
/**
* Starts writing a new tag to the stream. The tag's name must be given and
* its attributes should be specified by a fully constructed AttrVector
* object.
*
* @param tagName the name of the tag to write.
* @param attributes an XMLAttrVector containing the attributes to include
* in the tag.
*/
public void beginTag(String tagName, XMLAttrVector attributes) {
beginBeginTag(tagName);
if (attributes != null) {
attributes.display(out, indent);
}
endBeginTag(tagName);
}
public void beginBeginTag(String tagName) {
if (inTag) {
// complete the parent's start tag
if (compact) {
out.print(">");
} else {
out.println(">");
}
inTag = false;
}
displayIndent(out, indent);
out.print("<");
out.print(tagName);
}
public void endBeginTag(String tagName) {
if (glob) {
inTag = true;
} else if (compact) {
out.print(">");
} else {
out.println(">");
}
out.flush();
Stacks.push(tagStack, tagName);
indent++;
tagsWritten++;
}
/**
* Writes an attribute.
*/
public void attribute(String name, String value) {
printAtt(out, name, value);
}
/**
* If we are currently inside the start tag, finishes it off.
*/
public void beginNode() {
if (inTag) {
// complete the parent's start tag
if (compact) {
out.print(">");
} else {
out.println(">");
}
inTag = false;
}
}
/**
* Completes a tag. This outputs the end tag corresponding to the
* last exposed beginTag. The tag name must match the name of the
* corresponding beginTag.
* @param tagName the name of the end tag to write.
*/
public void endTag(String tagName) {
// Check that the end tag matches the corresponding start tag
Stacks.pop(tagStack, tagName);
// Lower the indent and display the end tag
indent--;
if (inTag) {
// we're still in the start tag -- this element had no children
if (compact) {
out.print("/>");
} else {
out.println("/>");
}
inTag = false;
} else {
displayIndent(out, indent);
out.print("</");
out.print(tagName);
if (compact) {
out.print(">");
} else {
out.println(">");
}
}
out.flush();
}
/**
* Writes an empty tag to the stream. An empty tag is one with no
* tags inside it, although it may still have attributes.
*
* @param tagName the name of the empty tag.
* @param attributes an XMLAttrVector containing the attributes to
* include in the tag.
*/
public void emptyTag(String tagName, XMLAttrVector attributes) {
if (inTag) {
// complete the parent's start tag
if (compact) {
out.print(">");
} else {
out.println(">");
}
inTag = false;
}
displayIndent(out, indent);
out.print("<");
out.print(tagName);
if (attributes != null) {
out.print(" ");
attributes.display(out, indent);
}
if (compact) {
out.print("/>");
} else {
out.println("/>");
}
out.flush();
tagsWritten++;
}
/**
* Writes a CDATA section. Such sections always appear on their own line.
* The nature in which the CDATA section is written depends on the actual
* string content with respect to these special characters/sequences:
* <ul>
* <li><code>&</code>
* <li><code>"</code>
* <li><code>'</code>
* <li><code><</code>
* <li><code>></code>
* </ul>
* Additionally, the sequence <code>]]></code> is special.
* <ul>
* <li>Content containing no special characters will be left as-is.
* <li>Content containing one or more special characters but not the
* sequence <code>]]></code> will be enclosed in a CDATA section.
* <li>Content containing special characters AND at least one
* <code>]]></code> sequence will be left as-is but have all of its
* special characters encoded as entities.
* </ul>
* These special treatment rules are required to allow cdata sections
* to contain XML strings which may themselves contain cdata sections.
* Traditional CDATA sections <b>do not nest</b>.
*/
public void cdata(String data) {
cdata(data, false);
}
/**
* Writes a CDATA section (as {@link #cdata(String)}).
*
* @param data string to write
* @param quote if true, quote in a <code><![CDATA[</code>
* ... <code>]]></code> regardless of the content of
* <code>data</code>; if false, quote only if the content needs it
*/
public void cdata(String data, boolean quote) {
if (inTag) {
// complete the parent's start tag
if (compact) {
out.print(">");
} else {
out.println(">");
}
inTag = false;
}
if (data == null) {
data = "";
}
boolean specials = false;
boolean cdataEnd = false;
// Scan the string for special characters
// If special characters are found, scan the string for ']]>'
if (stringHasXMLSpecials(data)) {
specials = true;
if (data.contains("]]>")) {
cdataEnd = true;
}
}
// Display the result
displayIndent(out, indent);
if (quote || alwaysQuoteCData) {
out.print("<![CDATA[");
out.print(data);
out.println("]]>");
} else if (!specials) {
out.print(data);
} else {
stringEncodeXML(data, out);
}
out.flush();
tagsWritten++;
}
/**
* Writes a String tag; a tag containing nothing but a CDATA section.
*/
public void stringTag(String name, String data) {
beginTag(name, null);
cdata(data);
endTag(name);
}
/**
* Writes content.
*/
public void content(String content) {
if (content != null) {
indent++;
LineNumberReader
in = new LineNumberReader(new StringReader(content));
try {
String line;
while ((line = in.readLine()) != null) {
displayIndent(out, indent);
out.println(line);
}
} catch (IOException ex) {
throw new AssertionError(ex);
}
indent--;
out.flush();
}
tagsWritten++;
}
/**
* Write header. Use default version 1.0.
*/
public void header() {
out.println("<?xml version=\"1.0\" ?>");
out.flush();
tagsWritten++;
}
/**
* Write header, take version as input.
*/
public void header(String version) {
out.print("<?xml version=\"");
out.print(version);
out.println("\" ?>");
out.flush();
tagsWritten++;
}
/**
* Get the total number of tags written
* @return the total number of tags written to the XML stream.
*/
public int numTagsWritten() {
return tagsWritten;
}
/** Print an XML attribute name and value for string val */
private static void printAtt(PrintWriter pw, String name, String val) {
if (val != null /* && !val.equals("") */) {
pw.print(" ");
pw.print(name);
pw.print("=\"");
pw.print(escapeForQuoting(val));
pw.print("\"");
}
}
/**
* Encode a String for XML output, displaying it to a PrintWriter.
* The String to be encoded is displayed, except that
* special characters are converted into entities.
* @param input a String to convert.
* @param out a PrintWriter to which to write the results.
*/
private static void stringEncodeXML(String input, PrintWriter out) {
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
switch (c) {
case '<':
case '>':
case '"':
case '\'':
case '&':
case '\t':
case '\n':
case '\r':
out.print("&#" + (int) c + ";");
break;
default:
out.print(c);
}
}
}
private static String escapeForQuoting(String val) {
return StringEscaper.XML_NUMERIC_ESCAPER.escapeString(val);
}
/**
* Returns whether a string contains any XML special characters.
*
* <p>If this function returns true, the string will need to be
* encoded either using the stringEncodeXML function above or using a
* CDATA section. Note that MSXML has a nasty bug whereby whitespace
* characters outside of a CDATA section are lost when parsing. To
* avoid hitting this bug, this method treats many whitespace characters
* as "special".</p>
*
* @param input the String to scan for XML special characters.
* @return true if the String contains any such characters.
*/
private static boolean stringHasXMLSpecials(String input) {
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
switch (c) {
case '<':
case '>':
case '"':
case '\'':
case '&':
case '\t':
case '\n':
case '\r':
return true;
}
}
return false;
}
/**
* Utility for replacing special characters
* with escape sequences in strings.
*
* <p>A StringEscaper starts out as an identity transform in the "mutable"
* state. Call {@link #defineEscape} as many times as necessary to set up
* mappings, and then call {@link #makeImmutable} before
* actually applying the defined transform. Or,
* use one of the global mappings pre-defined here.</p>
*/
static class StringEscaper implements Cloneable {
private ArrayList<String> translationVector;
private String [] translationTable;
public static final StringEscaper XML_ESCAPER;
public static final StringEscaper XML_NUMERIC_ESCAPER;
public static final StringEscaper HTML_ESCAPER;
public static final StringEscaper URL_ARG_ESCAPER;
public static final StringEscaper URL_ESCAPER;
/**
* Identity transform
*/
public StringEscaper() {
translationVector = new ArrayList<String>();
}
/**
* Map character "from" to escape sequence "to"
*/
public void defineEscape(char from, String to) {
int i = (int) from;
if (i >= translationVector.size()) {
// Extend list by adding the requisite number of nulls.
final int count = i + 1 - translationVector.size();
translationVector.addAll(Collections.<String>nCopies(count, null));
}
translationVector.set(i, to);
}
/**
* Call this before attempting to escape strings; after this,
* defineEscape may not be called again.
*/
public void makeImmutable() {
translationTable =
translationVector.toArray(new String[translationVector.size()]);
translationVector = null;
}
/**
* Apply an immutable transformation to the given string.
*/
public String escapeString(String s) {
StringBuilder sb = null;
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
String escape;
// codes >= 128 (e.g. Euro sign) are always escaped
if (c > 127) {
escape = "&#" + Integer.toString(c) + ";";
} else if (c >= translationTable.length) {
escape = null;
} else {
escape = translationTable[c];
}
if (escape == null) {
if (sb != null) {
sb.append(c);
}
} else {
if (sb == null) {
sb = new StringBuilder(n * 2);
sb.append(s.substring(0, i));
}
sb.append(escape);
}
}
if (sb == null) {
return s;
} else {
return sb.toString();
}
}
protected StringEscaper clone() {
StringEscaper clone = new StringEscaper();
if (translationVector != null) {
clone.translationVector = new ArrayList<String>(translationVector);
}
if (translationTable != null) {
clone.translationTable = translationTable.clone();
}
return clone;
}
/**
* Create a mutable escaper from an existing escaper, which may
* already be immutable.
*/
public StringEscaper getMutableClone() {
StringEscaper clone = clone();
if (clone.translationVector == null) {
clone.translationVector = Lists.newArrayList(clone.translationTable);
clone.translationTable = null;
}
return clone;
}
static {
HTML_ESCAPER = new StringEscaper();
HTML_ESCAPER.defineEscape('&', "&");
HTML_ESCAPER.defineEscape('"', """);
// htmlEscaper.defineEscape('\'',"'");
HTML_ESCAPER.defineEscape('\'', "'");
HTML_ESCAPER.defineEscape('<', "<");
HTML_ESCAPER.defineEscape('>', ">");
XML_NUMERIC_ESCAPER = new StringEscaper();
XML_NUMERIC_ESCAPER.defineEscape('&', "&");
XML_NUMERIC_ESCAPER.defineEscape('"', """);
XML_NUMERIC_ESCAPER.defineEscape('\'', "'");
XML_NUMERIC_ESCAPER.defineEscape('<', "<");
XML_NUMERIC_ESCAPER.defineEscape('>', ">");
URL_ARG_ESCAPER = new StringEscaper();
URL_ARG_ESCAPER.defineEscape('?', "%3f");
URL_ARG_ESCAPER.defineEscape('&', "%26");
URL_ESCAPER = URL_ARG_ESCAPER.getMutableClone();
URL_ESCAPER.defineEscape('%', "%%");
URL_ESCAPER.defineEscape('"', "%22");
URL_ESCAPER.defineEscape('\r', "+");
URL_ESCAPER.defineEscape('\n', "+");
URL_ESCAPER.defineEscape(' ', "+");
URL_ESCAPER.defineEscape('#', "%23");
HTML_ESCAPER.makeImmutable();
XML_ESCAPER = HTML_ESCAPER;
XML_NUMERIC_ESCAPER.makeImmutable();
URL_ARG_ESCAPER.makeImmutable();
URL_ESCAPER.makeImmutable();
}
}
/** List of attribute names and values. */
static class XMLAttrVector {
public void display(PrintWriter out, int indent) {
throw new UnsupportedOperationException();
}
}
}
// End XmlOutput.java
| |
/*
*
*/
package net.community.chest.io.encode.endian;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import net.community.chest.io.encode.InputDataDecoder;
/**
* <P>Copyright as per GPLv2</P>
*
* @author Lyor G.
* @since Jul 13, 2009 8:40:17 AM
*/
public abstract class AbstractEndianInputDecoder
implements InputDataDecoder, ByteOrderControlled {
private ByteOrder _inOrder;
/*
* @see net.community.chest.io.encode.endian.ByteOrderControlled#getByteOrder()
*/
@Override
public ByteOrder getByteOrder ()
{
return _inOrder;
}
/*
* @see net.community.chest.io.encode.endian.ByteOrderControlled#setByteOrder(java.nio.ByteOrder)
*/
@Override
public void setByteOrder (ByteOrder o)
{
_inOrder = o;
}
/*
* @see net.community.chest.io.encode.endian.ByteOrderControlled#isMutableByteOrder()
*/
@Override
public boolean isMutableByteOrder ()
{
return true;
}
protected AbstractEndianInputDecoder (final ByteOrder inOrder)
{
_inOrder = inOrder;
}
protected AbstractEndianInputDecoder ()
{
this(null);
}
private byte[] _workBuf;
/**
* @param reqSize Required size - if buffer size already at least the
* required value then current work buffer is returned
* @param createIfNotExist FALSE=do not create a buffer if none allocated
* or existing one not up to required size
* @return Work buffer instance
* @see #setWorkBuf(byte[])
*/
protected byte[] getWorkBuf (final int reqSize, final boolean createIfNotExist)
{
if (((null == _workBuf) || (_workBuf.length < reqSize)) && createIfNotExist)
_workBuf = new byte[Math.max(reqSize, 8 /* at least a long value */)];
return _workBuf;
}
// returns previous value
protected byte[] setWorkBuf (byte[] buf)
{
final byte[] prev=_workBuf;
_workBuf = buf;
return prev;
}
/*
* @see java.io.DataInput#readFully(byte[])
*/
@Override
public void readFully (byte[] b) throws IOException
{
readFully(b, 0, b.length);
}
/*
* @see java.io.DataInput#readInt()
*/
@Override
public int readInt () throws IOException
{
final byte[] workBuf=getWorkBuf(4, true);
readFully(workBuf, 0, 4);
try
{
return EndianEncoder.readSignedInt32(getByteOrder(), workBuf, 0, 4);
}
catch(NumberFormatException e)
{
throw new IOException("readInt() " + e.getMessage());
}
}
/*
* @see java.io.DataInput#readLong()
*/
@Override
public long readLong () throws IOException
{
final byte[] workBuf=getWorkBuf(8, true);
readFully(workBuf, 0, 8);
try
{
return EndianEncoder.readSignedInt64(getByteOrder(), workBuf, 0, 8);
}
catch(NumberFormatException e)
{
throw new IOException("readLong() " + e.getMessage());
}
}
/*
* @see java.io.DataInput#readShort()
*/
@Override
public short readShort () throws IOException
{
final byte[] workBuf=getWorkBuf(2, true);
readFully(workBuf, 0, 2);
try
{
return EndianEncoder.readSignedInt16(getByteOrder(), workBuf, 0, 2);
}
catch(NumberFormatException e)
{
throw new IOException("readShort() " + e.getMessage());
}
}
/*
* @see java.io.DataInput#readUnsignedByte()
*/
@Override
public int readUnsignedByte () throws IOException
{
return (readByte() & 0x00FF);
}
/*
* @see java.io.DataInput#readUnsignedShort()
*/
@Override
public int readUnsignedShort () throws IOException
{
final byte[] workBuf=getWorkBuf(2, true);
readFully(workBuf, 0, 2);
try
{
return EndianEncoder.readUnsignedInt16(getByteOrder(), workBuf, 0, 2);
}
catch(NumberFormatException e)
{
throw new IOException("readUnsignedShort() " + e.getMessage());
}
}
/*
* @see net.community.chest.io.encode.InputDataDecoder#readString(java.nio.charset.CharsetDecoder)
*/
@Override
public String readString (CharsetDecoder charsetDec) throws IOException
{
return readString(charsetDec.charset());
}
/*
* @see net.community.chest.io.encode.InputDataDecoder#readString(java.lang.String)
*/
@Override
public String readString (String charsetName) throws IOException
{
return readString(Charset.forName(charsetName));
}
/*
* @see java.io.DataInput#readUTF()
*/
@Override
public String readUTF () throws IOException
{
return readString("UTF-8");
}
/*
* @see java.io.DataInput#readBoolean()
*/
@Override
public boolean readBoolean () throws IOException
{
throw new StreamCorruptedException("readBoolean() N/A");
}
/*
* @see java.io.DataInput#readChar()
*/
@Override
public char readChar () throws IOException
{
throw new StreamCorruptedException("readChar() N/A");
}
/*
* @see java.io.DataInput#readDouble()
*/
@Override
public double readDouble () throws IOException
{
throw new StreamCorruptedException("readDouble() N/A");
}
/*
* @see java.io.DataInput#readFloat()
*/
@Override
public float readFloat () throws IOException
{
throw new StreamCorruptedException("readFloat() N/A");
}
/*
* @see java.io.DataInput#readLine()
*/
@Override
public String readLine () throws IOException
{
throw new StreamCorruptedException("readLine() N/A");
}
/*
* @see java.io.DataInput#skipBytes(int)
*/
@Override
public int skipBytes (int n) throws IOException
{
throw new StreamCorruptedException("skipBytes(" + n + ") N/A");
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.transport.nio.channel;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.transport.nio.SocketSelector;
import org.elasticsearch.transport.nio.WriteOperation;
import org.junit.Before;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class TcpWriteContextTests extends ESTestCase {
private SocketSelector selector;
private ActionListener<NioChannel> listener;
private TcpWriteContext writeContext;
private NioSocketChannel channel;
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
super.setUp();
selector = mock(SocketSelector.class);
listener = mock(ActionListener.class);
channel = mock(NioSocketChannel.class);
writeContext = new TcpWriteContext(channel);
when(channel.getSelector()).thenReturn(selector);
when(selector.isOnCurrentThread()).thenReturn(true);
}
public void testWriteFailsIfChannelNotWritable() throws Exception {
when(channel.isWritable()).thenReturn(false);
writeContext.sendMessage(new BytesArray(generateBytes(10)), listener);
verify(listener).onFailure(any(ClosedChannelException.class));
}
public void testSendMessageFromDifferentThreadIsQueuedWithSelector() throws Exception {
byte[] bytes = generateBytes(10);
BytesArray bytesArray = new BytesArray(bytes);
ArgumentCaptor<WriteOperation> writeOpCaptor = ArgumentCaptor.forClass(WriteOperation.class);
when(selector.isOnCurrentThread()).thenReturn(false);
when(channel.isWritable()).thenReturn(true);
writeContext.sendMessage(bytesArray, listener);
verify(selector).queueWrite(writeOpCaptor.capture());
WriteOperation writeOp = writeOpCaptor.getValue();
assertSame(listener, writeOp.getListener());
assertSame(channel, writeOp.getChannel());
assertEquals(ByteBuffer.wrap(bytes), writeOp.getByteReferences()[0].getReadByteBuffer());
}
public void testSendMessageFromSameThreadIsQueuedInChannel() throws Exception {
byte[] bytes = generateBytes(10);
BytesArray bytesArray = new BytesArray(bytes);
ArgumentCaptor<WriteOperation> writeOpCaptor = ArgumentCaptor.forClass(WriteOperation.class);
when(channel.isWritable()).thenReturn(true);
writeContext.sendMessage(bytesArray, listener);
verify(selector).queueWriteInChannelBuffer(writeOpCaptor.capture());
WriteOperation writeOp = writeOpCaptor.getValue();
assertSame(listener, writeOp.getListener());
assertSame(channel, writeOp.getChannel());
assertEquals(ByteBuffer.wrap(bytes), writeOp.getByteReferences()[0].getReadByteBuffer());
}
public void testWriteIsQueuedInChannel() throws Exception {
assertFalse(writeContext.hasQueuedWriteOps());
writeContext.queueWriteOperations(new WriteOperation(channel, new BytesArray(generateBytes(10)), listener));
assertTrue(writeContext.hasQueuedWriteOps());
}
public void testWriteOpsCanBeCleared() throws Exception {
assertFalse(writeContext.hasQueuedWriteOps());
writeContext.queueWriteOperations(new WriteOperation(channel, new BytesArray(generateBytes(10)), listener));
assertTrue(writeContext.hasQueuedWriteOps());
ClosedChannelException e = new ClosedChannelException();
writeContext.clearQueuedWriteOps(e);
verify(listener).onFailure(e);
assertFalse(writeContext.hasQueuedWriteOps());
}
public void testQueuedWriteIsFlushedInFlushCall() throws Exception {
assertFalse(writeContext.hasQueuedWriteOps());
WriteOperation writeOperation = mock(WriteOperation.class);
writeContext.queueWriteOperations(writeOperation);
assertTrue(writeContext.hasQueuedWriteOps());
when(writeOperation.isFullyFlushed()).thenReturn(true);
when(writeOperation.getListener()).thenReturn(listener);
writeContext.flushChannel();
verify(writeOperation).flush();
verify(listener).onResponse(channel);
assertFalse(writeContext.hasQueuedWriteOps());
}
public void testPartialFlush() throws IOException {
assertFalse(writeContext.hasQueuedWriteOps());
WriteOperation writeOperation = mock(WriteOperation.class);
writeContext.queueWriteOperations(writeOperation);
assertTrue(writeContext.hasQueuedWriteOps());
when(writeOperation.isFullyFlushed()).thenReturn(false);
writeContext.flushChannel();
verify(listener, times(0)).onResponse(channel);
assertTrue(writeContext.hasQueuedWriteOps());
}
@SuppressWarnings("unchecked")
public void testMultipleWritesPartialFlushes() throws IOException {
assertFalse(writeContext.hasQueuedWriteOps());
ActionListener listener2 = mock(ActionListener.class);
WriteOperation writeOperation1 = mock(WriteOperation.class);
WriteOperation writeOperation2 = mock(WriteOperation.class);
when(writeOperation1.getListener()).thenReturn(listener);
when(writeOperation2.getListener()).thenReturn(listener2);
writeContext.queueWriteOperations(writeOperation1);
writeContext.queueWriteOperations(writeOperation2);
assertTrue(writeContext.hasQueuedWriteOps());
when(writeOperation1.isFullyFlushed()).thenReturn(true);
when(writeOperation2.isFullyFlushed()).thenReturn(false);
writeContext.flushChannel();
verify(listener).onResponse(channel);
verify(listener2, times(0)).onResponse(channel);
assertTrue(writeContext.hasQueuedWriteOps());
when(writeOperation2.isFullyFlushed()).thenReturn(true);
writeContext.flushChannel();
verify(listener2).onResponse(channel);
assertFalse(writeContext.hasQueuedWriteOps());
}
public void testWhenIOExceptionThrownListenerIsCalled() throws IOException {
assertFalse(writeContext.hasQueuedWriteOps());
WriteOperation writeOperation = mock(WriteOperation.class);
writeContext.queueWriteOperations(writeOperation);
assertTrue(writeContext.hasQueuedWriteOps());
IOException exception = new IOException();
when(writeOperation.flush()).thenThrow(exception);
when(writeOperation.getListener()).thenReturn(listener);
expectThrows(IOException.class, () -> writeContext.flushChannel());
verify(listener).onFailure(exception);
assertFalse(writeContext.hasQueuedWriteOps());
}
private byte[] generateBytes(int n) {
n += 10;
byte[] bytes = new byte[n];
for (int i = 0; i < n; ++i) {
bytes[i] = randomByte();
}
return bytes;
}
}
| |
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.api;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.api.util.CredentialManagementResponseBuilder;
import org.wso2.carbon.mdm.api.util.MDMAPIUtils;
import org.wso2.carbon.mdm.api.util.ResponsePayload;
import org.wso2.carbon.mdm.beans.UserCredentialWrapper;
import org.wso2.carbon.mdm.beans.UserWrapper;
import org.wso2.carbon.mdm.util.Constants;
import org.wso2.carbon.mdm.util.SetReferenceTransformer;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException;
import java.util.*;
/**
* This class represents the JAX-RS services of User related functionality.
*/
public class User {
private static Log log = LogFactory.getLog(User.class);
private static final String ROLE_EVERYONE = "Internal/everyone";
/**
* Method to add user to emm-user-store.
*
* @param userWrapper Wrapper object representing input json payload
* @return {Response} Status of the request wrapped inside Response object
* @throws MDMAPIException
*/
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response addUser(UserWrapper userWrapper) throws MDMAPIException {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
ResponsePayload responsePayload = new ResponsePayload();
try {
if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
// if user already exists
if (log.isDebugEnabled()) {
log.debug("User by username: " + userWrapper.getUsername() +
" already exists. Therefore, request made to add user was refused.");
}
// returning response with bad request state
responsePayload.setStatusCode(HttpStatus.SC_CONFLICT);
responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() +
" already exists. Therefore, request made to add user was refused.");
return Response.status(HttpStatus.SC_CONFLICT).entity(responsePayload).build();
} else {
String initialUserPassword = generateInitialUserPassword();
Map<String, String> defaultUserClaims =
buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(),
userWrapper.getEmailAddress());
// calling addUser method of carbon user api
userStoreManager.addUser(userWrapper.getUsername(), initialUserPassword,
userWrapper.getRoles(), defaultUserClaims, null);
// invite newly added user to enroll device
inviteNewlyAddedUserToEnrollDevice(userWrapper.getUsername(), initialUserPassword);
// Outputting debug message upon successful addition of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + userWrapper.getUsername() + " was successfully added.");
}
// returning response with success state
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() +
" was successfully added.");
return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build();
}
} catch (UserStoreException e) {
String msg = "Exception in trying to add user by username: " + userWrapper.getUsername();
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
}
/**
* Method to get user information from emm-user-store.
*
* @param username User-name of the user
* @return {Response} Status of the request wrapped inside Response object
* @throws MDMAPIException
*/
@GET
@Path("view")
@Produces({MediaType.APPLICATION_JSON})
public Response getUser(@QueryParam("username") String username) throws MDMAPIException {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
ResponsePayload responsePayload = new ResponsePayload();
try {
if (userStoreManager.isExistingUser(username)) {
UserWrapper user = new UserWrapper();
user.setUsername(username);
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
// Outputting debug message upon successful retrieval of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " was found.");
}
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("User information was retrieved successfully.");
responsePayload.setResponseContent(user);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else {
// Outputting debug message upon trying to remove non-existing user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist.");
}
// returning response with bad request state
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer(
"User by username: " + username + " does not exist.");
return Response.status(HttpStatus.SC_NOT_FOUND).entity(responsePayload).build();
}
} catch (UserStoreException e) {
String msg = "Exception in trying to retrieve user by username: " + username;
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
}
/**
* Update user in user store
*
* @param userWrapper Wrapper object representing input json payload
* @return {Response} Status of the request wrapped inside Response object
* @throws MDMAPIException
*/
@PUT
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username)
throws MDMAPIException {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
ResponsePayload responsePayload = new ResponsePayload();
try {
if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
Map<String, String> defaultUserClaims =
buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(),
userWrapper.getEmailAddress());
if (StringUtils.isNotEmpty(userWrapper.getPassword())) {
// Decoding Base64 encoded password
byte[] decodedBytes = Base64.decodeBase64(userWrapper.getPassword());
userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(),
new String(decodedBytes, "UTF-8"));
log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed");
}
List<String> listofFilteredRoles = getFilteredRoles(userStoreManager, userWrapper.getUsername());
final String[] existingRoles = listofFilteredRoles.toArray(new String[listofFilteredRoles.size()]);
/*
Use the Set theory to find the roles to delete and roles to add
The difference of roles in existingRolesSet and newRolesSet needed to be deleted
new roles to add = newRolesSet - The intersection of roles in existingRolesSet and newRolesSet
*/
final TreeSet<String> existingRolesSet = new TreeSet<>();
Collections.addAll(existingRolesSet, existingRoles);
final TreeSet<String> newRolesSet = new TreeSet<>();
Collections.addAll(newRolesSet, userWrapper.getRoles());
existingRolesSet.removeAll(newRolesSet);
// Now we have the roles to delete
String[] rolesToDelete = existingRolesSet.toArray(new String[existingRolesSet.size()]);
List<String> roles = new ArrayList<>(Arrays.asList(rolesToDelete));
roles.remove(ROLE_EVERYONE);
rolesToDelete = new String[0];
// Clearing and re-initializing the set
existingRolesSet.clear();
Collections.addAll(existingRolesSet, existingRoles);
newRolesSet.removeAll(existingRolesSet);
// Now we have the roles to add
String[] rolesToAdd = newRolesSet.toArray(new String[newRolesSet.size()]);
userStoreManager.updateRoleListOfUser(userWrapper.getUsername(), rolesToDelete, rolesToAdd);
userStoreManager.setUserClaimValues(userWrapper.getUsername(), defaultUserClaims, null);
// Outputting debug message upon successful addition of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + userWrapper.getUsername() + " was successfully updated.");
}
// returning response with success state
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() +
" was successfully updated.");
return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build();
} else {
if (log.isDebugEnabled()) {
log.debug("User by username: " + userWrapper.getUsername() +
" doesn't exists. Therefore, request made to update user was refused.");
}
// returning response with bad request state
responsePayload.setStatusCode(HttpStatus.SC_CONFLICT);
responsePayload.
setMessageFromServer("User by username: " + userWrapper.getUsername() +
" doesn't exists. Therefore, request made to update user was refused.");
return Response.status(HttpStatus.SC_CONFLICT).entity(responsePayload).build();
}
} catch (UserStoreException | UnsupportedEncodingException e) {
String msg = "Exception in trying to update user by username: " + userWrapper.getUsername();
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
}
/**
* Private method to be used by addUser() to
* generate an initial user password for a user.
* This will be the password used by a user for his initial login to the system.
*
* @return {string} Initial User Password
*/
private String generateInitialUserPassword() {
int passwordLength = 6;
//defining the pool of characters to be used for initial password generation
String lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz";
String upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String numericCharset = "0123456789";
Random randomGenerator = new Random();
String totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset;
int totalCharsetLength = totalCharset.length();
StringBuilder initialUserPassword = new StringBuilder();
for (int i = 0; i < passwordLength; i++) {
initialUserPassword
.append(totalCharset.charAt(randomGenerator.nextInt(totalCharsetLength)));
}
if (log.isDebugEnabled()) {
log.debug("Initial user password is created for new user: " + initialUserPassword);
}
return initialUserPassword.toString();
}
/**
* Method to build default user claims.
*
* @param firstname First name of the user
* @param lastname Last name of the user
* @param emailAddress Email address of the user
* @return {Object} Default user claims to be provided
*/
private Map<String, String> buildDefaultUserClaims(String firstname, String lastname, String emailAddress) {
Map<String, String> defaultUserClaims = new HashMap<>();
defaultUserClaims.put(Constants.USER_CLAIM_FIRST_NAME, firstname);
defaultUserClaims.put(Constants.USER_CLAIM_LAST_NAME, lastname);
defaultUserClaims.put(Constants.USER_CLAIM_EMAIL_ADDRESS, emailAddress);
if (log.isDebugEnabled()) {
log.debug("Default claim map is created for new user: " + defaultUserClaims.toString());
}
return defaultUserClaims;
}
/**
* Method to remove user from emm-user-store.
*
* @param username Username of the user
* @return {Response} Status of the request wrapped inside Response object
* @throws MDMAPIException
*/
@DELETE
@Produces({MediaType.APPLICATION_JSON})
public Response removeUser(@QueryParam("username") String username) throws MDMAPIException {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
ResponsePayload responsePayload = new ResponsePayload();
try {
if (userStoreManager.isExistingUser(username)) {
// if user already exists, trying to remove user
userStoreManager.deleteUser(username);
// Outputting debug message upon successful removal of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " was successfully removed.");
}
// returning response with success state
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer(
"User by username: " + username + " was successfully removed.");
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else {
// Outputting debug message upon trying to remove non-existing user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist for removal.");
}
// returning response with bad request state
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer(
"User by username: " + username + " does not exist for removal.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(responsePayload).build();
}
} catch (UserStoreException e) {
String msg = "Exception in trying to remove user by username: " + username;
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
}
/**
* get all the roles except for the internal/xxx and application/xxx
*
* @param userStoreManager User Store Manager associated with the currently logged in user
* @param username Username of the currently logged in user
* @return the list of filtered roles
* @throws UserStoreException
*/
private List<String> getFilteredRoles(UserStoreManager userStoreManager, String username)
throws UserStoreException {
String[] roleListOfUser = userStoreManager.getRoleListOfUser(username);
List<String> filteredRoles = new ArrayList<>();
for (String role : roleListOfUser) {
if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) {
filteredRoles.add(role);
}
}
return filteredRoles;
}
/**
* Get user's roles by username
*
* @param username Username of the user
* @return {Response} Status of the request wrapped inside Response object
* @throws MDMAPIException
*/
@GET
@Path("roles")
@Produces({MediaType.APPLICATION_JSON})
public Response getRoles(@QueryParam("username") String username) throws MDMAPIException {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
ResponsePayload responsePayload = new ResponsePayload();
try {
if (userStoreManager.isExistingUser(username)) {
responsePayload.setResponseContent(Arrays.asList(getFilteredRoles(userStoreManager, username)));
// Outputting debug message upon successful removal of user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " was successfully removed.");
}
// returning response with success state
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer(
"User roles obtained for user " + username);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} else {
// Outputting debug message upon trying to remove non-existing user
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist for role retrieval.");
}
// returning response with bad request state
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
responsePayload.setMessageFromServer(
"User by username: " + username + " does not exist for role retrieval.");
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(responsePayload).build();
}
} catch (UserStoreException e) {
String msg = "Exception in trying to retrieve roles for user by username: " + username;
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
}
/**
* Get the list of all users with all user-related info.
*
* @return A list of users
* @throws MDMAPIException
*/
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getAllUsers() throws MDMAPIException {
if (log.isDebugEnabled()) {
log.debug("Getting the list of users with all user-related information");
}
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
List<UserWrapper> userList;
try {
String[] users = userStoreManager.listUsers("*", -1);
userList = new ArrayList<>(users.length);
UserWrapper user;
for (String username : users) {
user = new UserWrapper();
user.setUsername(username);
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user);
}
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving the list of users";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
int count;
count = userList.size();
responsePayload.setMessageFromServer("All users were successfully retrieved. " +
"Obtained user count: " + count);
responsePayload.setResponseContent(userList);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
/**
* Get the list of all users with all user-related info.
*
* @return A list of users
* @throws MDMAPIException
*/
@GET
@Path("{filter}")
@Produces({MediaType.APPLICATION_JSON})
public Response getMatchingUsers(@PathParam("filter") String filter) throws MDMAPIException {
if (log.isDebugEnabled()) {
log.debug("Getting the list of users with all user-related information using the filter : " + filter);
}
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
List<UserWrapper> userList;
try {
String[] users = userStoreManager.listUsers(filter + "*", -1);
userList = new ArrayList<>(users.length);
UserWrapper user;
for (String username : users) {
user = new UserWrapper();
user.setUsername(username);
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user);
}
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving the list of users using the filter : " + filter;
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
int count;
count = userList.size();
responsePayload.setMessageFromServer("All users were successfully retrieved. " +
"Obtained user count: " + count);
responsePayload.setResponseContent(userList);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
/**
* Get the list of user names in the system.
*
* @return A list of user names.
* @throws MDMAPIException
*/
@GET
@Path("view-users")
public Response getAllUsersByUsername(@QueryParam("username") String userName) throws MDMAPIException {
if (log.isDebugEnabled()) {
log.debug("Getting the list of users by name");
}
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
List<UserWrapper> userList;
try {
String[] users = userStoreManager.listUsers("*" + userName + "*", -1);
userList = new ArrayList<>(users.length);
UserWrapper user;
for (String username : users) {
user = new UserWrapper();
user.setUsername(username);
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
userList.add(user);
}
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving the list of users";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
int count;
count = userList.size();
responsePayload.setMessageFromServer("All users by username were successfully retrieved. " +
"Obtained user count: " + count);
responsePayload.setResponseContent(userList);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
/**
* Get the list of user names in the system.
*
* @return A list of user names.
* @throws MDMAPIException
*/
@GET
@Path("users-by-username")
public Response getAllUserNamesByUsername(@QueryParam("username") String userName) throws MDMAPIException {
if (log.isDebugEnabled()) {
log.debug("Getting the list of users by name");
}
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
List<String> userList;
try {
String[] users = userStoreManager.listUsers("*" + userName + "*", -1);
userList = new ArrayList<>(users.length);
Collections.addAll(userList, users);
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving the list of users";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
int count;
count = userList.size();
responsePayload.setMessageFromServer("All users by username were successfully retrieved. " +
"Obtained user count: " + count);
responsePayload.setResponseContent(userList);
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
/**
* Gets a claim-value from user-store.
*
* @param username Username of the user
* @param claimUri required ClaimUri
* @return A list of usernames
* @throws MDMAPIException, UserStoreException
*/
private String getClaimValue(String username, String claimUri) throws MDMAPIException {
UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
try {
return userStoreManager.getUserClaimValue(username, claimUri, null);
} catch (UserStoreException e) {
throw new MDMAPIException("Error occurred while retrieving value assigned to the claim '" +
claimUri + "'", e);
}
}
/**
* Method used to send an invitation email to a new user to enroll a device.
*
* @param username Username of the user
* @throws MDMAPIException, UserStoreException, DeviceManagementException
*/
private void inviteNewlyAddedUserToEnrollDevice(
String username, String password) throws MDMAPIException {
if (log.isDebugEnabled()) {
log.debug("Sending invitation mail to user by username: " + username);
}
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) {
tenantDomain = "";
}
if (!username.contains("/")) {
username = "/" + username;
}
String[] usernameBits = username.split("/");
DeviceManagementProviderService deviceManagementProviderService = MDMAPIUtils.getDeviceManagementService();
Properties props = new Properties();
props.setProperty("username", usernameBits[1]);
props.setProperty("domain-name", tenantDomain);
props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
props.setProperty("password", password);
String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS);
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
try {
deviceManagementProviderService.sendRegistrationEmail(metaInfo);
} catch (DeviceManagementException e) {
String msg = "Error occurred while sending registration email to user '" + username + "'";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
}
/**
* Method used to send an invitation email to a existing user to enroll a device.
*
* @param usernames Username list of the users to be invited
* @throws MDMAPIException
*/
@POST
@Path("email-invitation")
@Produces({MediaType.APPLICATION_JSON})
public Response inviteExistingUsersToEnrollDevice(List<String> usernames) throws MDMAPIException {
if (log.isDebugEnabled()) {
log.debug("Sending enrollment invitation mail to existing user.");
}
DeviceManagementProviderService deviceManagementProviderService = MDMAPIUtils.getDeviceManagementService();
try {
for (String username : usernames) {
String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS);
Properties props = new Properties();
props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
props.setProperty("username", username);
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
deviceManagementProviderService.sendEnrolmentInvitation(metaInfo);
}
} catch (DeviceManagementException e) {
String msg = "Error occurred while inviting user to enrol their device";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Email invitation was successfully sent to user.");
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
}
/**
* Get a list of devices based on the username.
*
* @param username Username of the device owner
* @return A list of devices
* @throws MDMAPIException
*/
@GET
@Produces({MediaType.APPLICATION_JSON})
@Path("devices")
public Object getAllDeviceOfUser(@QueryParam("username") String username, @QueryParam("start") int startIdx,
@QueryParam("length") int length)
throws MDMAPIException {
DeviceManagementProviderService dmService;
try {
dmService = MDMAPIUtils.getDeviceManagementService();
if (length > 0) {
PaginationRequest request = new PaginationRequest(startIdx, length);
request.setOwner(username);
return dmService.getDevicesOfUser(request);
}
return dmService.getDevicesOfUser(username);
} catch (DeviceManagementException e) {
String msg = "Device management error";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
}
/**
* This method is used to retrieve the user count of the system.
*
* @return returns the count.
* @throws MDMAPIException
*/
@GET
@Path("count")
public int getUserCount() throws MDMAPIException {
try {
String[] users = MDMAPIUtils.getUserStoreManager().listUsers("*", -1);
if (users == null) {
return 0;
}
return users.length;
} catch (UserStoreException e) {
String msg =
"Error occurred while retrieving the list of users that exist within the current tenant";
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
}
/**
* API is used to update roles of a user
*
* @param username
* @param userList
* @return
* @throws MDMAPIException
*/
@PUT
@Path("{roleName}/users")
@Produces({MediaType.APPLICATION_JSON})
public Response updateRoles(@PathParam("username") String username, List<String> userList)
throws MDMAPIException {
final UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager();
try {
if (log.isDebugEnabled()) {
log.debug("Updating the roles of a user");
}
SetReferenceTransformer transformer = new SetReferenceTransformer();
transformer.transform(Arrays.asList(userStoreManager.getRoleListOfUser(username)),
userList);
final String[] rolesToAdd = (String[])
transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]);
final String[] rolesToDelete = (String[])
transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]);
userStoreManager.updateRoleListOfUser(username, rolesToDelete, rolesToAdd);
} catch (UserStoreException e) {
String msg = "Error occurred while saving the roles for user: " + username;
log.error(msg, e);
throw new MDMAPIException(msg, e);
}
return Response.status(HttpStatus.SC_OK).build();
}
/**
* Method to change the user password.
*
* @param credentials Wrapper object representing user credentials.
* @return {Response} Status of the request wrapped inside Response object.
* @throws MDMAPIException
*/
@POST
@Path("change-password")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response resetPassword(UserCredentialWrapper credentials) throws MDMAPIException {
return CredentialManagementResponseBuilder.buildChangePasswordResponse(credentials);
}
/**
* Method to change the user password.
*
* @param credentials Wrapper object representing user credentials.
* @return {Response} Status of the request wrapped inside Response object.
* @throws MDMAPIException
*/
@POST
@Path("reset-password")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response resetPasswordByAdmin(UserCredentialWrapper credentials) throws MDMAPIException {
return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.query.internal.index;
import static org.apache.geode.cache.Region.SEPARATOR;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheException;
import org.apache.geode.cache.CacheExistsException;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.query.Index;
import org.apache.geode.cache.query.IndexStatistics;
import org.apache.geode.cache.query.data.Portfolio;
import org.apache.geode.cache.query.data.Position;
import org.apache.geode.cache.query.internal.index.AbstractIndex.RegionEntryToValuesMap;
import org.apache.geode.cache.query.internal.index.IndexStore.IndexStoreEntry;
import org.apache.geode.cache.query.internal.index.MemoryIndexStore.MemoryIndexStoreEntry;
import org.apache.geode.cache.query.partitioned.PRQueryDUnitHelper;
import org.apache.geode.cache30.CacheSerializableRunnable;
import org.apache.geode.cache30.CacheTestCase;
import org.apache.geode.internal.cache.CachedDeserializable;
import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.internal.cache.LocalRegion;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.internal.cache.RegionEntry;
import org.apache.geode.internal.cache.Token;
import org.apache.geode.internal.cache.persistence.query.CloseableIterator;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.AsyncInvocation;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.Invoke;
import org.apache.geode.test.dunit.LogWriterUtils;
import org.apache.geode.test.dunit.SerializableRunnableIF;
import org.apache.geode.test.dunit.ThreadUtils;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
import org.apache.geode.test.junit.categories.OQLIndexTest;
import org.apache.geode.util.internal.GeodeGlossary;
/**
* This test is similar to {@link ConcurrentIndexUpdateWithoutWLDUnitTest} except that it sets
* system property gemfire.index.INPLACE_OBJECT_MODIFICATION to false so no reverse map is used for
* {@link CompactRangeIndex}.
*
* During validation all region operations are paused for a while. Validation happens multiple time
* during one test run on a fixed time interval.
*/
@Category({OQLIndexTest.class})
public class ConcurrentIndexUpdateWithInplaceObjectModFalseDUnitTest
extends JUnit4DistributedTestCase {
PRQueryDUnitHelper helper = new PRQueryDUnitHelper();
private static String regionName = "Portfolios";
private int redundancy = 1;
// CompactRangeIndex
private String indexName = "idIndex";
private String indexedExpression = "ID";
private String fromClause = SEPARATOR + regionName;
private String alias = "p";
private String rindexName = "secidIndex";
private String rindexedExpression = "pos.secId";
private String rfromClause = SEPARATOR + regionName + " p, p.positions.values pos";
private String ralias = "pos";
int stepSize = 10;
private int totalDataSize = 50;
public void setCacheInVMs(VM... vms) {
for (VM vm : vms) {
vm.invoke(() -> getAvailableCacheElseCreateCache());
}
}
private void getAvailableCacheElseCreateCache() {
synchronized (ConcurrentIndexUpdateWithInplaceObjectModFalseDUnitTest.class) {
try {
Cache newCache = GemFireCacheImpl.getInstance();
if (null == newCache) {
System.setProperty(
GeodeGlossary.GEMFIRE_PREFIX + "DISABLE_DISCONNECT_DS_ON_CACHE_CLOSE", "true");
newCache = CacheFactory.create(getSystem());
}
PRQueryDUnitHelper.setCache(newCache);
} catch (CacheExistsException e) {
Assert.fail("the cache already exists", e); // TODO: remove error handling
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
Assert.fail("Checked exception while initializing cache??", ex);
} finally {
System.clearProperty(
GeodeGlossary.GEMFIRE_PREFIX + "DISABLE_DISCONNECT_DS_ON_CACHE_CLOSE");
}
}
}
@Override
public final void preSetUp() throws Exception {
Invoke.invokeInEveryVM(new CacheSerializableRunnable("Set INPLACE_OBJECT_MODIFICATION false") {
@Override
public void run2() throws CacheException {
// System.setProperty("gemfire.index.INPLACE_OBJECT_MODIFICATION", "false");
IndexManager.INPLACE_OBJECT_MODIFICATION_FOR_TEST = true;
}
});
}
/**
* Tear down a PartitionedRegionTestCase by cleaning up the existing cache (mainly because we want
* to destroy any existing PartitionedRegions)
*/
@Override
public final void preTearDown() throws Exception {
Invoke.invokeInEveryVM(new CacheSerializableRunnable("Set INPLACE_OBJECT_MODIFICATION false") {
@Override
public void run2() throws CacheException {
// System.setProperty("gemfire.index.INPLACE_OBJECT_MODIFICATION", "false");
IndexManager.INPLACE_OBJECT_MODIFICATION_FOR_TEST = false;
}
});
Invoke.invokeInEveryVM(ConcurrentIndexUpdateWithInplaceObjectModFalseDUnitTest.class,
"destroyRegions");
Invoke.invokeInEveryVM(CacheTestCase.class, "closeCache");
}
public static synchronized void destroyRegions() {
Cache cache = GemFireCacheImpl.getInstance();
if (cache != null) {
Region region = cache.getRegion(regionName);
if (region != null)
region.destroyRegion();
}
}
// Tests on Local/Replicated Region
@Test
public void testCompactRangeIndex() {
// Create a Local Region.
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
setCacheInVMs(vm0);
vm0.invoke(helper.getCacheSerializableRunnableForReplicatedRegionCreation(regionName));
vm0.invoke(helper.getCacheSerializableRunnableForPRIndexCreate(regionName, indexName,
indexedExpression, fromClause, alias));
AsyncInvocation[] asyncInvs = new AsyncInvocation[2];
asyncInvs[0] =
vm0.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName, 0, stepSize));
asyncInvs[1] =
vm0.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName, 0, stepSize));
for (AsyncInvocation inv : asyncInvs) {
ThreadUtils.join(inv, 30 * 000);
}
for (AsyncInvocation inv : asyncInvs) {
if (inv.exceptionOccurred()) {
Assert.fail("Random region operation failed on VM_" + inv.getId(), inv.getException());
}
}
vm0.invoke(getCacheSerializableRunnableForIndexValidation(regionName, indexName));
}
private SerializableRunnableIF getCacheSerializableRunnableForIndexValidation(
final String regionName, final String indexName) {
return new CacheSerializableRunnable("Index Validate") {
@Override
public void run2() throws CacheException {
Cache cache = helper.getCache();
Region region = cache.getRegion(regionName);
IndexValidator validator = new IndexValidator();
validator.validate(region);
}
};
}
@Test
public void testRangeIndex() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
setCacheInVMs(vm0);
vm0.invoke(helper.getCacheSerializableRunnableForReplicatedRegionCreation(regionName));
vm0.invoke(helper.getCacheSerializableRunnableForPRIndexCreate(regionName, rindexName,
rindexedExpression, rfromClause, ralias));
AsyncInvocation[] asyncInvs = new AsyncInvocation[2];
asyncInvs[0] = vm0.invokeAsync(
helper.getCacheSerializableRunnableForPRRandomOps(regionName, 0, totalDataSize));
asyncInvs[1] = vm0.invokeAsync(
helper.getCacheSerializableRunnableForPRRandomOps(regionName, 0, totalDataSize));
for (AsyncInvocation inv : asyncInvs) {
ThreadUtils.join(inv, 30 * 000);
}
for (AsyncInvocation inv : asyncInvs) {
if (inv.exceptionOccurred()) {
Assert.fail("Random region operation failed on VM_" + inv.getId(), inv.getException());
}
}
vm0.invoke(getCacheSerializableRunnableForIndexValidation(regionName, rindexName));
}
// Tests on Partition Region
@Test
public void testCompactRangeIndexOnPR() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
VM vm3 = host.getVM(3);
setCacheInVMs(vm0, vm1, vm2, vm3);
vm0.invoke(helper.getCacheSerializableRunnableForPRAccessorCreate(regionName, redundancy,
Portfolio.class));
vm1.invoke(
helper.getCacheSerializableRunnableForPRCreate(regionName, redundancy, Portfolio.class));
vm2.invoke(
helper.getCacheSerializableRunnableForPRCreate(regionName, redundancy, Portfolio.class));
vm3.invoke(
helper.getCacheSerializableRunnableForPRCreate(regionName, redundancy, Portfolio.class));
vm0.invoke(helper.getCacheSerializableRunnableForPRIndexCreate(regionName, indexName,
indexedExpression, fromClause, alias));
AsyncInvocation[] asyncInvs = new AsyncInvocation[12];
asyncInvs[0] =
vm0.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName, 0, stepSize));
asyncInvs[1] = vm1.invokeAsync(
helper.getCacheSerializableRunnableForPRRandomOps(regionName, stepSize, (2 * stepSize)));
asyncInvs[2] = vm2.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName,
(2 * stepSize), (3 * stepSize)));
asyncInvs[3] = vm3.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName,
(3 * (stepSize)), totalDataSize));
asyncInvs[4] =
vm0.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName, 0, stepSize));
asyncInvs[5] = vm1.invokeAsync(
helper.getCacheSerializableRunnableForPRRandomOps(regionName, stepSize, (2 * stepSize)));
asyncInvs[6] = vm2.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName,
(2 * stepSize), (3 * stepSize)));
asyncInvs[7] = vm3.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName,
(3 * (stepSize)), totalDataSize));
asyncInvs[8] =
vm0.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName, 0, stepSize));
asyncInvs[9] = vm1.invokeAsync(
helper.getCacheSerializableRunnableForPRRandomOps(regionName, stepSize, (2 * stepSize)));
asyncInvs[10] = vm2.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName,
(2 * stepSize), (3 * stepSize)));
asyncInvs[11] = vm3.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName,
(3 * (stepSize)), totalDataSize));
for (AsyncInvocation inv : asyncInvs) {
ThreadUtils.join(inv, 60 * 000);
}
for (AsyncInvocation inv : asyncInvs) {
if (inv.exceptionOccurred()) {
Assert.fail("Random region operation failed on VM_" + inv.getId(), inv.getException());
}
}
vm0.invoke(getCacheSerializableRunnableForIndexValidation(regionName, indexName));
vm1.invoke(getCacheSerializableRunnableForIndexValidation(regionName, indexName));
vm2.invoke(getCacheSerializableRunnableForIndexValidation(regionName, indexName));
vm3.invoke(getCacheSerializableRunnableForIndexValidation(regionName, indexName));
}
@Test
public void testRangeIndexOnPR() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
VM vm3 = host.getVM(3);
setCacheInVMs(vm0, vm1, vm2, vm3);
vm0.invoke(helper.getCacheSerializableRunnableForPRAccessorCreate(regionName, redundancy,
Portfolio.class));
vm1.invoke(
helper.getCacheSerializableRunnableForPRCreate(regionName, redundancy, Portfolio.class));
vm2.invoke(
helper.getCacheSerializableRunnableForPRCreate(regionName, redundancy, Portfolio.class));
vm3.invoke(
helper.getCacheSerializableRunnableForPRCreate(regionName, redundancy, Portfolio.class));
vm0.invoke(helper.getCacheSerializableRunnableForPRIndexCreate(regionName, rindexName,
rindexedExpression, rfromClause, ralias));
AsyncInvocation[] asyncInvs = new AsyncInvocation[12];
asyncInvs[0] =
vm0.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName, 0, stepSize));
asyncInvs[1] = vm1.invokeAsync(
helper.getCacheSerializableRunnableForPRRandomOps(regionName, stepSize, (2 * stepSize)));
asyncInvs[2] = vm2.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName,
(2 * stepSize), (3 * stepSize)));
asyncInvs[3] = vm3.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName,
(3 * (stepSize)), totalDataSize));
asyncInvs[4] =
vm0.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName, 0, stepSize));
asyncInvs[5] = vm1.invokeAsync(
helper.getCacheSerializableRunnableForPRRandomOps(regionName, stepSize, (2 * stepSize)));
asyncInvs[6] = vm2.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName,
(2 * stepSize), (3 * stepSize)));
asyncInvs[7] = vm3.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName,
(3 * (stepSize)), totalDataSize));
asyncInvs[8] =
vm0.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName, 0, stepSize));
asyncInvs[9] = vm1.invokeAsync(
helper.getCacheSerializableRunnableForPRRandomOps(regionName, stepSize, (2 * stepSize)));
asyncInvs[10] = vm2.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName,
(2 * stepSize), (3 * stepSize)));
asyncInvs[11] = vm3.invokeAsync(helper.getCacheSerializableRunnableForPRRandomOps(regionName,
(3 * (stepSize)), totalDataSize));
for (AsyncInvocation inv : asyncInvs) {
ThreadUtils.join(inv, 60 * 000);
}
for (AsyncInvocation inv : asyncInvs) {
if (inv.exceptionOccurred()) {
Assert.fail("Random region operation failed on VM_" + inv.getId(), inv.getException());
}
}
vm0.invoke(getCacheSerializableRunnableForIndexValidation(regionName, rindexName));
vm1.invoke(getCacheSerializableRunnableForIndexValidation(regionName, rindexName));
vm2.invoke(getCacheSerializableRunnableForIndexValidation(regionName, rindexName));
vm3.invoke(getCacheSerializableRunnableForIndexValidation(regionName, rindexName));
}
/**
* This validator will iterate over RegionEntries and verify their corresponding index key and
* entry presence in index valuesToEntriesMap.
*
*
*/
public class IndexValidator {
public IndexValidator() {
}
private boolean isValidationInProgress;
/**
* Validation is done in the end of test on all indexes of a region by verifying last on a
* region key and verifying state of index based on the last operation.
*
* @param region being validated for all of its indexes.
*/
public void validate(Region region) {
// Get List of All indexes.
Collection<Index> indexes = ((LocalRegion) region).getIndexManager().getIndexes();
// validate each index one by one
for (Index index : indexes) {
if (region instanceof PartitionedRegion) {
validateOnPR((PartitionedRegion) region, (PartitionedIndex) index);
} else {
validate(region, index);
}
}
}
private void validate(Region region, Index index) {
// Get index expression
String indexExpr = index.getIndexedExpression();
int expectedIndexSize = 0;
int expectedNullEntries = 0;
int expectedUndefinedEntries = 0;
// Lets check if it contains a '.'
if (indexExpr.indexOf(".") != -1) {
indexExpr = indexExpr.substring(indexExpr.indexOf(".") + 1);
}
// do a get<indexExpr>() on each region value and verify if the
// evaluated index key is part of index and has RE as a reference to it
Collection<RegionEntry> entries = ((LocalRegion) region).entries.regionEntries();
for (RegionEntry internalEntry : entries) {
Object value = internalEntry.getValueInVM((LocalRegion) region);
if (value instanceof CachedDeserializable) {
value = ((CachedDeserializable) value).getDeserializedValue(region, internalEntry);
}
if (indexExpr.equals("ID")) {
// Compact Range Index
if (index instanceof CompactRangeIndex) {
// Ignore invalid values.
if (value != Token.INVALID && value != Token.TOMBSTONE) {
LogWriterUtils.getLogWriter().info("Portfolio: " + ((Portfolio) value));
Integer ID = ((Portfolio) value).getID();
assertTrue(
"Did not find index key for REgionEntry [key: " + internalEntry.getKey()
+ " , value: " + value + " ] in index: " + index.getName(),
((CompactRangeIndex) index).getIndexStorage().get(ID) == null ? false : true);
// Get Index value for the evaluated index key.
CloseableIterator<IndexStoreEntry> valuesForKeyIterator = null;
try {
valuesForKeyIterator = ((CompactRangeIndex) index).getIndexStorage().get(ID);
// Check if RegionEntry is present in Index for the key
// evaluated from
// region value.
while (valuesForKeyIterator.hasNext()) {
assertTrue(
"Did not find index value for REgionEntry [key: " + internalEntry.getKey()
+ " , value: " + value + " ] in index: " + index.getName()
+ " For index key: " + ID,
(((MemoryIndexStoreEntry) valuesForKeyIterator.next())
.getRegionEntry() == internalEntry));
}
} finally {
if (valuesForKeyIterator != null) {
valuesForKeyIterator.close();
}
}
if (ID != IndexManager.NULL) {
expectedIndexSize++;
} else {
expectedNullEntries++;
}
} else {
LogWriterUtils.getLogWriter().info(internalEntry.getKey() + "");
expectedUndefinedEntries++;
}
}
} else if (indexExpr.equals("secId")) {
if (index instanceof RangeIndex) {
// Ignore invalid values.
if (value != Token.INVALID && value != Token.TOMBSTONE) {
Collection<Position> positions = ((Portfolio) value).positions.values();
for (Position pos : positions) {
if (pos != null) {
LogWriterUtils.getLogWriter()
.info("Portfolio: " + ((Portfolio) value) + "Position: " + pos);
String secId = pos.secId;
assertTrue(
"Did not find index key for REgionEntry [key: " + internalEntry.getKey()
+ " , value: " + value + " ] in index: " + index.getName(),
((RangeIndex) index).valueToEntriesMap.containsKey(secId));
// Get Index value for the evaluated index key.
Object valuesForKey = ((RangeIndex) index).valueToEntriesMap.get(secId);
// Check if RegionEntry is present in Index for the key evaluated from
// region value.
if (!(valuesForKey instanceof RegionEntryToValuesMap)) {
assertTrue(
"Did not find index value for REgionEntry [key: " + internalEntry.getKey()
+ " , value: " + value + " ] in index: " + index.getName()
+ " For index key: " + secId,
((RegionEntry) valuesForKey == internalEntry));
} else {
assertTrue(
"Did not find index value for REgionEntry [key: " + internalEntry.getKey()
+ " , value: " + value + " ] in index: " + index.getName()
+ " For index key: " + secId,
(((RegionEntryToValuesMap) valuesForKey).containsEntry(internalEntry)));
}
if (secId != null) {
expectedIndexSize++;
} else {
expectedNullEntries++;
}
} else {
expectedUndefinedEntries++;
}
}
}
}
}
}
// Validate sizes for index map, null and undefined maps.
int actualSize = 0;
if (index instanceof CompactRangeIndex) {
CloseableIterator<IndexStoreEntry> iter = null;
try {
iter = ((CompactRangeIndex) index).getIndexStorage().iterator(null);
while (iter.hasNext()) {
Object value = iter.next().getDeserializedValue();
// getLogWriter().info(
// "Index Values : " + value);
actualSize++;
}
} finally {
if (iter != null) {
iter.close();
}
}
}
if (index instanceof RangeIndex) {
for (Object value : ((RangeIndex) index).valueToEntriesMap.values()) {
if (value instanceof RegionEntry) {
actualSize++;
} else {
// for (Object obj: ((RegionEntryToValuesMap)value).map.values()) {
// getLogWriter().info("Index Values : "+ obj.toString());
// }
actualSize += ((RegionEntryToValuesMap) value).getNumValues();
}
}
}
IndexStatistics stats = index.getStatistics();
if (index instanceof CompactRangeIndex) {
/*
* getLogWriter().info( " Actual Size of Index is: " + actualSize + " Undefined size is: " +
* ((CompactRangeIndex) index).undefinedMappedEntries.size() + " And NULL size is: " +
* ((CompactRangeIndex) index).nullMappedEntries.size()); for (Object obj :
* ((CompactRangeIndex) index).undefinedMappedEntries .toArray()) {
* getLogWriter().info(((RegionEntry) obj).getKey() + ""); }
*/ LogWriterUtils.getLogWriter()
.info(" Expected Size of Index is: " + expectedIndexSize + " Undefined size is: "
+ expectedUndefinedEntries + " And NULL size is: " + expectedNullEntries);
assertEquals(
"No of index keys NOT equals the no shown in statistics for index:" + index.getName(),
((CompactRangeIndex) index).getIndexStorage().size(), stats.getNumberOfKeys());
} else {
LogWriterUtils.getLogWriter()
.info(" Actual Size of Index is: " + actualSize + " Undefined size is: "
+ ((RangeIndex) index).undefinedMappedEntries.getNumEntries()
+ " And NULL size is: " + ((RangeIndex) index).nullMappedEntries.getNumEntries());
for (Object obj : ((RangeIndex) index).undefinedMappedEntries.map.keySet()) {
LogWriterUtils.getLogWriter().info(((RegionEntry) obj).getKey() + "");
}
LogWriterUtils.getLogWriter()
.info(" Expected Size of Index is: " + expectedIndexSize + " Undefined size is: "
+ expectedUndefinedEntries + " And NULL size is: " + expectedNullEntries);
assertEquals(
"No of index keys NOT equals the no shown in statistics for index:" + index.getName(),
((RangeIndex) index).valueToEntriesMap.keySet().size(), stats.getNumberOfKeys());
}
assertEquals(
"No of index entries NOT equal the No of RegionEntries Basec on statistics for index:"
+ index.getName(),
(expectedIndexSize + expectedNullEntries), stats.getNumberOfValues());
assertEquals(
"No of index entries NOT equals the No of RegionEntries for index:" + index.getName(),
expectedIndexSize, actualSize);
GemFireCacheImpl.getInstance().getLogger().fine("Finishing the validation for region: "
+ region.getFullPath() + " and Index: " + index.getName());
}
private void validateOnPR(PartitionedRegion pr, PartitionedIndex ind) {
// Get index expression
String indexExpr = ind.getIndexedExpression();
int expectedIndexSize = 0;
int expectedNullEntries = 0;
int expectedUndefinedEntries = 0;
// Lets check if it contains a '.'
if (indexExpr.indexOf(".") != -1) {
indexExpr = indexExpr.substring(indexExpr.indexOf(".") + 1);
}
int actualValueSize = 0;
int actualKeySize = 0;
for (Object idx : ind.getBucketIndexes()) {
Index index = (Index) idx;
assertTrue("Bucket stats are different than PR stats for bucket: " + index.getRegion(),
index.getStatistics() == ind.getStatistics());
Region region = index.getRegion();
// do a get<indexExpr>() on each region value and verify if the
// evaluated index key is part of index and has RE as a reference to it
Collection<RegionEntry> entries = ((LocalRegion) region).entries.regionEntries();
for (RegionEntry internalEntry : entries) {
Object value = internalEntry.getValueInVM((LocalRegion) region);
if (value instanceof CachedDeserializable) {
value = ((CachedDeserializable) value).getDeserializedValue(region, internalEntry);
}
if (indexExpr.equals("ID")) {
// Compact Range Index
if (index instanceof CompactRangeIndex) {
// Ignore invalid values.
if (value != Token.INVALID && value != Token.TOMBSTONE) {
LogWriterUtils.getLogWriter().info("Portfolio: " + ((Portfolio) value));
Integer ID = ((Portfolio) value).getID();
assertTrue(
"Did not find index key for REgionEntry [key: " + internalEntry.getKey()
+ " , value: " + value + " ] in index: " + index.getName(),
((CompactRangeIndex) index).getIndexStorage().get(ID) == null ? false : true);
// Get Index value for the evaluated index key.
CloseableIterator<IndexStoreEntry> valuesForKeyIterator = null;
try {
valuesForKeyIterator = ((CompactRangeIndex) index).getIndexStorage().get(ID);
// Check if RegionEntry is present in Index for the key
// evaluated from
// region value.
while (valuesForKeyIterator.hasNext()) {
assertTrue(
"Did not find index value for REgionEntry [key: " + internalEntry.getKey()
+ " , value: " + value + " ] in index: " + index.getName()
+ " For index key: " + ID,
(((MemoryIndexStoreEntry) valuesForKeyIterator.next())
.getRegionEntry() == internalEntry));
}
} finally {
if (valuesForKeyIterator != null) {
valuesForKeyIterator.close();
}
}
if (ID != IndexManager.NULL) {
expectedIndexSize++;
} else {
expectedNullEntries++;
}
} else {
expectedUndefinedEntries++;
}
}
} else if (indexExpr.equals("secId")) {
if (index instanceof RangeIndex) {
// Ignore invalid values.
if (value != Token.INVALID && value != Token.TOMBSTONE) {
Collection<Position> positions = ((Portfolio) value).positions.values();
for (Position pos : positions) {
if (pos != null) {
LogWriterUtils.getLogWriter()
.info("Portfolio: " + ((Portfolio) value) + "Position: " + pos);
String secId = pos.secId;
assertTrue(
"Did not find index key for REgionEntry [key: " + internalEntry.getKey()
+ " , value: " + value + " ] in index: " + index.getName(),
((RangeIndex) index).valueToEntriesMap.containsKey(secId));
// Get Index value for the evaluated index key.
Object valuesForKey = ((RangeIndex) index).valueToEntriesMap.get(secId);
// Check if RegionEntry is present in Index for the key evaluated from
// region value.
if (!(valuesForKey instanceof RegionEntryToValuesMap)) {
assertTrue(
"Did not find index value for REgionEntry [key: " + internalEntry.getKey()
+ " , value: " + value + " ] in index: " + index.getName()
+ " For index key: " + secId,
((RegionEntry) valuesForKey == internalEntry));
} else {
assertTrue(
"Did not find index value for REgionEntry [key: " + internalEntry.getKey()
+ " , value: " + value + " ] in index: " + index.getName()
+ " For index key: " + secId,
(((RegionEntryToValuesMap) valuesForKey).containsEntry(internalEntry)));
}
if (secId != null) {
expectedIndexSize++;
} else {
expectedNullEntries++;
}
} else {
expectedUndefinedEntries++;
}
}
}
}
}
}
// Validate sizes for index map, null and undefined maps.
if (index instanceof CompactRangeIndex) {
CloseableIterator<IndexStoreEntry> iter = null;
try {
iter = ((CompactRangeIndex) index).getIndexStorage().iterator(null);
while (iter.hasNext()) {
Object value = iter.next().getDeserializedValue();
// getLogWriter().info(
// "Index Values : " + value);
actualValueSize++;
}
} finally {
if (iter != null) {
iter.close();
}
}
}
if (index instanceof RangeIndex) {
for (Object value : ((RangeIndex) index).valueToEntriesMap.values()) {
if (value instanceof RegionEntry) {
actualValueSize++;
} else {
actualValueSize += ((RegionEntryToValuesMap) value).getNumValues();
}
}
}
if (index instanceof CompactRangeIndex) {
actualKeySize += ((CompactRangeIndex) index).getIndexStorage().size();
} else {
actualKeySize += ((RangeIndex) index).valueToEntriesMap.keySet().size();
}
}
assertEquals(
"No of index entries NOT equals the No of RegionENtries NOT based on stats for index:"
+ ind.getName(),
expectedIndexSize, actualValueSize);
IndexStatistics stats = ind.getStatistics();
assertEquals(
"No of index entries NOT equals the No of RegionENtries based on statistics for index:"
+ ind.getName(),
(expectedIndexSize + expectedNullEntries), stats.getNumberOfValues());
GemFireCacheImpl.getInstance().getLogger().fine("Finishing the validation for region: "
+ pr.getFullPath() + " and Index: " + ind.getName());
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapreduce.counters;
import static org.apache.hadoop.thirdparty.com.google.common.base.Preconditions.checkNotNull;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.util.ResourceBundles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.thirdparty.com.google.common.collect.AbstractIterator;
import org.apache.hadoop.thirdparty.com.google.common.collect.Iterators;
/**
* An abstract class to provide common implementation for the framework
* counter group in both mapred and mapreduce packages.
*
* @param <T> type of the counter enum class
* @param <C> type of the counter
*/
@InterfaceAudience.Private
public abstract class FrameworkCounterGroup<T extends Enum<T>,
C extends Counter> implements CounterGroupBase<C> {
private static final Logger LOG =
LoggerFactory.getLogger(FrameworkCounterGroup.class);
private final Class<T> enumClass; // for Enum.valueOf
private final Object[] counters; // local casts are OK and save a class ref
private String displayName = null;
/**
* A counter facade for framework counters.
* Use old (which extends new) interface to make compatibility easier.
*/
@InterfaceAudience.Private
public static class FrameworkCounter<T extends Enum<T>> extends AbstractCounter {
final T key;
final String groupName;
private long value;
public FrameworkCounter(T ref, String groupName) {
key = ref;
this.groupName = groupName;
}
@Private
public T getKey() {
return key;
}
@Private
public String getGroupName() {
return groupName;
}
@Override
public String getName() {
return key.name();
}
@Override
public String getDisplayName() {
return ResourceBundles.getCounterName(groupName, getName(), getName());
}
@Override
public long getValue() {
return value;
}
@Override
public void setValue(long value) {
this.value = value;
}
@Override
public void increment(long incr) {
if (key.name().endsWith("_MAX")) {
value = value > incr ? value : incr;
} else {
value += incr;
}
}
@Override
public void write(DataOutput out) throws IOException {
assert false : "shouldn't be called";
}
@Override
public void readFields(DataInput in) throws IOException {
assert false : "shouldn't be called";
}
@Override
public Counter getUnderlyingCounter() {
return this;
}
}
@SuppressWarnings("unchecked")
public FrameworkCounterGroup(Class<T> enumClass) {
this.enumClass = enumClass;
T[] enums = enumClass.getEnumConstants();
counters = new Object[enums.length];
}
@Override
public String getName() {
return enumClass.getName();
}
@Override
public String getDisplayName() {
if (displayName == null) {
displayName = ResourceBundles.getCounterGroupName(getName(), getName());
}
return displayName;
}
@Override
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
private T valueOf(String name) {
return Enum.valueOf(enumClass, name);
}
@Override
public void addCounter(C counter) {
C ours = findCounter(counter.getName());
if (ours != null) {
ours.setValue(counter.getValue());
} else {
LOG.warn(counter.getName() + "is not a known counter.");
}
}
@Override
public C addCounter(String name, String displayName, long value) {
C counter = findCounter(name);
if (counter != null) {
counter.setValue(value);
} else {
LOG.warn(name + "is not a known counter.");
}
return counter;
}
@Override
public C findCounter(String counterName, String displayName) {
return findCounter(counterName);
}
@Override
public C findCounter(String counterName, boolean create) {
try {
return findCounter(valueOf(counterName));
}
catch (Exception e) {
if (create) throw new IllegalArgumentException(e);
return null;
}
}
@Override
public C findCounter(String counterName) {
try {
T enumValue = valueOf(counterName);
return findCounter(enumValue);
} catch (IllegalArgumentException e) {
LOG.warn(counterName + " is not a recognized counter.");
return null;
}
}
@SuppressWarnings("unchecked")
private C findCounter(T key) {
int i = key.ordinal();
if (counters[i] == null) {
counters[i] = newCounter(key);
}
return (C) counters[i];
}
/**
* Abstract factory method for new framework counter
* @param key for the enum value of a counter
* @return a new counter for the key
*/
protected abstract C newCounter(T key);
@Override
public int size() {
int n = 0;
for (int i = 0; i < counters.length; ++i) {
if (counters[i] != null) ++n;
}
return n;
}
@Override
@SuppressWarnings("rawtypes")
public void incrAllCounters(CounterGroupBase<C> other) {
if (checkNotNull(other, "other counter group")
instanceof FrameworkCounterGroup<?, ?>) {
for (Counter counter : other) {
C c = findCounter(((FrameworkCounter) counter).key.name());
if (c != null) {
c.increment(counter.getValue());
}
}
}
}
/**
* FrameworkGroup ::= #counter (key value)*
*/
@Override
@SuppressWarnings("unchecked")
public void write(DataOutput out) throws IOException {
WritableUtils.writeVInt(out, size());
for (int i = 0; i < counters.length; ++i) {
Counter counter = (C) counters[i];
if (counter != null) {
WritableUtils.writeVInt(out, i);
WritableUtils.writeVLong(out, counter.getValue());
}
}
}
@Override
public void readFields(DataInput in) throws IOException {
clear();
int len = WritableUtils.readVInt(in);
T[] enums = enumClass.getEnumConstants();
for (int i = 0; i < len; ++i) {
int ord = WritableUtils.readVInt(in);
Counter counter = newCounter(enums[ord]);
counter.setValue(WritableUtils.readVLong(in));
counters[ord] = counter;
}
}
private void clear() {
for (int i = 0; i < counters.length; ++i) {
counters[i] = null;
}
}
@Override
public Iterator<C> iterator() {
return new AbstractIterator<C>() {
int i = 0;
@Override
protected C computeNext() {
while (i < counters.length) {
@SuppressWarnings("unchecked")
C counter = (C) counters[i++];
if (counter != null) return counter;
}
return endOfData();
}
};
}
@Override
public boolean equals(Object genericRight) {
if (genericRight instanceof CounterGroupBase<?>) {
@SuppressWarnings("unchecked")
CounterGroupBase<C> right = (CounterGroupBase<C>) genericRight;
return Iterators.elementsEqual(iterator(), right.iterator());
}
return false;
}
@Override
public synchronized int hashCode() {
// need to be deep as counters is an array
return Arrays.deepHashCode(new Object[]{enumClass, counters, displayName});
}
}
| |
/*
* #%L
* ELK Reasoner
*
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2011 Department of Computer Science, University of Oxford
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.semanticweb.elk.util.collections;
import java.io.IOException;
import java.io.Writer;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* Some useful static methods for collections
*
* @author "Yevgeny Kazakov"
*
*/
public class Operations {
public static final Multimap<?, ?> EMPTY_MULTIMAP = new Multimap<Object, Object>() {
@Override
public boolean contains(Object key, Object value) {
return false;
}
@Override
public boolean add(Object key, Object value) {
throw new UnsupportedOperationException(
"The Empty multimap cannot be modified!");
}
@Override
public Collection<Object> get(Object key) {
return Collections.emptySet();
}
@Override
public boolean remove(Object key, Object value) {
return false;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public Set<Object> keySet() {
return Collections.emptySet();
}
@Override
public void clear() {
}
@Override
public Collection<Object> remove(Object key) {
return Collections.emptySet();
}
};
@SuppressWarnings("unchecked")
public static <S, T> Multimap<S, T> emptyMultimap() {
return (Multimap<S, T>) EMPTY_MULTIMAP;
}
public static <T> Iterable<T> concat(final Iterable<? extends T>... inputs) {
return concat(Arrays.asList(inputs));
}
public static <T> Iterable<T> singleton(final T element) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
boolean hasNext = true;
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public T next() {
hasNext = false;
return element;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
/**
* Concatenates several {@link Iterable}s into one
*
* @param inputs
* the {@link Iterable} of {@link Iterable}s to be concatenated
* @return {@link Iterable} consisting of all elements found in input
* {@link Iterable}s
*/
public static <T> Iterable<T> concat(
final Iterable<? extends Iterable<? extends T>> inputs) {
assert inputs != null;
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
Iterator<? extends Iterable<? extends T>> outer = inputs
.iterator();
Iterator<? extends T> inner;
boolean hasNext = advance();
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public T next() {
if (hasNext) {
T result = inner.next();
hasNext = advance();
return result;
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
boolean advance() {
while (true) {
if (inner != null && inner.hasNext())
return true;
if (outer.hasNext())
inner = outer.next().iterator();
else
return false;
}
}
};
}
};
}
/**
* Splits the input {@link Iterable} on batches with at most given number of
* elements.
*
* @param elements
* the {@link Iterable} to be split
* @param batchSize
* the maximal number of elements in batches
* @return a {@link Iterable} of batches containing elements from the input
* collection
* @see #concat(Iterable)
*/
public static <T> Iterable<ArrayList<T>> split(
final Iterable<? extends T> elements, final int batchSize) {
return new Iterable<ArrayList<T>>() {
@Override
public Iterator<ArrayList<T>> iterator() {
return new Iterator<ArrayList<T>>() {
final Iterator<? extends T> elementsIterator = elements
.iterator();
@Override
public boolean hasNext() {
return elementsIterator.hasNext();
}
@Override
public ArrayList<T> next() {
final ArrayList<T> nextBatch = new ArrayList<T>(
batchSize);
int count = 0;
while (count++ < batchSize
&& elementsIterator.hasNext()) {
nextBatch.add(elementsIterator.next());
}
return nextBatch;
}
@Override
public void remove() {
throw new UnsupportedOperationException(
"Deletion is not supported");
}
};
}
};
}
/**
* Splits the input {@link Collection} on batches with at most given number
* of elements.
*
* @param elements
* the {@link Collection} to be split
* @param batchSize
* the maximal number of elements in batches
* @return a {@link Collection} of batches containing elements from the
* input collection
*/
public static <T> Collection<ArrayList<T>> split(
final Collection<? extends T> elements, final int batchSize) {
return new AbstractCollection<ArrayList<T>>() {
@Override
public Iterator<ArrayList<T>> iterator() {
return split((Iterable<? extends T>) elements, batchSize)
.iterator();
}
@Override
public int size() {
// rounding up
return (elements.size() + batchSize - 1) / batchSize;
}
};
}
public static <T> Collection<T> getCollection(final Iterable<T> iterable,
final int size) {
return new AbstractCollection<T>() {
@Override
public Iterator<T> iterator() {
return iterable.iterator();
}
@Override
public int size() {
return size;
}
};
}
/**
* Boolean conditions over some type.
*
* @param <T>
* the type of elements which can be used with this condition
*
*/
public interface Condition<T> {
/**
* Checks if the condition holds for an element
*
* @param element
* the element for which to check the condition
* @return {@code true} if the condition holds for the element and
* otherwise {@code false}
*/
public boolean holds(T element);
}
/**
*
* @param input
* the input iterator
* @param condition
* the condition used for filtering
* @return the filtered iterator
*
*/
public static <T> Iterable<T> filter(final Iterable<T> input,
final Condition<? super T> condition) {
assert input != null;
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
Iterator<T> i = input.iterator();
T next;
boolean hasNext = advance();
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public T next() {
if (hasNext) {
T result = next;
hasNext = advance();
return result;
}
throw new NoSuchElementException();
}
@Override
public void remove() {
i.remove();
}
boolean advance() {
while (i.hasNext()) {
next = i.next();
if (condition.holds(next))
return true;
}
return false;
}
};
}
};
}
@SuppressWarnings("unchecked")
public static <T, S> Iterable<T> filter(final Iterable<S> input,
final Class<T> type) {
return (Iterable<T>) filter(input, new Condition<S>() {
@Override
public boolean holds(S element) {
return type.isInstance(element);
}
});
}
/**
* Returns read-only view of the given set consisting of the elements
* satisfying a given condition, if the number of such elements is known
*
* @param input
* the given set to be filtered
* @param condition
* the condition used for filtering the set. Must be consistent
* with equals() for T, that is: a.equals(b) must imply that
* holds(a) == holds(b)
* @param size
* the number of elements in the filtered set
* @return the set consisting of the elements of the input set satisfying
* the given condition
*/
public static <T> Set<T> filter(final Set<T> input,
final Condition<? super T> condition, final int size) {
return new Set<T>() {
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
if (!input.contains(o))
return false;
T elem = null;
try {
elem = (T) o;
} catch (ClassCastException cce) {
return false;
}
/*
* here's why the condition must be consistent with equals(): we
* check it on the passed element while we really need to check
* it on the element which is in the underlying set (and is
* equal to o according to equals()). However, as long as the
* condition is consistent, the result will be the same.
*/
return condition.holds(elem);
}
@Override
public Iterator<T> iterator() {
return filter(input, condition).iterator();
}
@Override
public Object[] toArray() {
Object[] result = new Object[size];
int i = 0;
for (Object o : filter(input, condition)) {
result[i++] = o;
}
return result;
}
@Override
public <S> S[] toArray(S[] a) {
throw new UnsupportedOperationException();
}
@Override
public boolean add(T e) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c) {
for (Object o : c) {
if (contains(o))
return false;
}
return true;
}
@Override
public boolean addAll(Collection<? extends T> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
};
}
/**
* Transformations of input values to output values
*
* @param <I>
* the type of the input of the transformation
* @param <O>
* the type of the output of the transformation
*/
public interface Transformation<I, O> {
/**
* Transforms the input element
*
* @param element
* the element to be transformed
* @return the result of the transformation
*/
public O transform(I element);
}
// TODO: get rid of Conditions in favour of transformations
/**
* Transforms elements using a given {@link Transformation} the output
* elements consist of the result of the transformation in the same order;
* if the transformation returns {@code null}, it is not included in the
* output
*
* @param input
* the input elements
* @param transformation
* the transformation for elements
* @return the transformed output elements
*
*/
public static <I, O> Iterable<O> map(final Iterable<I> input,
final Transformation<? super I, O> transformation) {
assert input != null;
return new Iterable<O>() {
@Override
public Iterator<O> iterator() {
return new Iterator<O>() {
Iterator<I> i = input.iterator();
O next;
boolean hasNext = advance();
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public O next() {
if (hasNext) {
O result = next;
hasNext = advance();
return result;
}
throw new NoSuchElementException();
}
@Override
public void remove() {
i.remove();
}
boolean advance() {
while (i.hasNext()) {
next = transformation.transform(i.next());
if (next != null)
return true;
}
return false;
}
};
}
};
}
/**
* Prints key-value entries present in the first {@link Multimap} but not in
* the second {@link Multimap} using the given {@link Writer} and prefixing
* all messages with a given prefix.
*
* @param first
* @param second
* @param writer
* @param prefix
* @throws IOException
*/
public static <K, V> void dumpDiff(Multimap<K, V> first,
Multimap<K, V> second, Writer writer, String prefix)
throws IOException {
for (K key : first.keySet()) {
Collection<V> firstValues = first.get(key);
Collection<V> secondValues = second.get(key);
dumpDiff(firstValues, secondValues, writer, prefix + key + "->");
}
}
/**
* Prints the elements present in the first {@link Collection} but not in
* the second {@link Collection} using the given {@link Writer} and
* prefixing all messages with a given prefix.
*
* @param first
* @param second
* @param writer
* @param prefix
* @throws IOException
*/
public static <T> void dumpDiff(Collection<T> first, Collection<T> second,
Writer writer, String prefix) throws IOException {
for (T element : first)
if (!second.contains(element))
writer.append(prefix + element + "\n");
}
/**
* A simple object that transforms objects of type I to objects of type O
*
* @author Pavel Klinov
*
* pavel.klinov@uni-ulm.de
*/
public interface Functor<I, O> {
public O apply(I element);
}
/**
* An extension of {@link Functor} which can do the reverse transformation
*
* @author Pavel Klinov
*
* pavel.klinov@uni-ulm.de
*/
public interface FunctorEx<I, O> extends Functor<I, O> {
/**
* The reason this method takes Objects rather than instances of O is
* because it's primarily used for an efficient implementation of
* {@link Set#contains(Object)}, which takes an Object
*
* @return Can return null if the transformation is not possible
*/
public I deapply(Object element);
}
/**
*
* @author Pavel Klinov
*
* pavel.klinov@uni-ulm.de
*/
private static class MapIterator<I, O> implements Iterator<O> {
private final Iterator<? extends I> iter_;
private final Functor<I, O> functor_;
MapIterator(Iterator<? extends I> iter, Functor<I, O> functor) {
iter_ = iter;
functor_ = functor;
}
@Override
public boolean hasNext() {
return iter_.hasNext();
}
@Override
public O next() {
return functor_.apply(iter_.next());
}
@Override
public void remove() {
iter_.remove();
}
}
/**
* A simple second-order map function
*
* @param input
* @param functor
* @return a set which contains the results of applying the functor to the
* elements in the input set
*/
public static <I, O> Set<O> map(final Set<? extends I> input,
final FunctorEx<I, O> functor) {
return new AbstractSet<O>() {
@Override
public Iterator<O> iterator() {
return new MapIterator<I, O>(input.iterator(), functor);
}
@Override
public boolean contains(Object o) {
I element = functor.deapply(o);
return element == null ? false : input.contains(element);
}
@Override
public int size() {
return input.size();
}
};
}
}
| |
/**
* Copyright 2014 Mike Hearn
* Copyright 2014 Andreas Schildbach
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bitcoinj.wallet;
import com.google.common.base.*;
import com.google.common.collect.*;
import com.google.protobuf.*;
import org.bitcoinj.core.*;
import org.bitcoinj.crypto.*;
import org.bitcoinj.script.*;
import org.bitcoinj.store.*;
import org.bitcoinj.utils.*;
import org.slf4j.*;
import org.spongycastle.crypto.params.*;
import javax.annotation.*;
import java.security.*;
import java.util.*;
import java.util.concurrent.*;
import static com.google.common.base.Preconditions.*;
/**
* <p>A KeyChainGroup is used by the {@link org.bitcoinj.core.Wallet} and
* manages: a {@link BasicKeyChain} object (which will normally be empty), and zero or more
* {@link DeterministicKeyChain}s. A deterministic key chain will be created lazily/on demand
* when a fresh or current key is requested, possibly being initialized from the private key bytes of the earliest non
* rotating key in the basic key chain if one is available, or from a fresh random seed if not.</p>
*
* <p>If a key rotation time is set, it may be necessary to add a new DeterministicKeyChain with a fresh seed
* and also preserve the old one, so funds can be swept from the rotating keys. In this case, there may be
* more than one deterministic chain. The latest chain is called the active chain and is where new keys are served
* from.</p>
*
* <p>The wallet delegates most key management tasks to this class. It is <b>not</b> thread safe and requires external
* locking, i.e. by the wallet lock. The group then in turn delegates most operations to the key chain objects,
* combining their responses together when necessary.</p>
*
* <p>Deterministic key chains have a concept of a lookahead size and threshold. Please see the discussion in the
* class docs for {@link DeterministicKeyChain} for more information on this topic.</p>
*/
public class KeyChainGroup implements KeyBag {
static {
// Init proper random number generator, as some old Android installations have bugs that make it unsecure.
if (Utils.isAndroidRuntime())
new LinuxSecureRandom();
}
private static final Logger log = LoggerFactory.getLogger(KeyChainGroup.class);
private BasicKeyChain basic;
private NetworkParameters params;
protected final LinkedList<DeterministicKeyChain> chains;
// currentKeys is used for normal, non-multisig/married wallets. currentAddresses is used when we're handing out
// P2SH addresses. They're mutually exclusive.
private final EnumMap<KeyChain.KeyPurpose, DeterministicKey> currentKeys;
private final EnumMap<KeyChain.KeyPurpose, Address> currentAddresses;
@Nullable private KeyCrypter keyCrypter;
private int lookaheadSize = -1;
private int lookaheadThreshold = -1;
/** Creates a keychain group with no basic chain, and a single, lazily created HD chain. */
public KeyChainGroup(NetworkParameters params) {
this(params, null, new ArrayList<DeterministicKeyChain>(1), null, null);
}
/** Creates a keychain group with no basic chain, and an HD chain initialized from the given seed. */
public KeyChainGroup(NetworkParameters params, DeterministicSeed seed) {
this(params, null, ImmutableList.of(new DeterministicKeyChain(seed)), null, null);
}
/**
* Creates a keychain group with no basic chain, and an HD chain that is watching the given watching key.
* This HAS to be an account key as returned by {@link DeterministicKeyChain#getWatchingKey()}.
*/
public KeyChainGroup(NetworkParameters params, DeterministicKey watchKey) {
this(params, null, ImmutableList.of(DeterministicKeyChain.watch(watchKey)), null, null);
}
/**
* Creates a keychain group with no basic chain, and an HD chain that is watching the given watching key which
* was assumed to be first used at the given UNIX time.
* This HAS to be an account key as returned by {@link DeterministicKeyChain#getWatchingKey()}.
*/
public KeyChainGroup(NetworkParameters params, DeterministicKey watchKey, long creationTimeSecondsSecs) {
this(params, null, ImmutableList.of(DeterministicKeyChain.watch(watchKey, creationTimeSecondsSecs)), null, null);
}
// Used for deserialization.
private KeyChainGroup(NetworkParameters params, @Nullable BasicKeyChain basicKeyChain, List<DeterministicKeyChain> chains,
@Nullable EnumMap<KeyChain.KeyPurpose, DeterministicKey> currentKeys, @Nullable KeyCrypter crypter) {
this.params = params;
this.basic = basicKeyChain == null ? new BasicKeyChain() : basicKeyChain;
this.chains = new LinkedList<DeterministicKeyChain>(checkNotNull(chains));
this.keyCrypter = crypter;
this.currentKeys = currentKeys == null
? new EnumMap<KeyChain.KeyPurpose, DeterministicKey>(KeyChain.KeyPurpose.class)
: currentKeys;
this.currentAddresses = new EnumMap<KeyChain.KeyPurpose, Address>(KeyChain.KeyPurpose.class);
maybeLookaheadScripts();
if (isMarried()) {
for (Map.Entry<KeyChain.KeyPurpose, DeterministicKey> entry : this.currentKeys.entrySet()) {
Address address = makeP2SHOutputScript(entry.getValue(), getActiveKeyChain()).getToAddress(params);
currentAddresses.put(entry.getKey(), address);
}
}
}
// This keeps married redeem data in sync with the number of keys issued
private void maybeLookaheadScripts() {
for (DeterministicKeyChain chain : chains) {
chain.maybeLookAheadScripts();
}
}
/** Adds a new HD chain to the chains list, and make it the default chain (from which keys are issued). */
public void createAndActivateNewHDChain() {
// We can't do auto upgrade here because we don't know the rotation time, if any.
final DeterministicKeyChain chain = new DeterministicKeyChain(new SecureRandom());
addAndActivateHDChain(chain);
}
/**
* Adds an HD chain to the chains list, and make it the default chain (from which keys are issued).
* Useful for adding a complex pre-configured keychain, such as a married wallet.
*/
public void addAndActivateHDChain(DeterministicKeyChain chain) {
log.info("Creating and activating a new HD chain: {}", chain);
for (ListenerRegistration<KeyChainEventListener> registration : basic.getListeners())
chain.addEventListener(registration.listener, registration.executor);
if (lookaheadSize >= 0)
chain.setLookaheadSize(lookaheadSize);
if (lookaheadThreshold >= 0)
chain.setLookaheadThreshold(lookaheadThreshold);
chains.add(chain);
}
/**
* Returns a key that hasn't been seen in a transaction yet, and which is suitable for displaying in a wallet
* user interface as "a convenient key to receive funds on" when the purpose parameter is
* {@link KeyChain.KeyPurpose#RECEIVE_FUNDS}. The returned key is stable until
* it's actually seen in a pending or confirmed transaction, at which point this method will start returning
* a different key (for each purpose independently).
* <p>This method is not supposed to be used for married keychains and will throw UnsupportedOperationException if
* the active chain is married.
* For married keychains use {@link #currentAddress(KeyChain.KeyPurpose)}
* to get a proper P2SH address</p>
*/
public DeterministicKey currentKey(KeyChain.KeyPurpose purpose) {
DeterministicKeyChain chain = getActiveKeyChain();
if (chain.isMarried()) {
throw new UnsupportedOperationException("Key is not suitable to receive coins for married keychains." +
" Use freshAddress to get P2SH address instead");
}
DeterministicKey current = currentKeys.get(purpose);
if (current == null) {
current = freshKey(purpose);
currentKeys.put(purpose, current);
}
return current;
}
/**
* Returns address for a {@link #currentKey(KeyChain.KeyPurpose)}
*/
public Address currentAddress(KeyChain.KeyPurpose purpose) {
DeterministicKeyChain chain = getActiveKeyChain();
if (chain.isMarried()) {
Address current = currentAddresses.get(purpose);
if (current == null) {
current = freshAddress(purpose);
currentAddresses.put(purpose, current);
}
return current;
} else {
return currentKey(purpose).toAddress(params);
}
}
/**
* Returns a key that has not been returned by this method before (fresh). You can think of this as being
* a newly created key, although the notion of "create" is not really valid for a
* {@link DeterministicKeyChain}. When the parameter is
* {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} the returned key is suitable for being put
* into a receive coins wizard type UI. You should use this when the user is definitely going to hand this key out
* to someone who wishes to send money.
* <p>This method is not supposed to be used for married keychains and will throw UnsupportedOperationException if
* the active chain is married.
* For married keychains use {@link #freshAddress(KeyChain.KeyPurpose)}
* to get a proper P2SH address</p>
*/
public DeterministicKey freshKey(KeyChain.KeyPurpose purpose) {
return freshKeys(purpose, 1).get(0);
}
/**
* Returns a key/s that have not been returned by this method before (fresh). You can think of this as being
* newly created key/s, although the notion of "create" is not really valid for a
* {@link DeterministicKeyChain}. When the parameter is
* {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} the returned key is suitable for being put
* into a receive coins wizard type UI. You should use this when the user is definitely going to hand this key out
* to someone who wishes to send money.
* <p>This method is not supposed to be used for married keychains and will throw UnsupportedOperationException if
* the active chain is married.
* For married keychains use {@link #freshAddress(KeyChain.KeyPurpose)}
* to get a proper P2SH address</p>
*/
public List<DeterministicKey> freshKeys(KeyChain.KeyPurpose purpose, int numberOfKeys) {
DeterministicKeyChain chain = getActiveKeyChain();
if (chain.isMarried()) {
throw new UnsupportedOperationException("Key is not suitable to receive coins for married keychains." +
" Use freshAddress to get P2SH address instead");
}
return chain.getKeys(purpose, numberOfKeys); // Always returns the next key along the key chain.
}
/**
* Returns address for a {@link #freshKey(KeyChain.KeyPurpose)}
*/
public Address freshAddress(KeyChain.KeyPurpose purpose) {
DeterministicKeyChain chain = getActiveKeyChain();
if (chain.isMarried()) {
Script outputScript = chain.freshOutputScript(purpose);
checkState(outputScript.isPayToScriptHash()); // Only handle P2SH for now
Address freshAddress = Address.fromP2SHScript(params, outputScript);
maybeLookaheadScripts();
currentAddresses.put(purpose, freshAddress);
return freshAddress;
} else {
return freshKey(purpose).toAddress(params);
}
}
/** Returns the key chain that's used for generation of fresh/current keys. This is always the newest HD chain. */
public DeterministicKeyChain getActiveKeyChain() {
if (chains.isEmpty()) {
if (basic.numKeys() > 0) {
log.warn("No HD chain present but random keys are: you probably deserialized an old wallet.");
// If called from the wallet (most likely) it'll try to upgrade us, as it knows the rotation time
// but not the password.
throw new DeterministicUpgradeRequiredException();
}
// Otherwise we have no HD chains and no random keys: we are a new born! So a random seed is fine.
createAndActivateNewHDChain();
}
return chains.get(chains.size() - 1);
}
/**
* Sets the lookahead buffer size for ALL deterministic key chains as well as for following key chains if any exist,
* see {@link DeterministicKeyChain#setLookaheadSize(int)}
* for more information.
*/
public void setLookaheadSize(int lookaheadSize) {
this.lookaheadSize = lookaheadSize;
for (DeterministicKeyChain chain : chains) {
chain.setLookaheadSize(lookaheadSize);
}
}
/**
* Gets the current lookahead size being used for ALL deterministic key chains. See
* {@link DeterministicKeyChain#setLookaheadSize(int)}
* for more information.
*/
public int getLookaheadSize() {
if (lookaheadSize == -1)
return getActiveKeyChain().getLookaheadSize();
else
return lookaheadSize;
}
/**
* Sets the lookahead buffer threshold for ALL deterministic key chains, see
* {@link DeterministicKeyChain#setLookaheadThreshold(int)}
* for more information.
*/
public void setLookaheadThreshold(int num) {
for (DeterministicKeyChain chain : chains) {
chain.setLookaheadThreshold(num);
}
}
/**
* Gets the current lookahead threshold being used for ALL deterministic key chains. See
* {@link DeterministicKeyChain#setLookaheadThreshold(int)}
* for more information.
*/
public int getLookaheadThreshold() {
if (lookaheadThreshold == -1)
return getActiveKeyChain().getLookaheadThreshold();
else
return lookaheadThreshold;
}
/** Imports the given keys into the basic chain, creating it if necessary. */
public int importKeys(List<ECKey> keys) {
return basic.importKeys(keys);
}
/** Imports the given keys into the basic chain, creating it if necessary. */
public int importKeys(ECKey... keys) {
return importKeys(ImmutableList.copyOf(keys));
}
public boolean checkPassword(CharSequence password) {
checkState(keyCrypter != null, "Not encrypted");
return checkAESKey(keyCrypter.deriveKey(password));
}
public boolean checkAESKey(KeyParameter aesKey) {
checkState(keyCrypter != null, "Not encrypted");
if (basic.numKeys() > 0)
return basic.checkAESKey(aesKey);
return getActiveKeyChain().checkAESKey(aesKey);
}
/** Imports the given unencrypted keys into the basic chain, encrypting them along the way with the given key. */
public int importKeysAndEncrypt(final List<ECKey> keys, KeyParameter aesKey) {
// TODO: Firstly check if the aes key can decrypt any of the existing keys successfully.
checkState(keyCrypter != null, "Not encrypted");
LinkedList<ECKey> encryptedKeys = Lists.newLinkedList();
for (ECKey key : keys) {
if (key.isEncrypted())
throw new IllegalArgumentException("Cannot provide already encrypted keys");
encryptedKeys.add(key.encrypt(keyCrypter, aesKey));
}
return importKeys(encryptedKeys);
}
@Nullable
public RedeemData findRedeemDataFromScriptHash(byte[] scriptHash) {
// Iterate in reverse order, since the active keychain is the one most likely to have the hit
for (Iterator<DeterministicKeyChain> iter = chains.descendingIterator() ; iter.hasNext() ; ) {
DeterministicKeyChain chain = iter.next();
RedeemData redeemData = chain.findRedeemDataByScriptHash(ByteString.copyFrom(scriptHash));
if (redeemData != null)
return redeemData;
}
return null;
}
public void markP2SHAddressAsUsed(Address address) {
checkState(isMarried());
checkArgument(address.isP2SHAddress());
RedeemData data = findRedeemDataFromScriptHash(address.getHash160());
if (data == null)
return; // Not our P2SH address.
for (ECKey key : data.keys) {
for (DeterministicKeyChain chain : chains) {
DeterministicKey k = chain.findKeyFromPubKey(key.getPubKey());
if (k == null) continue;
chain.markKeyAsUsed(k);
maybeMarkCurrentAddressAsUsed(address);
}
}
}
@Nullable
@Override
public ECKey findKeyFromPubHash(byte[] pubkeyHash) {
ECKey result;
if ((result = basic.findKeyFromPubHash(pubkeyHash)) != null)
return result;
for (DeterministicKeyChain chain : chains) {
if ((result = chain.findKeyFromPubHash(pubkeyHash)) != null)
return result;
}
return null;
}
/**
* Mark the DeterministicKeys as used, if they match the pubkeyHash
* See {@link DeterministicKeyChain#markKeyAsUsed(DeterministicKey)} for more info on this.
*/
public void markPubKeyHashAsUsed(byte[] pubkeyHash) {
for (DeterministicKeyChain chain : chains) {
DeterministicKey key;
if ((key = chain.markPubHashAsUsed(pubkeyHash)) != null) {
maybeMarkCurrentKeyAsUsed(key);
return;
}
}
}
/** If the given P2SH address is "current", advance it to a new one. */
private void maybeMarkCurrentAddressAsUsed(Address address) {
checkState(isMarried());
checkArgument(address.isP2SHAddress());
for (Map.Entry<KeyChain.KeyPurpose, Address> entry : currentAddresses.entrySet()) {
if (entry.getValue() != null && entry.getValue().equals(address)) {
log.info("Marking P2SH address as used: {}", address);
currentAddresses.put(entry.getKey(), freshAddress(entry.getKey()));
return;
}
}
}
/** If the given key is "current", advance the current key to a new one. */
private void maybeMarkCurrentKeyAsUsed(DeterministicKey key) {
// It's OK for currentKeys to be empty here: it means we're a married wallet and the key may be a part of a
// rotating chain.
for (Map.Entry<KeyChain.KeyPurpose, DeterministicKey> entry : currentKeys.entrySet()) {
if (entry.getValue() != null && entry.getValue().equals(key)) {
log.info("Marking key as used: {}", key);
currentKeys.put(entry.getKey(), freshKey(entry.getKey()));
return;
}
}
}
public boolean hasKey(ECKey key) {
if (basic.hasKey(key))
return true;
for (DeterministicKeyChain chain : chains)
if (chain.hasKey(key))
return true;
return false;
}
@Nullable
@Override
public ECKey findKeyFromPubKey(byte[] pubkey) {
ECKey result;
if ((result = basic.findKeyFromPubKey(pubkey)) != null)
return result;
for (DeterministicKeyChain chain : chains) {
if ((result = chain.findKeyFromPubKey(pubkey)) != null)
return result;
}
return null;
}
/**
* Mark the DeterministicKeys as used, if they match the pubkey
* See {@link DeterministicKeyChain#markKeyAsUsed(DeterministicKey)} for more info on this.
*/
public void markPubKeyAsUsed(byte[] pubkey) {
for (DeterministicKeyChain chain : chains) {
DeterministicKey key;
if ((key = chain.markPubKeyAsUsed(pubkey)) != null) {
maybeMarkCurrentKeyAsUsed(key);
return;
}
}
}
/** Returns the number of keys managed by this group, including the lookahead buffers. */
public int numKeys() {
int result = basic.numKeys();
for (DeterministicKeyChain chain : chains)
result += chain.numKeys();
return result;
}
/**
* Removes a key that was imported into the basic key chain. You cannot remove deterministic keys.
* @throws java.lang.IllegalArgumentException if the key is deterministic.
*/
public boolean removeImportedKey(ECKey key) {
checkNotNull(key);
checkArgument(!(key instanceof DeterministicKey));
return basic.removeKey(key);
}
/**
* Whether the active keychain is married. A keychain is married when it vends P2SH addresses
* from multiple keychains in a multisig relationship.
* @see org.bitcoinj.wallet.MarriedKeyChain
*/
public boolean isMarried() {
return !chains.isEmpty() && getActiveKeyChain().isMarried();
}
/**
* Encrypt the keys in the group using the KeyCrypter and the AES key. A good default KeyCrypter to use is
* {@link org.bitcoinj.crypto.KeyCrypterScrypt}.
*
* @throws org.bitcoinj.crypto.KeyCrypterException Thrown if the wallet encryption fails for some reason,
* leaving the group unchanged.
* @throws DeterministicUpgradeRequiredException Thrown if there are random keys but no HD chain.
*/
public void encrypt(KeyCrypter keyCrypter, KeyParameter aesKey) {
checkNotNull(keyCrypter);
checkNotNull(aesKey);
// This code must be exception safe.
BasicKeyChain newBasic = basic.toEncrypted(keyCrypter, aesKey);
List<DeterministicKeyChain> newChains = new ArrayList<DeterministicKeyChain>(chains.size());
if (chains.isEmpty() && basic.numKeys() == 0) {
// No HD chains and no random keys: encrypting an entirely empty keychain group. But we can't do that, we
// must have something to encrypt: so instantiate a new HD chain here.
createAndActivateNewHDChain();
}
for (DeterministicKeyChain chain : chains)
newChains.add(chain.toEncrypted(keyCrypter, aesKey));
this.keyCrypter = keyCrypter;
basic = newBasic;
chains.clear();
chains.addAll(newChains);
}
/**
* Decrypt the keys in the group using the previously given key crypter and the AES key. A good default
* KeyCrypter to use is {@link org.bitcoinj.crypto.KeyCrypterScrypt}.
*
* @throws org.bitcoinj.crypto.KeyCrypterException Thrown if the wallet decryption fails for some reason, leaving the group unchanged.
*/
public void decrypt(KeyParameter aesKey) {
// This code must be exception safe.
checkNotNull(aesKey);
BasicKeyChain newBasic = basic.toDecrypted(aesKey);
List<DeterministicKeyChain> newChains = new ArrayList<DeterministicKeyChain>(chains.size());
for (DeterministicKeyChain chain : chains)
newChains.add(chain.toDecrypted(aesKey));
this.keyCrypter = null;
basic = newBasic;
chains.clear();
chains.addAll(newChains);
}
/** Returns true if the group is encrypted. */
public boolean isEncrypted() {
return keyCrypter != null;
}
/**
* Returns whether this chain has only watching keys (unencrypted keys with no private part). Mixed chains are
* forbidden.
*
* @throws IllegalStateException if there are no keys, or if there is a mix between watching and non-watching keys.
*/
public boolean isWatching() {
BasicKeyChain.State basicState = basic.isWatching();
BasicKeyChain.State activeState = BasicKeyChain.State.EMPTY;
if (!chains.isEmpty()) {
if (getActiveKeyChain().isWatching())
activeState = BasicKeyChain.State.WATCHING;
else
activeState = BasicKeyChain.State.REGULAR;
}
if (basicState == BasicKeyChain.State.EMPTY) {
if (activeState == BasicKeyChain.State.EMPTY)
throw new IllegalStateException("Empty key chain group: cannot answer isWatching() query");
return activeState == BasicKeyChain.State.WATCHING;
} else if (activeState == BasicKeyChain.State.EMPTY)
return basicState == BasicKeyChain.State.WATCHING;
else {
if (activeState != basicState)
throw new IllegalStateException("Mix of watching and non-watching keys in wallet");
return activeState == BasicKeyChain.State.WATCHING;
}
}
/** Returns the key crypter or null if the group is not encrypted. */
@Nullable public KeyCrypter getKeyCrypter() { return keyCrypter; }
/**
* Returns a list of the non-deterministic keys that have been imported into the wallet, or the empty list if none.
*/
public List<ECKey> getImportedKeys() {
return basic.getKeys();
}
public long getEarliestKeyCreationTime() {
long time = basic.getEarliestKeyCreationTime(); // Long.MAX_VALUE if empty.
for (DeterministicKeyChain chain : chains)
time = Math.min(time, chain.getEarliestKeyCreationTime());
return time;
}
public int getBloomFilterElementCount() {
int result = basic.numBloomFilterEntries();
for (DeterministicKeyChain chain : chains) {
result += chain.numBloomFilterEntries();
}
return result;
}
public BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak) {
BloomFilter filter = new BloomFilter(size, falsePositiveRate, nTweak);
if (basic.numKeys() > 0)
filter.merge(basic.getFilter(size, falsePositiveRate, nTweak));
for (DeterministicKeyChain chain : chains) {
filter.merge(chain.getFilter(size, falsePositiveRate, nTweak));
}
return filter;
}
/** {@inheritDoc} */
public boolean isRequiringUpdateAllBloomFilter() {
throw new UnsupportedOperationException(); // Unused.
}
private Script makeP2SHOutputScript(DeterministicKey followedKey, DeterministicKeyChain chain) {
return ScriptBuilder.createP2SHOutputScript(chain.getRedeemData(followedKey).redeemScript);
}
/** Adds a listener for events that are run when keys are added, on the user thread. */
public void addEventListener(KeyChainEventListener listener) {
addEventListener(listener, Threading.USER_THREAD);
}
/** Adds a listener for events that are run when keys are added, on the given executor. */
public void addEventListener(KeyChainEventListener listener, Executor executor) {
checkNotNull(listener);
checkNotNull(executor);
basic.addEventListener(listener, executor);
for (DeterministicKeyChain chain : chains)
chain.addEventListener(listener, executor);
}
/** Removes a listener for events that are run when keys are added. */
public boolean removeEventListener(KeyChainEventListener listener) {
checkNotNull(listener);
for (DeterministicKeyChain chain : chains)
chain.removeEventListener(listener);
return basic.removeEventListener(listener);
}
/** Returns a list of key protobufs obtained by merging the chains. */
public List<Protos.Key> serializeToProtobuf() {
List<Protos.Key> result;
if (basic != null)
result = basic.serializeToProtobuf();
else
result = Lists.newArrayList();
for (DeterministicKeyChain chain : chains) {
List<Protos.Key> protos = chain.serializeToProtobuf();
result.addAll(protos);
}
return result;
}
static KeyChainGroup fromProtobufUnencrypted(NetworkParameters params, List<Protos.Key> keys) throws UnreadableWalletException {
return fromProtobufUnencrypted(params, keys, new DefaultKeyChainFactory());
}
public static KeyChainGroup fromProtobufUnencrypted(NetworkParameters params, List<Protos.Key> keys, KeyChainFactory factory) throws UnreadableWalletException {
BasicKeyChain basicKeyChain = BasicKeyChain.fromProtobufUnencrypted(keys);
List<DeterministicKeyChain> chains = DeterministicKeyChain.fromProtobuf(keys, null, factory);
EnumMap<KeyChain.KeyPurpose, DeterministicKey> currentKeys = null;
if (!chains.isEmpty())
currentKeys = createCurrentKeysMap(chains);
extractFollowingKeychains(chains);
return new KeyChainGroup(params, basicKeyChain, chains, currentKeys, null);
}
static KeyChainGroup fromProtobufEncrypted(NetworkParameters params, List<Protos.Key> keys, KeyCrypter crypter) throws UnreadableWalletException {
return fromProtobufEncrypted(params, keys, crypter, new DefaultKeyChainFactory());
}
public static KeyChainGroup fromProtobufEncrypted(NetworkParameters params, List<Protos.Key> keys, KeyCrypter crypter, KeyChainFactory factory) throws UnreadableWalletException {
checkNotNull(crypter);
BasicKeyChain basicKeyChain = BasicKeyChain.fromProtobufEncrypted(keys, crypter);
List<DeterministicKeyChain> chains = DeterministicKeyChain.fromProtobuf(keys, crypter, factory);
EnumMap<KeyChain.KeyPurpose, DeterministicKey> currentKeys = null;
if (!chains.isEmpty())
currentKeys = createCurrentKeysMap(chains);
extractFollowingKeychains(chains);
return new KeyChainGroup(params, basicKeyChain, chains, currentKeys, crypter);
}
/**
* If the key chain contains only random keys and no deterministic key chains, this method will create a chain
* based on the oldest non-rotating private key (i.e. the seed is derived from the old wallet).
*
* @param keyRotationTimeSecs If non-zero, UNIX time for which keys created before this are assumed to be
* compromised or weak, those keys will not be used for deterministic upgrade.
* @param aesKey If non-null, the encryption key the keychain is encrypted under. If the keychain is encrypted
* and this is not supplied, an exception is thrown letting you know you should ask the user for
* their password, turn it into a key, and then try again.
* @throws java.lang.IllegalStateException if there is already a deterministic key chain present or if there are
* no random keys (i.e. this is not an upgrade scenario), or if aesKey is
* provided but the wallet is not encrypted.
* @throws java.lang.IllegalArgumentException if the rotation time specified excludes all keys.
* @throws DeterministicUpgradeRequiresPassword if the key chain group is encrypted
* and you should provide the users encryption key.
* @return the DeterministicKeyChain that was created by the upgrade.
*/
public DeterministicKeyChain upgradeToDeterministic(long keyRotationTimeSecs, @Nullable KeyParameter aesKey) throws DeterministicUpgradeRequiresPassword, AllRandomKeysRotating {
checkState(basic.numKeys() > 0);
checkArgument(keyRotationTimeSecs >= 0);
// Subtract one because the key rotation time might have been set to the creation time of the first known good
// key, in which case, that's the one we want to find.
ECKey keyToUse = basic.findOldestKeyAfter(keyRotationTimeSecs - 1);
if (keyToUse == null)
throw new AllRandomKeysRotating();
if (keyToUse.isEncrypted()) {
if (aesKey == null) {
// We can't auto upgrade because we don't know the users password at this point. We throw an
// exception so the calling code knows to abort the load and ask the user for their password, they can
// then try loading the wallet again passing in the AES key.
//
// There are a few different approaches we could have used here, but they all suck. The most obvious
// is to try and be as lazy as possible, running in the old random-wallet mode until the user enters
// their password for some other reason and doing the upgrade then. But this could result in strange
// and unexpected UI flows for the user, as well as complicating the job of wallet developers who then
// have to support both "old" and "new" UI modes simultaneously, switching them on the fly. Given that
// this is a one-off transition, it seems more reasonable to just ask the user for their password
// on startup, and then the wallet app can have all the widgets for accessing seed words etc active
// all the time.
throw new DeterministicUpgradeRequiresPassword();
}
keyToUse = keyToUse.decrypt(aesKey);
} else if (aesKey != null) {
throw new IllegalStateException("AES Key was provided but wallet is not encrypted.");
}
if (chains.isEmpty()) {
log.info("Auto-upgrading pre-HD wallet to HD!");
} else {
log.info("Wallet with existing HD chain is being re-upgraded due to change in key rotation time.");
}
log.info("Instantiating new HD chain using oldest non-rotating private key (address: {})", keyToUse.toAddress(params));
byte[] entropy = checkNotNull(keyToUse.getSecretBytes());
// Private keys should be at least 128 bits long.
checkState(entropy.length >= DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS / 8);
// We reduce the entropy here to 128 bits because people like to write their seeds down on paper, and 128
// bits should be sufficient forever unless the laws of the universe change or ECC is broken; in either case
// we all have bigger problems.
entropy = Arrays.copyOfRange(entropy, 0, DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS / 8); // final argument is exclusive range.
checkState(entropy.length == DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS / 8);
String passphrase = ""; // FIXME allow non-empty passphrase
DeterministicKeyChain chain = new DeterministicKeyChain(entropy, passphrase, keyToUse.getCreationTimeSeconds());
if (aesKey != null) {
chain = chain.toEncrypted(checkNotNull(basic.getKeyCrypter()), aesKey);
}
chains.add(chain);
return chain;
}
/** Returns true if the group contains random keys but no HD chains. */
public boolean isDeterministicUpgradeRequired() {
return basic.numKeys() > 0 && chains.isEmpty();
}
private static EnumMap<KeyChain.KeyPurpose, DeterministicKey> createCurrentKeysMap(List<DeterministicKeyChain> chains) {
DeterministicKeyChain activeChain = chains.get(chains.size() - 1);
EnumMap<KeyChain.KeyPurpose, DeterministicKey> currentKeys = new EnumMap<KeyChain.KeyPurpose, DeterministicKey>(KeyChain.KeyPurpose.class);
// assuming that only RECEIVE and CHANGE keys are being used at the moment, we will treat latest issued external key
// as current RECEIVE key and latest issued internal key as CHANGE key. This should be changed as soon as other
// kinds of KeyPurpose are introduced.
if (activeChain.getIssuedExternalKeys() > 0) {
DeterministicKey currentExternalKey = activeChain.getKeyByPath(
HDUtils.append(
HDUtils.concat(activeChain.getAccountPath(), DeterministicKeyChain.EXTERNAL_SUBPATH),
new ChildNumber(activeChain.getIssuedExternalKeys() - 1)));
currentKeys.put(KeyChain.KeyPurpose.RECEIVE_FUNDS, currentExternalKey);
}
if (activeChain.getIssuedInternalKeys() > 0) {
DeterministicKey currentInternalKey = activeChain.getKeyByPath(
HDUtils.append(
HDUtils.concat(activeChain.getAccountPath(), DeterministicKeyChain.INTERNAL_SUBPATH),
new ChildNumber(activeChain.getIssuedInternalKeys() - 1)));
currentKeys.put(KeyChain.KeyPurpose.CHANGE, currentInternalKey);
}
return currentKeys;
}
private static void extractFollowingKeychains(List<DeterministicKeyChain> chains) {
// look for following key chains and map them to the watch keys of followed keychains
List<DeterministicKeyChain> followingChains = Lists.newArrayList();
for (Iterator<DeterministicKeyChain> it = chains.iterator(); it.hasNext(); ) {
DeterministicKeyChain chain = it.next();
if (chain.isFollowing()) {
followingChains.add(chain);
it.remove();
} else if (!followingChains.isEmpty()) {
if (!(chain instanceof MarriedKeyChain))
throw new IllegalStateException();
((MarriedKeyChain)chain).setFollowingKeyChains(followingChains);
followingChains = Lists.newArrayList();
}
}
}
public String toString(boolean includePrivateKeys) {
final StringBuilder builder = new StringBuilder();
if (basic != null) {
List<ECKey> keys = basic.getKeys();
Collections.sort(keys, ECKey.AGE_COMPARATOR);
for (ECKey key : keys)
key.formatKeyWithAddress(includePrivateKeys, builder, params);
}
List<String> chainStrs = Lists.newLinkedList();
for (DeterministicKeyChain chain : chains) {
chainStrs.add(chain.toString(includePrivateKeys, params));
}
builder.append(Joiner.on(String.format("%n")).join(chainStrs));
return builder.toString();
}
/** Returns a copy of the current list of chains. */
public List<DeterministicKeyChain> getDeterministicKeyChains() {
return new ArrayList<DeterministicKeyChain>(chains);
}
/**
* Returns a counter that increases (by an arbitrary amount) each time new keys have been calculated due to
* lookahead and thus the Bloom filter that was previously calculated has become stale.
*/
public int getCombinedKeyLookaheadEpochs() {
int epoch = 0;
for (DeterministicKeyChain chain : chains)
epoch += chain.getKeyLookaheadEpoch();
return epoch;
}
}
| |
/* Copyright (C) 2013-2022 TU Dortmund
* This file is part of AutomataLib, http://www.automatalib.net/.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.automatalib.util.automata.random;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Random;
import com.google.common.collect.Maps;
import net.automatalib.automata.Automaton;
import net.automatalib.automata.MutableDeterministic;
import net.automatalib.automata.fsa.DFA;
import net.automatalib.automata.fsa.impl.compact.CompactDFA;
import net.automatalib.automata.spa.SPA;
import net.automatalib.automata.spa.StackSPA;
import net.automatalib.automata.transducers.impl.compact.CompactMealy;
import net.automatalib.automata.transducers.impl.compact.CompactMoore;
import net.automatalib.automata.vpda.DefaultOneSEVPA;
import net.automatalib.automata.vpda.Location;
import net.automatalib.util.automata.Automata;
import net.automatalib.util.automata.fsa.DFAs;
import net.automatalib.util.automata.spa.SPAUtil;
import net.automatalib.util.minimizer.OneSEVPAMinimizer;
import net.automatalib.words.Alphabet;
import net.automatalib.words.SPAAlphabet;
import net.automatalib.words.VPDAlphabet;
import org.checkerframework.checker.index.qual.NonNegative;
public final class RandomAutomata {
private RandomAutomata() {
// prevent instantiation
}
/**
* Randomly generates an initially connected DFA (ICDFA), i.e., a DFA where all states are reachable from the
* initial state.
*
* @param rand
* the randomness source
* @param numStates
* the number of states of the generated automaton
* @param inputs
* the input alphabet
* @param minimize
* determines whether or not the DFA will be minimized before being returned. Note that if {@code true} is
* passed for this parameter, the resulting automaton might have a {@link Automaton#size() size} less than
* {@code numStates}
*
* @return a randomly generated ICDFA
*/
@SuppressWarnings("nullness") // false positive?
public static <I> CompactDFA<I> randomICDFA(Random rand,
@NonNegative int numStates,
Alphabet<I> inputs,
boolean minimize) {
final CompactDFA<I> dfa =
new RandomICAutomatonGenerator<Boolean, Void>().withStateProperties(Random::nextBoolean)
.generateICDeterministicAutomaton(numStates,
inputs,
new CompactDFA.Creator<>(),
rand);
return minimize ? DFAs.minimize(dfa) : dfa;
}
public static <I> DefaultOneSEVPA<I> randomOneSEVPA(final Random r,
final int locCount,
final VPDAlphabet<I> alphabet,
final double acceptanceProb,
final double initialRetTransProb,
final boolean minimize) {
final DefaultOneSEVPA<I> result = new DefaultOneSEVPA<>(alphabet, locCount);
result.addInitialLocation(r.nextDouble() < initialRetTransProb);
for (int i = 0; i < locCount - 1; i++) {
if (alphabet.getNumInternals() == 0 || r.nextDouble() < initialRetTransProb) {
I retSym;
Location srcLoc;
int stackSym;
do {
retSym = alphabet.getReturnSymbol(r.nextInt(alphabet.getNumReturns()));
srcLoc = result.getLocation(r.nextInt(result.size()));
I callSym = alphabet.getCallSymbol(r.nextInt(alphabet.getNumCalls()));
final Location stackLoc = result.getLocation(r.nextInt(result.size()));
stackSym = result.encodeStackSym(stackLoc, callSym);
} while (result.getReturnSuccessor(srcLoc, retSym, stackSym) != null);
final Location newLoc = result.addLocation(r.nextDouble() < acceptanceProb);
result.setReturnSuccessor(srcLoc, retSym, stackSym, newLoc);
} else {
I intSym;
Location srcLoc;
do {
intSym = alphabet.getInternalSymbol(r.nextInt(alphabet.getNumInternals()));
srcLoc = result.getLocation(r.nextInt(result.size()));
} while (result.getInternalSuccessor(srcLoc, intSym) != null);
final Location newLoc = result.addLocation(r.nextDouble() < acceptanceProb);
result.setInternalSuccessor(srcLoc, intSym, newLoc);
}
}
for (Location loc : result.getLocations()) {
for (I intSym : alphabet.getInternalAlphabet()) {
if (result.getInternalSuccessor(loc, intSym) == null) {
final Location tgtLoc = result.getLocation(r.nextInt(result.size()));
result.setInternalSuccessor(loc, intSym, tgtLoc);
}
}
for (I callSym : alphabet.getCallAlphabet()) {
for (Location stackLoc : result.getLocations()) {
int stackSym = result.encodeStackSym(stackLoc, callSym);
for (I retSym : alphabet.getReturnAlphabet()) {
if (result.getReturnSuccessor(loc, retSym, stackSym) == null) {
final Location tgtLoc = result.getLocation(r.nextInt(result.size()));
result.setReturnSuccessor(loc, retSym, stackSym, tgtLoc);
}
}
}
}
}
if (minimize) {
return OneSEVPAMinimizer.minimize(result, alphabet);
}
return result;
}
public static <I> SPA<?, I> randomSPA(Random random, SPAAlphabet<I> alphabet, int procedureSize) {
return randomSPA(random, alphabet, procedureSize, true);
}
public static <I> SPA<?, I> randomSPA(Random random, SPAAlphabet<I> alphabet, int procedureSize, boolean minimize) {
final Map<I, DFA<?, I>> dfas = Maps.newHashMapWithExpectedSize(alphabet.getNumCalls());
final Alphabet<I> proceduralAlphabet = alphabet.getProceduralAlphabet();
for (final I procedure : alphabet.getCallAlphabet()) {
final DFA<?, I> dfa = RandomAutomata.randomDFA(random, procedureSize, proceduralAlphabet, minimize);
dfas.put(procedure, dfa);
}
return new StackSPA<>(alphabet, alphabet.getCallSymbol(random.nextInt(alphabet.getNumCalls())), dfas);
}
public static <I> SPA<?, I> randomRedundancyFreeSPA(Random random, SPAAlphabet<I> alphabet, int procedureSize) {
return randomRedundancyFreeSPA(random, alphabet, procedureSize, true);
}
public static <I> SPA<?, I> randomRedundancyFreeSPA(Random random,
SPAAlphabet<I> alphabet,
int procedureSize,
boolean minimize) {
SPA<?, I> result;
do {
result = randomSPA(random, alphabet, procedureSize, minimize);
} while (!SPAUtil.isRedundancyFree(result));
return result;
}
public static <S, I, T, SP, TP, A extends MutableDeterministic<S, I, T, SP, TP>> A randomDeterministic(Random rand,
@NonNegative int numStates,
Collection<? extends I> inputs,
Collection<? extends SP> stateProps,
Collection<? extends TP> transProps,
A out) {
return randomDeterministic(rand, numStates, inputs, stateProps, transProps, out, true);
}
public static <S, I, T, SP, TP, A extends MutableDeterministic<S, I, T, SP, TP>> A randomDeterministic(Random rand,
@NonNegative int numStates,
Collection<? extends I> inputs,
Collection<? extends SP> stateProps,
Collection<? extends TP> transProps,
A out,
boolean minimize) {
RandomDeterministicAutomatonGenerator<S, I, T, SP, TP, A> gen =
new RandomDeterministicAutomatonGenerator<>(rand, inputs, stateProps, transProps, out);
gen.addStates(numStates);
gen.addTransitions();
gen.chooseInitial();
if (minimize) {
Automata.invasiveMinimize(out, inputs);
}
return out;
}
public static <I> CompactDFA<I> randomDFA(Random rand,
@NonNegative int numStates,
Alphabet<I> inputs,
boolean minimize) {
return randomDeterministic(rand,
numStates,
inputs,
DFA.STATE_PROPERTIES,
DFA.TRANSITION_PROPERTIES,
new CompactDFA<>(inputs),
minimize);
}
public static <I> CompactDFA<I> randomDFA(Random rand, @NonNegative int numStates, Alphabet<I> inputs) {
return randomDFA(rand, numStates, inputs, true);
}
public static <I, O> CompactMealy<I, O> randomMealy(Random rand,
@NonNegative int numStates,
Alphabet<I> inputs,
Collection<? extends O> outputs,
boolean minimize) {
return randomDeterministic(rand,
numStates,
inputs,
Collections.singleton(null),
outputs,
new CompactMealy<>(inputs),
minimize);
}
public static <I, O> CompactMealy<I, O> randomMealy(Random rand,
@NonNegative int numStates,
Alphabet<I> inputs,
Collection<? extends O> outputs) {
return randomMealy(rand, numStates, inputs, outputs, true);
}
public static <I, O> CompactMoore<I, O> randomMoore(Random rand,
@NonNegative int numStates,
Alphabet<I> inputs,
Collection<? extends O> outputs,
boolean minimize) {
return randomDeterministic(rand,
numStates,
inputs,
outputs,
Collections.singleton(null),
new CompactMoore<>(inputs),
minimize);
}
public static <I, O> CompactMoore<I, O> randomMoore(Random rand,
@NonNegative int numStates,
Alphabet<I> inputs,
Collection<? extends O> outputs) {
return randomMoore(rand, numStates, inputs, outputs, true);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.openaz.xacml.pdp.policy.expressions;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.openaz.xacml.api.Attribute;
import org.apache.openaz.xacml.api.AttributeValue;
import org.apache.openaz.xacml.api.DataType;
import org.apache.openaz.xacml.api.DataTypeException;
import org.apache.openaz.xacml.api.DataTypeFactory;
import org.apache.openaz.xacml.api.Identifier;
import org.apache.openaz.xacml.api.Request;
import org.apache.openaz.xacml.api.RequestAttributes;
import org.apache.openaz.xacml.api.StatusCode;
import org.apache.openaz.xacml.pdp.eval.EvaluationContext;
import org.apache.openaz.xacml.pdp.eval.EvaluationException;
import org.apache.openaz.xacml.pdp.policy.Bag;
import org.apache.openaz.xacml.pdp.policy.ExpressionResult;
import org.apache.openaz.xacml.pdp.policy.PolicyDefaults;
import org.apache.openaz.xacml.std.StdStatus;
import org.apache.openaz.xacml.std.StdStatusCode;
import org.apache.openaz.xacml.std.datatypes.DataTypes;
import org.apache.openaz.xacml.std.datatypes.NodeNamespaceContext;
import org.apache.openaz.xacml.std.datatypes.XPathExpressionWrapper;
import org.apache.openaz.xacml.std.dom.DOMStructureException;
import org.apache.openaz.xacml.std.dom.DOMUtil;
import org.apache.openaz.xacml.util.FactoryException;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* AttributeSelector extends {@link org.apache.openaz.xacml.pdp.policy.expressions.AttributeRetrievalBase}
* to implement the XACML AttributeSelector element.
*/
public class AttributeSelector extends AttributeRetrievalBase {
private Identifier contextSelectorId;
private String path;
@SuppressWarnings("unused")
private DataType<?> dataType;
protected DataType<?> getDataType() {
Identifier dataTypeIdThis = this.getDataTypeId();
if (dataTypeIdThis == null) {
return null;
} else {
DataTypeFactory dataTypeFactory = null;
try {
dataTypeFactory = DataTypeFactory.newInstance();
if (dataTypeFactory == null) {
return null;
}
} catch (FactoryException ex) {
return null;
}
return (this.dataType = dataTypeFactory.getDataType(dataTypeIdThis));
}
}
public AttributeSelector(StatusCode statusCodeIn, String statusMessageIn) {
super(statusCodeIn, statusMessageIn);
}
public AttributeSelector(StatusCode statusCodeIn) {
super(statusCodeIn);
}
public AttributeSelector() {
}
public Identifier getContextSelectorId() {
return this.contextSelectorId;
}
public void setContextSelectorId(Identifier identifier) {
this.contextSelectorId = identifier;
}
public String getPath() {
return this.path;
}
public void setPath(String pathIn) {
this.path = pathIn;
}
@Override
protected boolean validateComponent() {
if (!super.validateComponent()) {
return false;
} else if (this.getPath() == null) {
this.setStatus(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, "Missing Path");
return false;
} else {
return true;
}
}
/**
* If there is a context selector ID, get the attributes from the given <code>RequestAttributes</code>
* with that ID, ensure they are <code>XPathExpression</code>s and return them.
*
* @param requestAttributes
* @return
*/
protected List<XPathExpression> getContextSelectorValues(RequestAttributes requestAttributes) {
Identifier thisContextSelectorId = this.getContextSelectorId();
if (thisContextSelectorId == null) {
return null;
}
List<XPathExpression> listXPathExpressions = null;
Iterator<Attribute> iterAttributes = requestAttributes.getAttributes(thisContextSelectorId);
if (iterAttributes != null) {
while (iterAttributes.hasNext()) {
Attribute attribute = iterAttributes.next();
Iterator<AttributeValue<XPathExpressionWrapper>> iterXPathExpressions = attribute
.findValues(DataTypes.DT_XPATHEXPRESSION);
if (iterXPathExpressions != null && iterXPathExpressions.hasNext()) {
if (listXPathExpressions == null) {
listXPathExpressions = new ArrayList<XPathExpression>();
}
listXPathExpressions.add(iterXPathExpressions.next().getValue());
}
}
}
return listXPathExpressions;
}
@Override
public ExpressionResult evaluate(EvaluationContext evaluationContext, PolicyDefaults policyDefaults)
throws EvaluationException {
if (!this.validate()) {
return ExpressionResult.newError(new StdStatus(this.getStatusCode(), this.getStatusMessage()));
}
/*
* Get the DataType for this AttributeSelector for converting the resulting nodes into AttributeValues
*/
DataType<?> thisDataType = this.getDataType();
/*
* Get the Request so we can find the XPathExpression to locate the root node and to find the Content
* element of the requested category.
*/
Request request = evaluationContext.getRequest();
assert request != null;
/*
* Get the RequestAttributes objects for our Category. If none are found, then we abort quickly with
* either an empty or indeterminate result.
*/
Iterator<RequestAttributes> iterRequestAttributes = request.getRequestAttributes(this.getCategory());
if (iterRequestAttributes == null || !iterRequestAttributes.hasNext()) {
return this.getEmptyResult("No Attributes with Category " + this.getCategory().toString(), null);
}
/*
* Section 5.30 of the XACML 3.0 specification is a little vague about how to use the
* ContextSelectorId in the face of having multiple Attributes elements with the same CategoryId. My
* interpretation is that each is distinct, so we look for an attribute matching the ContextSelectorId
* in each matching Attributes element and use that to search the Content in that particular
* Attributes element. If either an Attribute matching the context selector id is not found or there
* is no Content, then that particular Attributes element is skipped.
*/
Bag bagAttributeValues = new Bag();
StdStatus statusFirstError = null;
while (iterRequestAttributes.hasNext()) {
RequestAttributes requestAttributes = iterRequestAttributes.next();
/*
* See if we have a Content element to query.
*/
Node nodeContentRoot = requestAttributes.getContentRoot();
if (nodeContentRoot != null) {
List<Node> listNodesToQuery = new ArrayList<Node>();
List<XPathExpression> listXPathExpressions = this.getContextSelectorValues(requestAttributes);
if (listXPathExpressions == null) {
listNodesToQuery.add(nodeContentRoot);
} else {
Iterator<XPathExpression> iterXPathExpressions = listXPathExpressions.iterator();
while (iterXPathExpressions.hasNext()) {
XPathExpression xpathExpression = iterXPathExpressions.next();
Node nodeContent = requestAttributes.getContentNodeByXpathExpression(xpathExpression);
if (nodeContent != null) {
listNodesToQuery.add(nodeContent);
}
}
}
/*
* If there are any nodes to query, do so now and add the results
*/
if (listNodesToQuery.size() > 0) {
for (Node nodeToQuery : listNodesToQuery) {
NodeList nodeList = null;
try {
XPath xPath = XPathFactory.newInstance().newXPath();
xPath
.setNamespaceContext(new NodeNamespaceContext(nodeToQuery.getOwnerDocument()));
XPathExpression xPathExpression = xPath.compile(this.getPath());
Node nodeToQueryDocumentRoot = null;
try {
nodeToQueryDocumentRoot = DOMUtil.getDirectDocumentChild(nodeToQuery);
} catch (DOMStructureException ex) {
return ExpressionResult
.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR,
"Exception processing context node: "
+ ex.getMessage()));
}
nodeList = (NodeList)xPathExpression.evaluate(nodeToQueryDocumentRoot,
XPathConstants.NODESET);
} catch (XPathExpressionException ex) {
if (statusFirstError == null) {
statusFirstError = new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR,
"XPathExpressionException: "
+ ex.getMessage());
}
}
if (nodeList != null && nodeList.getLength() > 0) {
for (int i = 0; i < nodeList.getLength(); i++) {
AttributeValue<?> attributeValueNode = null;
try {
attributeValueNode = thisDataType.createAttributeValue(nodeList.item(i));
} catch (DataTypeException ex) {
if (statusFirstError == null) {
statusFirstError = new StdStatus(
StdStatusCode.STATUS_CODE_PROCESSING_ERROR,
ex.getMessage());
}
}
if (attributeValueNode != null) {
bagAttributeValues.add(attributeValueNode);
} else if (statusFirstError == null) {
statusFirstError = new StdStatus(
StdStatusCode.STATUS_CODE_PROCESSING_ERROR,
"Unable to convert node to "
+ this.getDataTypeId().toString());
}
}
}
}
}
}
}
if (bagAttributeValues.size() == 0) {
if (statusFirstError == null) {
return this.getEmptyResult("No Content found", null);
} else {
return ExpressionResult.newError(statusFirstError);
}
} else {
return ExpressionResult.newBag(bagAttributeValues);
}
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("{");
stringBuilder.append("super=");
stringBuilder.append(super.toString());
Object objectToDump;
if ((objectToDump = this.getContextSelectorId()) != null) {
stringBuilder.append(",contextSelectorId=");
stringBuilder.append(objectToDump.toString());
}
if ((objectToDump = this.getPath()) != null) {
stringBuilder.append(",path=");
stringBuilder.append((String)objectToDump);
}
stringBuilder.append('}');
return stringBuilder.toString();
}
}
| |
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.partition.impl;
import com.hazelcast.config.ClasspathXmlConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.MemberGroupConfig;
import com.hazelcast.config.PartitionGroupConfig;
import com.hazelcast.cluster.Member;
import com.hazelcast.instance.BuildInfoProvider;
import com.hazelcast.cluster.impl.MemberImpl;
import com.hazelcast.internal.partition.InternalPartition;
import com.hazelcast.internal.partition.PartitionReplica;
import com.hazelcast.internal.partition.PartitionStateGenerator;
import com.hazelcast.internal.util.UuidUtil;
import com.hazelcast.cluster.Address;
import com.hazelcast.internal.partition.membergroup.ConfigMemberGroupFactory;
import com.hazelcast.internal.partition.membergroup.DefaultMemberGroup;
import com.hazelcast.internal.partition.membergroup.HostAwareMemberGroupFactory;
import com.hazelcast.spi.partitiongroup.MemberGroup;
import com.hazelcast.internal.partition.membergroup.MemberGroupFactory;
import com.hazelcast.internal.partition.membergroup.SingleMemberGroupFactory;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.version.MemberVersion;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class PartitionStateGeneratorTest {
private static final MemberVersion VERSION = MemberVersion.of(BuildInfoProvider.getBuildInfo().getVersion());
private static final boolean PRINT_STATE = false;
@Test
public void testRandomPartitionGenerator() throws Exception {
final MemberGroupFactory memberGroupFactory = new SingleMemberGroupFactory();
test(memberGroupFactory);
}
//"random host groups may cause non-uniform distribution of partitions when node size go down significantly!")
@Test
public void testHostAwarePartitionStateGenerator() throws Exception {
final HostAwareMemberGroupFactory memberGroupFactory = new HostAwareMemberGroupFactory();
test(memberGroupFactory);
}
@Test
public void testCustomPartitionStateGenerator() throws Exception {
final MemberGroupFactory memberGroupFactory = new MemberGroupFactory() {
public Collection<MemberGroup> createMemberGroups(Collection<? extends Member> members) {
MemberGroup[] g = new MemberGroup[4];
for (int i = 0; i < g.length; i++) {
g[i] = new DefaultMemberGroup();
}
for (Member member : members) {
Address address = member.getAddress();
if (even(address.getHost().hashCode()) && even(address.getPort())) {
g[0].addMember(member);
} else if (even(address.getHost().hashCode()) && !even(address.getPort())) {
g[1].addMember(member);
} else if (!even(address.getHost().hashCode()) && even(address.getPort())) {
g[2].addMember(member);
} else if (!even(address.getHost().hashCode()) && !even(address.getPort())) {
g[3].addMember(member);
}
}
List<MemberGroup> list = new LinkedList<MemberGroup>();
for (MemberGroup memberGroup : g) {
if (memberGroup.size() > 0) {
list.add(memberGroup);
}
}
return list;
}
boolean even(int k) {
return k % 2 == 0;
}
};
test(memberGroupFactory);
}
@Test
public void testConfigCustomPartitionStateGenerator() throws Exception {
PartitionGroupConfig config = new PartitionGroupConfig();
config.setEnabled(true);
config.setGroupType(PartitionGroupConfig.MemberGroupType.CUSTOM);
MemberGroupConfig mgCfg0 = new MemberGroupConfig();
MemberGroupConfig mgCfg1 = new MemberGroupConfig();
MemberGroupConfig mgCfg2 = new MemberGroupConfig();
MemberGroupConfig mgCfg3 = new MemberGroupConfig();
config.addMemberGroupConfig(mgCfg0);
config.addMemberGroupConfig(mgCfg1);
config.addMemberGroupConfig(mgCfg2);
config.addMemberGroupConfig(mgCfg3);
for (int k = 0; k < 3; k++) {
for (int i = 0; i < 255; i++) {
MemberGroupConfig mg;
switch (i % 4) {
case 0:
mg = mgCfg0;
break;
case 1:
mg = mgCfg1;
break;
case 2:
mg = mgCfg2;
break;
case 3:
mg = mgCfg3;
break;
default:
throw new IllegalArgumentException();
}
mg.addInterface("10.10." + k + "." + i);
}
}
test(new ConfigMemberGroupFactory(config.getMemberGroupConfigs()));
}
@Test
public void testXmlPartitionGroupConfig() {
Config config = new ClasspathXmlConfig("hazelcast-fullconfig.xml");
PartitionGroupConfig partitionGroupConfig = config.getPartitionGroupConfig();
assertTrue(partitionGroupConfig.isEnabled());
assertEquals(PartitionGroupConfig.MemberGroupType.CUSTOM, partitionGroupConfig.getGroupType());
assertEquals(2, partitionGroupConfig.getMemberGroupConfigs().size());
}
@Test
public void testOnlyUnassignedArrangement() throws Exception {
List<Member> memberList = createMembers(10, 1);
MemberGroupFactory memberGroupFactory = new SingleMemberGroupFactory();
Collection<MemberGroup> groups = memberGroupFactory.createMemberGroups(memberList);
PartitionStateGenerator generator = new PartitionStateGeneratorImpl();
PartitionReplica[][] state = generator.arrange(groups, emptyPartitionArray(100));
// unassign some partitions entirely
Collection<Integer> unassignedPartitions = new ArrayList<Integer>();
for (int i = 0; i < state.length; i++) {
if (i % 3 == 0) {
state[i] = new PartitionReplica[InternalPartition.MAX_REPLICA_COUNT];
unassignedPartitions.add(i);
}
}
// unassign only backup replicas of some partitions
for (int i = 0; i < state.length; i++) {
if (i % 10 == 0) {
Arrays.fill(state[i], 1, InternalPartition.MAX_REPLICA_COUNT, null);
}
}
InternalPartition[] partitions = toPartitionArray(state);
state = generator.arrange(groups, partitions, unassignedPartitions);
for (int pid = 0; pid < state.length; pid++) {
PartitionReplica[] addresses = state[pid];
if (unassignedPartitions.contains(pid)) {
for (PartitionReplica address : addresses) {
assertNotNull(address);
}
} else {
InternalPartition partition = partitions[pid];
for (int replicaIx = 0; replicaIx < InternalPartition.MAX_REPLICA_COUNT; replicaIx++) {
assertEquals(partition.getReplica(replicaIx), addresses[replicaIx]);
}
}
}
}
private void test(MemberGroupFactory memberGroupFactory) throws Exception {
PartitionStateGenerator generator = new PartitionStateGeneratorImpl();
int maxSameHostCount = 3;
int[] partitionCounts = new int[]{271, 787, 1549, 3217};
int[] members = new int[]{3, 6, 9, 10, 11, 17, 57, 100, 130, 77, 179, 93, 37, 26, 15, 5};
for (int partitionCount : partitionCounts) {
int memberCount = members[0];
List<Member> memberList = createMembers(memberCount, maxSameHostCount);
Collection<MemberGroup> groups = memberGroupFactory.createMemberGroups(memberList);
PartitionReplica[][] state = generator.arrange(groups, emptyPartitionArray(partitionCount));
checkTestResult(state, groups, partitionCount);
int previousMemberCount = memberCount;
for (int j = 1; j < members.length; j++) {
memberCount = members[j];
if (partitionCount / memberCount < 10) {
break;
}
if ((float) partitionCount / memberCount > 2) {
if (previousMemberCount == 0) {
memberList = createMembers(memberCount, maxSameHostCount);
} else if (memberCount > previousMemberCount) {
MemberImpl last = (MemberImpl) memberList.get(previousMemberCount - 1);
List<Member> extra = createMembers(last, (memberCount - previousMemberCount), maxSameHostCount);
memberList.addAll(extra);
} else {
List<Member> removedMembers = memberList.subList(memberCount, memberList.size());
memberList = memberList.subList(0, memberCount);
remove(state, removedMembers);
}
groups = memberGroupFactory.createMemberGroups(memberList);
state = generator.arrange(groups, toPartitionArray(state));
checkTestResult(state, groups, partitionCount);
previousMemberCount = memberCount;
}
}
}
}
static InternalPartition[] toPartitionArray(PartitionReplica[][] state) {
InternalPartition[] result = new InternalPartition[state.length];
for (int partitionId = 0; partitionId < state.length; partitionId++) {
result[partitionId] = new DummyInternalPartition(state[partitionId], partitionId);
}
return result;
}
static InternalPartition[] emptyPartitionArray(int partitionCount) {
InternalPartition[] result = new InternalPartition[partitionCount];
for (int partitionId = 0; partitionId < partitionCount; partitionId++) {
result[partitionId] = new DummyInternalPartition(new PartitionReplica[InternalPartition.MAX_REPLICA_COUNT], partitionId);
}
return result;
}
private static void remove(PartitionReplica[][] state, List<Member> removedMembers) {
Set<Address> addresses = new HashSet<Address>();
for (Member member : removedMembers) {
addresses.add(member.getAddress());
}
for (PartitionReplica[] replicas : state) {
for (int i = 0; i < replicas.length; i++) {
if (replicas[i] != null && !addresses.contains(replicas[i].address())) {
replicas[i] = null;
break;
}
}
}
}
static List<Member> createMembers(int memberCount, int maxSameHostCount) throws Exception {
return createMembers(null, memberCount, maxSameHostCount);
}
private static List<Member> createMembers(MemberImpl startAfter, int memberCount, int maxSameHostCount) throws Exception {
Random rand = new Random();
final byte[] ip = new byte[]{10, 10, 0, 0};
if (startAfter != null) {
Address address = startAfter.getAddress();
byte[] startIp = address.getInetAddress().getAddress();
if ((0xff & startIp[3]) < 255) {
ip[2] = startIp[2];
ip[3] = (byte) (startIp[3] + 1);
} else {
ip[2] = (byte) (startIp[2] + 1);
ip[3] = 0;
}
}
int count = 0;
int port = 5700;
List<Member> members = new ArrayList<Member>();
int sameHostCount = rand.nextInt(maxSameHostCount) + 1;
for (int i = 0; i < memberCount; i++) {
if (count == sameHostCount) {
ip[3] = ++ip[3];
count = 0;
port = 5700;
sameHostCount = rand.nextInt(maxSameHostCount) + 1;
}
count++;
port++;
MemberImpl m = new MemberImpl(new Address(InetAddress.getByAddress(new byte[]{ip[0], ip[1], ip[2], ip[3]})
, port), VERSION, false, UuidUtil.newUnsecureUUID());
members.add(m);
if ((0xff & ip[3]) == 255) {
ip[2] = ++ip[2];
}
}
return members;
}
private void checkTestResult(PartitionReplica[][] state, Collection<MemberGroup> groups, int partitionCount) {
Iterator<MemberGroup> iter = groups.iterator();
while (iter.hasNext()) {
if (iter.next().size() == 0) {
iter.remove();
}
}
int replicaCount = Math.min(groups.size(), InternalPartition.MAX_REPLICA_COUNT);
Map<MemberGroup, GroupPartitionState> groupPartitionStates = new HashMap<MemberGroup, GroupPartitionState>();
Set<PartitionReplica> set = new HashSet<PartitionReplica>();
int avgPartitionPerGroup = partitionCount / groups.size();
for (int partitionId = 0; partitionId < partitionCount; partitionId++) {
PartitionReplica[] replicas = state[partitionId];
for (int i = 0; i < replicaCount; i++) {
PartitionReplica owner = replicas[i];
assertNotNull(owner);
assertFalse("Duplicate owner of partition: " + partitionId,
set.contains(owner));
set.add(owner);
MemberGroup group = null;
for (MemberGroup g : groups) {
if (g.hasMember(new MemberImpl(owner.address(), VERSION, true, owner.uuid()))) {
group = g;
break;
}
}
assertNotNull(group);
GroupPartitionState groupState = groupPartitionStates.get(group);
if (groupState == null) {
groupState = new GroupPartitionState();
groupState.group = group;
groupPartitionStates.put(group, groupState);
}
groupState.groupPartitions[i].add(partitionId);
groupState.getNodePartitions(owner)[i].add(partitionId);
}
set.clear();
}
for (GroupPartitionState groupState : groupPartitionStates.values()) {
for (Map.Entry<PartitionReplica, Set<Integer>[]> entry : groupState.nodePartitionsMap.entrySet()) {
Collection<Integer>[] partitions = entry.getValue();
for (int i = 0; i < replicaCount; i++) {
int avgPartitionPerNode = groupState.groupPartitions[i].size() / groupState.nodePartitionsMap.size();
int count = partitions[i].size();
isInAllowedRange(count, avgPartitionPerNode, i, entry.getKey(), groups, partitionCount);
}
}
Collection<Integer>[] partitions = groupState.groupPartitions;
for (int i = 0; i < replicaCount; i++) {
int count = partitions[i].size();
isInAllowedRange(count, avgPartitionPerGroup, i, groupState.group, groups, partitionCount);
}
}
printTable(groupPartitionStates, replicaCount);
}
private static void isInAllowedRange(int count, int average, int replica,
Object owner, final Collection<MemberGroup> groups, final int partitionCount) {
if (average <= 10) {
return;
}
final float r = 2f;
assertTrue("Too low partition count! \nOwned: " + count + ", Avg: " + average
+ ", \nPartitionCount: " + partitionCount + ", Replica: " + replica
+ ", \nOwner: " + owner, count >= (float) (average) / r);
assertTrue("Too high partition count! \nOwned: " + count + ", Avg: " + average
+ ", \nPartitionCount: " + partitionCount + ", Replica: " + replica
+ ", \nOwner: " + owner, count <= (float) (average) * r);
}
private static void printTable(Map<MemberGroup, GroupPartitionState> groupPartitionStates, int replicaCount) {
if (!PRINT_STATE) {
return;
}
System.out.printf("%-20s", "Owner");
for (int i = 0; i < replicaCount; i++) {
System.out.printf("%-5s", "R-" + i);
}
System.out.printf("%5s%n", "Total");
System.out.println("_______________________________________________________________");
System.out.println();
int k = 1;
for (GroupPartitionState groupState : groupPartitionStates.values()) {
System.out.printf("%-20s%n", "MemberGroup[" + (k++) + "]");
for (Map.Entry<PartitionReplica, Set<Integer>[]> entry : groupState.nodePartitionsMap.entrySet()) {
int total = 0;
Address address = entry.getKey().address();
System.out.printf("%-20s", address.getHost() + ":" + address.getPort());
Collection<Integer>[] partitions = entry.getValue();
for (int i = 0; i < replicaCount; i++) {
int count = partitions[i].size();
System.out.printf("%-5s", count);
total += partitions[i].size();
}
System.out.printf("%-5s%n", total);
}
if (groupState.group.size() > 1) {
System.out.printf("%-20s", "Total");
int total = 0;
Collection<Integer>[] partitions = groupState.groupPartitions;
for (int i = 0; i < replicaCount; i++) {
int count = partitions[i].size();
System.out.printf("%-5s", count);
total += partitions[i].size();
}
System.out.printf("%-5s%n", total);
}
System.out.println("---------------------------------------------------------------");
System.out.println();
}
System.out.println();
System.out.println();
}
private static class GroupPartitionState {
MemberGroup group;
Set<Integer>[] groupPartitions = new Set[InternalPartition.MAX_REPLICA_COUNT];
Map<PartitionReplica, Set<Integer>[]> nodePartitionsMap = new HashMap<PartitionReplica, Set<Integer>[]>();
{
for (int i = 0; i < InternalPartition.MAX_REPLICA_COUNT; i++) {
groupPartitions[i] = new HashSet<Integer>();
}
}
Set<Integer>[] getNodePartitions(PartitionReplica node) {
Set<Integer>[] nodePartitions = nodePartitionsMap.get(node);
if (nodePartitions == null) {
nodePartitions = new Set[InternalPartition.MAX_REPLICA_COUNT];
for (int i = 0; i < InternalPartition.MAX_REPLICA_COUNT; i++) {
nodePartitions[i] = new HashSet<Integer>();
}
nodePartitionsMap.put(node, nodePartitions);
}
return nodePartitions;
}
}
}
| |
package xyz.upperlevel.uppercore.config.parser;
import lombok.Getter;
import lombok.Setter;
import org.yaml.snakeyaml.nodes.*;
import xyz.upperlevel.uppercore.config.*;
import xyz.upperlevel.uppercore.config.exceptions.*;
import xyz.upperlevel.uppercore.util.Pair;
import java.lang.reflect.*;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.util.Comparator.comparingInt;
public class ConstructorConfigParser<T> extends ConfigParser {
private ObjectConstructor<T> targetConstructor;
@Getter
private final ConstructorType type;
@Getter
private final Class<T> declaredClass;
@Getter
private final boolean inlineable;
private final boolean scalarInlineable;
@Getter
private final Map<String, Property> nodesByName;
@Getter
private final List<Property> positionalArguments;
private final Set<String> unfoldingNodes = new HashSet<>();
@Getter
@Setter
private Predicate<String> ignoreUnmatchedProperties = s -> false;
public ConstructorConfigParser(Class<T> declaredClass, ConfigParserRegistry registry, Parameter[] parameters, ObjectConstructor<T> constructor, boolean inlineable) {
super(declaredClass);
this.declaredClass = declaredClass;
this.inlineable = inlineable;
targetConstructor = constructor;
if (parameters.length == 1 && parameters[0].getType() == Node.class) {
// Raw node constructor (special case)
// The constructor will manually parse the node
type = ConstructorType.RAW_NODE;
nodesByName = null;
positionalArguments = null;
scalarInlineable = false;
} else if (parameters.length == 1 && parameters[0].getType() == Config.class) {
// Raw config constructor (special case)
// The constructor will manually parse the data from the Config instance
type = ConstructorType.RAW_CONFIG;
nodesByName = null;
positionalArguments = null;
scalarInlineable = false;
} else {
type = ConstructorType.NORMAL;
nodesByName = new HashMap<>();
positionalArguments = new ArrayList<>(parameters.length);
// Parse arguments
for (Parameter parameter : parameters) {
Property property = new Property(parameter, registry);
positionalArguments.add(property);
if (unfoldingNodes.contains(property.name)) {
throw onUsedPropertyUnfolding(property.name);
}
addUnfoldNodes(property.name);
if (nodesByName.put(property.name, property) != null) {
// The constructor class may be different (think about an external constructor)
throw new IllegalArgumentException(
"Found duplicate config value in " +
parameter.getDeclaringExecutable().getDeclaringClass().getName() +
", name: '" + property.name + "'"
);
}
}
scalarInlineable = inlineable &&
positionalArguments.stream()
.skip(1)
.noneMatch(x -> x.required);
}
}
public void addUnfoldNodes(String pname) {
int li = pname.length();
while (true) {
li = pname.lastIndexOf('.', li - 1);
if (li < 0) break;
String subn = pname.substring(0, li);
if (nodesByName.containsKey(subn)) {
throw onUsedPropertyUnfolding(subn);
}
if (!unfoldingNodes.add(subn)) return;
}
}
protected RuntimeException onUsedPropertyUnfolding(String name) {
return new IllegalArgumentException(
"Unfolding already used property in class " + declaredClass.getName() + ", name: '" + name + "'"
);
}
/**
* A ConstructorConfigParser is regular when it is defined with parameters, not with a catch-everything config
* object nor with a raw yaml Node, in the last two cases it is named as "special".
* @return true only if the node is "special"
*/
public boolean isSpecial() {
return type != ConstructorType.NORMAL;
}
protected T parseSpecial(Node root) {
Object param;
switch (type) {
case RAW_NODE: param = root; break;
case RAW_CONFIG: param = new TrackingConfig(root); break;
default: throw new IllegalStateException();
}
try {
return targetConstructor.construct(new Object[]{param});
} catch (Exception e) {
throw new ConfigException(null, null, e.getMessage(), root.getStartMark(), null, e);
}
}
public void mapUnfold(String prefix, MappingNode node) {
if (node.getValue().isEmpty()) return;
for (NodeTuple t : node.getValue()) {
fill(prefix, t.getKeyNode(), t.getValueNode());
}
}
public void fill(String prefix, Node key, Node value) {
String name = prefix + extractName(key);
if (unfoldingNodes.contains(name)) {
checkNodeId(value, NodeId.mapping);
mapUnfold( prefix + name + ".", (MappingNode) value);
return;
}
Property entry = nodesByName.get(name);
if (entry == null) {
if (ignoreUnmatchedProperties.test(name)) return;
throw new PropertyNotFoundParsingException(key, name, declaredClass);
}
if (entry.parsed != null) {
throw new DuplicatePropertyConfigException(key, entry.source, name);
}
entry.parse(key, value);
}
@Override
public T parse(Node root) {
if (isSpecial()) {
return parseSpecial(root);
}
resetEntries();
if (root.getNodeId() != NodeId.mapping) {
if (inlineable) {
return parseInline(root);
}
throw new WrongNodeTypeConfigException(root, NodeId.mapping);
}
MappingNode rootMap = (MappingNode) root;
for (NodeTuple tuple : rootMap.getValue()) {
fill("", tuple.getKeyNode(), tuple.getValueNode());
}
// Check for required but uninitialized properties
List<Property> uninitializedProperties = nodesByName.values().stream()
.filter(n -> n.required && n.parsed == null)
.collect(Collectors.toList());
if (!uninitializedProperties.isEmpty()) {
throw new RequiredPropertyNotFoundConfigException(root, uninitializedProperties.stream().map(p -> p.name).collect(Collectors.toList()));
}
return constructObject(root);
}
protected T parseInline(Node root) {
assert inlineable;// Cannot parseInline a non-inlineable object (or at least, it shouldn't be done)
if (root.getNodeId() == NodeId.scalar) {
if (!scalarInlineable) {
throw new ConfigException(declaredClass.getSimpleName() + " does not take only one argument", root);
}
// Single argument properties can be constructed even without an explicit list
if (!positionalArguments.isEmpty()) {
positionalArguments.get(0).parse(null, root);
}
} else if (root.getNodeId() == NodeId.sequence) {
SequenceNode node = ((SequenceNode) root);
int argsLen = node.getValue().size();
if (argsLen > positionalArguments.size()) {
throw new ConfigException("Too many arguments (max: " + positionalArguments.size() + ")", root);
}
for (int i = 0; i < argsLen; i++) {
positionalArguments.get(i).parse(null, node.getValue().get(i));
}
} else {
throw new WrongNodeTypeConfigException(root, NodeId.scalar, NodeId.sequence);
}
return constructObject(root);
}
protected T constructObject(Node root) {
int size = positionalArguments.size();
Object[] args = new Object[size];
int index = 0;
for (int i = 0; i < positionalArguments.size(); i++) {
args[index++] = positionalArguments.get(i).getOrDef();
}
try {
return targetConstructor.construct(args);
} catch (InvocationTargetException e) {
throw new ConfigException(null, null, e.getCause().getMessage(), root.getStartMark(), null, e.getCause());
} catch (Exception e) {
throw new ConfigException(null, null, e.getMessage(), root.getStartMark(), null, e);
}
}
protected String extractName(Node rawNode) {
if (rawNode.getNodeId() != NodeId.scalar) {
throw new WrongNodeTypeConfigException(rawNode, NodeId.scalar);
}
return ((ScalarNode) rawNode).getValue();
}
protected void resetEntries() {
nodesByName.values().forEach(Property::reset);
}
public void setIgnoreAllUnmatchedProperties(boolean ignoreAll) {
ignoreUnmatchedProperties = s -> ignoreAll;
}
public boolean isUsingArgument(String name) {
if (type != ConstructorType.NORMAL) {
// Well, we can't know
// If the constructor manages the build by itself we can't control
// which parameter it uses, that can give us strange behaviours
// in which the library ignores a parameter
// That is one of the main reasons that the raw types aren't encouraged
return false;
}
return nodesByName.containsKey(name);
}
private static <T> ConstructorConfigParser<T> createForClass(Class<T> clazz, ConfigParserRegistry registry) {
@SuppressWarnings("unchecked")
Constructor<T>[] constructors = (Constructor<T>[]) clazz.getDeclaredConstructors();
Constructor<T> targetConstructor = null;
for (Constructor<T> constructor : constructors) {
if (constructor.isAnnotationPresent(ConfigConstructor.class)) {
if (targetConstructor != null) {
throw new IllegalStateException("Multiple ConfigConstructors in class " + clazz.getName());
}
targetConstructor = constructor;
}
}
if (targetConstructor == null) {
return null;
}
targetConstructor.setAccessible(true);
Parameter[] parameters = targetConstructor.getParameters();
ObjectConstructor<T> refinedConstructor = targetConstructor::newInstance;
boolean inlineable = targetConstructor.getAnnotation(ConfigConstructor.class).inlineable();
return new ConstructorConfigParser<>(clazz, registry, parameters, refinedConstructor, inlineable);
}
private static ConstructorConfigParser<?> createDeclarator(ConfigExternalDeclarator declarator, Method method, ConfigConstructor annotation, ConfigParserRegistry registry) {
method.setAccessible(true);
Parameter[] parameters = method.getParameters();
Class<?> returnType = method.getReturnType();
ObjectConstructor<?> refinedConstructor = args -> method.invoke(declarator, args);
@SuppressWarnings("unchecked")
ConstructorConfigParser<?> parser = new ConstructorConfigParser(returnType, registry, parameters, refinedConstructor, annotation.inlineable());
return parser;
}
public static List<ConstructorConfigParser<?>> createFromDeclarator(ConfigExternalDeclarator declarator, ConfigParserRegistry registry) {
List<ConstructorConfigParser<?>> parsers = new ArrayList<>();
for (Method method : declarator.getClass().getDeclaredMethods()) {
ConfigConstructor annotation = method.getAnnotation(ConfigConstructor.class);
if (annotation == null) {
continue;
}
parsers.add(createDeclarator(declarator, method, annotation, registry));
}
if (parsers.isEmpty()) {
throw new IllegalStateException("Class " + declarator.getClass() + " does not define any ConfigConstructor!");
}
return parsers;
}
/**
* This method differs from {@link #createFromDeclarator(ConfigExternalDeclarator, ConfigParserRegistry)} because this
* instantly registers the declared config constructors inside of the registry.
* This permits the in-class config reference (you can first declare Date and then use it in the next method).
* TODO: this behaviour is not supported for now because the order is quite randomic, in the future it will be
* implemented trough a priority parameter inserted in the annotation
*
* @param declarator the declarator to load the parsers from
* @param registry the registry where the parsers will be inserted
*/
public static void loadFromDeclarator(ConfigExternalDeclarator declarator, ConfigParserRegistry registry) {
int loaded = 0;
List<Pair<Integer, Method>> entries = new ArrayList<>();
for (Method method : declarator.getClass().getDeclaredMethods()) {
if (!method.isAnnotationPresent(ConfigConstructor.class)) {
continue;
}
int priority = 100;
ExternalDeclaratorPriority priorityzer = method.getAnnotation(ExternalDeclaratorPriority.class);
if (priorityzer != null) {
priority = priorityzer.value();
}
entries.add(Pair.of(priority, method));
}
if (entries.isEmpty()) {
throw new IllegalStateException("Class " + declarator.getClass() + " does not define any ConfigConstructor!");
}
entries.sort(comparingInt(p -> -p.getFirst()));
for (Pair<Integer, Method> entry : entries) {
Method method = entry.getSecond();
ConfigConstructor annotation = method.getAnnotation(ConfigConstructor.class);
ConstructorConfigParser<?> parser = createDeclarator(declarator, method, annotation, registry);
registry.register((Class)parser.getHandleClass(), parser);
loaded++;
}
}
protected class Property {
public String name;
public boolean required;
public Parser parser;
public Object def = null;
public Node source;
public Object parsed;
public Property(Parameter parameter, ConfigParserRegistry registry) {
name = "";
required = true;
ConfigProperty annotation = parameter.getAnnotation(ConfigProperty.class);
if (annotation != null) {
name = annotation.value();
required = !annotation.optional();
} else if (!parameter.isNamePresent() && !inlineable) {
String methodName = parameter.getDeclaringExecutable().getName();
throw new IllegalArgumentException("Cannot find value of " + parameter.getName() + ","
+ " in class " + parameter.getDeclaringExecutable().getDeclaringClass().getName() + ","
+ " in method " + methodName + ","
+ " Use @ConfigProperty or compile with -parameters");
} else {
name = parameter.getName();
}
if (!required && parameter.getType().isPrimitive()) {
throw new IllegalArgumentException("Cannot have optional primitive (parameter: " +
parameter.getName() +
", class: " +
parameter.getDeclaringExecutable().getDeclaringClass() + ")");
}
if (parameter.getType() == Optional.class) {
required = false;
def = Optional.empty();
Type optType = ((ParameterizedType) parameter.getParameterizedType()).getActualTypeArguments()[0];
ConfigParser nonOptionalParser = registry.getFor(optType);
parser = node -> Optional.of(nonOptionalParser.parse(node));
} else {
parser = registry.getFor(parameter.getParameterizedType())::parse;
}
}
public void parse(Node key, Node value) {
source = key;
parsed = parser.parse(value);
}
public Object getOrDef() {
return parsed == null ? def : parsed;
}
public void reset() {
source = null;
parsed = null;
}
}
public interface ObjectConstructor<T> {
T construct(Object[] arguments) throws Exception;
}
public interface Parser {
Object parse(Node root);
}
public enum ConstructorType {
NORMAL, // A normal constructor
RAW_NODE, // A constructor that accepts a raw node
RAW_CONFIG, // A constructor that accepts a Config instance
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis2.jaxws.dispatch;
import org.apache.axiom.om.OMXMLBuilderFactory;
import org.apache.axis2.jaxws.TestLogger;
import org.apache.axis2.testutils.Axis2Server;
import org.junit.ClassRule;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Response;
import javax.xml.ws.Service;
import javax.xml.ws.WebServiceException;
import static org.apache.axis2.jaxws.framework.TestUtils.await;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.concurrent.Future;
/**
* This class tests the JAX-WS Dispatch with various forms of the
* javax.xml.transform.dom.DOMSource
*/
public class DOMSourceDispatchTests {
@ClassRule
public static final Axis2Server server = new Axis2Server("target/repo");
@Test
public void testSyncPayloadMode() throws Exception {
TestLogger.logger.debug("---------------------------------------");
// Initialize the JAX-WS client artifacts
Service svc = Service.create(DispatchTestConstants.QNAME_SERVICE);
svc.addPort(DispatchTestConstants.QNAME_PORT, null, server.getEndpoint("EchoService"));
Dispatch<Source> dispatch = svc.createDispatch(DispatchTestConstants.QNAME_PORT,
Source.class, Service.Mode.PAYLOAD);
// Create the DOMSource
DOMSource request = createDOMSourceFromString(DispatchTestConstants.sampleBodyContent);
TestLogger.logger.debug(">> Invoking sync Dispatch");
Source response = dispatch.invoke(request);
assertNotNull("dispatch invoke returned null",response);
// Turn the Source into a String so we can check it
String responseText = createStringFromSource(response);
TestLogger.logger.debug(responseText);
// Check to make sure the content is correct
assertTrue(!responseText.contains("soap"));
assertTrue(!responseText.contains("Envelope"));
assertTrue(!responseText.contains("Body"));
assertTrue(responseText.contains("echoStringResponse"));
}
@Test
public void testSyncMessageMode() throws Exception {
TestLogger.logger.debug("---------------------------------------");
// Initialize the JAX-WS client artifacts
Service svc = Service.create(DispatchTestConstants.QNAME_SERVICE);
svc.addPort(DispatchTestConstants.QNAME_PORT, null, server.getEndpoint("EchoService"));
Dispatch<Source> dispatch = svc.createDispatch(DispatchTestConstants.QNAME_PORT,
Source.class, Service.Mode.MESSAGE);
// Create the DOMSource
DOMSource request = createDOMSourceFromString(DispatchTestConstants.sampleSoapMessage);
TestLogger.logger.debug(">> Invoking sync Dispatch");
Source response = dispatch.invoke(request);
assertNotNull("dispatch invoke returned null",response);
// Turn the Source into a String so we can check it
String responseText = createStringFromSource(response);
TestLogger.logger.debug(responseText);
// Check to make sure the content is correct
assertTrue(responseText.contains("soap"));
assertTrue(responseText.contains("Envelope"));
assertTrue(responseText.contains("Body"));
assertTrue(responseText.contains("echoStringResponse"));
// Invoke a second time
response = dispatch.invoke(request);
assertNotNull("dispatch invoke returned null",response);
// Turn the Source into a String so we can check it
responseText = createStringFromSource(response);
TestLogger.logger.debug(responseText);
// Check to make sure the content is correct
assertTrue(responseText.contains("soap"));
assertTrue(responseText.contains("Envelope"));
assertTrue(responseText.contains("Body"));
assertTrue(responseText.contains("echoStringResponse"));
}
@Test
public void testAsyncCallbackPayloadMode() throws Exception {
TestLogger.logger.debug("---------------------------------------");
// Initialize the JAX-WS client artifacts
Service svc = Service.create(DispatchTestConstants.QNAME_SERVICE);
svc.addPort(DispatchTestConstants.QNAME_PORT, null, server.getEndpoint("EchoService"));
Dispatch<Source> dispatch = svc.createDispatch(DispatchTestConstants.QNAME_PORT,
Source.class, Service.Mode.PAYLOAD);
// Create the DOMSource
DOMSource request = createDOMSourceFromString(DispatchTestConstants.sampleBodyContent);
// Setup the callback for async responses
AsyncCallback<Source> callbackHandler = new AsyncCallback<Source>();
TestLogger.logger.debug(">> Invoking async (callback) Dispatch");
Future<?> monitor = dispatch.invokeAsync(request, callbackHandler);
await(monitor);
Source response = callbackHandler.getValue();
assertNotNull(response);
// Turn the Source into a String so we can check it
String responseText = createStringFromSource(response);
TestLogger.logger.debug(responseText);
// Check to make sure the content is correct
assertTrue(!responseText.contains("soap"));
assertTrue(!responseText.contains("Envelope"));
assertTrue(!responseText.contains("Body"));
assertTrue(responseText.contains("echoStringResponse"));
// Invoke a second time
// Setup the callback for async responses
callbackHandler = new AsyncCallback<Source>();
TestLogger.logger.debug(">> Invoking async (callback) Dispatch");
monitor = dispatch.invokeAsync(request, callbackHandler);
await(monitor);
response = callbackHandler.getValue();
assertNotNull(response);
// Turn the Source into a String so we can check it
responseText = createStringFromSource(response);
TestLogger.logger.debug(responseText);
// Check to make sure the content is correct
assertTrue(!responseText.contains("soap"));
assertTrue(!responseText.contains("Envelope"));
assertTrue(!responseText.contains("Body"));
assertTrue(responseText.contains("echoStringResponse"));
}
@Test
public void testAsyncCallbackMessageMode() throws Exception {
TestLogger.logger.debug("---------------------------------------");
// Initialize the JAX-WS client artifacts
Service svc = Service.create(DispatchTestConstants.QNAME_SERVICE);
svc.addPort(DispatchTestConstants.QNAME_PORT, null, server.getEndpoint("EchoService"));
Dispatch<Source> dispatch = svc.createDispatch(DispatchTestConstants.QNAME_PORT,
Source.class, Service.Mode.MESSAGE);
// Create the DOMSource
DOMSource request = createDOMSourceFromString(DispatchTestConstants.sampleSoapMessage);
// Setup the callback for async responses
AsyncCallback<Source> callbackHandler = new AsyncCallback<Source>();
TestLogger.logger.debug(">> Invoking async (callback) Dispatch");
Future<?> monitor = dispatch.invokeAsync(request, callbackHandler);
await(monitor);
Source response = callbackHandler.getValue();
assertNotNull(response);
// Turn the Source into a String so we can check it
String responseText = createStringFromSource(response);
TestLogger.logger.debug(responseText);
// Check to make sure the content is correct
assertTrue(responseText.contains("soap"));
assertTrue(responseText.contains("Envelope"));
assertTrue(responseText.contains("Body"));
assertTrue(responseText.contains("echoStringResponse"));
// Invoke a second time
// Setup the callback for async responses
callbackHandler = new AsyncCallback<Source>();
TestLogger.logger.debug(">> Invoking async (callback) Dispatch");
monitor = dispatch.invokeAsync(request, callbackHandler);
await(monitor);
response = callbackHandler.getValue();
assertNotNull(response);
// Turn the Source into a String so we can check it
responseText = createStringFromSource(response);
TestLogger.logger.debug(responseText);
// Check to make sure the content is correct
assertTrue(responseText.contains("soap"));
assertTrue(responseText.contains("Envelope"));
assertTrue(responseText.contains("Body"));
assertTrue(responseText.contains("echoStringResponse"));
}
@Test
public void testAsyncPollingPayloadMode() throws Exception {
TestLogger.logger.debug("---------------------------------------");
// Initialize the JAX-WS client artifacts
Service svc = Service.create(DispatchTestConstants.QNAME_SERVICE);
svc.addPort(DispatchTestConstants.QNAME_PORT, null, server.getEndpoint("EchoService"));
Dispatch<Source> dispatch = svc.createDispatch(DispatchTestConstants.QNAME_PORT,
Source.class, Service.Mode.PAYLOAD);
// Create the DOMSource
DOMSource request = createDOMSourceFromString(DispatchTestConstants.sampleBodyContent);
TestLogger.logger.debug(">> Invoking async (polling) Dispatch");
Response<Source> asyncResponse = dispatch.invokeAsync(request);
await(asyncResponse);
Source response = asyncResponse.get();
assertNotNull(response);
// Turn the Source into a String so we can check it
String responseText = createStringFromSource(response);
TestLogger.logger.debug(responseText);
// Check to make sure the content is correct
assertTrue(!responseText.contains("soap"));
assertTrue(!responseText.contains("Envelope"));
assertTrue(!responseText.contains("Body"));
assertTrue(responseText.contains("echoStringResponse"));
// Invoke a second time
TestLogger.logger.debug(">> Invoking async (polling) Dispatch");
asyncResponse = dispatch.invokeAsync(request);
await(asyncResponse);
response = asyncResponse.get();
assertNotNull(response);
// Turn the Source into a String so we can check it
responseText = createStringFromSource(response);
TestLogger.logger.debug(responseText);
// Check to make sure the content is correct
assertTrue(!responseText.contains("soap"));
assertTrue(!responseText.contains("Envelope"));
assertTrue(!responseText.contains("Body"));
assertTrue(responseText.contains("echoStringResponse"));
}
@Test
public void testAsyncPollingMessageMode() throws Exception {
TestLogger.logger.debug("---------------------------------------");
// Initialize the JAX-WS client artifacts
Service svc = Service.create(DispatchTestConstants.QNAME_SERVICE);
svc.addPort(DispatchTestConstants.QNAME_PORT, null, server.getEndpoint("EchoService"));
Dispatch<Source> dispatch = svc.createDispatch(DispatchTestConstants.QNAME_PORT,
Source.class, Service.Mode.MESSAGE);
// Create the DOMSource
DOMSource request = createDOMSourceFromString(DispatchTestConstants.sampleSoapMessage);
TestLogger.logger.debug(">> Invoking async (callback) Dispatch");
Response<Source> asyncResponse = dispatch.invokeAsync(request);
await(asyncResponse);
Source response = asyncResponse.get();
assertNotNull(response);
// Turn the Source into a String so we can check it
String responseText = createStringFromSource(response);
TestLogger.logger.debug(responseText);
// Check to make sure the content is correct
assertTrue(responseText.contains("soap"));
assertTrue(responseText.contains("Envelope"));
assertTrue(responseText.contains("Body"));
assertTrue(responseText.contains("echoStringResponse"));
// Invoke a second time
TestLogger.logger.debug(">> Invoking async (callback) Dispatch");
asyncResponse = dispatch.invokeAsync(request);
await(asyncResponse);
response = asyncResponse.get();
assertNotNull(response);
// Turn the Source into a String so we can check it
responseText = createStringFromSource(response);
TestLogger.logger.debug(responseText);
// Check to make sure the content is correct
assertTrue(responseText.contains("soap"));
assertTrue(responseText.contains("Envelope"));
assertTrue(responseText.contains("Body"));
assertTrue(responseText.contains("echoStringResponse"));
}
@Test
public void testOneWayPayloadMode() throws Exception {
TestLogger.logger.debug("---------------------------------------");
// Initialize the JAX-WS client artifacts
Service svc = Service.create(DispatchTestConstants.QNAME_SERVICE);
svc.addPort(DispatchTestConstants.QNAME_PORT, null, server.getEndpoint("EchoService"));
Dispatch<Source> dispatch = svc.createDispatch(DispatchTestConstants.QNAME_PORT,
Source.class, Service.Mode.PAYLOAD);
// Create the DOMSource
DOMSource request = createDOMSourceFromString(DispatchTestConstants.sampleBodyContent);
TestLogger.logger.debug(">> Invoking One Way Dispatch");
dispatch.invokeOneWay(request);
// Invoke a second time
TestLogger.logger.debug(">> Invoking One Way Dispatch");
dispatch.invokeOneWay(request);
}
@Test
public void testOneWayMessageMode() throws Exception {
TestLogger.logger.debug("---------------------------------------");
// Initialize the JAX-WS client artifacts
Service svc = Service.create(DispatchTestConstants.QNAME_SERVICE);
svc.addPort(DispatchTestConstants.QNAME_PORT, null, server.getEndpoint("EchoService"));
Dispatch<Source> dispatch = svc.createDispatch(DispatchTestConstants.QNAME_PORT,
Source.class, Service.Mode.MESSAGE);
// Create the DOMSource
DOMSource request = createDOMSourceFromString(DispatchTestConstants.sampleSoapMessage);
TestLogger.logger.debug(">> Invoking One Way Dispatch");
dispatch.invokeOneWay(request);
// Invoke a second time
TestLogger.logger.debug(">> Invoking One Way Dispatch");
dispatch.invokeOneWay(request);
}
@Test
public void testBadDOMSource() throws Exception {
TestLogger.logger.debug("---------------------------------------");
// Initialize the JAX-WS client artifacts
Service svc = Service.create(DispatchTestConstants.QNAME_SERVICE);
svc.addPort(DispatchTestConstants.QNAME_PORT, null, server.getEndpoint("EchoService"));
Dispatch<Source> dispatch = svc.createDispatch(DispatchTestConstants.QNAME_PORT,
Source.class, Service.Mode.PAYLOAD);
// Create the DOMSource
DOMSource request = new DOMSource();
try {
dispatch.invokeOneWay(request);
fail("WebServiceException was expected");
} catch (WebServiceException e) {
TestLogger.logger.debug("A Web Service Exception was expected: " + e.toString());
assertTrue(e.getMessage() != null);
} catch (Exception e) {
fail("WebServiceException was expected, but received " + e);
}
// Invoke a second time
try {
dispatch.invokeOneWay(request);
fail("WebServiceException was expected");
} catch (WebServiceException e) {
TestLogger.logger.debug("A Web Service Exception was expected: " + e.toString());
assertTrue(e.getMessage() != null);
} catch (Exception e) {
fail("WebServiceException was expected, but received " + e);
}
}
/**
* Create a DOMSource with the provided String as the content
* @param input
* @return
*/
private DOMSource createDOMSourceFromString(String input) throws Exception {
byte[] bytes = input.getBytes();
ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
Document domTree = domBuilder.parse(stream);
Node node = domTree.getDocumentElement();
DOMSource domSource = new DOMSource(node);
return domSource;
}
/**
* Create a String from the provided Source
* @param input
* @return
*/
private String createStringFromSource(Source input) throws Exception {
StringWriter sw = new StringWriter();
OMXMLBuilderFactory.createOMBuilder(input).getDocument().serializeAndConsume(sw);
return sw.toString();
}
}
| |
/*
* Copyright (c) 2011-2018 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* The code was inspired by the similarly named JCTools class:
* https://github.com/JCTools/JCTools/blob/master/jctools-core/src/main/java/org/jctools/queues/atomic
*/
package reactor.util.concurrent;
import java.util.AbstractQueue;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.function.BiPredicate;
import reactor.util.annotation.Nullable;
/**
* A multi-producer single consumer unbounded queue.
* @param <E> the contained value type
*/
final class MpscLinkedQueue<E> extends AbstractQueue<E> implements BiPredicate<E, E> {
private volatile LinkedQueueNode<E> producerNode;
private final static AtomicReferenceFieldUpdater<MpscLinkedQueue, LinkedQueueNode> PRODUCER_NODE_UPDATER
= AtomicReferenceFieldUpdater.newUpdater(MpscLinkedQueue.class, LinkedQueueNode.class, "producerNode");
private volatile LinkedQueueNode<E> consumerNode;
private final static AtomicReferenceFieldUpdater<MpscLinkedQueue, LinkedQueueNode> CONSUMER_NODE_UPDATER
= AtomicReferenceFieldUpdater.newUpdater(MpscLinkedQueue.class, LinkedQueueNode.class, "consumerNode");
public MpscLinkedQueue() {
LinkedQueueNode<E> node = new LinkedQueueNode<>();
CONSUMER_NODE_UPDATER.lazySet(this, node);
PRODUCER_NODE_UPDATER.getAndSet(this, node);// this ensures correct construction:
// StoreLoad
}
/**
* {@inheritDoc} <br>
* <p>
* IMPLEMENTATION NOTES:<br>
* Offer is allowed from multiple threads.<br>
* Offer allocates a new node and:
* <ol>
* <li>Swaps it atomically with current producer node (only one producer 'wins')
* <li>Sets the new node as the node following from the swapped producer node
* </ol>
* This works because each producer is guaranteed to 'plant' a new node and link the old node. No 2
* producers can get the same producer node as part of XCHG guarantee.
*
* @see java.util.Queue#offer(java.lang.Object)
*/
@Override
@SuppressWarnings("unchecked")
public final boolean offer(final E e) {
Objects.requireNonNull(e, "The offered value 'e' must be non-null");
final LinkedQueueNode<E> nextNode = new LinkedQueueNode<>(e);
final LinkedQueueNode<E> prevProducerNode = PRODUCER_NODE_UPDATER.getAndSet(this, nextNode);
// Should a producer thread get interrupted here the chain WILL be broken until that thread is resumed
// and completes the store in prev.next.
prevProducerNode.soNext(nextNode); // StoreStore
return true;
}
/**
* This is an additional {@link java.util.Queue} extension for
* {@link java.util.Queue#offer} which allows atomically offer two elements at once.
* <p>
* IMPLEMENTATION NOTES:<br>
* Offer over {@link #test} is allowed from multiple threads.<br>
* Offer over {@link #test} allocates a two new nodes and:
* <ol>
* <li>Swaps them atomically with current producer node (only one producer 'wins')
* <li>Sets the new nodes as the node following from the swapped producer node
* </ol>
* This works because each producer is guaranteed to 'plant' a new node and link the old node. No 2
* producers can get the same producer node as part of XCHG guarantee.
*
* @see java.util.Queue#offer(java.lang.Object)
*
* @param e1 first element to offer
* @param e2 second element to offer
*
* @return indicate whether elements has been successfully offered
*/
@Override
@SuppressWarnings("unchecked")
public boolean test(E e1, E e2) {
Objects.requireNonNull(e1, "The offered value 'e1' must be non-null");
Objects.requireNonNull(e2, "The offered value 'e2' must be non-null");
final LinkedQueueNode<E> nextNode = new LinkedQueueNode<>(e1);
final LinkedQueueNode<E> nextNextNode = new LinkedQueueNode<>(e2);
final LinkedQueueNode<E> prevProducerNode = PRODUCER_NODE_UPDATER.getAndSet(this, nextNextNode);
// Should a producer thread get interrupted here the chain WILL be broken until that thread is resumed
// and completes the store in prev.next.
nextNode.soNext(nextNextNode);
prevProducerNode.soNext(nextNode); // StoreStore
return true;
}
/**
* {@inheritDoc} <br>
* <p>
* IMPLEMENTATION NOTES:<br>
* Poll is allowed from a SINGLE thread.<br>
* Poll reads the next node from the consumerNode and:
* <ol>
* <li>If it is null, the queue is assumed empty (though it might not be).
* <li>If it is not null set it as the consumer node and return it's now evacuated value.
* </ol>
* This means the consumerNode.value is always null, which is also the starting point for the queue.
* Because null values are not allowed to be offered this is the only node with it's value set to null at
* any one time.
*
* @see java.util.Queue#poll()
*/
@Nullable
@Override
public E poll() {
LinkedQueueNode<E> currConsumerNode = consumerNode; // don't load twice, it's alright
LinkedQueueNode<E> nextNode = currConsumerNode.lvNext();
if (nextNode != null)
{
// we have to null out the value because we are going to hang on to the node
final E nextValue = nextNode.getAndNullValue();
// Fix up the next ref of currConsumerNode to prevent promoted nodes from keeping new ones alive.
// We use a reference to self instead of null because null is already a meaningful value (the next of
// producer node is null).
currConsumerNode.soNext(currConsumerNode);
CONSUMER_NODE_UPDATER.lazySet(this, nextNode);
// currConsumerNode is now no longer referenced and can be collected
return nextValue;
}
else if (currConsumerNode != producerNode)
{
while ((nextNode = currConsumerNode.lvNext()) == null) { }
// got the next node...
// we have to null out the value because we are going to hang on to the node
final E nextValue = nextNode.getAndNullValue();
// Fix up the next ref of currConsumerNode to prevent promoted nodes from keeping new ones alive.
// We use a reference to self instead of null because null is already a meaningful value (the next of
// producer node is null).
currConsumerNode.soNext(currConsumerNode);
CONSUMER_NODE_UPDATER.lazySet(this, nextNode);
// currConsumerNode is now no longer referenced and can be collected
return nextValue;
}
return null;
}
@Nullable
@Override
public E peek() {
LinkedQueueNode<E> currConsumerNode = consumerNode; // don't load twice, it's alright
LinkedQueueNode<E> nextNode = currConsumerNode.lvNext();
if (nextNode != null)
{
return nextNode.lpValue();
}
else if (currConsumerNode != producerNode)
{
while ((nextNode = currConsumerNode.lvNext()) == null) { }
// got the next node...
return nextNode.lpValue();
}
return null;
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
while (poll() != null && !isEmpty()) { } // NOPMD
}
@Override
public int size() {
// Read consumer first, this is important because if the producer is node is 'older' than the consumer
// the consumer may overtake it (consume past it) invalidating the 'snapshot' notion of size.
LinkedQueueNode<E> chaserNode = consumerNode;
LinkedQueueNode<E> producerNode = this.producerNode;
int size = 0;
// must chase the nodes all the way to the producer node, but there's no need to count beyond expected head.
while (chaserNode != producerNode && // don't go passed producer node
chaserNode != null && // stop at last node
size < Integer.MAX_VALUE) // stop at max int
{
LinkedQueueNode<E> next;
next = chaserNode.lvNext();
// check if this node has been consumed, if so return what we have
if (next == chaserNode)
{
return size;
}
chaserNode = next;
size++;
}
return size;
}
@Override
public boolean isEmpty() {
return consumerNode == producerNode;
}
@Override
public Iterator<E> iterator() {
throw new UnsupportedOperationException();
}
static final class LinkedQueueNode<E>
{
private volatile LinkedQueueNode<E> next;
private final static AtomicReferenceFieldUpdater<LinkedQueueNode, LinkedQueueNode> NEXT_UPDATER
= AtomicReferenceFieldUpdater.newUpdater(LinkedQueueNode.class, LinkedQueueNode.class, "next");
private E value;
LinkedQueueNode()
{
this(null);
}
LinkedQueueNode(@Nullable E val)
{
spValue(val);
}
/**
* Gets the current value and nulls out the reference to it from this node.
*
* @return value
*/
@Nullable
public E getAndNullValue()
{
E temp = lpValue();
spValue(null);
return temp;
}
@Nullable
public E lpValue()
{
return value;
}
public void spValue(@Nullable E newValue)
{
value = newValue;
}
public void soNext(@Nullable LinkedQueueNode<E> n)
{
NEXT_UPDATER.lazySet(this, n);
}
@Nullable
public LinkedQueueNode<E> lvNext()
{
return next;
}
}
}
| |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), available at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* TIANI Medgraph AG.
* Portions created by the Initial Developer are Copyright (C) 2003-2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Gunter Zeilinger <gunter.zeilinger@tiani.com>
* Franz Willer <franz.willer@gwi-ag.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4chex.archive.util;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.stream.FileImageInputStream;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmEncodeParam;
import org.dcm4che.data.DcmObjectFactory;
import org.dcm4che.data.DcmParser;
import org.dcm4che.data.DcmParserFactory;
import org.dcm4che.data.FileFormat;
import org.dcm4che.dict.Tags;
import org.dcm4che.dict.UIDs;
import org.dcm4che.dict.VRs;
import org.dcm4che.net.DataSource;
import org.dcm4chex.archive.codec.DecompressCmd;
import org.jboss.logging.Logger;
/**
* @author Gunter.Zeilinger@tiani.com
* @version $Revision: 2173 $
* @since 18.09.2003
*/
public class FileDataSource implements DataSource {
private static final Logger log = Logger.getLogger(FileDataSource.class);;
private final File file;
private final Dataset mergeAttrs;
private final byte[] buffer;
/** if true use Dataset.writeFile instead of writeDataset */
private boolean writeFile = false;
private boolean withoutPixeldata = false;
// buffer == null => send no Pixeldata
public FileDataSource(File file, Dataset mergeAttrs, byte[] buffer) {
this.file = file;
this.mergeAttrs = mergeAttrs;
this.buffer = buffer;
}
/**
* @return Returns the writeFile.
*/
public final boolean isWriteFile() {
return writeFile;
}
/**
* Set the write method (file or net).
* <p>
* If true, this datasource use writeFile instead of writeDataset.
* Therefore the FileMetaInfo will be only written if writeFile is set to true explicitly!
*
* @param writeFile The writeFile to set.
*/
public final void setWriteFile(boolean writeFile) {
this.writeFile = writeFile;
}
public final boolean isWithoutPixeldata() {
return withoutPixeldata;
}
public final void setWithoutPixeldata(boolean withoutPixelData) {
this.withoutPixeldata = withoutPixelData;
}
/**
*
* @param out
* @param tsUID
* @param writeFile
* @throws IOException
*/
public void writeTo(OutputStream out, String tsUID) throws IOException {
log.info("M-READ file:" + file);
FileImageInputStream fiis = new FileImageInputStream(file);
try {
DcmParser parser = DcmParserFactory.getInstance().newDcmParser(fiis);
Dataset ds = DcmObjectFactory.getInstance().newDataset();
parser.setDcmHandler(ds.getDcmHandler());
parser.parseDcmFile(FileFormat.DICOM_FILE, Tags.PixelData);
ds.putAll(mergeAttrs);
String tsOrig = null;
if ( writeFile && ds.getFileMetaInfo() != null ) {
tsOrig = ds.getFileMetaInfo().getTransferSyntaxUID();
if ( tsUID != null ) {
if ( tsUID.equals( UIDs.ExplicitVRLittleEndian) || ! tsUID.equals( tsOrig ) ) { //can only decompress here!
tsUID = UIDs.ExplicitVRLittleEndian;
ds.setFileMetaInfo( DcmObjectFactory.getInstance().newFileMetaInfo(ds, tsUID));
}
} else {
tsUID = tsOrig;
}
}
DcmEncodeParam enc = DcmEncodeParam.valueOf(tsUID);
if (withoutPixeldata || parser.getReadTag() != Tags.PixelData) {
log.debug("Dataset:\n");
log.debug(ds);
if ( writeFile )
ds.writeFile(out, enc);
else
ds.writeDataset(out, enc);
return;
}
int len = parser.getReadLength();
if (len == -1 && !enc.encapsulated) {
DecompressCmd cmd = new DecompressCmd(ds, tsOrig, parser);
len = cmd.getPixelDataLength();
log.debug("Dataset:\n");
log.debug(ds);
if ( writeFile )
ds.writeFile(out, enc);
else
ds.writeDataset(out, enc);
ds.writeHeader(out, enc, Tags.PixelData, VRs.OW, (len+1)&~1);
try {
cmd.decompress(enc.byteOrder, out);
} catch (IOException e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException("Decompression failed:", e);
}
if ((len&1)!=0)
out.write(0);
} else {
log.debug("Dataset:\n");
log.debug(ds);
if ( writeFile )
ds.writeFile(out, enc);
else
ds.writeDataset(out, enc);
ds.writeHeader(out, enc, Tags.PixelData, VRs.OB, len);
if (len == -1) {
parser.parseHeader();
int itemlen;
while (parser.getReadTag() == Tags.Item) {
itemlen = parser.getReadLength();
ds.writeHeader(out, enc, Tags.Item, VRs.NONE, itemlen);
copy(fiis, out, itemlen, buffer);
parser.parseHeader();
}
ds.writeHeader(out, enc, Tags.SeqDelimitationItem,
VRs.NONE, 0);
} else {
copy(fiis, out, len, buffer);
}
}
parser.parseDataset(parser.getDcmDecodeParam(), -1);
ds.subSet(Tags.PixelData, -1).writeDataset(out, enc);
} finally {
try {
fiis.close();
} catch (IOException ignore) {
}
}
}
private void copy(FileImageInputStream fiis, OutputStream out, int totLen,
byte[] buffer) throws IOException {
for (int len, toRead = totLen; toRead > 0; toRead -= len) {
len = fiis.read(buffer, 0, Math.min(toRead, buffer.length));
if (len == -1) { throw new EOFException(); }
out.write(buffer, 0, len);
}
}
}
| |
/* Generator.java
Sasha Chislenko, Madan Ramakrishnan
*/
import java.io.*;
import java.util.StringTokenizer;
import java.lang.*;
public class Generator {
//----------------------------------------------------------------------------
public static void main(String argv[]) {
// Declare all necessary variables (descriptions of variables above)
// Initialize miscellaneous function object
MiscFunc miscFunctions;
miscFunctions = new MiscFunc();
long h,currentTime;
int i,j,k;
int currentSite,bannerToShow,matchingCategory;
boolean sitesCheck[] = new boolean[MiscFunc.NUM_SITES];
Site siteList[] = new Site[MiscFunc.NUM_SITES];
Banner bannerList[] = new Banner[MiscFunc.NUM_BANNERS];
int tempSiteFreq[] = new int[MiscFunc.NUM_SITES];
int tempSiteFreqMax = 0;
// Initialize site array
for (i = 0; i < siteList.length; i++) {
siteList[i] = new Site();
}
// Initialize category info
Category categories = new Category(siteList);
// Initialize Banner array
for (i = 0; i < bannerList.length; i++) {
bannerList[i] = new Banner(siteList[i]);
}
// ACCESS GENERATOR
// set up sites that are born and sites that are born in the middle of run
for (j=0; j < MiscFunc.NUM_SITES_BORN; j++) {
do {
currentSite = miscFunctions.RandomVal(0,MiscFunc.NUM_SITES);
System.out.println ("currentSite: " + currentSite + " birthTime: " +
siteList[currentSite].birthTime);
} while (siteList[currentSite].birthTime != 0);
siteList[currentSite].birthTime =
miscFunctions.RandomVal(1,MiscFunc.TIME_STEP * MiscFunc.NUM_ACCESSES);
bannerList[currentSite].birthTime = siteList[currentSite].birthTime;
}
System.out.println ("Set up sites that get born in the middle of run");
for (j=0; j < MiscFunc.NUM_SITES_DEAD; j++) {
do {
currentSite = miscFunctions.RandomVal(0,MiscFunc.NUM_SITES);
} while (siteList[currentSite].deathTime != 9999999);
siteList[currentSite].deathTime =
miscFunctions.RandomVal(siteList[currentSite].birthTime,
MiscFunc.TIME_STEP * MiscFunc.NUM_ACCESSES);
System.out.println ("currentSite: " + currentSite + " deathTime: " +
siteList[currentSite].deathTime);
bannerList[currentSite].deathTime = siteList[currentSite].deathTime;
}
System.out.println ("Finished setting up sites that die in the middle of run");
try {
FileOutputStream fout = new FileOutputStream("ACCESS.DAT");
PrintStream accessOutput = new PrintStream(fout);
currentTime = 0;
h = 0;
while (h < MiscFunc.NUM_ACCESSES) {
if (h % 1000 == 0)
System.out.println("ACC. GENERATOR: " + h + "/" + MiscFunc.NUM_ACCESSES);
currentTime += (long) miscFunctions.RandomVal(0,MiscFunc.TIME_STEP);
currentSite = miscFunctions.RandomVal(0,MiscFunc.NUM_SITES);
if (siteList[currentSite].birthTime <= currentTime &&
siteList[currentSite].deathTime > currentTime)
{
h++;
siteList[currentSite].intFreq++;
accessOutput.println(currentTime + " " + currentSite);
}
}
} // end try
catch (IOException e) {
System.out.println("Error opening file ACCESS.DAT");
System.exit(1);
}
System.out.println("Finished generating accesses");
// Initialize frequency values of Site
for (i = 0; i < siteList.length; i++) {
siteList[i].frequency = (double)
Math.floor(MiscFunc.PREC_FACTOR * siteList[i].intFreq /
MiscFunc.NUM_ACCESSES) / MiscFunc.PREC_FACTOR;
}
System.out.println("Finished with frequencies");
for (j=0; j < MiscFunc.NUM_BANNERS; j++) {
bannerList[j].RestartBannerCount();
}
System.out.println ("Restarted banner counts; About to write SITE.DAT");
// Write site data to file
try {
FileOutputStream fout = new FileOutputStream("SITE.DAT");
PrintStream siteOutput = new PrintStream(fout);
siteOutput.println("ID" + "\t" +
"IntFreq" + "\t" +
"birth" + "\t" +
"death" + "\t" +
"freq" + "\t" +
"bias" + "\t" +
"bShift" + "\t" +
"bPeriod" + "\t" +
"#catIn" + "\t" +
"catIn");
for (i = 0; i < MiscFunc.NUM_SITES; i++) {
siteOutput.print(i + "\t" + siteList[i].intFreq + "\t" +
siteList[i].birthTime + "\t" + siteList[i].deathTime + "\t" +
siteList[i].frequency + "\t" + siteList[i].bias + "\t" +
siteList[i].biasShift + "\t" + siteList[i].biasPeriod + "\t" +
siteList[i].numCategoriesIn + " ");
for (j=0; j < siteList[i].numCategoriesIn; j++) {
siteOutput.print(siteList[i].categoriesIn[j] + " ");
}
siteOutput.println("");
}
}
catch (IOException e) {
System.out.println("Error opening file: SITE.DAT " + e);
}
System.out.println("Wrote SITE.DAT; about to write SITEVSCAT.DAT");
// Write site vs. category biases to file
try {
FileOutputStream fout = new FileOutputStream("SITEVSCAT.DAT");
PrintStream siteOutput = new PrintStream(fout);
siteOutput.println("siteID (site are rows, categories are columns)");
for (i = 0; i < MiscFunc.NUM_SITES; i++) {
siteOutput.print(i);
for (j=0; j < MiscFunc.NUM_CATEGORIES; j++) {
siteOutput.print("\t" + siteList[i].siteVsCatBias[j]);
}
siteOutput.println("");
}
}
catch (IOException e) {
System.out.println("Error opening file: SITEVSCAT.DAT " + e);
}
// Write general banner data to file
System.out.println("Finished with SITEVSCAT.DAT; about to write BANNER.DAT");
try {
FileOutputStream fout = new FileOutputStream("BANNER.DAT");
PrintStream bannerOutput = new PrintStream(fout);
bannerOutput.println("ID" + "\t" +
"numLeft" + "\t" +
"bias" + "\t" +
"bShift" + "\t" +
"bPeriod" + "\t" +
"birth" + "\t" +
"death" + "\t" +
"#catIn" + "\t" +
"catIn");
for (i = 0; i < MiscFunc.NUM_BANNERS; i++)
{
bannerOutput.print(i + "\t" + bannerList[i].numLeft +
"\t" + bannerList[i].bias +
"\t" + bannerList[i].biasShift +
"\t" + bannerList[i].biasPeriod +
"\t" + bannerList[i].birthTime +
"\t" + bannerList[i].deathTime +
"\t" + bannerList[i].numCategoriesIn +
"\t");
for (j=0; j < bannerList[i].numCategoriesIn; j++) {
bannerOutput.print(bannerList[i].categoriesIn[j] + " ");
}
bannerOutput.println("");
}
}
catch (IOException e) {
System.out.println("Error opening file: " + e);
System.exit(1);
}
// Write banner vs category bias data to file
System.out.println("Finished with BANNER.DAT; " +
"Now writing on BANVSCAT.DAT");
try {
FileOutputStream fout = new FileOutputStream("BANVSCAT.DAT");
PrintStream bannerOutput = new PrintStream(fout);
bannerOutput.println("BannerID (Banners are rows, categories are columns)");
for (i = 0; i < MiscFunc.NUM_BANNERS; i++)
{
bannerOutput.print(i);
for (j=0; j < MiscFunc.NUM_CATEGORIES; j++) {
bannerOutput.print("\t" + bannerList[i].banVsCatBias[j]);
}
bannerOutput.println("");
}
}
catch (IOException e) {
System.out.println("Error opening file: " + e);
System.exit(1);
}
// Write banner vs site bias data to file
System.out.println("Finished with BANVSCAT.DAT; " +
"Now writing on BANVSSITE.DAT");
try {
FileOutputStream fout = new FileOutputStream("BANVSSITE.DAT");
PrintStream bannerOutput = new PrintStream(fout);
bannerOutput.println("BannerID (Banners are rows, sites are columns)");
for (i = 0; i < MiscFunc.NUM_BANNERS; i++)
{
bannerOutput.print(i);
for (j=0; j < MiscFunc.NUM_SITES; j++) {
bannerOutput.print("\t" + bannerList[i].banVsSiteBias[j]);
}
bannerOutput.println("");
}
}
catch (IOException e) {
System.out.println("Error opening file: " + e);
System.exit(1);
}
// Write category data to file
System.out.println("Finished with BANVSSITE.DAT; about to write CATEGORY.DAT");
try {
FileOutputStream fout = new FileOutputStream("CATEGORY.DAT");
PrintStream catOutput = new PrintStream(fout);
catOutput.println("CatID" + "\t" +
"bias" + "\t" +
"bAmp" + "\t" +
"bPeriod" + "\t" +
"bShift" + "\t" +
"#sitesIn" + "\t" +
"sitesIn");
for (i = 0; i < MiscFunc.NUM_CATEGORIES; i++) {
catOutput.print(i + " \t" +
categories.bias[i] + "\t" +
categories.fluct_bias_amplitude[i] + "\t" +
categories.fluct_bias_period[i] + "\t" +
categories.fluct_bias_shift[i] + "\t" +
categories.sitesPerCat[i][MiscFunc.NUM_SITES] + "\t");
for (j=0; j < categories.sitesPerCat[i][MiscFunc.NUM_SITES]; j++) {
catOutput.print(categories.sitesPerCat[i][j] + " ");
}
catOutput.println("");
}
}
catch (IOException e) {
System.out.println("Error opening file: " + e);
System.exit(1);
}
System.out.println("Finished with CATEGORY.DAT; Done with Generator");
}
}
| |
/*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.multimap;
import com.hazelcast.config.Config;
import com.hazelcast.config.MultiMapConfig;
import com.hazelcast.core.BaseMultiMap;
import com.hazelcast.core.EntryAdapter;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.MultiMap;
import com.hazelcast.core.TransactionalMultiMap;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.transaction.TransactionContext;
import com.hazelcast.transaction.TransactionException;
import com.hazelcast.transaction.TransactionNotActiveException;
import com.hazelcast.transaction.TransactionalTask;
import com.hazelcast.transaction.TransactionalTaskContext;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class TxnMultiMapTest extends HazelcastTestSupport {
@Test
public void testTxnCommit() throws TransactionException {
final String map1 = "map1";
final String map2 = "map2";
final String key = "1";
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance h1 = factory.newHazelcastInstance();
HazelcastInstance h2 = factory.newHazelcastInstance();
boolean success = h1.executeTransaction(new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
TransactionalMultiMap<String, String> txMap1 = context.getMultiMap(map1);
TransactionalMultiMap<String, String> txMap2 = context.getMultiMap(map2);
assertTrue(txMap1.put(key, "value1"));
Object value1 = getSingleValue(txMap1, key);
assertEquals("value1", value1);
assertTrue(txMap2.put(key, "value2"));
Object value2 = getSingleValue(txMap2, key);
assertEquals("value2", value2);
return true;
}
});
assertTrue(success);
assertEquals("value1", getSingleValue(h1.<String, String>getMultiMap(map1), key));
assertEquals("value1", getSingleValue(h2.<String, String>getMultiMap(map1), key));
assertEquals("value2", getSingleValue(h1.<String, String>getMultiMap(map2), key));
assertEquals("value2", getSingleValue(h2.<String, String>getMultiMap(map2), key));
}
@Test
public void testPutRemove() {
String name = "defMM";
Config config = new Config();
config.getMultiMapConfig(name)
.setValueCollectionType(MultiMapConfig.ValueCollectionType.SET);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(4);
HazelcastInstance[] instances = factory.newInstances(config);
TransactionContext context = instances[0].newTransactionContext();
try {
context.beginTransaction();
TransactionalMultiMap<String, String> txnMultiMap = context.getMultiMap(name);
assertEquals(0, txnMultiMap.get("key1").size());
assertEquals(0, txnMultiMap.valueCount("key1"));
assertTrue(txnMultiMap.put("key1", "value1"));
assertFalse(txnMultiMap.put("key1", "value1"));
assertEquals(1, txnMultiMap.get("key1").size());
assertEquals(1, txnMultiMap.valueCount("key1"));
assertFalse(txnMultiMap.remove("key1", "value2"));
assertTrue(txnMultiMap.remove("key1", "value1"));
assertFalse(txnMultiMap.remove("key2", "value2"));
context.commitTransaction();
} catch (Exception e) {
fail(e.getMessage());
context.rollbackTransaction();
}
assertEquals(0, instances[1].getMultiMap(name).size());
assertTrue(instances[2].getMultiMap(name).put("key1", "value1"));
assertTrue(instances[2].getMultiMap(name).put("key2", "value2"));
}
@Test(expected = TransactionNotActiveException.class)
public void testTxnMultimapOuterTransaction() {
HazelcastInstance hz = createHazelcastInstance();
TransactionContext transactionContext = hz.newTransactionContext();
transactionContext.beginTransaction();
TransactionalMultiMap<String, String> txnMultiMap = transactionContext.getMultiMap("testTxnMultimapOuterTransaction");
txnMultiMap.put("key", "value");
transactionContext.commitTransaction();
txnMultiMap.get("key");
}
@Test
public void testListener() {
String mapName = "mm";
long key = 1L;
String value = "value";
String value2 = "value2";
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance instance1 = factory.newHazelcastInstance();
HazelcastInstance instance2 = factory.newHazelcastInstance();
final CountingEntryListener<String, String> listener = new CountingEntryListener<String, String>();
MultiMap<String, String> multiMap = instance1.getMultiMap(mapName);
multiMap.addEntryListener(listener, true);
TransactionContext ctx1 = instance2.newTransactionContext();
ctx1.beginTransaction();
ctx1.getMultiMap(mapName).put(key, value);
ctx1.commitTransaction();
TransactionContext ctx2 = instance2.newTransactionContext();
ctx2.beginTransaction();
ctx2.getMultiMap(mapName).remove(key, value);
ctx2.commitTransaction();
TransactionContext ctx3 = instance2.newTransactionContext();
ctx3.beginTransaction();
ctx3.getMultiMap(mapName).put(key, value2);
ctx3.commitTransaction();
TransactionContext ctx4 = instance1.newTransactionContext();
ctx4.beginTransaction();
ctx4.getMultiMap(mapName).remove(key, value2);
ctx4.commitTransaction();
assertTrueEventually(new AssertTask() {
@Override
public void run() {
assertEquals(2, listener.getAddedCount());
assertEquals(2, listener.getRemovedCount());
}
});
}
@Test
public void testIssue1276Lock() {
Long key = 1L;
Long value = 1L;
String mapName = "myMultimap";
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance instance1 = factory.newHazelcastInstance();
HazelcastInstance instance2 = factory.newHazelcastInstance();
for (int i = 0; i < 2; i++) {
TransactionContext ctx1 = instance1.newTransactionContext();
ctx1.beginTransaction();
BaseMultiMap<Long, Long> txProfileTasks1 = ctx1.getMultiMap(mapName);
txProfileTasks1.put(key, value);
ctx1.commitTransaction();
TransactionContext ctx2 = instance2.newTransactionContext();
ctx2.beginTransaction();
BaseMultiMap<Long, Long> txProfileTasks2 = ctx2.getMultiMap(mapName);
txProfileTasks2.remove(key, value);
ctx2.commitTransaction();
}
}
@Test
public void testMultiMapContainsEntryTxn() {
final HazelcastInstance instance = createHazelcastInstance();
final TransactionContext context = instance.newTransactionContext();
final MultiMap<Object, Object> mm = instance.getMultiMap("testMultiMapContainsEntry");
mm.put("1", "value");
assertTrue(mm.containsEntry("1", "value"));
context.beginTransaction();
TransactionalMultiMap<String, String> txnMap = context.getMultiMap("testMultiMapContainsEntry");
txnMap.put("1", "value2");
assertTrue(mm.containsEntry("1", "value"));
assertFalse(mm.containsEntry("1", "value2"));
txnMap.remove("1", "value2");
assertTrue(mm.containsEntry("1", "value"));
assertFalse(mm.containsEntry("1", "value2"));
context.commitTransaction();
assertTrue(mm.containsEntry("1", "value"));
assertEquals(1, mm.size());
}
@Test
public void testMultiMapPutRemoveWithTxn() {
final HazelcastInstance instance = createHazelcastInstance();
MultiMap<String, String> multiMap = instance.getMultiMap("testMultiMapPutRemoveWithTxn");
multiMap.put("1", "C");
multiMap.put("2", "x");
multiMap.put("2", "y");
final TransactionContext context = instance.newTransactionContext();
context.beginTransaction();
TransactionalMultiMap<String, String> txnMap = context.getMultiMap("testMultiMapPutRemoveWithTxn");
txnMap.put("1", "A");
txnMap.put("1", "B");
Collection g1 = txnMap.get("1");
assertContains(g1, "A");
assertContains(g1, "B");
assertContains(g1, "C");
assertTrue(txnMap.remove("1", "C"));
assertEquals(4, txnMap.size());
Collection g2 = txnMap.get("1");
assertContains(g2, "A");
assertContains(g2, "B");
assertFalse(g2.contains("C"));
Collection r1 = txnMap.remove("2");
assertContains(r1, "x");
assertContains(r1, "y");
assertEquals(0, txnMap.get("2").size());
Collection r2 = txnMap.remove("1");
assertEquals(2, r2.size());
assertContains(r2, "A");
assertContains(r2, "B");
assertEquals(0, txnMap.get("1").size());
assertEquals(0, txnMap.size());
assertEquals(3, multiMap.size());
context.commitTransaction();
assertEquals(0, multiMap.size());
}
private static String getSingleValue(BaseMultiMap<String, String> multiMap, String key) {
Collection<String> collection = multiMap.get(key);
assertEquals(1, collection.size());
return collection.iterator().next();
}
private static class CountingEntryListener<K, V> extends EntryAdapter<K, V> {
private final AtomicInteger addedCount = new AtomicInteger();
private final AtomicInteger removedCount = new AtomicInteger();
public void entryAdded(EntryEvent<K, V> event) {
addedCount.incrementAndGet();
}
public void entryRemoved(EntryEvent<K, V> event) {
removedCount.incrementAndGet();
}
public int getAddedCount() {
return addedCount.intValue();
}
public int getRemovedCount() {
return removedCount.intValue();
}
}
}
| |
/*
* Copyright 2013 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp.fuzzing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import junit.framework.TestCase;
import java.util.Map.Entry;
import java.util.Random;
/**
* @author zplin@google.com (Zhongpeng Lin)
*/
public class FuzzerTest extends TestCase{
private FuzzingContext context;
@Override
public void setUp() {
Random random = new Random(123);
JsonObject config = TestConfig.getConfig();
context = new FuzzingContext(random, config, true);
}
public void testGenerateArray() {
ArrayFuzzer fuzzer =
new ArrayFuzzer(context);
int budget = 10;
Node node = fuzzer.generate(budget);
String code = ArrayFuzzer.getPrettyCode(node);
assertTrue(code.startsWith("["));
assertTrue(code.endsWith("]"));
JsonObject config = fuzzer.getOwnConfig();
assertTrue(
"\nGenerated code: \n" + code,
code.split(",").length
< (int) (config.get("maxLength").getAsDouble()
* (budget - 1)));
}
public void testGenerateNull() {
SimpleFuzzer fuzzer = new SimpleFuzzer(Token.NULL, "null", Type.OBJECT);
Node node = fuzzer.generate(30);
assertEquals("null", SimpleFuzzer.getPrettyCode(node));
}
public void testGenerateBoolean() {
BooleanFuzzer fuzzer = new BooleanFuzzer(context);
Node node = fuzzer.generate(10);
String code = BooleanFuzzer.getPrettyCode(node).trim();
assertTrue(
"\nGenerated code: \n" + code,
code.equals("true") || code.equals("false"));
}
public void testGenerateNumeric() {
NumericFuzzer fuzzer = new NumericFuzzer(context);
Node node = fuzzer.generate(10);
String code = NumericFuzzer.getPrettyCode(node);
for (int i = 0; i < code.length(); i++) {
assertTrue("\nGenerated code: \n" + code, code.charAt(i) >= '0');
assertTrue("\nGenerated code: \n" + code, code.charAt(i) <= '9');
}
}
public void testGenerateString() {
StringFuzzer fuzzer = new StringFuzzer(context);
Node node = fuzzer.generate(10);
String code = StringFuzzer.getPrettyCode(node);
assertTrue("\nGenerated code: \n" + code, code.startsWith("\""));
assertTrue("\nGenerated code: \n" + code, code.endsWith("\""));
}
public void testGenerateRegex() {
RegularExprFuzzer fuzzer = new RegularExprFuzzer(context);
Node node = fuzzer.generate(10);
String code = RegularExprFuzzer.getPrettyCode(node);
assertTrue("\nGenerated code: \n" + code, code.startsWith("/"));
assertNotSame('/', code.charAt(1));
}
public void testGenerateObjectLiteral() {
ObjectFuzzer fuzzer = new ObjectFuzzer(context);
Node node = fuzzer.generate(10);
String code = ObjectFuzzer.getPrettyCode(node);
assertTrue("\nGenerated code: \n" + code, code.startsWith("{"));
assertTrue("\nGenerated code: \n" + code, code.endsWith("}"));
}
public void testGenerateLiteral() throws JsonParseException {
int budget = 0;
LiteralFuzzer literalFuzzer = new LiteralFuzzer(context);
LiteralFuzzer spyFuzzer = spy(literalFuzzer);
doThrow(new RuntimeException("Not enough budget for literal")).
when(spyFuzzer).generate(budget);
budget = 1;
leaveOneSubtype(literalFuzzer.getOwnConfig(), "null");
Node node = literalFuzzer.generate(budget);
String code = AbstractFuzzer.getPrettyCode(node);
assertEquals("null", code.trim());
}
public void testPostfixExpressions() throws JsonParseException {
String[] postfixes = {"++", "--"};
String[] types = {"postInc", "postDec"};
for (int i = 0; i < postfixes.length; i++) {
setUp();
UnaryExprFuzzer fuzzer = new UnaryExprFuzzer(context);
leaveOneSubtype(fuzzer.getOwnConfig(), types[i]);
Node node = fuzzer.generate(10);
String code = UnaryExprFuzzer.getPrettyCode(node);
assertTrue(code.endsWith(postfixes[i]));
}
}
public void testPrefixExpressions() throws JsonParseException {
String[] prefixes =
{"void", "typeof", "+", "-", "~", "!", "++", "--", "delete"};
String[] types = {"void", "typeof", "pos", "neg", "bitNot", "not", "inc",
"dec", "delProp"};
for (int i = 0; i < prefixes.length; i++) {
setUp();
UnaryExprFuzzer fuzzer = new UnaryExprFuzzer(context);
leaveOneSubtype(fuzzer.getOwnConfig(), types[i]);
Node node = fuzzer.generate(10);
String code = UnaryExprFuzzer.getPrettyCode(node);
assertTrue(code.startsWith(prefixes[i]));
}
}
public void testNewExpression() throws JsonParseException {
FunctionCallFuzzer fuzzer =
new FunctionCallFuzzer(context);
leaveOneSubtype(fuzzer.getOwnConfig(), "constructorCall");
Node node = fuzzer.generate(10);
String code = FunctionCallFuzzer.getPrettyCode(node);
assertTrue(code.startsWith("new "));
}
public void testCallExpression() throws JsonParseException {
FunctionCallFuzzer fuzzer =
new FunctionCallFuzzer(context);
leaveOneSubtype(fuzzer.getOwnConfig(), "normalCall");
Node node = fuzzer.generate(10);
String code = FunctionCallFuzzer.getPrettyCode(node);
assertFalse(code.startsWith("new "));
}
public void testGenerateBinaryExpression() throws JsonParseException {
int budget = 50;
String[] operators = {"*", "/", "%", "+", "-", "<<", ">>", ">>>", "<", ">",
"<=", ">=", "instanceof", "in", "==", "!=", "===", "!==", "&", "^",
"|", "&&", "||", "=", "*=", "/=", "%=", "+=", "-=", "<<=", ">>=",
">>>=", "&=", "^=", "|="};
String[] types = {"mul", "div", "mod", "add", "sub", "lsh", "rsh", "ursh",
"lt", "gt", "le", "ge", "instanceof", "in", "eq", "ne", "sheq", "shne",
"bitAnd", "bitXor", "bitOr", "and", "or", "assign", "assignMul",
"assignDiv", "assignMod", "assignAdd", "assignSub", "assignLsh",
"assignRsh", "assignUrsh", "assignBitAnd", "assignBitXor",
"assignBitOr"};
for (int i = 0; i < operators.length; i++) {
context =
new FuzzingContext(new Random(123), TestConfig.getConfig(), true);
BinaryExprFuzzer fuzzer =
new BinaryExprFuzzer(context);
leaveOneSubtype(fuzzer.getOwnConfig(), types[i]);
Node node = fuzzer.generate(budget);
String code = BinaryExprFuzzer.getPrettyCode(node).trim();
assertNotSame(-1, code.indexOf(" " + operators[i] + " "));
}
}
public void testTrinaryExpression() {
TernaryExprFuzzer fuzzer =
new TernaryExprFuzzer(context);
Node node = fuzzer.generate(4);
String code = TernaryExprFuzzer.getPrettyCode(node);
assertNotSame(-1, code.indexOf(" ? "));
assertTrue(code.indexOf(" : ") > code.indexOf(" ? "));
}
public void testVariableStatement() {
VarFuzzer fuzzer = new VarFuzzer(context);
Node node = fuzzer.generate(10);
String code = VarFuzzer.getPrettyCode(node);
assertTrue(code.startsWith("var "));
}
public void testEmptyStatement() {
SimpleFuzzer fuzzer = new SimpleFuzzer(Token.EMPTY, "empty", Type.UNDEFINED);
Node emptyStmt = fuzzer.generate(10);
assertEquals(Token.EMPTY, emptyStmt.getType());
}
public void testIfStatement() {
IfFuzzer fuzzer = new IfFuzzer(context);
Node ifStatement = fuzzer.generate(10);
String code = IfFuzzer.getPrettyCode(ifStatement);
assertTrue(code.startsWith("if ("));
}
public void testWhileStatement() {
WhileFuzzer fuzzer =
new WhileFuzzer(context);
Node whileStatement = fuzzer.generate(10);
String code = WhileFuzzer.getPrettyCode(whileStatement);
assertTrue(code.startsWith("while ("));
}
public void testDoWhileStatement() {
DoWhileFuzzer fuzzer =
new DoWhileFuzzer(context);
Node doStatement = fuzzer.generate(10);
String code = DoWhileFuzzer.getPrettyCode(doStatement);
assertTrue(code.startsWith("do {"));
assertTrue(code.trim().endsWith(");"));
}
public void testForStatement() {
ForFuzzer fuzzer = new ForFuzzer(context);
Node forStatement = fuzzer.generate(10);
String code = ForFuzzer.getPrettyCode(forStatement);
assertTrue(code.startsWith("for ("));
}
public void testForInStatement() {
ForInFuzzer fuzzer =
new ForInFuzzer(context);
Node forInStatement = fuzzer.generate(10);
String code = ForInFuzzer.getPrettyCode(forInStatement);
assertTrue("\nGenerated code: \n" + code, code.startsWith("for ("));
assertTrue("\nGenerated code: \n" + code, code.contains(" in "));
}
public void testSwitchStatement() {
SwitchFuzzer fuzzer =
new SwitchFuzzer(context);
Node switchStmt = fuzzer.generate(20);
String code = SwitchFuzzer.getPrettyCode(switchStmt);
assertTrue("\nGenerated code: \n" + code, code.startsWith("switch("));
}
public void testThrowStatement() {
ThrowFuzzer fuzzer =
new ThrowFuzzer(context);
Node throwStatement = fuzzer.generate(10);
String code = ThrowFuzzer.getPrettyCode(throwStatement);
assertTrue("\nGenerated code: \n" + code, code.startsWith("throw"));
}
public void testTryStatement() {
TryFuzzer fuzzer = new TryFuzzer(context);
Node tryStatement = fuzzer.generate(20);
String code = TryFuzzer.getPrettyCode(tryStatement);
assertTrue("\nGenerated code: \n" + code, code.startsWith("try {"));
}
public void testFunctionDeclaration() {
FunctionFuzzer fuzzer =
new FunctionFuzzer(context, false);
Node functionDecl = fuzzer.generate(20);
String code = FunctionFuzzer.getPrettyCode(functionDecl);
assertTrue("\nGenerated code: \n" + code, code.startsWith("function "));
}
public void testBreakStatement() throws JsonParseException {
BreakFuzzer fuzzer = new BreakFuzzer(context);
fuzzer.getOwnConfig().addProperty("toLabel", 1);
Scope scope = context.scopeManager.localScope();
scope.otherLabels.add("testLabel");
Node breakStmt = fuzzer.generate(10);
String code = BreakFuzzer.getPrettyCode(breakStmt);
assertEquals("break testLabel;", code.trim());
}
public void testContinueStatement() throws JsonParseException {
ContinueFuzzer fuzzer = new ContinueFuzzer(context);
fuzzer.getOwnConfig().addProperty("toLabel", 1);
Scope scope = context.scopeManager.localScope();
scope.loopLabels.add("testLabel");
Node continueStmt = fuzzer.generate(10);
String code = ContinueFuzzer.getPrettyCode(continueStmt);
assertEquals("continue testLabel;", code.trim());
}
public void testDeterministicProgramGenerating() {
ScriptFuzzer fuzzer = new ScriptFuzzer(context);
Node nodes = fuzzer.generate(100);
String code1 = ScriptFuzzer.getPrettyCode(nodes);
setUp();
context =
new FuzzingContext(new Random(123), TestConfig.getConfig(), true);
fuzzer = new ScriptFuzzer(context);
nodes = fuzzer.generate(100);
String code2 = ScriptFuzzer.getPrettyCode(nodes);
assertEquals(code1, code2);
}
private static void leaveOneSubtype(JsonObject typeConfig, String subtypeName)
throws JsonParseException {
JsonObject weightConfig = typeConfig.get("weights").getAsJsonObject();
for (Entry<String, JsonElement> entry : weightConfig.entrySet()) {
String name = entry.getKey();
if (name.equals(subtypeName)) {
weightConfig.addProperty(name, 1);
} else {
weightConfig.addProperty(name, 0);
}
}
}
}
| |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.core.validation.impl;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.core.TestingGraphInstanceBuilder;
import org.kie.workbench.common.stunner.core.TestingGraphMockHandler;
import org.kie.workbench.common.stunner.core.diagram.Diagram;
import org.kie.workbench.common.stunner.core.diagram.Metadata;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.processing.traverse.tree.TreeWalkTraverseProcessorImpl;
import org.kie.workbench.common.stunner.core.rule.RuleEvaluationContext;
import org.kie.workbench.common.stunner.core.rule.RuleSet;
import org.kie.workbench.common.stunner.core.rule.RuleViolation;
import org.kie.workbench.common.stunner.core.rule.violations.DefaultRuleViolations;
import org.kie.workbench.common.stunner.core.util.UUID;
import org.kie.workbench.common.stunner.core.validation.DiagramElementViolation;
import org.kie.workbench.common.stunner.core.validation.ModelBeanViolation;
import org.kie.workbench.common.stunner.core.validation.ModelValidator;
import org.kie.workbench.common.stunner.core.validation.Violation;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DiagramValidatorTest {
public static final String MODEL_VIOLATION = "model violation";
public static final String RULE_VIOLATION = "rule violation";
@Mock
ModelValidator modelValidator;
@Mock
Diagram diagram;
@Mock
Metadata metadata;
private TestDiagramValidator tested;
private TestingGraphMockHandler graphTestHandler;
private class TestDiagramValidator extends AbstractDiagramValidator {
private TestDiagramValidator() {
super(graphTestHandler.getDefinitionManager(),
graphTestHandler.getRuleManager(),
new TreeWalkTraverseProcessorImpl(),
modelValidator);
}
}
@Before
public void setup() throws Exception {
this.graphTestHandler = new TestingGraphMockHandler();
when(diagram.getName()).thenReturn("Test diagram");
when(diagram.getMetadata()).thenReturn(metadata);
this.tested = new TestDiagramValidator();
}
@Test
@SuppressWarnings("unchecked")
public void testValidateDiagram1() {
final TestingGraphInstanceBuilder.TestGraph1 graph1 = TestingGraphInstanceBuilder.newGraph1(graphTestHandler);
when(diagram.getGraph()).thenReturn(graphTestHandler.graph);
tested.validate(diagram,
this::assertNoErrors);
verify(modelValidator,
times(1)).validate(eq(graph1.startNode),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.intermNode),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.endNode),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.edge1),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.edge2),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graphTestHandler.graph),
any(Consumer.class));
}
@Test
@SuppressWarnings("unchecked")
public void testValidateDiagram1InvalidBean() {
final TestingGraphInstanceBuilder.TestGraph1 graph1 = TestingGraphInstanceBuilder.newGraph1(graphTestHandler);
when(diagram.getGraph()).thenReturn(graphTestHandler.graph);
//model violation
final ModelBeanViolation beanViolation = mock(ModelBeanViolation.class);
when(beanViolation.getViolationType()).thenReturn(Violation.Type.ERROR);
when(beanViolation.getMessage()).thenReturn(MODEL_VIOLATION);
doAnswer(invocationOnMock -> {
final Consumer<Collection<ModelBeanViolation>> validationsConsumer =
(Consumer<Collection<ModelBeanViolation>>) invocationOnMock.getArguments()[1];
validationsConsumer.accept(Collections.singleton(beanViolation));
return null;
}).when(modelValidator).validate(eq(graph1.intermNode),
any(Consumer.class));
//graph violation
RuleViolation ruleViolation = mock(RuleViolation.class);
when(ruleViolation.getViolationType()).thenReturn(Violation.Type.ERROR);
when(ruleViolation.getMessage()).thenReturn(RULE_VIOLATION);
when(graphTestHandler.getRuleManager().evaluate(any(RuleSet.class),
any(RuleEvaluationContext.class))).thenReturn(new DefaultRuleViolations().addViolation(ruleViolation));
tested.validate(diagram,
violations -> assertElementError(violations,
TestingGraphInstanceBuilder.INTERM_NODE_UUID));
verify(modelValidator,
times(1)).validate(eq(graph1.startNode),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.intermNode),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.endNode),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.edge1),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.edge2),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graphTestHandler.graph),
any(Consumer.class));
}
@Test
@SuppressWarnings("unchecked")
public void testValidateDiagramOneRuleViolationEmptyModelViolations() {
final TestingGraphInstanceBuilder.TestGraph1 graph1 = TestingGraphInstanceBuilder.newGraph1(graphTestHandler);
when(diagram.getGraph()).thenReturn(graphTestHandler.graph);
//"Empty" model violation
doAnswer(invocationOnMock -> {
final Consumer<Collection<ModelBeanViolation>> validationsConsumer =
(Consumer<Collection<ModelBeanViolation>>) invocationOnMock.getArguments()[1];
validationsConsumer.accept(Collections.emptyList());
return null;
}).when(modelValidator).validate(eq(graph1.intermNode),
any(Consumer.class));
//graph violation
RuleViolation ruleViolation = mock(RuleViolation.class);
when(ruleViolation.getViolationType()).thenReturn(Violation.Type.ERROR);
when(ruleViolation.getMessage()).thenReturn(RULE_VIOLATION);
when(graphTestHandler.getRuleManager().evaluate(any(RuleSet.class),
any(RuleEvaluationContext.class))).thenReturn(new DefaultRuleViolations().addViolation(ruleViolation));
tested.validate(diagram,
violations -> assertElementError(violations,
TestingGraphInstanceBuilder.INTERM_NODE_UUID));
verify(modelValidator,
times(1)).validate(eq(graph1.startNode),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.intermNode),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.endNode),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.edge1),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.edge2),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graphTestHandler.graph),
any(Consumer.class));
}
@Test
@SuppressWarnings("unchecked")
public void testValidateDiagramZeroRuleViolationsEmptyModelViolations() {
final TestingGraphInstanceBuilder.TestGraph1 graph1 = TestingGraphInstanceBuilder.newGraph1(graphTestHandler);
when(diagram.getGraph()).thenReturn(graphTestHandler.graph);
//"Empty" model violation
doAnswer(invocationOnMock -> {
final Consumer<Collection<ModelBeanViolation>> validationsConsumer =
(Consumer<Collection<ModelBeanViolation>>) invocationOnMock.getArguments()[1];
validationsConsumer.accept(Collections.emptyList());
return null;
}).when(modelValidator).validate(eq(graph1.intermNode),
any(Consumer.class));
tested.validate(diagram,
violations -> assertTrue(violations.isEmpty()));
verify(modelValidator,
times(1)).validate(eq(graph1.startNode),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.intermNode),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.endNode),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.edge1),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graph1.edge2),
any(Consumer.class));
verify(modelValidator,
times(1)).validate(eq(graphTestHandler.graph),
any(Consumer.class));
}
private void assertNoErrors(final
Collection<DiagramElementViolation<RuleViolation>> violations) {
assertNotNull(violations);
assertFalse(violations.stream().anyMatch(v -> Violation.Type.ERROR.equals(v.getViolationType())));
}
private void assertElementError(final
Collection<DiagramElementViolation<RuleViolation>> violations,
final String uuid) {
assertNotNull(violations);
assertTrue(violations.stream()
.filter(v -> Violation.Type.ERROR.equals(v.getViolationType()))
.anyMatch(v -> v.getUUID().equals(uuid)));
//model violations
assertTrue(violations.stream()
.map(DiagramElementViolation::getModelViolations)
.flatMap(Collection::stream)
.allMatch(v -> v.getMessage().equals(MODEL_VIOLATION)));
//graph violations
assertTrue(violations.stream()
.map(DiagramElementViolation::getGraphViolations)
.flatMap(Collection::stream)
.allMatch(v -> v.getMessage().equals(RULE_VIOLATION)));
}
@Test
@SuppressWarnings("unchecked")
public void testValidateDiagramWithNullBean() {
final Node nullNode = graphTestHandler.newNode(UUID.uuid(), Optional.empty());
nullNode.setContent(null);
when(diagram.getGraph()).thenReturn(graphTestHandler.graph);
tested.validate(diagram, this::assertNoErrors);
}
}
| |
package nz.org.winters.legodisplaysequencer.dialogs;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bignerdranch.android.multiselector.MultiSelector;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
import java.util.List;
import nz.org.winters.legodisplaysequencer.R;
import nz.org.winters.legodisplaysequencer.TestActivity;
import nz.org.winters.legodisplaysequencer.caches.LegoColoursCache;
import nz.org.winters.legodisplaysequencer.storage.LegoColour;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static nz.org.winters.legodisplaysequencer.CustomMatchers.legoColourEq;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.doReturn;
/**
* Created by mathew on 9/9/17.
* In project lego-display-sequencer
*/
@RunWith(AndroidJUnit4.class)
public class DialogUseColourSettingsTest {
@Rule
public ActivityTestRule<TestActivity> mActivityRule = new ActivityTestRule<>(
TestActivity.class);
private List<LegoColour> list = new ArrayList<>();
@Mock
private LegoColoursCache legoColoursCacheMock;
private RecyclerView.Adapter<LegoColoursCache.ViewHolder> adapter;
private MultiSelector selector = new MultiSelector();
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
LegoColoursCache.replaceInstance(legoColoursCacheMock);
adapter = getRecyclerAdapter(InstrumentationRegistry.getTargetContext());
list.add(LegoColour.colours.Lego_Brick_Red.getLegoColour());
list.add(LegoColour.colours.Lego_Brick_Yellow.getLegoColour());
list.add(LegoColour.colours.Lego_White.getLegoColour());
doReturn(adapter).when(legoColoursCacheMock).getRecyclerAdapter(any(Context.class));
doReturn(selector).when(legoColoursCacheMock).getSelector();
selector.setSelectable(true);
}
public RecyclerView.Adapter<LegoColoursCache.ViewHolder> getRecyclerAdapter(@NonNull final Context context){
RecyclerView.Adapter<LegoColoursCache.ViewHolder> adapter =new RecyclerView.Adapter<LegoColoursCache.ViewHolder>() {
@Override
public LegoColoursCache.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_colour, parent, false);
return new LegoColoursCache.ViewHolder(view, selector);
}
@Override
public void onBindViewHolder(LegoColoursCache.ViewHolder holder, int position) {
holder.bind(context, list.get(position));
}
@Override
public int getItemCount() {
return list.size();
}
};
return adapter;
}
@Test
public void testCreate(){
DialogUseColoursSettings.showDialog(mActivityRule.getActivity());
onView(withId(android.R.id.button1)).check(matches(isDisplayed()));
onView(withId(R.id.listView)).check(matches(isDisplayed()));
onView(withId(R.id.imageButtonAdd)).check(matches(isDisplayed()));
onView(withId(R.id.imageButtonDelete)).check(matches(isDisplayed()));
onView(withText("Fabuland Brown")).check(matches(isDisplayed()));
onView(withText("Tan")).check(matches(isDisplayed()));
onView(withText("White")).check(matches(isDisplayed()));
onView(withId(android.R.id.button1)).perform(click());
}
@Test
public void testAddColour(){
InOrder inOrder = Mockito.inOrder(legoColoursCacheMock);
DialogUseColoursSettings.showDialog(mActivityRule.getActivity());
onView(withId(android.R.id.button1)).check(matches(isDisplayed()));
onView(withId(R.id.listView)).check(matches(isDisplayed()));
onView(withId(R.id.imageButtonAdd)).check(matches(isDisplayed()));
onView(withId(R.id.imageButtonDelete)).check(matches(isDisplayed()));
onView(withText("Fabuland Brown")).check(matches(isDisplayed()));
onView(withText("Tan")).check(matches(isDisplayed()));
onView(withText("White")).check(matches(isDisplayed()));
onView(withId(R.id.imageButtonAdd)).perform(click());
doReturn(false).when(legoColoursCacheMock).hasColour(eq(LegoColour.colours.Lego_Orange));
doReturn("key-1").when(legoColoursCacheMock).getNewChildKey();
onView(withText("Select Lego Colour")).check(matches(isDisplayed()));
onView(withText("Orange")).check(matches(isDisplayed())).perform(click());
then(legoColoursCacheMock).should(inOrder).hasColour(eq(LegoColour.colours.Lego_Orange));
then(legoColoursCacheMock).should(inOrder).getNewChildKey();
then(legoColoursCacheMock).should(inOrder).write(legoColourEq(LegoColour.colours.Lego_Orange.getLegoColour()));
onView(withId(android.R.id.button1)).perform(click());
then(legoColoursCacheMock).should(inOrder).stopRecyclerAdapter();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testDeleteColour(){
InOrder inOrder = Mockito.inOrder(legoColoursCacheMock);
DialogUseColoursSettings.showDialog(mActivityRule.getActivity());
onView(withId(android.R.id.button1)).check(matches(isDisplayed()));
onView(withId(R.id.listView)).check(matches(isDisplayed()));
onView(withId(R.id.imageButtonAdd)).check(matches(isDisplayed()));
onView(withId(R.id.imageButtonDelete)).check(matches(isDisplayed()));
onView(withText("Fabuland Brown")).check(matches(isDisplayed()));
onView(withText("Tan")).check(matches(isDisplayed()));
onView(withText("White")).check(matches(isDisplayed()));
onView(withText("Fabuland Brown")).perform(click());
assertEquals(1,selector.getSelectedPositions().size());
onView(withText("Tan")).perform(click());
assertEquals(2,selector.getSelectedPositions().size());
doReturn(LegoColour.colours.Lego_Brick_Red.getLegoColour()).when(legoColoursCacheMock).get(eq(0));
doReturn(LegoColour.colours.Lego_Brick_Yellow.getLegoColour()).when(legoColoursCacheMock).get(eq(1));
onView(withId(R.id.imageButtonDelete)).perform(click());
then(legoColoursCacheMock).should(inOrder).get(eq(0));
then(legoColoursCacheMock).should(inOrder).get(eq(1));
onView(withText("Are you sure you want to delete")).check(matches(isDisplayed()));
onView(withId(android.R.id.button1)).perform(click());
then(legoColoursCacheMock).should(inOrder).delete(legoColourEq(LegoColour.colours.Lego_Brick_Red.getLegoColour()));
then(legoColoursCacheMock).should(inOrder).delete(legoColourEq(LegoColour.colours.Lego_Brick_Yellow.getLegoColour()));
onView(withId(android.R.id.button1)).perform(click());
then(legoColoursCacheMock).should(inOrder).stopRecyclerAdapter();
inOrder.verifyNoMoreInteractions();
}
}
| |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.synapse.v2019_06_01_preview.implementation;
import com.microsoft.azure.AzureEnvironment;
import com.microsoft.azure.AzureResponseBuilder;
import com.microsoft.azure.credentials.AzureTokenCredentials;
import com.microsoft.azure.management.apigeneration.Beta;
import com.microsoft.azure.management.apigeneration.Beta.SinceVersion;
import com.microsoft.azure.arm.resources.AzureConfigurable;
import com.microsoft.azure.serializer.AzureJacksonAdapter;
import com.microsoft.rest.RestClient;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.BigDataPools;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.Operations;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.IpFirewallRules;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPools;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolMetadataSyncConfigs;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolOperationResults;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolGeoBackupPolicies;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolDataWarehouseUserActivities;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolRestorePoints;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolReplicationLinks;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolTransparentDataEncryptions;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolBlobAuditingPolicies;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolOperations;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolUsages;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolSensitivityLabels;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolSchemas;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolTables;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolTableColumns;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolConnectionPolicies;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolVulnerabilityAssessments;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolVulnerabilityAssessmentScans;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolSecurityAlertPolicies;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.SqlPoolVulnerabilityAssessmentRuleBaselines;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.Workspaces;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.WorkspaceAadAdmins;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.WorkspaceManagedIdentitySqlControlSettings;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.IntegrationRuntimes;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.IntegrationRuntimeNodeIpAddressOperations;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.IntegrationRuntimeObjectMetadatas;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.IntegrationRuntimeNodes;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.IntegrationRuntimeCredentials;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.IntegrationRuntimeConnectionInfos;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.IntegrationRuntimeAuthKeysOperations;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.IntegrationRuntimeMonitoringDatas;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.IntegrationRuntimeStatusOperations;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.PrivateLinkResources;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.PrivateEndpointConnections;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.PrivateLinkHubs;
import com.microsoft.azure.arm.resources.implementation.AzureConfigurableCoreImpl;
import com.microsoft.azure.arm.resources.implementation.ManagerCore;
/**
* Entry point to Azure Synapse resource management.
*/
public final class SynapseManager extends ManagerCore<SynapseManager, SynapseManagementClientImpl> {
private BigDataPools bigDataPools;
private Operations operations;
private IpFirewallRules ipFirewallRules;
private SqlPools sqlPools;
private SqlPoolMetadataSyncConfigs sqlPoolMetadataSyncConfigs;
private SqlPoolOperationResults sqlPoolOperationResults;
private SqlPoolGeoBackupPolicies sqlPoolGeoBackupPolicies;
private SqlPoolDataWarehouseUserActivities sqlPoolDataWarehouseUserActivities;
private SqlPoolRestorePoints sqlPoolRestorePoints;
private SqlPoolReplicationLinks sqlPoolReplicationLinks;
private SqlPoolTransparentDataEncryptions sqlPoolTransparentDataEncryptions;
private SqlPoolBlobAuditingPolicies sqlPoolBlobAuditingPolicies;
private SqlPoolOperations sqlPoolOperations;
private SqlPoolUsages sqlPoolUsages;
private SqlPoolSensitivityLabels sqlPoolSensitivityLabels;
private SqlPoolSchemas sqlPoolSchemas;
private SqlPoolTables sqlPoolTables;
private SqlPoolTableColumns sqlPoolTableColumns;
private SqlPoolConnectionPolicies sqlPoolConnectionPolicies;
private SqlPoolVulnerabilityAssessments sqlPoolVulnerabilityAssessments;
private SqlPoolVulnerabilityAssessmentScans sqlPoolVulnerabilityAssessmentScans;
private SqlPoolSecurityAlertPolicies sqlPoolSecurityAlertPolicies;
private SqlPoolVulnerabilityAssessmentRuleBaselines sqlPoolVulnerabilityAssessmentRuleBaselines;
private Workspaces workspaces;
private WorkspaceAadAdmins workspaceAadAdmins;
private WorkspaceManagedIdentitySqlControlSettings workspaceManagedIdentitySqlControlSettings;
private IntegrationRuntimes integrationRuntimes;
private IntegrationRuntimeNodeIpAddressOperations integrationRuntimeNodeIpAddressOperations;
private IntegrationRuntimeObjectMetadatas integrationRuntimeObjectMetadatas;
private IntegrationRuntimeNodes integrationRuntimeNodes;
private IntegrationRuntimeCredentials integrationRuntimeCredentials;
private IntegrationRuntimeConnectionInfos integrationRuntimeConnectionInfos;
private IntegrationRuntimeAuthKeysOperations integrationRuntimeAuthKeysOperations;
private IntegrationRuntimeMonitoringDatas integrationRuntimeMonitoringDatas;
private IntegrationRuntimeStatusOperations integrationRuntimeStatusOperations;
private PrivateLinkResources privateLinkResources;
private PrivateEndpointConnections privateEndpointConnections;
private PrivateLinkHubs privateLinkHubs;
/**
* Get a Configurable instance that can be used to create SynapseManager with optional configuration.
*
* @return the instance allowing configurations
*/
public static Configurable configure() {
return new SynapseManager.ConfigurableImpl();
}
/**
* Creates an instance of SynapseManager that exposes Synapse resource management API entry points.
*
* @param credentials the credentials to use
* @param subscriptionId the subscription UUID
* @return the SynapseManager
*/
public static SynapseManager authenticate(AzureTokenCredentials credentials, String subscriptionId) {
return new SynapseManager(new RestClient.Builder()
.withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER)
.withCredentials(credentials)
.withSerializerAdapter(new AzureJacksonAdapter())
.withResponseBuilderFactory(new AzureResponseBuilder.Factory())
.build(), subscriptionId);
}
/**
* Creates an instance of SynapseManager that exposes Synapse resource management API entry points.
*
* @param restClient the RestClient to be used for API calls.
* @param subscriptionId the subscription UUID
* @return the SynapseManager
*/
public static SynapseManager authenticate(RestClient restClient, String subscriptionId) {
return new SynapseManager(restClient, subscriptionId);
}
/**
* The interface allowing configurations to be set.
*/
public interface Configurable extends AzureConfigurable<Configurable> {
/**
* Creates an instance of SynapseManager that exposes Synapse management API entry points.
*
* @param credentials the credentials to use
* @param subscriptionId the subscription UUID
* @return the interface exposing Synapse management API entry points that work across subscriptions
*/
SynapseManager authenticate(AzureTokenCredentials credentials, String subscriptionId);
}
/**
* @return Entry point to manage BigDataPools.
*/
public BigDataPools bigDataPools() {
if (this.bigDataPools == null) {
this.bigDataPools = new BigDataPoolsImpl(this);
}
return this.bigDataPools;
}
/**
* @return Entry point to manage Operations.
*/
public Operations operations() {
if (this.operations == null) {
this.operations = new OperationsImpl(this);
}
return this.operations;
}
/**
* @return Entry point to manage IpFirewallRules.
*/
public IpFirewallRules ipFirewallRules() {
if (this.ipFirewallRules == null) {
this.ipFirewallRules = new IpFirewallRulesImpl(this);
}
return this.ipFirewallRules;
}
/**
* @return Entry point to manage SqlPools.
*/
public SqlPools sqlPools() {
if (this.sqlPools == null) {
this.sqlPools = new SqlPoolsImpl(this);
}
return this.sqlPools;
}
/**
* @return Entry point to manage SqlPoolMetadataSyncConfigs.
*/
public SqlPoolMetadataSyncConfigs sqlPoolMetadataSyncConfigs() {
if (this.sqlPoolMetadataSyncConfigs == null) {
this.sqlPoolMetadataSyncConfigs = new SqlPoolMetadataSyncConfigsImpl(this);
}
return this.sqlPoolMetadataSyncConfigs;
}
/**
* @return Entry point to manage SqlPoolOperationResults.
*/
public SqlPoolOperationResults sqlPoolOperationResults() {
if (this.sqlPoolOperationResults == null) {
this.sqlPoolOperationResults = new SqlPoolOperationResultsImpl(this);
}
return this.sqlPoolOperationResults;
}
/**
* @return Entry point to manage SqlPoolGeoBackupPolicies.
*/
public SqlPoolGeoBackupPolicies sqlPoolGeoBackupPolicies() {
if (this.sqlPoolGeoBackupPolicies == null) {
this.sqlPoolGeoBackupPolicies = new SqlPoolGeoBackupPoliciesImpl(this);
}
return this.sqlPoolGeoBackupPolicies;
}
/**
* @return Entry point to manage SqlPoolDataWarehouseUserActivities.
*/
public SqlPoolDataWarehouseUserActivities sqlPoolDataWarehouseUserActivities() {
if (this.sqlPoolDataWarehouseUserActivities == null) {
this.sqlPoolDataWarehouseUserActivities = new SqlPoolDataWarehouseUserActivitiesImpl(this);
}
return this.sqlPoolDataWarehouseUserActivities;
}
/**
* @return Entry point to manage SqlPoolRestorePoints.
*/
public SqlPoolRestorePoints sqlPoolRestorePoints() {
if (this.sqlPoolRestorePoints == null) {
this.sqlPoolRestorePoints = new SqlPoolRestorePointsImpl(this);
}
return this.sqlPoolRestorePoints;
}
/**
* @return Entry point to manage SqlPoolReplicationLinks.
*/
public SqlPoolReplicationLinks sqlPoolReplicationLinks() {
if (this.sqlPoolReplicationLinks == null) {
this.sqlPoolReplicationLinks = new SqlPoolReplicationLinksImpl(this);
}
return this.sqlPoolReplicationLinks;
}
/**
* @return Entry point to manage SqlPoolTransparentDataEncryptions.
*/
public SqlPoolTransparentDataEncryptions sqlPoolTransparentDataEncryptions() {
if (this.sqlPoolTransparentDataEncryptions == null) {
this.sqlPoolTransparentDataEncryptions = new SqlPoolTransparentDataEncryptionsImpl(this);
}
return this.sqlPoolTransparentDataEncryptions;
}
/**
* @return Entry point to manage SqlPoolBlobAuditingPolicies.
*/
public SqlPoolBlobAuditingPolicies sqlPoolBlobAuditingPolicies() {
if (this.sqlPoolBlobAuditingPolicies == null) {
this.sqlPoolBlobAuditingPolicies = new SqlPoolBlobAuditingPoliciesImpl(this);
}
return this.sqlPoolBlobAuditingPolicies;
}
/**
* @return Entry point to manage SqlPoolOperations.
*/
public SqlPoolOperations sqlPoolOperations() {
if (this.sqlPoolOperations == null) {
this.sqlPoolOperations = new SqlPoolOperationsImpl(this);
}
return this.sqlPoolOperations;
}
/**
* @return Entry point to manage SqlPoolUsages.
*/
public SqlPoolUsages sqlPoolUsages() {
if (this.sqlPoolUsages == null) {
this.sqlPoolUsages = new SqlPoolUsagesImpl(this);
}
return this.sqlPoolUsages;
}
/**
* @return Entry point to manage SqlPoolSensitivityLabels.
*/
public SqlPoolSensitivityLabels sqlPoolSensitivityLabels() {
if (this.sqlPoolSensitivityLabels == null) {
this.sqlPoolSensitivityLabels = new SqlPoolSensitivityLabelsImpl(this);
}
return this.sqlPoolSensitivityLabels;
}
/**
* @return Entry point to manage SqlPoolSchemas.
*/
public SqlPoolSchemas sqlPoolSchemas() {
if (this.sqlPoolSchemas == null) {
this.sqlPoolSchemas = new SqlPoolSchemasImpl(this);
}
return this.sqlPoolSchemas;
}
/**
* @return Entry point to manage SqlPoolTables.
*/
public SqlPoolTables sqlPoolTables() {
if (this.sqlPoolTables == null) {
this.sqlPoolTables = new SqlPoolTablesImpl(this);
}
return this.sqlPoolTables;
}
/**
* @return Entry point to manage SqlPoolTableColumns.
*/
public SqlPoolTableColumns sqlPoolTableColumns() {
if (this.sqlPoolTableColumns == null) {
this.sqlPoolTableColumns = new SqlPoolTableColumnsImpl(this);
}
return this.sqlPoolTableColumns;
}
/**
* @return Entry point to manage SqlPoolConnectionPolicies.
*/
public SqlPoolConnectionPolicies sqlPoolConnectionPolicies() {
if (this.sqlPoolConnectionPolicies == null) {
this.sqlPoolConnectionPolicies = new SqlPoolConnectionPoliciesImpl(this);
}
return this.sqlPoolConnectionPolicies;
}
/**
* @return Entry point to manage SqlPoolVulnerabilityAssessments.
*/
public SqlPoolVulnerabilityAssessments sqlPoolVulnerabilityAssessments() {
if (this.sqlPoolVulnerabilityAssessments == null) {
this.sqlPoolVulnerabilityAssessments = new SqlPoolVulnerabilityAssessmentsImpl(this);
}
return this.sqlPoolVulnerabilityAssessments;
}
/**
* @return Entry point to manage SqlPoolVulnerabilityAssessmentScans.
*/
public SqlPoolVulnerabilityAssessmentScans sqlPoolVulnerabilityAssessmentScans() {
if (this.sqlPoolVulnerabilityAssessmentScans == null) {
this.sqlPoolVulnerabilityAssessmentScans = new SqlPoolVulnerabilityAssessmentScansImpl(this);
}
return this.sqlPoolVulnerabilityAssessmentScans;
}
/**
* @return Entry point to manage SqlPoolSecurityAlertPolicies.
*/
public SqlPoolSecurityAlertPolicies sqlPoolSecurityAlertPolicies() {
if (this.sqlPoolSecurityAlertPolicies == null) {
this.sqlPoolSecurityAlertPolicies = new SqlPoolSecurityAlertPoliciesImpl(this);
}
return this.sqlPoolSecurityAlertPolicies;
}
/**
* @return Entry point to manage SqlPoolVulnerabilityAssessmentRuleBaselines.
*/
public SqlPoolVulnerabilityAssessmentRuleBaselines sqlPoolVulnerabilityAssessmentRuleBaselines() {
if (this.sqlPoolVulnerabilityAssessmentRuleBaselines == null) {
this.sqlPoolVulnerabilityAssessmentRuleBaselines = new SqlPoolVulnerabilityAssessmentRuleBaselinesImpl(this);
}
return this.sqlPoolVulnerabilityAssessmentRuleBaselines;
}
/**
* @return Entry point to manage Workspaces.
*/
public Workspaces workspaces() {
if (this.workspaces == null) {
this.workspaces = new WorkspacesImpl(this);
}
return this.workspaces;
}
/**
* @return Entry point to manage WorkspaceAadAdmins.
*/
public WorkspaceAadAdmins workspaceAadAdmins() {
if (this.workspaceAadAdmins == null) {
this.workspaceAadAdmins = new WorkspaceAadAdminsImpl(this);
}
return this.workspaceAadAdmins;
}
/**
* @return Entry point to manage WorkspaceManagedIdentitySqlControlSettings.
*/
public WorkspaceManagedIdentitySqlControlSettings workspaceManagedIdentitySqlControlSettings() {
if (this.workspaceManagedIdentitySqlControlSettings == null) {
this.workspaceManagedIdentitySqlControlSettings = new WorkspaceManagedIdentitySqlControlSettingsImpl(this);
}
return this.workspaceManagedIdentitySqlControlSettings;
}
/**
* @return Entry point to manage IntegrationRuntimes.
*/
public IntegrationRuntimes integrationRuntimes() {
if (this.integrationRuntimes == null) {
this.integrationRuntimes = new IntegrationRuntimesImpl(this);
}
return this.integrationRuntimes;
}
/**
* @return Entry point to manage IntegrationRuntimeNodeIpAddressOperations.
*/
public IntegrationRuntimeNodeIpAddressOperations integrationRuntimeNodeIpAddressOperations() {
if (this.integrationRuntimeNodeIpAddressOperations == null) {
this.integrationRuntimeNodeIpAddressOperations = new IntegrationRuntimeNodeIpAddressOperationsImpl(this);
}
return this.integrationRuntimeNodeIpAddressOperations;
}
/**
* @return Entry point to manage IntegrationRuntimeObjectMetadatas.
*/
public IntegrationRuntimeObjectMetadatas integrationRuntimeObjectMetadatas() {
if (this.integrationRuntimeObjectMetadatas == null) {
this.integrationRuntimeObjectMetadatas = new IntegrationRuntimeObjectMetadatasImpl(this);
}
return this.integrationRuntimeObjectMetadatas;
}
/**
* @return Entry point to manage IntegrationRuntimeNodes.
*/
public IntegrationRuntimeNodes integrationRuntimeNodes() {
if (this.integrationRuntimeNodes == null) {
this.integrationRuntimeNodes = new IntegrationRuntimeNodesImpl(this);
}
return this.integrationRuntimeNodes;
}
/**
* @return Entry point to manage IntegrationRuntimeCredentials.
*/
public IntegrationRuntimeCredentials integrationRuntimeCredentials() {
if (this.integrationRuntimeCredentials == null) {
this.integrationRuntimeCredentials = new IntegrationRuntimeCredentialsImpl(this);
}
return this.integrationRuntimeCredentials;
}
/**
* @return Entry point to manage IntegrationRuntimeConnectionInfos.
*/
public IntegrationRuntimeConnectionInfos integrationRuntimeConnectionInfos() {
if (this.integrationRuntimeConnectionInfos == null) {
this.integrationRuntimeConnectionInfos = new IntegrationRuntimeConnectionInfosImpl(this);
}
return this.integrationRuntimeConnectionInfos;
}
/**
* @return Entry point to manage IntegrationRuntimeAuthKeysOperations.
*/
public IntegrationRuntimeAuthKeysOperations integrationRuntimeAuthKeysOperations() {
if (this.integrationRuntimeAuthKeysOperations == null) {
this.integrationRuntimeAuthKeysOperations = new IntegrationRuntimeAuthKeysOperationsImpl(this);
}
return this.integrationRuntimeAuthKeysOperations;
}
/**
* @return Entry point to manage IntegrationRuntimeMonitoringDatas.
*/
public IntegrationRuntimeMonitoringDatas integrationRuntimeMonitoringDatas() {
if (this.integrationRuntimeMonitoringDatas == null) {
this.integrationRuntimeMonitoringDatas = new IntegrationRuntimeMonitoringDatasImpl(this);
}
return this.integrationRuntimeMonitoringDatas;
}
/**
* @return Entry point to manage IntegrationRuntimeStatusOperations.
*/
public IntegrationRuntimeStatusOperations integrationRuntimeStatusOperations() {
if (this.integrationRuntimeStatusOperations == null) {
this.integrationRuntimeStatusOperations = new IntegrationRuntimeStatusOperationsImpl(this);
}
return this.integrationRuntimeStatusOperations;
}
/**
* @return Entry point to manage PrivateLinkResources.
*/
public PrivateLinkResources privateLinkResources() {
if (this.privateLinkResources == null) {
this.privateLinkResources = new PrivateLinkResourcesImpl(this);
}
return this.privateLinkResources;
}
/**
* @return Entry point to manage PrivateEndpointConnections.
*/
public PrivateEndpointConnections privateEndpointConnections() {
if (this.privateEndpointConnections == null) {
this.privateEndpointConnections = new PrivateEndpointConnectionsImpl(this);
}
return this.privateEndpointConnections;
}
/**
* @return Entry point to manage PrivateLinkHubs.
*/
public PrivateLinkHubs privateLinkHubs() {
if (this.privateLinkHubs == null) {
this.privateLinkHubs = new PrivateLinkHubsImpl(this);
}
return this.privateLinkHubs;
}
/**
* The implementation for Configurable interface.
*/
private static final class ConfigurableImpl extends AzureConfigurableCoreImpl<Configurable> implements Configurable {
public SynapseManager authenticate(AzureTokenCredentials credentials, String subscriptionId) {
return SynapseManager.authenticate(buildRestClient(credentials), subscriptionId);
}
}
private SynapseManager(RestClient restClient, String subscriptionId) {
super(
restClient,
subscriptionId,
new SynapseManagementClientImpl(restClient).withSubscriptionId(subscriptionId));
}
}
| |
//------------------------------------------------------------------------------
// <wsdl2code-generated>
// This code was generated by http://www.wsdl2code.com version Beta 1.2
//
// Please dont change this code, regeneration will override your changes
//</wsdl2code-generated>
//
//------------------------------------------------------------------------------
//
//This source code was auto-generated by Wsdl2Code Beta Version
//
package com.WSParser.WebServices.EidssService;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
import java.util.Hashtable;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import com.WSParser.WebServices.EidssService.BaseReferenceItem;
public class AddressInfo implements KvmSerializable {
public String NAMESPACE =" http://bv.com/eidss";
public BaseReferenceItem country;
public BaseReferenceItem region;
public BaseReferenceItem rayon;
public BaseReferenceItem settlement;
public String building;
public String house;
public String apartment;
public String street;
public String zipCode;
public String homePhone;
public AddressInfo(){}
public AddressInfo(SoapObject soapObject){
if (soapObject.hasProperty("Country"))
{
SoapObject j59 = (SoapObject)soapObject.getProperty("Country");
country = new BaseReferenceItem (j59);
}
if (soapObject.hasProperty("Region"))
{
SoapObject j60 = (SoapObject)soapObject.getProperty("Region");
region = new BaseReferenceItem (j60);
}
if (soapObject.hasProperty("Rayon"))
{
SoapObject j61 = (SoapObject)soapObject.getProperty("Rayon");
rayon = new BaseReferenceItem (j61);
}
if (soapObject.hasProperty("Settlement"))
{
SoapObject j62 = (SoapObject)soapObject.getProperty("Settlement");
settlement = new BaseReferenceItem (j62);
}
if (soapObject.hasProperty("Building"))
{
Object obj = soapObject.getProperty("Building");
if (obj != null && obj.getClass().equals(SoapPrimitive.class)){
SoapPrimitive j63 =(SoapPrimitive) soapObject.getProperty("Building");
building = j63.toString();
}
}
if (soapObject.hasProperty("House"))
{
Object obj = soapObject.getProperty("House");
if (obj != null && obj.getClass().equals(SoapPrimitive.class)){
SoapPrimitive j64 =(SoapPrimitive) soapObject.getProperty("House");
house = j64.toString();
}
}
if (soapObject.hasProperty("Apartment"))
{
Object obj = soapObject.getProperty("Apartment");
if (obj != null && obj.getClass().equals(SoapPrimitive.class)){
SoapPrimitive j65 =(SoapPrimitive) soapObject.getProperty("Apartment");
apartment = j65.toString();
}
}
if (soapObject.hasProperty("Street"))
{
Object obj = soapObject.getProperty("Street");
if (obj != null && obj.getClass().equals(SoapPrimitive.class)){
SoapPrimitive j66 =(SoapPrimitive) soapObject.getProperty("Street");
street = j66.toString();
}
}
if (soapObject.hasProperty("ZipCode"))
{
Object obj = soapObject.getProperty("ZipCode");
if (obj != null && obj.getClass().equals(SoapPrimitive.class)){
SoapPrimitive j67 =(SoapPrimitive) soapObject.getProperty("ZipCode");
zipCode = j67.toString();
}
}
if (soapObject.hasProperty("HomePhone"))
{
Object obj = soapObject.getProperty("HomePhone");
if (obj != null && obj.getClass().equals(SoapPrimitive.class)){
SoapPrimitive j68 =(SoapPrimitive) soapObject.getProperty("HomePhone");
homePhone = j68.toString();
}
}
}
@Override
public Object getProperty(int arg0) {
switch(arg0){
case 0:
return country;
case 1:
return region;
case 2:
return rayon;
case 3:
return settlement;
case 4:
return building;
case 5:
return house;
case 6:
return apartment;
case 7:
return street;
case 8:
return zipCode;
case 9:
return homePhone;
}
return null;
}
@Override
public int getPropertyCount() {
return 10;
}
@Override
public void getPropertyInfo(int index, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo info) {
switch(index){
case 0:
info.type = BaseReferenceItem.class;
info.name = "Country";
break;
case 1:
info.type = BaseReferenceItem.class;
info.name = "Region";
break;
case 2:
info.type = BaseReferenceItem.class;
info.name = "Rayon";
break;
case 3:
info.type = BaseReferenceItem.class;
info.name = "Settlement";
break;
case 4:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Building";
break;
case 5:
info.type = PropertyInfo.STRING_CLASS;
info.name = "House";
break;
case 6:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Apartment";
break;
case 7:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Street";
break;
case 8:
info.type = PropertyInfo.STRING_CLASS;
info.name = "ZipCode";
break;
case 9:
info.type = PropertyInfo.STRING_CLASS;
info.name = "HomePhone";
break;
}
}
@Override
public void setProperty(int index, Object value) {
switch(index){
case 0:
country = (BaseReferenceItem)value;
break;
case 1:
region = (BaseReferenceItem)value;
break;
case 2:
rayon = (BaseReferenceItem)value;
break;
case 3:
settlement = (BaseReferenceItem)value;
break;
case 4:
building = value.toString() ;
break;
case 5:
house = value.toString() ;
break;
case 6:
apartment = value.toString() ;
break;
case 7:
street = value.toString() ;
break;
case 8:
zipCode = value.toString() ;
break;
case 9:
homePhone = value.toString() ;
break;
}
}
}
| |
/*
* Copyright (c) 2009-present, b3log.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.latke.logging;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
/**
* Latke logger.
*
* <p>
* The logging will delegate to slf4j.
* </p>
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.1.1, Jan 4, 2016
* @see Level
*/
public final class Logger {
/**
* The fully qualified class name.
*/
private static final String FQCN = Logger.class.getName();
/**
* SLF4j logger.
*/
private org.slf4j.Logger proxy;
/**
* Constructs a logger with the specified class name.
*
* @param className the specified class name
*/
private Logger(final String className) {
proxy = LoggerFactory.getLogger(className);
}
/**
* Gets a logger with the specified class name.
*
* @param className the specified class name
* @return logger
*/
public static Logger getLogger(final String className) {
return new Logger(className);
}
/**
* Gets a logger with the specified class.
*
* @param clazz the specified class
* @return logger
*/
public static Logger getLogger(final Class<?> clazz) {
return new Logger(clazz.getName());
}
/**
* Logs the specified message at the ERROR level.
*
* @param msg the specified message
*/
public void error(final String msg) {
if (proxy.isErrorEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, null, null);
} else {
proxy.error(msg);
}
}
}
/**
* Logs the specified message at the WARN level.
*
* @param msg the specified message
*/
public void warn(final String msg) {
if (proxy.isWarnEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, null);
} else {
proxy.warn(msg);
}
}
}
/**
* Logs the specified message at the INFO level.
*
* @param msg the specified message
*/
public void info(final String msg) {
if (proxy.isInfoEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.INFO_INT, msg, null, null);
} else {
proxy.info(msg);
}
}
}
/**
* Logs the specified message at the DEBUG level.
*
* @param msg the specified message
*/
public void debug(final String msg) {
if (proxy.isDebugEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, null);
} else {
proxy.debug(msg);
}
}
}
/**
* Logs the specified message at the TRACE level.
*
* @param msg the specified message
*/
public void trace(final String msg) {
if (proxy.isTraceEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.TRACE_INT, msg, null, null);
} else {
proxy.trace(msg);
}
}
}
/**
* Logs the specified message with the specified logging level and throwable.
*
* @param level the specified logging level
* @param msg the specified message
* @param throwable the specified throwable
*/
public void log(final Level level, final String msg, final Throwable throwable) {
switch (level) {
case ERROR:
if (proxy.isErrorEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, null, throwable);
} else {
proxy.error(msg, throwable);
}
}
break;
case WARN:
if (proxy.isWarnEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, throwable);
} else {
proxy.warn(msg, throwable);
}
}
break;
case INFO:
if (proxy.isInfoEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.INFO_INT, msg, null, throwable);
} else {
proxy.info(msg, throwable);
}
}
break;
case DEBUG:
if (proxy.isDebugEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, throwable);
} else {
proxy.debug(msg, throwable);
}
}
break;
case TRACE:
if (proxy.isTraceEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.TRACE_INT, msg, null, throwable);
} else {
proxy.trace(msg, throwable);
}
}
break;
default:
throw new IllegalStateException("Logging level [" + level + "] is invalid");
}
}
/**
* Logs the specified message with the specified logging level and arguments.
*
* @param level the specified logging level
* @param msg the specified message
* @param args the specified arguments
*/
public void log(final Level level, final String msg, final Object... args) {
String message = msg;
if (null != args && 0 < args.length) {
// Is it a java.text style format?
// Ideally we could match with Pattern.compile("\\{\\d").matcher(format).find())
// However the cost is 14% higher, so we cheaply check for 1 of the first 4 parameters
if (msg.indexOf("{0") >= 0 || msg.indexOf("{1") >= 0 || msg.indexOf("{2") >= 0 || msg.indexOf("{3") >= 0) {
message = java.text.MessageFormat.format(msg, args);
}
}
switch (level) {
case ERROR:
if (proxy.isErrorEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.ERROR_INT, message, null, null);
} else {
proxy.error(message);
}
}
break;
case WARN:
if (proxy.isWarnEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.WARN_INT, message, null, null);
} else {
proxy.warn(message);
}
}
break;
case INFO:
if (proxy.isInfoEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.INFO_INT, message, null, null);
} else {
proxy.info(message);
}
}
break;
case DEBUG:
if (proxy.isDebugEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.DEBUG_INT, message, null, null);
} else {
proxy.debug(message);
}
}
break;
case TRACE:
if (proxy.isTraceEnabled()) {
if (proxy instanceof LocationAwareLogger) {
((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.TRACE_INT, message, null, null);
} else {
proxy.trace(message);
}
}
break;
default:
throw new IllegalStateException("Logging level [" + level + "] is invalid");
}
}
/**
* Determines whether this logger enabled for ERROR level.
*
* @return {@code true} if it is enabled for ERROR level, return {@code false} otherwise
*/
public boolean isErrorEnabled() {
if (proxy instanceof LocationAwareLogger) {
return ((LocationAwareLogger) proxy).isErrorEnabled();
} else {
return proxy.isErrorEnabled();
}
}
/**
* Determines whether this logger enabled for WARN level.
*
* @return {@code true} if it is enabled for WARN level, return {@code false} otherwise
*/
public boolean isWarnEnabled() {
if (proxy instanceof LocationAwareLogger) {
return ((LocationAwareLogger) proxy).isWarnEnabled();
} else {
return proxy.isWarnEnabled();
}
}
/**
* Determines whether this logger enabled for INFO level.
*
* @return {@code true} if it is enabled for INFO level, return {@code false} otherwise
*/
public boolean isInfoEnabled() {
if (proxy instanceof LocationAwareLogger) {
return ((LocationAwareLogger) proxy).isInfoEnabled();
} else {
return proxy.isInfoEnabled();
}
}
/**
* Determines whether this logger enabled for DEBUG level.
*
* @return {@code true} if it is enabled for DEBUG level, return {@code false} otherwise
*/
public boolean isDebugEnabled() {
if (proxy instanceof LocationAwareLogger) {
return ((LocationAwareLogger) proxy).isDebugEnabled();
} else {
return proxy.isDebugEnabled();
}
}
/**
* Determines whether this logger enabled for TRACE level.
*
* @return {@code true} if it is enabled for TRACE level, return {@code false} otherwise
*/
public boolean isTraceEnabled() {
if (proxy instanceof LocationAwareLogger) {
return ((LocationAwareLogger) proxy).isTraceEnabled();
} else {
return proxy.isTraceEnabled();
}
}
/**
* Checks if a message of the given level would actually be logged by this logger.
*
* @param level the given level
* @return {@code true} if it could, returns {@code false} if it couldn't
*/
public boolean isLoggable(final Level level) {
switch (level) {
case TRACE:
return isTraceEnabled();
case DEBUG:
return isDebugEnabled();
case INFO:
return isInfoEnabled();
case WARN:
return isWarnEnabled();
case ERROR:
return isErrorEnabled();
default:
throw new IllegalStateException("Logging level [" + level + "] is invalid");
}
}
}
| |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options.codeStyle;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.codeStyle.CustomCodeStyleSettings;
import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider;
import com.intellij.psi.codeStyle.presentation.CodeStyleSettingPresentation;
import com.intellij.ui.OptionGroup;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.fields.IntegerField;
import com.intellij.util.SmartList;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.lang.reflect.Field;
import java.util.List;
import java.util.*;
public class CodeStyleBlankLinesPanel extends CustomizableLanguageCodeStylePanel {
private static final Logger LOG = Logger.getInstance(CodeStyleBlankLinesPanel.class);
private final List<IntOption> myOptions = new ArrayList<>();
private final Set<String> myAllowedOptions = new HashSet<>();
private boolean myAllOptionsAllowed = false;
private boolean myIsFirstUpdate = true;
private final Map<String, String> myRenamedFields = new THashMap<>();
private final MultiMap<String, IntOption> myCustomOptions = new MultiMap<>();
private final JPanel myPanel = new JPanel(new GridBagLayout());
public CodeStyleBlankLinesPanel(CodeStyleSettings settings) {
super(settings);
init();
}
@Override
protected void init() {
super.init();
JPanel optionsPanel = new JPanel(new GridBagLayout());
Map<CodeStyleSettingPresentation.SettingsGroup, List<CodeStyleSettingPresentation>> settings = CodeStyleSettingPresentation
.getStandardSettings(getSettingsType());
OptionGroup keepBlankLinesOptionsGroup = createOptionsGroup(BLANK_LINES_KEEP, settings.get(new CodeStyleSettingPresentation.SettingsGroup(BLANK_LINES_KEEP)));
OptionGroup blankLinesOptionsGroup = createOptionsGroup(BLANK_LINES, settings.get(new CodeStyleSettingPresentation.SettingsGroup(BLANK_LINES)));
if (keepBlankLinesOptionsGroup != null) {
keepBlankLinesOptionsGroup.setAnchor(keepBlankLinesOptionsGroup.findAnchor());
optionsPanel.add(keepBlankLinesOptionsGroup.createPanel(),
new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
JBUI.emptyInsets(), 0, 0));
}
if (blankLinesOptionsGroup != null) {
blankLinesOptionsGroup.setAnchor(blankLinesOptionsGroup.findAnchor());
optionsPanel.add(blankLinesOptionsGroup.createPanel(),
new GridBagConstraints(0, 1, 1, 1, 1, 0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
JBUI.emptyInsets(), 0, 0));
}
UIUtil.mergeComponentsWithAnchor(keepBlankLinesOptionsGroup, blankLinesOptionsGroup);
optionsPanel.add(new JPanel(),
new GridBagConstraints(0, 2, 1, 1, 0, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0,
0));
optionsPanel.setBorder(JBUI.Borders.empty(0, 10));
JScrollPane scroll = ScrollPaneFactory.createScrollPane(optionsPanel, true);
scroll.setMinimumSize(new Dimension(optionsPanel.getPreferredSize().width + scroll.getVerticalScrollBar().getPreferredSize().width + 5, -1));
scroll.setPreferredSize(scroll.getMinimumSize());
myPanel
.add(scroll,
new GridBagConstraints(0, 0, 1, 1, 0, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0));
final JPanel previewPanel = createPreviewPanel();
myPanel
.add(previewPanel,
new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0));
installPreviewPanel(previewPanel);
addPanelToWatch(myPanel);
myIsFirstUpdate = false;
}
@Override
public LanguageCodeStyleSettingsProvider.SettingsType getSettingsType() {
return LanguageCodeStyleSettingsProvider.SettingsType.BLANK_LINES_SETTINGS;
}
@Nullable
private OptionGroup createOptionsGroup(@NotNull String groupName, @NotNull List<? extends CodeStyleSettingPresentation> settings) {
OptionGroup optionGroup = new OptionGroup(groupName);
final List<IntOption> groupOptions = new SmartList<>();
for (CodeStyleSettingPresentation setting: settings) {
if (myAllOptionsAllowed || myAllowedOptions.contains(setting.getFieldName())) {
groupOptions.add(new IntOption(setting.getUiName(), setting.getFieldName()));
}
}
groupOptions.addAll(myCustomOptions.get(groupName));
sortOptions(groupOptions).forEach(option -> addToOptionGroup(optionGroup, option));
myOptions.addAll(groupOptions);
if (optionGroup.getComponents().length == 0) return null;
return optionGroup;
}
private void addToOptionGroup(OptionGroup optionGroup, IntOption option) {
String title = option.myIntField.getName();
String renamed = myRenamedFields.get(option.getOptionName());
if (renamed != null) title = renamed;
optionGroup.add(new JBLabel(title), option.myIntField);
}
@Override
protected void resetImpl(final CodeStyleSettings settings) {
for (IntOption option : myOptions) {
option.setValue(option.getFieldValue(settings));
}
}
@Override
public void apply(CodeStyleSettings settings) throws ConfigurationException {
for (IntOption option : myOptions) {
option.myIntField.validateContent();
}
for (IntOption option : myOptions) {
option.setFieldValue(settings, option.getValue());
}
}
@Override
public boolean isModified(CodeStyleSettings settings) {
for (IntOption option : myOptions) {
if (option.getFieldValue(settings) != option.getValue()) {
return true;
}
}
return false;
}
@Override
public JComponent getPanel() {
return myPanel;
}
@Override
public void showAllStandardOptions() {
myAllOptionsAllowed = true;
for (IntOption option : myOptions) {
option.myIntField.setEnabled(true);
}
}
@Override
public void showStandardOptions(String... optionNames) {
if (myIsFirstUpdate) {
Collections.addAll(myAllowedOptions, optionNames);
}
for (IntOption option : myOptions) {
option.myIntField.setEnabled(false);
for (String optionName : optionNames) {
if (option.myTarget.getName().equals(optionName)) {
option.myIntField.setEnabled(true);
break;
}
}
}
}
@Override
public void showCustomOption(Class<? extends CustomCodeStyleSettings> settingsClass,
String fieldName,
String title,
String groupName, Object... options) {
showCustomOption(settingsClass, fieldName, title, groupName, null, null, options);
}
@Override
public void showCustomOption(Class<? extends CustomCodeStyleSettings> settingsClass,
String fieldName,
String title,
String groupName,
@Nullable OptionAnchor anchor,
@Nullable String anchorFieldName,
Object... options) {
if (myIsFirstUpdate) {
myCustomOptions.putValue(groupName, new IntOption(title, settingsClass, fieldName,anchor, anchorFieldName));
}
for (IntOption option : myOptions) {
if (option.myTarget.getName().equals(fieldName)) {
option.myIntField.setEnabled(true);
}
}
}
@Override
public void renameStandardOption(String fieldName, String newTitle) {
if (myIsFirstUpdate) {
myRenamedFields.put(fieldName, newTitle);
}
for (IntOption option : myOptions) {
option.myIntField.invalidate();
}
}
private class IntOption extends OrderedOption{
private final IntegerField myIntField;
private final Field myTarget;
private Class<? extends CustomCodeStyleSettings> myTargetClass;
private int myCurrValue = Integer.MAX_VALUE;
private IntOption(@NotNull String title, String fieldName) {
this(title, CommonCodeStyleSettings.class, fieldName, false);
}
private IntOption(@NotNull String title, Class<? extends CustomCodeStyleSettings> targetClass, String fieldName, @Nullable OptionAnchor anchor, @Nullable String anchorOptionName) {
this(title, targetClass, fieldName, false, anchor, anchorOptionName);
myTargetClass = targetClass;
}
// dummy is used to distinguish constructors
private IntOption(@NotNull String title, Class<?> fieldClass, String fieldName, boolean dummy) {
this(title, fieldClass, fieldName, dummy, null, null);
}
private IntOption(@NotNull String title, Class<?> fieldClass, String fieldName, boolean dummy, @Nullable OptionAnchor anchor, @Nullable String anchorOptionName) {
super(fieldName, anchor, anchorOptionName);
try {
myTarget = fieldClass.getField(fieldName);
}
catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
myIntField = new IntegerField(null, 0, 10);
myIntField.setColumns(6);
myIntField.setName(title);
myIntField.setMinimumSize(new Dimension(30, myIntField.getMinimumSize().height));
}
private int getFieldValue(CodeStyleSettings settings) {
try {
if (myTargetClass != null) {
return myTarget.getInt(settings.getCustomSettings(myTargetClass));
}
CommonCodeStyleSettings commonSettings = settings.getCommonSettings(getDefaultLanguage());
return myTarget.getInt(commonSettings);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public void setFieldValue(CodeStyleSettings settings, int value) {
try {
if (myTargetClass != null) {
myTarget.setInt(settings.getCustomSettings(myTargetClass), value);
}
else {
CommonCodeStyleSettings commonSettings = settings.getCommonSettings(getDefaultLanguage());
myTarget.setInt(commonSettings, value);
}
}
catch (IllegalAccessException e) {
LOG.error(e);
}
}
private int getValue() {
try {
myCurrValue = Integer.parseInt(myIntField.getText());
if (myCurrValue < 0) {
myCurrValue = 0;
}
if (myCurrValue > 10) {
myCurrValue = 10;
}
}
catch (NumberFormatException e) {
//bad number entered
myCurrValue = 0;
}
return myCurrValue;
}
public void setValue(int fieldValue) {
if (fieldValue != myCurrValue) {
myCurrValue = fieldValue;
myIntField.setText(String.valueOf(fieldValue));
}
}
}
@Override
protected String getTabTitle() {
return ApplicationBundle.message("title.blank.lines");
}
}
| |
/*L
* Copyright Oracle inc, SAIC-F
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cadsr-util/LICENSE.txt for details.
*/
package gov.nih.nci.ncicb.cadsr.common.persistence.bc4j;
import oracle.jbo.server.EntityImpl;
import oracle.jbo.server.EntityDefImpl;
import oracle.jbo.server.AttributeDefImpl;
import oracle.jbo.RowIterator;
import oracle.jbo.domain.Number;
import oracle.jbo.domain.Date;
import oracle.jbo.Key;
// ---------------------------------------------------------------
// --- File generated by Oracle Business Components for Java.
// ---------------------------------------------------------------
public class DataElementsImpl extends EntityImpl
{
public static final int DEIDSEQ = 0;
public static final int VERSION = 1;
public static final int CONTEIDSEQ = 2;
public static final int PREFERREDNAME = 3;
public static final int VDIDSEQ = 4;
public static final int DECIDSEQ = 5;
public static final int PREFERREDDEFINITION = 6;
public static final int ASLNAME = 7;
public static final int LONGNAME = 8;
public static final int LATESTVERSIONIND = 9;
public static final int DELETEDIND = 10;
public static final int DATECREATED = 11;
public static final int BEGINDATE = 12;
public static final int CREATEDBY = 13;
public static final int ENDDATE = 14;
public static final int DATEMODIFIED = 15;
public static final int MODIFIEDBY = 16;
public static final int CHANGENOTE = 17;
public static final int ORIGIN = 18;
public static final int CDEID = 19;
public static final int QUESTION = 20;
public static final int CONTEXTS = 21;
public static final int DATAELEMENTCONCEPTS = 22;
public static final int VALUEDOMAINS = 23;
public static final int QUESTCONTENTSEXT = 24;
private static EntityDefImpl mDefinitionObject;
/**
*
* This is the default constructor (do not remove)
*/
public DataElementsImpl()
{
}
/**
*
* Retrieves the definition object for this instance class.
*/
public static synchronized EntityDefImpl getDefinitionObject()
{
if (mDefinitionObject == null)
{
mDefinitionObject = (EntityDefImpl)EntityDefImpl.findDefObject("gov.nih.nci.ncicb.cadsr.common.persistence.bc4j.DataElements");
}
return mDefinitionObject;
}
/**
*
* Gets the attribute value for DeIdseq, using the alias name DeIdseq
*/
public String getDeIdseq()
{
return (String)getAttributeInternal(DEIDSEQ);
}
/**
*
* Sets <code>value</code> as the attribute value for DeIdseq
*/
public void setDeIdseq(String value)
{
setAttributeInternal(DEIDSEQ, value);
}
/**
*
* Gets the attribute value for Version, using the alias name Version
*/
public Number getVersion()
{
return (Number)getAttributeInternal(VERSION);
}
/**
*
* Sets <code>value</code> as the attribute value for Version
*/
public void setVersion(Number value)
{
setAttributeInternal(VERSION, value);
}
/**
*
* Gets the attribute value for ConteIdseq, using the alias name ConteIdseq
*/
public String getConteIdseq()
{
return (String)getAttributeInternal(CONTEIDSEQ);
}
/**
*
* Sets <code>value</code> as the attribute value for ConteIdseq
*/
public void setConteIdseq(String value)
{
setAttributeInternal(CONTEIDSEQ, value);
}
/**
*
* Gets the attribute value for PreferredName, using the alias name PreferredName
*/
public String getPreferredName()
{
return (String)getAttributeInternal(PREFERREDNAME);
}
/**
*
* Sets <code>value</code> as the attribute value for PreferredName
*/
public void setPreferredName(String value)
{
setAttributeInternal(PREFERREDNAME, value);
}
/**
*
* Gets the attribute value for VdIdseq, using the alias name VdIdseq
*/
public String getVdIdseq()
{
return (String)getAttributeInternal(VDIDSEQ);
}
/**
*
* Sets <code>value</code> as the attribute value for VdIdseq
*/
public void setVdIdseq(String value)
{
setAttributeInternal(VDIDSEQ, value);
}
/**
*
* Gets the attribute value for DecIdseq, using the alias name DecIdseq
*/
public String getDecIdseq()
{
return (String)getAttributeInternal(DECIDSEQ);
}
/**
*
* Sets <code>value</code> as the attribute value for DecIdseq
*/
public void setDecIdseq(String value)
{
setAttributeInternal(DECIDSEQ, value);
}
/**
*
* Gets the attribute value for PreferredDefinition, using the alias name PreferredDefinition
*/
public String getPreferredDefinition()
{
return (String)getAttributeInternal(PREFERREDDEFINITION);
}
/**
*
* Sets <code>value</code> as the attribute value for PreferredDefinition
*/
public void setPreferredDefinition(String value)
{
setAttributeInternal(PREFERREDDEFINITION, value);
}
/**
*
* Gets the attribute value for AslName, using the alias name AslName
*/
public String getAslName()
{
return (String)getAttributeInternal(ASLNAME);
}
/**
*
* Sets <code>value</code> as the attribute value for AslName
*/
public void setAslName(String value)
{
setAttributeInternal(ASLNAME, value);
}
/**
*
* Gets the attribute value for LongName, using the alias name LongName
*/
public String getLongName()
{
return (String)getAttributeInternal(LONGNAME);
}
/**
*
* Sets <code>value</code> as the attribute value for LongName
*/
public void setLongName(String value)
{
setAttributeInternal(LONGNAME, value);
}
/**
*
* Gets the attribute value for LatestVersionInd, using the alias name LatestVersionInd
*/
public String getLatestVersionInd()
{
return (String)getAttributeInternal(LATESTVERSIONIND);
}
/**
*
* Sets <code>value</code> as the attribute value for LatestVersionInd
*/
public void setLatestVersionInd(String value)
{
setAttributeInternal(LATESTVERSIONIND, value);
}
/**
*
* Gets the attribute value for DeletedInd, using the alias name DeletedInd
*/
public String getDeletedInd()
{
return (String)getAttributeInternal(DELETEDIND);
}
/**
*
* Sets <code>value</code> as the attribute value for DeletedInd
*/
public void setDeletedInd(String value)
{
setAttributeInternal(DELETEDIND, value);
}
/**
*
* Gets the attribute value for DateCreated, using the alias name DateCreated
*/
public Date getDateCreated()
{
return (Date)getAttributeInternal(DATECREATED);
}
/**
*
* Sets <code>value</code> as the attribute value for DateCreated
*/
public void setDateCreated(Date value)
{
setAttributeInternal(DATECREATED, value);
}
/**
*
* Gets the attribute value for BeginDate, using the alias name BeginDate
*/
public Date getBeginDate()
{
return (Date)getAttributeInternal(BEGINDATE);
}
/**
*
* Sets <code>value</code> as the attribute value for BeginDate
*/
public void setBeginDate(Date value)
{
setAttributeInternal(BEGINDATE, value);
}
/**
*
* Gets the attribute value for CreatedBy, using the alias name CreatedBy
*/
public String getCreatedBy()
{
return (String)getAttributeInternal(CREATEDBY);
}
/**
*
* Sets <code>value</code> as the attribute value for CreatedBy
*/
public void setCreatedBy(String value)
{
setAttributeInternal(CREATEDBY, value);
}
/**
*
* Gets the attribute value for EndDate, using the alias name EndDate
*/
public Date getEndDate()
{
return (Date)getAttributeInternal(ENDDATE);
}
/**
*
* Sets <code>value</code> as the attribute value for EndDate
*/
public void setEndDate(Date value)
{
setAttributeInternal(ENDDATE, value);
}
/**
*
* Gets the attribute value for DateModified, using the alias name DateModified
*/
public Date getDateModified()
{
return (Date)getAttributeInternal(DATEMODIFIED);
}
/**
*
* Sets <code>value</code> as the attribute value for DateModified
*/
public void setDateModified(Date value)
{
setAttributeInternal(DATEMODIFIED, value);
}
/**
*
* Gets the attribute value for ModifiedBy, using the alias name ModifiedBy
*/
public String getModifiedBy()
{
return (String)getAttributeInternal(MODIFIEDBY);
}
/**
*
* Sets <code>value</code> as the attribute value for ModifiedBy
*/
public void setModifiedBy(String value)
{
setAttributeInternal(MODIFIEDBY, value);
}
/**
*
* Gets the attribute value for ChangeNote, using the alias name ChangeNote
*/
public String getChangeNote()
{
return (String)getAttributeInternal(CHANGENOTE);
}
/**
*
* Sets <code>value</code> as the attribute value for ChangeNote
*/
public void setChangeNote(String value)
{
setAttributeInternal(CHANGENOTE, value);
}
// Generated method. Do not modify.
protected Object getAttrInvokeAccessor(int index, AttributeDefImpl attrDef) throws Exception
{
switch (index)
{
case DEIDSEQ:
return getDeIdseq();
case VERSION:
return getVersion();
case CONTEIDSEQ:
return getConteIdseq();
case PREFERREDNAME:
return getPreferredName();
case VDIDSEQ:
return getVdIdseq();
case DECIDSEQ:
return getDecIdseq();
case PREFERREDDEFINITION:
return getPreferredDefinition();
case ASLNAME:
return getAslName();
case LONGNAME:
return getLongName();
case LATESTVERSIONIND:
return getLatestVersionInd();
case DELETEDIND:
return getDeletedInd();
case DATECREATED:
return getDateCreated();
case BEGINDATE:
return getBeginDate();
case CREATEDBY:
return getCreatedBy();
case ENDDATE:
return getEndDate();
case DATEMODIFIED:
return getDateModified();
case MODIFIEDBY:
return getModifiedBy();
case CHANGENOTE:
return getChangeNote();
case ORIGIN:
return getOrigin();
case CDEID:
return getCdeId();
case QUESTION:
return getQuestion();
case QUESTCONTENTSEXT:
return getQuestContentsExt();
case CONTEXTS:
return getContexts();
case DATAELEMENTCONCEPTS:
return getDataElementConcepts();
case VALUEDOMAINS:
return getValueDomains();
default:
return super.getAttrInvokeAccessor(index, attrDef);
}
}
// Generated method. Do not modify.
protected void setAttrInvokeAccessor(int index, Object value, AttributeDefImpl attrDef) throws Exception
{
switch (index)
{
case DEIDSEQ:
setDeIdseq((String)value);
return;
case VERSION:
setVersion((Number)value);
return;
case CONTEIDSEQ:
setConteIdseq((String)value);
return;
case PREFERREDNAME:
setPreferredName((String)value);
return;
case VDIDSEQ:
setVdIdseq((String)value);
return;
case DECIDSEQ:
setDecIdseq((String)value);
return;
case PREFERREDDEFINITION:
setPreferredDefinition((String)value);
return;
case ASLNAME:
setAslName((String)value);
return;
case LONGNAME:
setLongName((String)value);
return;
case LATESTVERSIONIND:
setLatestVersionInd((String)value);
return;
case DELETEDIND:
setDeletedInd((String)value);
return;
case DATECREATED:
setDateCreated((Date)value);
return;
case BEGINDATE:
setBeginDate((Date)value);
return;
case CREATEDBY:
setCreatedBy((String)value);
return;
case ENDDATE:
setEndDate((Date)value);
return;
case DATEMODIFIED:
setDateModified((Date)value);
return;
case MODIFIEDBY:
setModifiedBy((String)value);
return;
case CHANGENOTE:
setChangeNote((String)value);
return;
case ORIGIN:
setOrigin((String)value);
return;
case CDEID:
setCdeId((Number)value);
return;
case QUESTION:
setQuestion((String)value);
return;
default:
super.setAttrInvokeAccessor(index, value, attrDef);
return;
}
}
/**
*
* Gets the associated entity ContextsImpl
*/
public ContextsImpl getContexts()
{
return (ContextsImpl)getAttributeInternal(CONTEXTS);
}
/**
*
* Sets <code>value</code> as the associated entity ContextsImpl
*/
public void setContexts(ContextsImpl value)
{
setAttributeInternal(CONTEXTS, value);
}
/**
*
* Gets the associated entity DataElementConceptsImpl
*/
public DataElementConceptsImpl getDataElementConcepts()
{
return (DataElementConceptsImpl)getAttributeInternal(DATAELEMENTCONCEPTS);
}
/**
*
* Sets <code>value</code> as the associated entity DataElementConceptsImpl
*/
public void setDataElementConcepts(DataElementConceptsImpl value)
{
setAttributeInternal(DATAELEMENTCONCEPTS, value);
}
/**
*
* Gets the associated entity ValueDomainsImpl
*/
public ValueDomainsImpl getValueDomains()
{
return (ValueDomainsImpl)getAttributeInternal(VALUEDOMAINS);
}
/**
*
* Sets <code>value</code> as the associated entity ValueDomainsImpl
*/
public void setValueDomains(ValueDomainsImpl value)
{
setAttributeInternal(VALUEDOMAINS, value);
}
/**
*
* Gets the attribute value for Origin, using the alias name Origin
*/
public String getOrigin()
{
return (String)getAttributeInternal(ORIGIN);
}
/**
*
* Sets <code>value</code> as the attribute value for Origin
*/
public void setOrigin(String value)
{
setAttributeInternal(ORIGIN, value);
}
/**
*
* Gets the attribute value for CdeId, using the alias name CdeId
*/
public Number getCdeId()
{
return (Number)getAttributeInternal(CDEID);
}
/**
*
* Sets <code>value</code> as the attribute value for CdeId
*/
public void setCdeId(Number value)
{
setAttributeInternal(CDEID, value);
}
/**
*
* Gets the attribute value for Question, using the alias name Question
*/
public String getQuestion()
{
return (String)getAttributeInternal(QUESTION);
}
/**
*
* Sets <code>value</code> as the attribute value for Question
*/
public void setQuestion(String value)
{
setAttributeInternal(QUESTION, value);
}
/**
*
* Gets the associated entity oracle.jbo.RowIterator
*/
public RowIterator getQuestContentsExt()
{
return (RowIterator)getAttributeInternal(QUESTCONTENTSEXT);
}
/**
*
* Creates a Key object based on given key constituents
*/
public static Key createPrimaryKey(String deIdseq)
{
return new Key(new Object[] {deIdseq});
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.metrics;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import org.apache.cassandra.net.OutboundConnections;
import static org.apache.cassandra.metrics.CassandraMetricsRegistry.Metrics;
import org.apache.cassandra.locator.InetAddressAndPort;
/**
* Metrics for internode connections.
*/
public class InternodeOutboundMetrics
{
public static final String TYPE_NAME = "Connection";
/** Total number of callbacks that were not completed successfully for messages that were sent to this node
* TODO this was always broken, as it never counted those messages without callbacks? So perhaps we can redefine it. */
public static final Meter totalExpiredCallbacks = Metrics.meter(DefaultNameFactory.createMetricName(TYPE_NAME, "TotalTimeouts", null));
/** Number of timeouts for specific IP */
public final Meter expiredCallbacks;
public final String address;
/** Pending tasks for large message TCP Connections */
public final Gauge<Integer> largeMessagePendingTasks;
/** Pending bytes for large message TCP Connections */
public final Gauge<Long> largeMessagePendingBytes;
/** Completed tasks for large message TCP Connections */
public final Gauge<Long> largeMessageCompletedTasks;
/** Completed bytes for large message TCP Connections */
public final Gauge<Long> largeMessageCompletedBytes;
/** Dropped tasks for large message TCP Connections */
public final Gauge<Long> largeMessageDropped;
/** Dropped tasks because of timeout for large message TCP Connections */
public final Gauge<Long> largeMessageDroppedTasksDueToTimeout;
/** Dropped bytes because of timeout for large message TCP Connections */
public final Gauge<Long> largeMessageDroppedBytesDueToTimeout;
/** Dropped tasks because of overload for large message TCP Connections */
public final Gauge<Long> largeMessageDroppedTasksDueToOverload;
/** Dropped bytes because of overload for large message TCP Connections */
public final Gauge<Long> largeMessageDroppedBytesDueToOverload;
/** Dropped tasks because of error for large message TCP Connections */
public final Gauge<Long> largeMessageDroppedTasksDueToError;
/** Dropped bytes because of error for large message TCP Connections */
public final Gauge<Long> largeMessageDroppedBytesDueToError;
/** Pending tasks for small message TCP Connections */
public final Gauge<Integer> smallMessagePendingTasks;
/** Pending bytes for small message TCP Connections */
public final Gauge<Long> smallMessagePendingBytes;
/** Completed tasks for small message TCP Connections */
public final Gauge<Long> smallMessageCompletedTasks;
/** Completed bytes for small message TCP Connections */
public final Gauge<Long> smallMessageCompletedBytes;
/** Dropped tasks for small message TCP Connections */
public final Gauge<Long> smallMessageDroppedTasks;
/** Dropped tasks because of timeout for small message TCP Connections */
public final Gauge<Long> smallMessageDroppedTasksDueToTimeout;
/** Dropped bytes because of timeout for small message TCP Connections */
public final Gauge<Long> smallMessageDroppedBytesDueToTimeout;
/** Dropped tasks because of overload for small message TCP Connections */
public final Gauge<Long> smallMessageDroppedTasksDueToOverload;
/** Dropped bytes because of overload for small message TCP Connections */
public final Gauge<Long> smallMessageDroppedBytesDueToOverload;
/** Dropped tasks because of error for small message TCP Connections */
public final Gauge<Long> smallMessageDroppedTasksDueToError;
/** Dropped bytes because of error for small message TCP Connections */
public final Gauge<Long> smallMessageDroppedBytesDueToError;
/** Pending tasks for small message TCP Connections */
public final Gauge<Integer> urgentMessagePendingTasks;
/** Pending bytes for urgent message TCP Connections */
public final Gauge<Long> urgentMessagePendingBytes;
/** Completed tasks for urgent message TCP Connections */
public final Gauge<Long> urgentMessageCompletedTasks;
/** Completed bytes for urgent message TCP Connections */
public final Gauge<Long> urgentMessageCompletedBytes;
/** Dropped tasks for urgent message TCP Connections */
public final Gauge<Long> urgentMessageDroppedTasks;
/** Dropped tasks because of timeout for urgent message TCP Connections */
public final Gauge<Long> urgentMessageDroppedTasksDueToTimeout;
/** Dropped bytes because of timeout for urgent message TCP Connections */
public final Gauge<Long> urgentMessageDroppedBytesDueToTimeout;
/** Dropped tasks because of overload for urgent message TCP Connections */
public final Gauge<Long> urgentMessageDroppedTasksDueToOverload;
/** Dropped bytes because of overload for urgent message TCP Connections */
public final Gauge<Long> urgentMessageDroppedBytesDueToOverload;
/** Dropped tasks because of error for urgent message TCP Connections */
public final Gauge<Long> urgentMessageDroppedTasksDueToError;
/** Dropped bytes because of error for urgent message TCP Connections */
public final Gauge<Long> urgentMessageDroppedBytesDueToError;
private final MetricNameFactory factory;
/**
* Create metrics for given connection pool.
*
* @param ip IP address to use for metrics label
*/
public InternodeOutboundMetrics(InetAddressAndPort ip, final OutboundConnections messagingPool)
{
// ipv6 addresses will contain colons, which are invalid in a JMX ObjectName
address = ip.getHostAddressAndPortForJMX();
factory = new DefaultNameFactory("Connection", address);
largeMessagePendingTasks = Metrics.register(factory.createMetricName("LargeMessagePendingTasks"), messagingPool.large::pendingCount);
largeMessagePendingBytes = Metrics.register(factory.createMetricName("LargeMessagePendingBytes"), messagingPool.large::pendingBytes);
largeMessageCompletedTasks = Metrics.register(factory.createMetricName("LargeMessageCompletedTasks"),messagingPool.large::sentCount);
largeMessageCompletedBytes = Metrics.register(factory.createMetricName("LargeMessageCompletedBytes"),messagingPool.large::sentBytes);
largeMessageDropped = Metrics.register(factory.createMetricName("LargeMessageDroppedTasks"), messagingPool.large::dropped);
largeMessageDroppedTasksDueToOverload = Metrics.register(factory.createMetricName("LargeMessageDroppedTasksDueToOverload"), messagingPool.large::overloadedCount);
largeMessageDroppedBytesDueToOverload = Metrics.register(factory.createMetricName("LargeMessageDroppedBytesDueToOverload"), messagingPool.large::overloadedBytes);
largeMessageDroppedTasksDueToTimeout = Metrics.register(factory.createMetricName("LargeMessageDroppedTasksDueToTimeout"), messagingPool.large::expiredCount);
largeMessageDroppedBytesDueToTimeout = Metrics.register(factory.createMetricName("LargeMessageDroppedBytesDueToTimeout"), messagingPool.large::expiredBytes);
largeMessageDroppedTasksDueToError = Metrics.register(factory.createMetricName("LargeMessageDroppedTasksDueToError"), messagingPool.large::errorCount);
largeMessageDroppedBytesDueToError = Metrics.register(factory.createMetricName("LargeMessageDroppedBytesDueToError"), messagingPool.large::errorBytes);
smallMessagePendingTasks = Metrics.register(factory.createMetricName("SmallMessagePendingTasks"), messagingPool.small::pendingCount);
smallMessagePendingBytes = Metrics.register(factory.createMetricName("SmallMessagePendingBytes"), messagingPool.small::pendingBytes);
smallMessageCompletedTasks = Metrics.register(factory.createMetricName("SmallMessageCompletedTasks"), messagingPool.small::sentCount);
smallMessageCompletedBytes = Metrics.register(factory.createMetricName("SmallMessageCompletedBytes"),messagingPool.small::sentBytes);
smallMessageDroppedTasks = Metrics.register(factory.createMetricName("SmallMessageDroppedTasks"), messagingPool.small::dropped);
smallMessageDroppedTasksDueToOverload = Metrics.register(factory.createMetricName("SmallMessageDroppedTasksDueToOverload"), messagingPool.small::overloadedCount);
smallMessageDroppedBytesDueToOverload = Metrics.register(factory.createMetricName("SmallMessageDroppedBytesDueToOverload"), messagingPool.small::overloadedBytes);
smallMessageDroppedTasksDueToTimeout = Metrics.register(factory.createMetricName("SmallMessageDroppedTasksDueToTimeout"), messagingPool.small::expiredCount);
smallMessageDroppedBytesDueToTimeout = Metrics.register(factory.createMetricName("SmallMessageDroppedBytesDueToTimeout"), messagingPool.small::expiredBytes);
smallMessageDroppedTasksDueToError = Metrics.register(factory.createMetricName("SmallMessageDroppedTasksDueToError"), messagingPool.small::errorCount);
smallMessageDroppedBytesDueToError = Metrics.register(factory.createMetricName("SmallMessageDroppedBytesDueToError"), messagingPool.small::errorBytes);
urgentMessagePendingTasks = Metrics.register(factory.createMetricName("UrgentMessagePendingTasks"), messagingPool.urgent::pendingCount);
urgentMessagePendingBytes = Metrics.register(factory.createMetricName("UrgentMessagePendingBytes"), messagingPool.urgent::pendingBytes);
urgentMessageCompletedTasks = Metrics.register(factory.createMetricName("UrgentMessageCompletedTasks"), messagingPool.urgent::sentCount);
urgentMessageCompletedBytes = Metrics.register(factory.createMetricName("UrgentMessageCompletedBytes"),messagingPool.urgent::sentBytes);
urgentMessageDroppedTasks = Metrics.register(factory.createMetricName("UrgentMessageDroppedTasks"), messagingPool.urgent::dropped);
urgentMessageDroppedTasksDueToOverload = Metrics.register(factory.createMetricName("UrgentMessageDroppedTasksDueToOverload"), messagingPool.urgent::overloadedCount);
urgentMessageDroppedBytesDueToOverload = Metrics.register(factory.createMetricName("UrgentMessageDroppedBytesDueToOverload"), messagingPool.urgent::overloadedBytes);
urgentMessageDroppedTasksDueToTimeout = Metrics.register(factory.createMetricName("UrgentMessageDroppedTasksDueToTimeout"), messagingPool.urgent::expiredCount);
urgentMessageDroppedBytesDueToTimeout = Metrics.register(factory.createMetricName("UrgentMessageDroppedBytesDueToTimeout"), messagingPool.urgent::expiredBytes);
urgentMessageDroppedTasksDueToError = Metrics.register(factory.createMetricName("UrgentMessageDroppedTasksDueToError"), messagingPool.urgent::errorCount);
urgentMessageDroppedBytesDueToError = Metrics.register(factory.createMetricName("UrgentMessageDroppedBytesDueToError"), messagingPool.urgent::errorBytes);
expiredCallbacks = Metrics.meter(factory.createMetricName("Timeouts"));
// deprecated
Metrics.register(factory.createMetricName("GossipMessagePendingTasks"), (Gauge<Integer>) messagingPool.urgent::pendingCount);
Metrics.register(factory.createMetricName("GossipMessageCompletedTasks"), (Gauge<Long>) messagingPool.urgent::sentCount);
Metrics.register(factory.createMetricName("GossipMessageDroppedTasks"), (Gauge<Long>) messagingPool.urgent::dropped);
}
public void release()
{
Metrics.remove(factory.createMetricName("LargeMessagePendingTasks"));
Metrics.remove(factory.createMetricName("LargeMessagePendingBytes"));
Metrics.remove(factory.createMetricName("LargeMessageCompletedTasks"));
Metrics.remove(factory.createMetricName("LargeMessageCompletedBytes"));
Metrics.remove(factory.createMetricName("LargeMessageDroppedTasks"));
Metrics.remove(factory.createMetricName("LargeMessageDroppedTasksDueToTimeout"));
Metrics.remove(factory.createMetricName("LargeMessageDroppedBytesDueToTimeout"));
Metrics.remove(factory.createMetricName("LargeMessageDroppedTasksDueToOverload"));
Metrics.remove(factory.createMetricName("LargeMessageDroppedBytesDueToOverload"));
Metrics.remove(factory.createMetricName("LargeMessageDroppedTasksDueToError"));
Metrics.remove(factory.createMetricName("LargeMessageDroppedBytesDueToError"));
Metrics.remove(factory.createMetricName("SmallMessagePendingTasks"));
Metrics.remove(factory.createMetricName("SmallMessagePendingBytes"));
Metrics.remove(factory.createMetricName("SmallMessageCompletedTasks"));
Metrics.remove(factory.createMetricName("SmallMessageCompletedBytes"));
Metrics.remove(factory.createMetricName("SmallMessageDroppedTasks"));
Metrics.remove(factory.createMetricName("SmallMessageDroppedTasksDueToTimeout"));
Metrics.remove(factory.createMetricName("SmallMessageDroppedBytesDueToTimeout"));
Metrics.remove(factory.createMetricName("SmallMessageDroppedTasksDueToOverload"));
Metrics.remove(factory.createMetricName("SmallMessageDroppedBytesDueToOverload"));
Metrics.remove(factory.createMetricName("SmallMessageDroppedTasksDueToError"));
Metrics.remove(factory.createMetricName("SmallMessageDroppedBytesDueToError"));
Metrics.remove(factory.createMetricName("GossipMessagePendingTasks"));
Metrics.remove(factory.createMetricName("GossipMessageCompletedTasks"));
Metrics.remove(factory.createMetricName("GossipMessageDroppedTasks"));
Metrics.remove(factory.createMetricName("UrgentMessagePendingTasks"));
Metrics.remove(factory.createMetricName("UrgentMessagePendingBytes"));
Metrics.remove(factory.createMetricName("UrgentMessageCompletedTasks"));
Metrics.remove(factory.createMetricName("UrgentMessageCompletedBytes"));
Metrics.remove(factory.createMetricName("UrgentMessageDroppedTasks"));
Metrics.remove(factory.createMetricName("UrgentMessageDroppedTasksDueToTimeout"));
Metrics.remove(factory.createMetricName("UrgentMessageDroppedBytesDueToTimeout"));
Metrics.remove(factory.createMetricName("UrgentMessageDroppedTasksDueToOverload"));
Metrics.remove(factory.createMetricName("UrgentMessageDroppedBytesDueToOverload"));
Metrics.remove(factory.createMetricName("UrgentMessageDroppedTasksDueToError"));
Metrics.remove(factory.createMetricName("UrgentMessageDroppedBytesDueToError"));
Metrics.remove(factory.createMetricName("Timeouts"));
}
}
| |
/*
* Copyright (c) 2014. Real Time Genomics Limited.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rtg.vcf;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import com.rtg.launcher.AbstractNanoTest;
import com.rtg.launcher.MainResult;
import com.rtg.util.StringUtils;
import com.rtg.util.TestUtils;
import com.rtg.util.io.FileUtils;
import com.rtg.util.io.MemoryPrintStream;
import com.rtg.util.io.TestDirectory;
import com.rtg.util.test.FileHelper;
import com.rtg.vcf.header.VcfHeader;
/**
*/
public class VariantStatisticsTest extends AbstractNanoTest {
public void testGetRatio() {
assertEquals("- (1/0)", VariantStatistics.divide(1L, 0L));
assertEquals("0.00 (0/1)", VariantStatistics.divide(0L, 1L));
assertEquals("0.33 (1/3)", VariantStatistics.divide(1L, 3L));
}
private static final String[] BASE_OUTPUT = {
"Passed Filters : 0" + StringUtils.LS
, "Failed Filters : 0" + StringUtils.LS
};
public void testGetStatistics() {
final VariantStatistics stats = new VariantStatistics(null);
TestUtils.containsAll(stats.getStatistics(), BASE_OUTPUT);
}
public void testPrintStatistics() throws IOException {
final MemoryPrintStream ps = new MemoryPrintStream();
final VariantStatistics stats = new VariantStatistics(null);
stats.printStatistics(ps.outputStream());
TestUtils.containsAll(ps.toString(), BASE_OUTPUT);
}
private static final String[] VARIANTS = {
"seq\t0\t.\tA\tC" + "\t.\tPASS\t.\tGT\t0/0"
, "seq\t0\t.\tA\tC" + "\t.\ta10.0\t.\tGT\t0/0"
, "seq\t0\t.\tA\tC" + "\t.\tOC\t.\tGT\t0/0"
, "seq\t0\t.\tA\t." + "\t.\tRC\t.\tGT\t0/0"
, "seq\t0\t.\tA\t." + "\t.\tRC\t.\tGT\t0/0"
, "seq\t0\t.\tACGT\t." + "\t.\tOTHER\t.\tGT\t0/0"
, "seq\t0\t.\tG\tGA" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tG\tGA,GT" + "\t.\tPASS\t.\tGT\t1/2"
, "seq\t0\t.\tA\tC" + "\t.\tPASS\t.\tGT\t0/1"
, "seq\t0\t.\tA\tT" + "\t.\tPASS\t.\tGT\t1/0"
, "seq\t0\t.\tG\tGAAT" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tG\tGAAT,GT" + "\t.\tPASS\t.\tGT\t1/2"
, "seq\t0\t.\tG\tGT" + "\t.\tPASS\t.\tGT\t0/1"
, "seq\t0\t.\tG\tGAAT" + "\t.\tPASS\t.\tGT\t0/1"
, "seq\t0\t.\tA\tG" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tG\tA" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tA\tG" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tA\tG" + "\t.\tPASS\t.\tGT\t1/0"
, "seq\t0\t.\tA\tG,C" + "\t.\tPASS\t.\tGT\t1/2"
, "seq\t0\t.\tT\tC" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tA\tG,T" + "\t.\tPASS\t.\tGT\t1/2"
, "seq\t0\t.\tT\tG,C" + "\t.\tPASS\t.\tGT\t1/2"
, "seq\t0\t.\tAG\tGA" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tAG\tGA" + "\t.\tPASS\t.\tGT\t0/1"
, "seq\t0\t.\tAG\tGT" + "\t.\tPASS\t.\tGT\t1/0"
, "seq\t0\t.\tGA\tG" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tGA\tG" + "\t.\tPASS\t.\tGT\t0/1"
, "seq\t0\t.\tGA\tG" + "\t.\tPASS\t.\tGT\t1/0"
, "seq\t0\t.\tGACT\tG" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tGACT\tG" + "\t.\tPASS\t.\tGT\t0/1"
, "seq\t0\t.\tGACT\tG,GA" + "\t.\tPASS\t.\tGT\t1/2"
, "seq\t0\t.\tGACT\tGC" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tGACT\tGC,GT" + "\t.\tPASS\t.\tGT\t1/2"
, "seq\t0\t.\tGACT\tG,GC" + "\t.\tPASS\t.\tGT\t1/2"
, "seq\t0\t.\tGA\tGGC" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tGA\tG,GAA" + "\t.\tPASS\t.\tGT\t1/2"
, "seq\t0\t.\tGA\tG,GG" + "\t.\tPASS\t.\tGT\t1/2"
, "seq\t0\t.\tGACT\tGGACT,GA" + "\t.\tPASS\t.\tGT\t1/2"
, "seq\t0\t.\tGA\tGGG" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tGGG\tGA" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tGGG\tG" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tGGAG\tGG" + "\t.\tPASS\t.\tGT\t1/1"
, "seq\t0\t.\tGGG\tGGAG" + "\t.\tPASS\t.\tGT\t1/1"
};
public void testVariantStatistics() {
final VcfHeader h = new VcfHeader();
h.addCommonHeader();
h.addSampleName("SAMPLE");
final VariantStatistics stats = new VariantStatistics(null);
for (final String variant : VARIANTS) {
final VcfRecord r = VcfReaderTest.vcfLineToRecord(variant);
r.addFilter("RX");
stats.tallyVariant(h, r);
}
final VcfRecord missingGT = VcfReaderTest.vcfLineToRecord("seq\t0\t.\tGGG\tGGAG" + "\t.\tPASS\t.\tGT\t.");
stats.tallyVariant(h, missingGT);
for (final String variant : VARIANTS) {
final VcfRecord r = VcfReaderTest.vcfLineToRecord(variant);
stats.tallyVariant(h, r);
stats.tallyVariant(h, r);
stats.tallyVariant(h, r);
}
TestUtils.containsAll(stats.getStatistics()
, "Passed Filters : 115" + StringUtils.LS
, "Failed Filters : 58" + StringUtils.LS
, "SNPs : 30" + StringUtils.LS
, "MNPs : 9" + StringUtils.LS
, "Insertions : 21" + StringUtils.LS
, "Deletions : 27" + StringUtils.LS
, "Indels : 24" + StringUtils.LS
, "Same as reference : 3" + StringUtils.LS
, "Missing Genotype : 1" + StringUtils.LS
, "SNP Transitions/Transversions: 2.40 (36/15)" + StringUtils.LS
, "Total Het/Hom ratio : 1.31 (63/48)" + StringUtils.LS
, "SNP Het/Hom ratio : 1.50 (18/12)" + StringUtils.LS
, "MNP Het/Hom ratio : 2.00 (6/3)" + StringUtils.LS
, "Insertion Het/Hom ratio : 1.33 (12/9)" + StringUtils.LS
, "Deletion Het/Hom ratio : 1.25 (15/12)" + StringUtils.LS
, "Indel Het/Hom ratio : 1.00 (12/12)" + StringUtils.LS
, "Insertion/Deletion ratio : 0.78 (21/27)" + StringUtils.LS
, "Indel/SNP+MNP ratio : 1.85 (72/39)" + StringUtils.LS
);
}
public void testLengthHistograms() {
final VariantStatistics stats = new VariantStatistics(null);
stats.showLengthHistograms(true);
stats.showAlleleCountHistograms(true);
final VcfHeader h = new VcfHeader();
h.addCommonHeader();
h.addSampleName("SAMPLE");
for (final String variant : VARIANTS) {
final VcfRecord r = VcfReaderTest.vcfLineToRecord(variant);
r.addFilter("RX");
stats.tallyVariant(h, r);
}
final VcfRecord missingGT = VcfReaderTest.vcfLineToRecord("seq\t0\t.\tGGG\tGGAG" + "\t.\tPASS\t.\tGT\t.");
stats.tallyVariant(h, missingGT);
for (final String variant : VARIANTS) {
final VcfRecord r = VcfReaderTest.vcfLineToRecord(variant);
stats.tallyVariant(h, r);
stats.tallyVariant(h, r);
stats.tallyVariant(h, r);
}
//System.err.println(stats.getStatistics());
TestUtils.containsAll(stats.getStatistics()
, "Passed Filters : 115" + StringUtils.LS
, "Failed Filters : 58" + StringUtils.LS
, "Number of Alleles : 0\t1" + StringUtils.LS
, " 1\t51" + StringUtils.LS
, " 2\t63" + StringUtils.LS
, "SNPs : 30" + StringUtils.LS
, "MNPs : 9" + StringUtils.LS
, "Insertions : 21" + StringUtils.LS
, "Deletions : 27" + StringUtils.LS
, "Indels : 24" + StringUtils.LS
, "Same as reference : 3" + StringUtils.LS
, "Missing Genotype : 1" + StringUtils.LS
, "SNP Transitions/Transversions: 2.40 (36/15)" + StringUtils.LS
, "Total Het/Hom ratio : 1.31 (63/48)" + StringUtils.LS
, "SNP Het/Hom ratio : 1.50 (18/12)" + StringUtils.LS
, "MNP Het/Hom ratio : 2.00 (6/3)" + StringUtils.LS
, "Insertion Het/Hom ratio : 1.33 (12/9)" + StringUtils.LS
, "Deletion Het/Hom ratio : 1.25 (15/12)" + StringUtils.LS
, "Indel Het/Hom ratio : 1.00 (12/12)" + StringUtils.LS
, "Insertion/Deletion ratio : 0.78 (21/27)" + StringUtils.LS
, "Indel/SNP+MNP ratio : 1.85 (72/39)" + StringUtils.LS
, "Variant Allele Lengths :" + StringUtils.LS
, "length SNP MNP Delete Insert Indel".replaceAll(" ", "\t") + StringUtils.LS
, "1 54 0 18 30 18".replaceAll(" ", "\t") + StringUtils.LS
, "2 0 12 21 0 12".replaceAll(" ", "\t") + StringUtils.LS
, "3 0 0 15 12 0".replaceAll(" ", "\t") + StringUtils.LS
);
}
public void testMultiVariantStatistics() {
final VariantStatistics stats = new VariantStatistics(null);
final String[] sampleNames = {"sam1", "sam2", "sam3"};
final VcfRecord rec = VcfReaderTest.vcfLineToRecord("test\t5\t.\tA\tG,CT,T\t.\tPASS\tDP=12\tGT:DP:RE:GQ:RS\t1/1:4:0.020:13:G,4,0.020\t2:4:0.020:13:CT,4,0.020\t3/1:4:0.020:13:T,4,0.020,G,4,0.020");
stats.tallyVariant(rec, Arrays.asList(sampleNames));
assertEquals(""
+ "Failed Filters : 0" + StringUtils.LS
+ "Passed Filters : 1" + StringUtils.LS
+ StringUtils.LS
+ "Sample Name: sam1" + StringUtils.LS
+ "SNPs : 1" + StringUtils.LS
+ "MNPs : 0" + StringUtils.LS
+ "Insertions : 0" + StringUtils.LS
+ "Deletions : 0" + StringUtils.LS
+ "Indels : 0" + StringUtils.LS
+ "Same as reference : 0" + StringUtils.LS
+ "SNP Transitions/Transversions: - (2/0)" + StringUtils.LS
+ "Total Het/Hom ratio : 0.00 (0/1)" + StringUtils.LS
+ "SNP Het/Hom ratio : 0.00 (0/1)" + StringUtils.LS
+ "MNP Het/Hom ratio : - (0/0)" + StringUtils.LS
+ "Insertion Het/Hom ratio : - (0/0)" + StringUtils.LS
+ "Deletion Het/Hom ratio : - (0/0)" + StringUtils.LS
+ "Indel Het/Hom ratio : - (0/0)" + StringUtils.LS
+ "Insertion/Deletion ratio : - (0/0)" + StringUtils.LS
+ "Indel/SNP+MNP ratio : 0.00 (0/1)" + StringUtils.LS
+ StringUtils.LS
+ "Sample Name: sam2" + StringUtils.LS
+ "SNPs : 0" + StringUtils.LS
+ "MNPs : 0" + StringUtils.LS
+ "Insertions : 0" + StringUtils.LS
+ "Deletions : 0" + StringUtils.LS
+ "Indels : 1" + StringUtils.LS
+ "Same as reference : 0" + StringUtils.LS
+ "Total Haploid : 1" + StringUtils.LS
+ "Haploid SNPs : 0" + StringUtils.LS
+ "Haploid MNPs : 0" + StringUtils.LS
+ "Haploid Insertions : 0" + StringUtils.LS
+ "Haploid Deletions : 0" + StringUtils.LS
+ "Haploid Indels : 1" + StringUtils.LS
+ "SNP Transitions/Transversions: - (0/0)" + StringUtils.LS
+ "Insertion/Deletion ratio : - (0/0)" + StringUtils.LS
+ "Indel/SNP+MNP ratio : - (1/0)" + StringUtils.LS
+ StringUtils.LS
+ "Sample Name: sam3" + StringUtils.LS
+ "SNPs : 1" + StringUtils.LS
+ "MNPs : 0" + StringUtils.LS
+ "Insertions : 0" + StringUtils.LS
+ "Deletions : 0" + StringUtils.LS
+ "Indels : 0" + StringUtils.LS
+ "Same as reference : 0" + StringUtils.LS
+ "SNP Transitions/Transversions: 1.00 (1/1)" + StringUtils.LS
+ "Total Het/Hom ratio : - (1/0)" + StringUtils.LS
+ "SNP Het/Hom ratio : - (1/0)" + StringUtils.LS
+ "MNP Het/Hom ratio : - (0/0)" + StringUtils.LS
+ "Insertion Het/Hom ratio : - (0/0)" + StringUtils.LS
+ "Deletion Het/Hom ratio : - (0/0)" + StringUtils.LS
+ "Indel Het/Hom ratio : - (0/0)" + StringUtils.LS
+ "Insertion/Deletion ratio : - (0/0)" + StringUtils.LS
+ "Indel/SNP+MNP ratio : 0.00 (0/1)" + StringUtils.LS, stats.getStatistics());
}
public void testMultiVariantStatisticsNulls() {
final VariantStatistics stats = new VariantStatistics(null);
final String[] sampleNames = {"sam1", "sam2", "sam3"};
final VcfRecord rec = VcfReaderTest.vcfLineToRecord("test\t5\t.\tA\tG\t.\tPASS\tDP=4\tGT:DP:RE:GQ:RS\t1:4:0.020:13:G,4,0.020\t.\t.");
stats.tallyVariant(rec, Arrays.asList(sampleNames));
assertEquals(""
+ "Failed Filters : 0" + StringUtils.LS
+ "Passed Filters : 1" + StringUtils.LS
+ StringUtils.LS
+ "Sample Name: sam1" + StringUtils.LS
+ "SNPs : 1" + StringUtils.LS
+ "MNPs : 0" + StringUtils.LS
+ "Insertions : 0" + StringUtils.LS
+ "Deletions : 0" + StringUtils.LS
+ "Indels : 0" + StringUtils.LS
+ "Same as reference : 0" + StringUtils.LS
+ "Total Haploid : 1" + StringUtils.LS
+ "Haploid SNPs : 1" + StringUtils.LS
+ "Haploid MNPs : 0" + StringUtils.LS
+ "Haploid Insertions : 0" + StringUtils.LS
+ "Haploid Deletions : 0" + StringUtils.LS
+ "Haploid Indels : 0" + StringUtils.LS
+ "SNP Transitions/Transversions: - (1/0)" + StringUtils.LS
+ "Insertion/Deletion ratio : - (0/0)" + StringUtils.LS
+ "Indel/SNP+MNP ratio : 0.00 (0/1)" + StringUtils.LS
+ StringUtils.LS
+ "Sample Name: sam2" + StringUtils.LS
+ "SNPs : 0" + StringUtils.LS
+ "MNPs : 0" + StringUtils.LS
+ "Insertions : 0" + StringUtils.LS
+ "Deletions : 0" + StringUtils.LS
+ "Indels : 0" + StringUtils.LS
+ "Same as reference : 0" + StringUtils.LS
+ "Missing Genotype : 1" + StringUtils.LS
+ "SNP Transitions/Transversions: - (0/0)" + StringUtils.LS
+ "Insertion/Deletion ratio : - (0/0)" + StringUtils.LS
+ "Indel/SNP+MNP ratio : - (0/0)" + StringUtils.LS
+ StringUtils.LS
+ "Sample Name: sam3" + StringUtils.LS
+ "SNPs : 0" + StringUtils.LS
+ "MNPs : 0" + StringUtils.LS
+ "Insertions : 0" + StringUtils.LS
+ "Deletions : 0" + StringUtils.LS
+ "Indels : 0" + StringUtils.LS
+ "Same as reference : 0" + StringUtils.LS
+ "Missing Genotype : 1" + StringUtils.LS
+ "SNP Transitions/Transversions: - (0/0)" + StringUtils.LS
+ "Insertion/Deletion ratio : - (0/0)" + StringUtils.LS
+ "Indel/SNP+MNP ratio : - (0/0)" + StringUtils.LS, stats.getStatistics());
}
private static final String VCF = ""
+ "##fileformat=VCFv4.1\n"
+ "##fileDate=20120210\n"
+ "##source=RTGvPOST-2.4 build <not found> (<not found>)\n"
+ "##CL=copy pasta\n"
+ "##RUN-ID=bce4adcc-dc18-4e92-bb05-e487aa60e1bc\n"
+ "##TEMPLATE-SDF-ID=4a99be67-0ae0-48f2-ad13-bed3a66a2643\n"
+ "##reference=/rtgshare/data/human/ref/sdf/hg18\n"
+ "##contig=<ID=chr1,length=247249719>\n"
+ "##INFO=<ID=LOH,Number=1,Type=String,Description=\"Indicates whether or not variant is a potential loss of heterozygosity\">\n"
+ "##INFO=<ID=RSS,Number=1,Type=Float,Description=\"RTG somatic call score\">\n"
+ "##INFO=<ID=XRX,Number=0,Type=Flag,Description=\"RTG variant was called using complex caller\">\n"
+ "##INFO=<ID=RCE,Number=0,Type=Flag,Description=\"RTG variant is equivalent to the previous variant\">\n"
+ "##INFO=<ID=CT,Number=1,Type=Integer,Description=\"Coverage threshold that was applied\">\n"
+ "##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Combined read depth for variant over all samples\">\n"
+ "##FILTER=<ID=OC,Description=\"Coverage threshold exceeded\">\n"
+ "##FILTER=<ID=a10.0,Description=\"Ambiguity exceeded 10.0\">\n"
+ "##FILTER=<ID=RC,Description=\"RTG variant is a complex region\">\n"
+ "##FILTER=<ID=RX,Description=\"RTG variant contained within hypercomplex region\">\n"
+ "##FILTER=<ID=RCEQUIV,Description=\"RTG variant is equivalent to the previous variant\">\n"
+ "##FILTER=<ID=OTHER,Description=\"Variant is invalid for unknown reasons\">\n"
+ "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">\n"
+ "##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"Read Depth\">\n"
+ "##FORMAT=<ID=GQ,Number=1,Type=Float,Description=\"Genotype Quality\">\n"
+ "##FORMAT=<ID=RE,Number=1,Type=Float,Description=\"RTG Total Error\">\n"
+ "##FORMAT=<ID=AR,Number=1,Type=Float,Description=\"Ambiguity Ratio\">\n"
+ "##FORMAT=<ID=AB,Number=1,Type=Float,Description=\"Allele Balance\">\n"
+ "##FORMAT=<ID=RQ,Number=1,Type=Float,Description=\"RTG sample quality\">\n"
+ "##FORMAT=<ID=RS,Number=.,Type=String,Description=\"RTG Support Statistics\">\n"
+ "##SAMPLE=<ID=EM0231,Genomes=EM0231,Mixture=1.0,Description=\"Original genome\">\n"
+ "##SAMPLE=<ID=EM0231_T1,Genomes=EM0231;EM0231_T1,Mixture=0.15;0.85,Description=\"Original genome;Derived genome\">\n"
+ "##PEDIGREE=<Derived=EM0231_T1,Original=EM0231>\n"
+ "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tEM0231\tEM0231_T1\n"
+ "chr1\t799550\t.\tG\tC\t6.0\tPASS\tLOH=1.0;RSS=0.5;DP=96\tGT:DP:RE:AR:AB:GQ:RS\t1/0:28:4.396:0.036:0.714:6.0:C,6,0.600,G,20,3.194,T,2,0.601\t0:68:12.244:0.074:0.779:24.5:A,1,0.251,C,12,1.216,G,53,10.577,T,2,0.200\n"
+ "chr1\t805742\trs1\tG\tA\t8.6\ta10.0\tLOH=1.0;RSS=0.8;DP=95\tGT:DP:RE:AR:AB:GQ:RS\t1/0:44:10.800:0.159:0.659:9.0:A,13,4.902,C,2,2.000,G,29,3.898\t0:51:10.055:0.078:0.745:18.9:A,12,3.928,G,38,5.729,T,1,0.398\n"
+ "chr1\t805870\trs2\tG\tT\t44.7\tOC\tLOH=1.0;RSS=4.5;DP=722;CT=156\tGT:DP:RE:AR:AB:GQ:RS\t0/1:284:167.524:0.542:0.803:44.7:C,1,1.000,G,228,134.836,T,55,31.688\t0:438:241.295:0.498:0.801:147.3:C,1,1.000,G,351,184.773,T,86,55.522\n"
+ "chr1\t1255017\trs3\tT\tC\t4.0\tPASS\tLOH=1.0;RSS=0.2;DP=52\tGT:DP:RE:AR:AB:GQ:RS\t1/0:15:2.253:0.000:0.333:4.0:A,1,0.100,C,9,1.199,T,5,0.954\t1:37:4.497:0.000:0.027:60.8:A,4,0.833,C,31,3.313,G,1,0.251,T,1,0.100\n"
+ "chr1\t1256603\trs4\tT\tA\t19.5\tPASS\tLOH=-1.0;RSS=1.9;DP=41\tGT:DP:RE:AR:AB:GQ:RS\t0/0:8:1.017:0.000:0.875:19.5:C,1,0.316,T,7,0.701\t1/0:33:3.612:0.000:0.545:62.1:A,15,1.810,T,18,1.801\n"
+ "chr1\t1257249\trs5\tG\tGC\t16.3\tPASS\tLOH=1.0;RSS=1.6;DP=43;XRX\tGT:DP:RE:GQ\t0/1:8:0.001:44.1\t0:35:0.304:16.3\n"
+ "chr1\t1257257\trs6\tG\tGGG\t18.7\tPASS\tLOH=1.0;RSS=1.9;DP=38;XRX\tGT:DP:RE:GQ\t0/1:10:0.431:54.3\t0:28:0.104:18.7\n"
+ "chr1\t92998003\t.\tCT\tCC,C\t5.1\tPASS\tLOH=-1.0;RSS=0.2;DP=26;XRX\tGT:DP:RE:GQ\t1/1:10:1.217:11.9\t2/1:16:1.343:4.9\n"
+ "chr1\t181263907\t.\tTTCCT\tTTC,TTCCC\t5.3\tPASS\tLOH=-1.0;RSS=0.1;DP=66;XRX\tGT:DP:RE:GQ:SS\t1/1:26:3.559:15.8\t1/2:40:4.499:3.6:2\n"
+ "chr1\t240295482\t.\tTC\tT,TT\t31.8\tPASS\tLOH=-1.0;RSS=2.9;DP=67;XRX\tGT:DP:RE:GQ\t1/1:30:2.627:29.4\t1/2:37:5.703:30.5\n"
+ "chr1\t240295492\t.\tTC\tT,TT\t31.8\tPASS\tLOH=-1.0;RSS=2.9;DP=67;XRX\tGT:DP:RE:GQ\t1/1/2:30:2.627:29.4\t./2:37:5.703:30.5\n"
+ "chr1\t240430567\t.\tAT\tA,AA\t10.6\tPASS\tLOH=-1.0;RSS=1.0;DP=88;XRX\tGT:DP:RE:GQ:DN\t1/1:38:2.961:14.8\t1/2:50:4.304:11.3:Y\n"
+ "chr1\t240430569\t.\tAT\tA,AA\t10.6\tPASS\tLOH=-1.0;RSS=1.0;DP=88;XRX\tGT:DP:RE:GQ\t2/1/0:38:2.961:14.8\t2/2:50:4.304:11.3\n"
+ "chr1\t240430571\t.\tAT\tA,AA\t10.6\tPASS\tLOH=-1.0;RSS=1.0;DP=88;XRX\tGT:DP:RE:GQ\t0:38:2.961:14.8\t1:50:4.304:11.3\n"
;
public void testBasic() throws IOException {
try (final TestDirectory tdir = new TestDirectory("vcfstats")) {
final File vcfFile = File.createTempFile("example", ".vcf", tdir);
FileUtils.stringToFile(VCF, vcfFile);
MainResult res = MainResult.run(new VcfStatsCli(), vcfFile.getPath(), "--Xvariant");
assertEquals(res.err(), 0, res.rc());
final String outVariant = res.out();
mNano.check("variantstatistics.txt", outVariant.substring(outVariant.indexOf(StringUtils.LS) + StringUtils.LS.length()), true);
res = MainResult.run(new VcfStatsCli(), vcfFile.getPath());
assertEquals(res.err(), 0, res.rc());
final String outVcfRecord = res.out();
assertEquals(outVariant, outVcfRecord);
mNano.check("variantstatistics.txt", outVcfRecord.substring(outVcfRecord.indexOf(StringUtils.LS) + StringUtils.LS.length()), true);
res = MainResult.run(new VcfStatsCli(), vcfFile.getPath(), "--known");
assertEquals(res.err(), 0, res.rc());
String outStats = res.out();
mNano.check("variantstatistics-known.txt", outStats.substring(outStats.indexOf(StringUtils.LS) + StringUtils.LS.length()), true);
res = MainResult.run(new VcfStatsCli(), vcfFile.getPath(), "--novel");
assertEquals(res.err(), 0, res.rc());
outStats = res.out();
mNano.check("variantstatistics-novel.txt", outStats.substring(outStats.indexOf(StringUtils.LS) + StringUtils.LS.length()), true);
}
}
public void testBasicLengthHistogram() throws IOException {
final File vcfFile = FileHelper.createTempFile();
try {
FileUtils.stringToFile(VCF, vcfFile);
final MainResult res = MainResult.run(new VcfStatsCli(), vcfFile.getPath(), "--allele-lengths");
assertEquals(res.err(), 0, res.rc());
final String outVariant = res.out();
mNano.check("variantstatistics2.txt", outVariant.substring(outVariant.indexOf(StringUtils.LS) + StringUtils.LS.length()), true);
} finally {
assertTrue(vcfFile.delete());
}
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.server;
import com.facebook.presto.client.QueryResults;
import com.facebook.presto.execution.AddColumnTask;
import com.facebook.presto.execution.CallTask;
import com.facebook.presto.execution.CommitTask;
import com.facebook.presto.execution.CreateSchemaTask;
import com.facebook.presto.execution.CreateTableTask;
import com.facebook.presto.execution.CreateViewTask;
import com.facebook.presto.execution.DataDefinitionTask;
import com.facebook.presto.execution.DeallocateTask;
import com.facebook.presto.execution.DropSchemaTask;
import com.facebook.presto.execution.DropTableTask;
import com.facebook.presto.execution.DropViewTask;
import com.facebook.presto.execution.ForQueryExecution;
import com.facebook.presto.execution.GrantTask;
import com.facebook.presto.execution.PrepareTask;
import com.facebook.presto.execution.QueryExecution;
import com.facebook.presto.execution.QueryExecutionMBean;
import com.facebook.presto.execution.QueryIdGenerator;
import com.facebook.presto.execution.QueryInfo;
import com.facebook.presto.execution.QueryManager;
import com.facebook.presto.execution.QueryQueueManager;
import com.facebook.presto.execution.QueryQueueRule;
import com.facebook.presto.execution.QueryQueueRuleFactory;
import com.facebook.presto.execution.RemoteTaskFactory;
import com.facebook.presto.execution.RenameColumnTask;
import com.facebook.presto.execution.RenameSchemaTask;
import com.facebook.presto.execution.RenameTableTask;
import com.facebook.presto.execution.ResetSessionTask;
import com.facebook.presto.execution.RevokeTask;
import com.facebook.presto.execution.RollbackTask;
import com.facebook.presto.execution.SetSessionTask;
import com.facebook.presto.execution.SqlQueryManager;
import com.facebook.presto.execution.SqlQueryQueueManager;
import com.facebook.presto.execution.StartTransactionTask;
import com.facebook.presto.execution.TaskInfo;
import com.facebook.presto.execution.resourceGroups.InternalResourceGroupManager;
import com.facebook.presto.execution.resourceGroups.LegacyResourceGroupConfigurationManagerFactory;
import com.facebook.presto.execution.resourceGroups.ResourceGroupManager;
import com.facebook.presto.execution.scheduler.AllAtOnceExecutionPolicy;
import com.facebook.presto.execution.scheduler.ExecutionPolicy;
import com.facebook.presto.execution.scheduler.PhasedExecutionPolicy;
import com.facebook.presto.execution.scheduler.SplitSchedulerStats;
import com.facebook.presto.memory.ClusterMemoryManager;
import com.facebook.presto.memory.ForMemoryManager;
import com.facebook.presto.operator.ForScheduler;
import com.facebook.presto.server.remotetask.RemoteTaskStats;
import com.facebook.presto.spi.memory.ClusterMemoryPoolManager;
import com.facebook.presto.sql.analyzer.FeaturesConfig;
import com.facebook.presto.sql.analyzer.QueryExplainer;
import com.facebook.presto.sql.tree.AddColumn;
import com.facebook.presto.sql.tree.Call;
import com.facebook.presto.sql.tree.Commit;
import com.facebook.presto.sql.tree.CreateSchema;
import com.facebook.presto.sql.tree.CreateTable;
import com.facebook.presto.sql.tree.CreateTableAsSelect;
import com.facebook.presto.sql.tree.CreateView;
import com.facebook.presto.sql.tree.Deallocate;
import com.facebook.presto.sql.tree.Delete;
import com.facebook.presto.sql.tree.DescribeInput;
import com.facebook.presto.sql.tree.DropSchema;
import com.facebook.presto.sql.tree.DropTable;
import com.facebook.presto.sql.tree.DropView;
import com.facebook.presto.sql.tree.Explain;
import com.facebook.presto.sql.tree.Grant;
import com.facebook.presto.sql.tree.Insert;
import com.facebook.presto.sql.tree.Prepare;
import com.facebook.presto.sql.tree.Query;
import com.facebook.presto.sql.tree.RenameColumn;
import com.facebook.presto.sql.tree.RenameSchema;
import com.facebook.presto.sql.tree.RenameTable;
import com.facebook.presto.sql.tree.ResetSession;
import com.facebook.presto.sql.tree.Revoke;
import com.facebook.presto.sql.tree.Rollback;
import com.facebook.presto.sql.tree.SetSession;
import com.facebook.presto.sql.tree.ShowCatalogs;
import com.facebook.presto.sql.tree.ShowColumns;
import com.facebook.presto.sql.tree.ShowCreate;
import com.facebook.presto.sql.tree.ShowFunctions;
import com.facebook.presto.sql.tree.ShowPartitions;
import com.facebook.presto.sql.tree.ShowSchemas;
import com.facebook.presto.sql.tree.ShowSession;
import com.facebook.presto.sql.tree.ShowTables;
import com.facebook.presto.sql.tree.StartTransaction;
import com.facebook.presto.sql.tree.Statement;
import com.facebook.presto.sql.tree.Use;
import com.google.inject.Binder;
import com.google.inject.Scopes;
import com.google.inject.TypeLiteral;
import com.google.inject.multibindings.MapBinder;
import io.airlift.configuration.AbstractConfigurationAwareModule;
import io.airlift.units.Duration;
import java.util.List;
import java.util.concurrent.ExecutorService;
import static com.facebook.presto.execution.DataDefinitionExecution.DataDefinitionExecutionFactory;
import static com.facebook.presto.execution.QueryExecution.QueryExecutionFactory;
import static com.facebook.presto.execution.SqlQueryExecution.SqlQueryExecutionFactory;
import static com.google.inject.multibindings.MapBinder.newMapBinder;
import static io.airlift.concurrent.Threads.threadsNamed;
import static io.airlift.discovery.client.DiscoveryBinder.discoveryBinder;
import static io.airlift.http.client.HttpClientBinder.httpClientBinder;
import static io.airlift.http.server.HttpServerBinder.httpServerBinder;
import static io.airlift.jaxrs.JaxrsBinder.jaxrsBinder;
import static io.airlift.json.JsonCodecBinder.jsonCodecBinder;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.weakref.jmx.ObjectNames.generatedNameOf;
import static org.weakref.jmx.guice.ExportBinder.newExporter;
public class CoordinatorModule
extends AbstractConfigurationAwareModule
{
@Override
protected void setup(Binder binder)
{
httpServerBinder(binder).bindResource("/", "webapp").withWelcomeFile("index.html");
// presto coordinator announcement
discoveryBinder(binder).bindHttpAnnouncement("presto-coordinator");
// statement resource
jsonCodecBinder(binder).bindJsonCodec(QueryInfo.class);
jsonCodecBinder(binder).bindJsonCodec(TaskInfo.class);
jsonCodecBinder(binder).bindJsonCodec(QueryResults.class);
jaxrsBinder(binder).bind(StatementResource.class);
// execute resource
jaxrsBinder(binder).bind(ExecuteResource.class);
httpClientBinder(binder).bindHttpClient("execute", ForExecute.class)
.withTracing()
.withConfigDefaults(config -> {
config.setIdleTimeout(new Duration(30, SECONDS));
config.setRequestTimeout(new Duration(10, SECONDS));
});
// query execution visualizer
jaxrsBinder(binder).bind(QueryExecutionResource.class);
// query manager
jaxrsBinder(binder).bind(QueryResource.class);
jaxrsBinder(binder).bind(StageResource.class);
binder.bind(QueryIdGenerator.class).in(Scopes.SINGLETON);
binder.bind(QueryManager.class).to(SqlQueryManager.class).in(Scopes.SINGLETON);
binder.bind(InternalResourceGroupManager.class).in(Scopes.SINGLETON);
binder.bind(ResourceGroupManager.class).to(InternalResourceGroupManager.class);
binder.bind(LegacyResourceGroupConfigurationManagerFactory.class).in(Scopes.SINGLETON);
if (buildConfigObject(FeaturesConfig.class).isResourceGroupsEnabled()) {
binder.bind(QueryQueueManager.class).to(InternalResourceGroupManager.class);
}
else {
binder.bind(QueryQueueManager.class).to(SqlQueryQueueManager.class).in(Scopes.SINGLETON);
binder.bind(new TypeLiteral<List<QueryQueueRule>>() {}).toProvider(QueryQueueRuleFactory.class).in(Scopes.SINGLETON);
}
newExporter(binder).export(QueryManager.class).withGeneratedName();
// cluster memory manager
binder.bind(ClusterMemoryManager.class).in(Scopes.SINGLETON);
binder.bind(ClusterMemoryPoolManager.class).to(ClusterMemoryManager.class).in(Scopes.SINGLETON);
httpClientBinder(binder).bindHttpClient("memoryManager", ForMemoryManager.class)
.withTracing()
.withConfigDefaults(config -> {
config.setIdleTimeout(new Duration(30, SECONDS));
config.setRequestTimeout(new Duration(10, SECONDS));
});
newExporter(binder).export(ClusterMemoryManager.class).withGeneratedName();
// cluster statistics
jaxrsBinder(binder).bind(ClusterStatsResource.class);
// query explainer
binder.bind(QueryExplainer.class).in(Scopes.SINGLETON);
// execution scheduler
binder.bind(RemoteTaskFactory.class).to(HttpRemoteTaskFactory.class).in(Scopes.SINGLETON);
newExporter(binder).export(RemoteTaskFactory.class).withGeneratedName();
binder.bind(RemoteTaskStats.class).in(Scopes.SINGLETON);
newExporter(binder).export(RemoteTaskStats.class).withGeneratedName();
httpClientBinder(binder).bindHttpClient("scheduler", ForScheduler.class)
.withTracing()
.withConfigDefaults(config -> {
config.setIdleTimeout(new Duration(30, SECONDS));
config.setRequestTimeout(new Duration(10, SECONDS));
config.setMaxConnectionsPerServer(250);
});
// query execution
binder.bind(ExecutorService.class).annotatedWith(ForQueryExecution.class)
.toInstance(newCachedThreadPool(threadsNamed("query-execution-%s")));
binder.bind(QueryExecutionMBean.class).in(Scopes.SINGLETON);
newExporter(binder).export(QueryExecutionMBean.class).as(generatedNameOf(QueryExecution.class));
MapBinder<Class<? extends Statement>, QueryExecutionFactory<?>> executionBinder = newMapBinder(binder,
new TypeLiteral<Class<? extends Statement>>() {}, new TypeLiteral<QueryExecutionFactory<?>>() {});
binder.bind(SplitSchedulerStats.class).in(Scopes.SINGLETON);
newExporter(binder).export(SplitSchedulerStats.class).withGeneratedName();
binder.bind(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(Query.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(Explain.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(ShowCreate.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(ShowColumns.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(ShowPartitions.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(ShowFunctions.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(ShowTables.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(ShowSchemas.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(ShowCatalogs.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(Use.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(ShowSession.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(CreateTableAsSelect.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(Insert.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(Delete.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
executionBinder.addBinding(DescribeInput.class).to(SqlQueryExecutionFactory.class).in(Scopes.SINGLETON);
binder.bind(DataDefinitionExecutionFactory.class).in(Scopes.SINGLETON);
bindDataDefinitionTask(binder, executionBinder, CreateSchema.class, CreateSchemaTask.class);
bindDataDefinitionTask(binder, executionBinder, DropSchema.class, DropSchemaTask.class);
bindDataDefinitionTask(binder, executionBinder, RenameSchema.class, RenameSchemaTask.class);
bindDataDefinitionTask(binder, executionBinder, AddColumn.class, AddColumnTask.class);
bindDataDefinitionTask(binder, executionBinder, CreateTable.class, CreateTableTask.class);
bindDataDefinitionTask(binder, executionBinder, RenameTable.class, RenameTableTask.class);
bindDataDefinitionTask(binder, executionBinder, RenameColumn.class, RenameColumnTask.class);
bindDataDefinitionTask(binder, executionBinder, DropTable.class, DropTableTask.class);
bindDataDefinitionTask(binder, executionBinder, CreateView.class, CreateViewTask.class);
bindDataDefinitionTask(binder, executionBinder, DropView.class, DropViewTask.class);
bindDataDefinitionTask(binder, executionBinder, SetSession.class, SetSessionTask.class);
bindDataDefinitionTask(binder, executionBinder, ResetSession.class, ResetSessionTask.class);
bindDataDefinitionTask(binder, executionBinder, StartTransaction.class, StartTransactionTask.class);
bindDataDefinitionTask(binder, executionBinder, Commit.class, CommitTask.class);
bindDataDefinitionTask(binder, executionBinder, Rollback.class, RollbackTask.class);
bindDataDefinitionTask(binder, executionBinder, Call.class, CallTask.class);
bindDataDefinitionTask(binder, executionBinder, Grant.class, GrantTask.class);
bindDataDefinitionTask(binder, executionBinder, Revoke.class, RevokeTask.class);
bindDataDefinitionTask(binder, executionBinder, Prepare.class, PrepareTask.class);
bindDataDefinitionTask(binder, executionBinder, Deallocate.class, DeallocateTask.class);
MapBinder<String, ExecutionPolicy> executionPolicyBinder = newMapBinder(binder, String.class, ExecutionPolicy.class);
executionPolicyBinder.addBinding("all-at-once").to(AllAtOnceExecutionPolicy.class);
executionPolicyBinder.addBinding("phased").to(PhasedExecutionPolicy.class);
}
private static <T extends Statement> void bindDataDefinitionTask(
Binder binder,
MapBinder<Class<? extends Statement>, QueryExecutionFactory<?>> executionBinder,
Class<T> statement,
Class<? extends DataDefinitionTask<T>> task)
{
MapBinder<Class<? extends Statement>, DataDefinitionTask<?>> taskBinder = newMapBinder(binder,
new TypeLiteral<Class<? extends Statement>>() {}, new TypeLiteral<DataDefinitionTask<?>>() {});
taskBinder.addBinding(statement).to(task).in(Scopes.SINGLETON);
executionBinder.addBinding(statement).to(DataDefinitionExecutionFactory.class).in(Scopes.SINGLETON);
}
}
| |
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.trilead.ssh2.crypto.Base64;
import jenkins.model.Jenkins;
import hudson.Util;
import org.kohsuke.stapler.Stapler;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.security.GeneralSecurityException;
/**
* Glorified {@link String} that uses encryption in the persisted form, to avoid accidental exposure of a secret.
*
* <p>
* Note that since the cryptography relies on {@link jenkins.model.Jenkins#getSecretKey()}, this is not meant as a protection
* against code running in the same VM, nor against an attacker who has local file system access.
*
* <p>
* {@link Secret}s can correctly read-in plain text password, so this allows the existing
* String field to be updated to {@link Secret}.
*
* @author Kohsuke Kawaguchi
*/
public final class Secret implements Serializable {
/**
* Unencrypted secret text.
*/
private final String value;
private Secret(String value) {
this.value = value;
}
/**
* Obtains the secret in a plain text.
*
* @see #getEncryptedValue()
* @deprecated as of 1.356
* Use {@link #toString(Secret)} to avoid NPE in case Secret is null.
* Or if you really know what you are doing, use the {@link #getPlainText()} method.
*/
@Override
public String toString() {
return value;
}
/**
* Obtains the plain text password.
* Before using this method, ask yourself if you'd be better off using {@link Secret#toString(Secret)}
* to avoid NPE.
*/
public String getPlainText() {
return value;
}
@Override
public boolean equals(Object that) {
return that instanceof Secret && value.equals(((Secret)that).value);
}
@Override
public int hashCode() {
return value.hashCode();
}
/**
* Turns {@link jenkins.model.Jenkins#getSecretKey()} into an AES key.
*/
private static SecretKey getKey() throws UnsupportedEncodingException, GeneralSecurityException {
String secret = SECRET;
if(secret==null) return Jenkins.getInstance().getSecretKeyAsAES128();
return Util.toAes128Key(secret);
}
/**
* Encrypts {@link #value} and returns it in an encoded printable form.
*
* @see #toString()
*/
public String getEncryptedValue() {
try {
Cipher cipher = getCipher("AES");
cipher.init(Cipher.ENCRYPT_MODE, getKey());
// add the magic suffix which works like a check sum.
return new String(Base64.encode(cipher.doFinal((value+MAGIC).getBytes("UTF-8"))));
} catch (GeneralSecurityException e) {
throw new Error(e); // impossible
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
}
}
/**
* Reverse operation of {@link #getEncryptedValue()}. Returns null
* if the given cipher text was invalid.
*/
public static Secret decrypt(String data) {
if(data==null) return null;
try {
Cipher cipher = getCipher("AES");
cipher.init(Cipher.DECRYPT_MODE, getKey());
String plainText = new String(cipher.doFinal(Base64.decode(data.toCharArray())), "UTF-8");
if(plainText.endsWith(MAGIC))
return new Secret(plainText.substring(0,plainText.length()-MAGIC.length()));
return null;
} catch (GeneralSecurityException e) {
return null;
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
} catch (IOException e) {
return null;
}
}
/**
* Workaround for HUDSON-6459 / https://glassfish.dev.java.net/issues/show_bug.cgi?id=11862 .
* This method uses specific provider selected via hudson.util.Secret.provider system property
* to provide a workaround for the above bug where default provide gives an unusable instance.
* (Glassfish Enterprise users should set value of this property to "SunJCE")
*/
public static Cipher getCipher(String algorithm) throws GeneralSecurityException {
return PROVIDER != null ? Cipher.getInstance(algorithm, PROVIDER)
: Cipher.getInstance(algorithm);
}
/**
* Attempts to treat the given string first as a cipher text, and if it doesn't work,
* treat the given string as the unencrypted secret value.
*
* <p>
* Useful for recovering a value from a form field.
*
* @return never null
*/
public static Secret fromString(String data) {
data = Util.fixNull(data);
Secret s = decrypt(data);
if(s==null) s=new Secret(data);
return s;
}
/**
* Works just like {@link Secret#toString()} but avoids NPE when the secret is null.
* To be consistent with {@link #fromString(String)}, this method doesn't distinguish
* empty password and null password.
*/
public static String toString(Secret s) {
return s==null ? "" : s.value;
}
public static final class ConverterImpl implements Converter {
public ConverterImpl() {
}
public boolean canConvert(Class type) {
return type==Secret.class;
}
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
Secret src = (Secret) source;
writer.setValue(src.getEncryptedValue());
}
public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) {
return fromString(reader.getValue());
}
}
private static final String MAGIC = "::::MAGIC::::";
/**
* Workaround for HUDSON-6459 / https://glassfish.dev.java.net/issues/show_bug.cgi?id=11862 .
* @see #getCipher(String)
*/
private static final String PROVIDER = System.getProperty(Secret.class.getName()+".provider");
/**
* For testing only. Override the secret key so that we can test this class without {@link jenkins.model.Jenkins}.
*/
/*package*/ static String SECRET = null;
private static final long serialVersionUID = 1L;
static {
Stapler.CONVERT_UTILS.register(new org.apache.commons.beanutils.Converter() {
public Secret convert(Class type, Object value) {
return Secret.fromString(value.toString());
}
}, Secret.class);
}
}
| |
/**
* Copyright (C) 2012-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ninja.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import ninja.NinjaTest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.common.collect.Maps;
public class NinjaTestBrowser {
private DefaultHttpClient httpClient;
public NinjaTestBrowser() {
httpClient = new DefaultHttpClient();
}
/**
* The raw HttpClient. You can use it to fire your own requests.
*
* Note 1: This HttpClient will save the state by reusing cookies. You can
* do login / logout cycles using this class.
*
* Note 2: Will be shut down when calling the shutdown method. This is
* generally done by another test helper (like {@link NinjaTest}) that
* encapsulates this class.
*
* @return The HttpClient. Ready and there to be used.
*/
public HttpClient getHttpClient() {
return this.httpClient;
}
/**
* @return all cookies saved by this TestBrowser.
*/
public List<Cookie> getCookies() {
return httpClient.getCookieStore().getCookies();
}
public Cookie getCookieWithName(String name) {
List<Cookie> cookies = getCookies();
// skip through cookies and return cookie you want
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
return null;
}
public HttpResponse makeRequestAndGetResponse(String url,
Map<String, String> headers) {
HttpResponse response = null;
try {
HttpGet getRequest = new HttpGet(url);
// add all headers
for (Entry<String, String> header : headers.entrySet()) {
getRequest.addHeader(header.getKey(), header.getValue());
}
response = httpClient.execute(getRequest);
getRequest.reset();
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
public String makeRequest(String url) {
return makeRequest(url, null);
}
public String makeRequest(String url, Map<String, String> headers) {
StringBuffer sb = new StringBuffer();
try {
HttpGet getRequest = new HttpGet(url);
if (headers != null) {
// add all headers
for (Entry<String, String> header : headers.entrySet()) {
getRequest.addHeader(header.getKey(), header.getValue());
}
}
HttpResponse response;
response = httpClient.execute(getRequest);
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
getRequest.releaseConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
return sb.toString();
}
public String makePostRequestWithFormParameters(String url,
Map<String, String> headers,
Map<String, String> formParameters) {
StringBuffer sb = new StringBuffer();
try {
HttpPost postRequest = new HttpPost(url);
if (headers != null) {
// add all headers
for (Entry<String, String> header : headers.entrySet()) {
postRequest.addHeader(header.getKey(), header.getValue());
}
}
// add form parameters:
List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
if (formParameters != null) {
for (Entry<String, String> parameter : formParameters
.entrySet()) {
formparams.add(new BasicNameValuePair(parameter.getKey(),
parameter.getValue()));
}
}
// encode form parameters and add
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams);
postRequest.setEntity(entity);
HttpResponse response;
response = httpClient.execute(postRequest);
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
postRequest.releaseConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
return sb.toString();
}
public String uploadFile(String url, String paramName, File fileToUpload) {
String response = null;
try {
httpClient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// For File parameters
entity.addPart(paramName, new FileBody((File) fileToUpload));
post.setEntity(entity);
// Here we go!
response = EntityUtils.toString(httpClient.execute(post)
.getEntity(), "UTF-8");
post.releaseConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
public String makeJsonRequest(String url) {
Map<String, String> headers = Maps.newHashMap();
headers.put("accept", "application/json; charset=utf-8");
return makeRequest(url, headers);
}
public String makeXmlRequest(String url) {
Map<String, String> headers = Maps.newHashMap();
headers.put("accept", "application/xml; charset=utf-8");
return makeRequest(url, headers);
}
public String postJson(String url, Object object) {
try {
httpClient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(
new ObjectMapper().writeValueAsString(object), "utf-8");
entity.setContentType("application/json; charset=utf-8");
post.setEntity(entity);
post.releaseConnection();
// Here we go!
return EntityUtils.toString(httpClient.execute(post).getEntity(),
"UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String postXml(String url, Object object) {
try {
httpClient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(
new XmlMapper().writeValueAsString(object), "utf-8");
entity.setContentType("application/xml; charset=utf-8");
post.setEntity(entity);
post.releaseConnection();
// Here we go!
return EntityUtils.toString(httpClient.execute(post).getEntity(),
"UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void shutdown() {
httpClient.getConnectionManager().shutdown();
}
}
| |
/*
* Copyright 2014 Niek Haarman
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nhaarman.listviewanimations.itemmanipulation;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.nhaarman.listviewanimations.BaseAdapterDecorator;
import com.nhaarman.listviewanimations.itemmanipulation.animateaddition.AnimateAdditionAdapter;
import com.nhaarman.listviewanimations.itemmanipulation.dragdrop.DragAndDropHandler;
import com.nhaarman.listviewanimations.itemmanipulation.dragdrop.DraggableManager;
import com.nhaarman.listviewanimations.itemmanipulation.dragdrop.DynamicListViewWrapper;
import com.nhaarman.listviewanimations.itemmanipulation.dragdrop.OnItemMovedListener;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.DismissableManager;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.OnDismissCallback;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeDismissTouchListener;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeTouchListener;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo.SwipeUndoAdapter;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo.SwipeUndoTouchListener;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo.UndoCallback;
import com.nhaarman.listviewanimations.util.Insertable;
import java.util.Collection;
import java.util.HashSet;
/**
* A {@link android.widget.ListView} implementation which provides the following functionality:
* <ul>
* <li>Drag and drop</li>
* <li>Swipe to dismiss</li>
* <li>Swipe to dismiss with contextual undo</li>
* <li>Animate addition</li>
* </ul>
*/
public class DynamicListView extends ListView {
@NonNull
private final MyOnScrollListener mMyOnScrollListener;
/**
* The {@link com.nhaarman.listviewanimations.itemmanipulation.dragdrop.DragAndDropHandler}
* that will handle drag and drop functionality, if set.
*/
@Nullable
private DragAndDropHandler mDragAndDropHandler;
/**
* The {@link com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeTouchListener}
* that will handle swipe movement functionality, if set.
*/
@Nullable
private SwipeTouchListener mSwipeTouchListener;
/**
* The {@link com.nhaarman.listviewanimations.itemmanipulation.TouchEventHandler}
* that is currently actively consuming {@code MotionEvent}s.
*/
@Nullable
private TouchEventHandler mCurrentHandlingTouchEventHandler;
/**
* The {@link com.nhaarman.listviewanimations.itemmanipulation.animateaddition.AnimateAdditionAdapter}
* that is possibly set to animate insertions.
*/
@Nullable
private AnimateAdditionAdapter<Object> mAnimateAdditionAdapter;
@Nullable
private SwipeUndoAdapter mSwipeUndoAdapter;
public DynamicListView(@NonNull final Context context) {
this(context, null);
}
public DynamicListView(@NonNull final Context context, @Nullable final AttributeSet attrs) {
//noinspection HardCodedStringLiteral
this(context, attrs, Resources.getSystem().getIdentifier("listViewStyle", "attr", "android"));
}
public DynamicListView(@NonNull final Context context, @Nullable final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
mMyOnScrollListener = new MyOnScrollListener();
super.setOnScrollListener(mMyOnScrollListener);
}
@Override
public void setOnTouchListener(final OnTouchListener onTouchListener) {
if (onTouchListener instanceof SwipeTouchListener) {
return;
}
super.setOnTouchListener(onTouchListener);
}
@Override
public void setOnScrollListener(final OnScrollListener onScrollListener) {
mMyOnScrollListener.addOnScrollListener(onScrollListener);
}
/**
* Enables the drag and drop functionality for this {@code DynamicListView}.
* <p/>
* <b>NOTE: This method can only be called on devices running ICS (14) and above, otherwise an exception will be thrown.</b>
*
* @throws java.lang.UnsupportedOperationException if the device uses an older API than 14.
*/
public void enableDragAndDrop() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
throw new UnsupportedOperationException("Drag and drop is only supported API levels 14 and up!");
}
mDragAndDropHandler = new DragAndDropHandler(this);
}
/**
* Disables the drag and drop functionality.
*/
public void disableDragAndDrop() {
mDragAndDropHandler = null;
}
/**
* Enables swipe to dismiss functionality for this {@code DynamicListView}.
*
* @param onDismissCallback the {@link com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.OnDismissCallback}
* that is notified of dismissals.
*/
public void enableSwipeToDismiss(@NonNull final OnDismissCallback onDismissCallback) {
mSwipeTouchListener = new SwipeDismissTouchListener(new DynamicListViewWrapper(this), onDismissCallback);
}
/**
* Enables swipe to dismiss with contextual undo for this {@code DynamicListView}.
*
* @param undoCallback the {@link com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo.UndoCallback}
* that is used.
*/
public void enableSwipeUndo(@NonNull final UndoCallback undoCallback) {
mSwipeTouchListener = new SwipeUndoTouchListener(new DynamicListViewWrapper(this), undoCallback);
}
/**
* Enables swipe to dismiss with contextual undo for this {@code DynamicListView}.
* This method requires that a {@link com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo.SwipeUndoAdapter} has been set.
* It is allowed to have the {@code SwipeUndoAdapter} wrapped in a {@link com.nhaarman.listviewanimations.BaseAdapterDecorator}.
*
* @throws java.lang.IllegalStateException if the adapter that was set does not extend {@code SwipeUndoAdapter}.
*/
public void enableSimpleSwipeUndo() {
if (mSwipeUndoAdapter == null) {
throw new IllegalStateException("enableSimpleSwipeUndo requires a SwipeUndoAdapter to be set as an adapter");
}
mSwipeTouchListener = new SwipeUndoTouchListener(new DynamicListViewWrapper(this), mSwipeUndoAdapter.getUndoCallback());
mSwipeUndoAdapter.setSwipeUndoTouchListener((SwipeUndoTouchListener) mSwipeTouchListener);
}
/**
* Disables any swipe to dismiss functionality set by either {@link #enableSwipeToDismiss(com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.OnDismissCallback)},
* {@link #enableSwipeUndo(com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo.UndoCallback)} or {@link #enableSimpleSwipeUndo()}.
*/
public void disableSwipeToDismiss() {
mSwipeTouchListener = null;
}
/**
* Sets the {@link ListAdapter} for this {@code DynamicListView}.
* If the drag and drop functionality is or will be enabled, the adapter should have stable ids,
* and should implement {@link com.nhaarman.listviewanimations.util.Swappable}.
*
* @param adapter the adapter.
*
* @throws java.lang.IllegalStateException if the drag and drop functionality is enabled
* and the adapter does not have stable ids.
* @throws java.lang.IllegalArgumentException if the drag and drop functionality is enabled
* and the adapter does not implement {@link com.nhaarman.listviewanimations.util.Swappable}.
*/
@Override
public void setAdapter(final ListAdapter adapter) {
ListAdapter wrappedAdapter = adapter;
mSwipeUndoAdapter = null;
if (adapter instanceof BaseAdapter) {
BaseAdapter rootAdapter = (BaseAdapter) wrappedAdapter;
while (rootAdapter instanceof BaseAdapterDecorator) {
if (rootAdapter instanceof SwipeUndoAdapter) {
mSwipeUndoAdapter = (SwipeUndoAdapter) rootAdapter;
}
rootAdapter = ((BaseAdapterDecorator) rootAdapter).getDecoratedBaseAdapter();
}
if (rootAdapter instanceof Insertable) {
mAnimateAdditionAdapter = new AnimateAdditionAdapter((BaseAdapter) wrappedAdapter);
mAnimateAdditionAdapter.setListView(this);
wrappedAdapter = mAnimateAdditionAdapter;
}
}
super.setAdapter(wrappedAdapter);
if (mDragAndDropHandler != null) {
mDragAndDropHandler.setAdapter(adapter);
}
}
@Override
public boolean dispatchTouchEvent(@NonNull final MotionEvent ev) {
if (mCurrentHandlingTouchEventHandler == null) {
/* None of the TouchEventHandlers are actively consuming events yet. */
boolean firstTimeInteracting = false;
/* We don't support dragging items when there are items in the undo state. */
if (!(mSwipeTouchListener instanceof SwipeUndoTouchListener) || !((SwipeUndoTouchListener) mSwipeTouchListener).hasPendingItems()) {
/* Offer the event to the DragAndDropHandler */
if (mDragAndDropHandler != null) {
mDragAndDropHandler.onTouchEvent(ev);
firstTimeInteracting = mDragAndDropHandler.isInteracting();
if (firstTimeInteracting) {
mCurrentHandlingTouchEventHandler = mDragAndDropHandler;
sendCancelEvent(mSwipeTouchListener, ev);
}
}
}
/* If not handled, offer the event to the SwipeDismissTouchListener */
if (mCurrentHandlingTouchEventHandler == null && mSwipeTouchListener != null) {
mSwipeTouchListener.onTouchEvent(ev);
firstTimeInteracting = mSwipeTouchListener.isInteracting();
if (firstTimeInteracting) {
mCurrentHandlingTouchEventHandler = mSwipeTouchListener;
sendCancelEvent(mDragAndDropHandler, ev);
}
}
if (firstTimeInteracting) {
/* One of the TouchEventHandlers is now taking over control.
Cancel touch event handling on this DynamicListView */
MotionEvent cancelEvent = MotionEvent.obtain(ev);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(cancelEvent);
}
return firstTimeInteracting || super.dispatchTouchEvent(ev);
} else {
return onTouchEvent(ev);
}
}
@Override
public boolean onTouchEvent(@NonNull final MotionEvent ev) {
if (mCurrentHandlingTouchEventHandler != null) {
mCurrentHandlingTouchEventHandler.onTouchEvent(ev);
}
if (ev.getActionMasked() == MotionEvent.ACTION_UP || ev.getActionMasked() == MotionEvent.ACTION_CANCEL) {
/* Gesture is finished, reset the active TouchEventHandler */
mCurrentHandlingTouchEventHandler = null;
}
return mCurrentHandlingTouchEventHandler != null || super.onTouchEvent(ev);
}
/**
* Sends a cancel event to given {@link com.nhaarman.listviewanimations.itemmanipulation.TouchEventHandler}.
*
* @param touchEventHandler the {@code TouchEventHandler} to send the event to.
* @param motionEvent the {@link MotionEvent} to base the cancel event on.
*/
private void sendCancelEvent(@Nullable final TouchEventHandler touchEventHandler, @NonNull final MotionEvent motionEvent) {
if (touchEventHandler != null) {
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL);
touchEventHandler.onTouchEvent(cancelEvent);
}
}
@Override
protected void dispatchDraw(@NonNull final Canvas canvas) {
super.dispatchDraw(canvas);
if (mDragAndDropHandler != null) {
mDragAndDropHandler.dispatchDraw(canvas);
}
}
@Override
public int computeVerticalScrollOffset() {
return super.computeVerticalScrollOffset();
}
@Override
public int computeVerticalScrollExtent() {
return super.computeVerticalScrollExtent();
}
@Override
public int computeVerticalScrollRange() {
return super.computeVerticalScrollRange();
}
/* Proxy methods below */
/**
* Inserts an item at given index. Will show an entrance animation for the new item if the newly added item is visible.
* Will also call {@link Insertable#add(int, Object)} of the root {@link android.widget.BaseAdapter}.
*
* @param index the index the new item should be inserted at.
* @param item the item to insert.
*
* @throws java.lang.IllegalStateException if the adapter that was set does not implement {@link com.nhaarman.listviewanimations.util.Insertable}.
*/
public void insert(final int index, final Object item) {
if (mAnimateAdditionAdapter == null) {
throw new IllegalStateException("Adapter should implement Insertable!");
}
mAnimateAdditionAdapter.insert(index, item);
}
/**
* Inserts items, starting at given index. Will show an entrance animation for the new items if the newly added items are visible.
* Will also call {@link Insertable#add(int, Object)} of the root {@link android.widget.BaseAdapter}.
*
* @param index the starting index the new items should be inserted at.
* @param items the items to insert.
*
* @throws java.lang.IllegalStateException if the adapter that was set does not implement {@link com.nhaarman.listviewanimations.util.Insertable}.
*/
public void insert(final int index, final Object... items) {
if (mAnimateAdditionAdapter == null) {
throw new IllegalStateException("Adapter should implement Insertable!");
}
mAnimateAdditionAdapter.insert(index, items);
}
/**
* Inserts items at given indexes. Will show an entrance animation for the new items if the newly added item is visible.
* Will also call {@link Insertable#add(int, Object)} of the root {@link android.widget.BaseAdapter}.
*
* @param indexItemPairs the index-item pairs to insert. The first argument of the {@code Pair} is the index, the second argument is the item.
*
* @throws java.lang.IllegalStateException if the adapter that was set does not implement {@link com.nhaarman.listviewanimations.util.Insertable}.
*/
public <T> void insert(@NonNull final Pair<Integer, T>... indexItemPairs) {
if (mAnimateAdditionAdapter == null) {
throw new IllegalStateException("Adapter should implement Insertable!");
}
((AnimateAdditionAdapter<T>) mAnimateAdditionAdapter).insert(indexItemPairs);
}
/**
* Insert items at given indexes. Will show an entrance animation for the new items if the newly added item is visible.
* Will also call {@link Insertable#add(int, Object)} of the root {@link android.widget.BaseAdapter}.
*
* @param indexItemPairs the index-item pairs to insert. The first argument of the {@code Pair} is the index, the second argument is the item.
*
* @throws java.lang.IllegalStateException if the adapter that was set does not implement {@link com.nhaarman.listviewanimations.util.Insertable}.
*/
public <T> void insert(@NonNull final Iterable<Pair<Integer, T>> indexItemPairs) {
if (mAnimateAdditionAdapter == null) {
throw new IllegalStateException("Adapter should implement Insertable!");
}
((AnimateAdditionAdapter<T>) mAnimateAdditionAdapter).insert(indexItemPairs);
}
/**
* Sets the {@link com.nhaarman.listviewanimations.itemmanipulation.dragdrop.DraggableManager} to be used
* for determining whether an item should be dragged when the user issues a down {@code MotionEvent}.
* <p/>
* This method does nothing if the drag and drop functionality is not enabled.
*/
public void setDraggableManager(@NonNull final DraggableManager draggableManager) {
if (mDragAndDropHandler != null) {
mDragAndDropHandler.setDraggableManager(draggableManager);
}
}
/**
* Sets the {@link com.nhaarman.listviewanimations.itemmanipulation.dragdrop.OnItemMovedListener}
* that is notified when user has dropped a dragging item.
* <p/>
* This method does nothing if the drag and drop functionality is not enabled.
*/
public void setOnItemMovedListener(@Nullable final OnItemMovedListener onItemMovedListener) {
if (mDragAndDropHandler != null) {
mDragAndDropHandler.setOnItemMovedListener(onItemMovedListener);
}
}
/**
* Starts dragging the item at given position. User must be touching this {@code DynamicListView}.
* <p/>
* This method does nothing if the drag and drop functionality is not enabled.
*
* @param position the position of the item in the adapter to start dragging. Be sure to subtract any header views.
*
* @throws java.lang.IllegalStateException if the user is not touching this {@code DynamicListView},
* or if there is no adapter set.
*/
public void startDragging(final int position) {
/* We don't support dragging items when items are in the undo state. */
if (mSwipeTouchListener instanceof SwipeUndoTouchListener && ((SwipeUndoTouchListener) mSwipeTouchListener).hasPendingItems()) {
return;
}
if (mDragAndDropHandler != null) {
mDragAndDropHandler.startDragging(position);
}
}
/**
* Sets the scroll speed when dragging an item. Defaults to {@code 1.0f}.
* <p/>
* This method does nothing if the drag and drop functionality is not enabled.
*
* @param speed {@code <1.0f} to slow down scrolling, {@code >1.0f} to speed up scrolling.
*/
public void setScrollSpeed(final float speed) {
if (mDragAndDropHandler != null) {
mDragAndDropHandler.setScrollSpeed(speed);
}
}
/**
* Sets the {@link com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.DismissableManager} to specify which views can or cannot be swiped.
* <p/>
* This method does nothing if no swipe functionality is enabled.
*
* @param dismissableManager {@code null} for no restrictions.
*/
public void setDismissableManager(@Nullable final DismissableManager dismissableManager) {
if (mSwipeTouchListener != null) {
mSwipeTouchListener.setDismissableManager(dismissableManager);
}
}
/**
* Flings the {@link android.view.View} corresponding to given position out of sight.
* Calling this method has the same effect as manually swiping an item off the screen.
* <p/>
* This method does nothing if no swipe functionality is enabled.
*
* @param position the position of the item in the {@link android.widget.ListAdapter}. Must be visible.
*/
public void fling(final int position) {
if (mSwipeTouchListener != null) {
mSwipeTouchListener.fling(position);
}
}
/**
* Sets the resource id of a child view that should be touched to engage swipe.
* When the user touches a region outside of that view, no swiping will occur.
* <p/>
* This method does nothing if no swipe functionality is enabled.
*
* @param childResId The resource id of the list items' child that the user should touch to be able to swipe the list items.
*/
public void setSwipeTouchChild(final int childResId) {
if (mSwipeTouchListener != null) {
mSwipeTouchListener.setTouchChild(childResId);
}
}
/**
* Sets the minimum value of the alpha property swiping Views should have.
* <p/>
* This method does nothing if no swipe functionality is enabled.
*
* @param minimumAlpha the alpha value between 0.0f and 1.0f.
*/
public void setMinimumAlpha(final float minimumAlpha) {
if (mSwipeTouchListener != null) {
mSwipeTouchListener.setMinimumAlpha(minimumAlpha);
}
}
/**
* Dismisses the {@link android.view.View} corresponding to given position.
* Calling this method has the same effect as manually swiping an item off the screen.
* <p/>
* This method does nothing if no swipe functionality is enabled.
* It will however throw an exception if an incompatible swipe functionality is enabled.
*
* @param position the position of the item in the {@link android.widget.ListAdapter}. Must be visible.
*
* @throws java.lang.IllegalStateException if the {@link com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeTouchListener}
* that is enabled does not extend {@link com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeDismissTouchListener}.
*/
public void dismiss(final int position) {
if (mSwipeTouchListener != null) {
if (mSwipeTouchListener instanceof SwipeDismissTouchListener) {
((SwipeDismissTouchListener) mSwipeTouchListener).dismiss(position);
} else {
throw new IllegalStateException("Enabled swipe functionality does not support dismiss");
}
}
}
/**
* Performs the undo animation and restores the original state for given {@link android.view.View}.
* <p/>
* This method does nothing if no swipe functionality is enabled.
* It will however throw an exception if an incompatible swipe functionality is enabled.
*
* @param view the parent {@code View} which contains both primary and undo {@code View}s.
*
* @throws java.lang.IllegalStateException if the {@link com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeTouchListener}
* that is enabled doe snot extend {@link com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo.SwipeUndoTouchListener}.
*/
public void undo(@NonNull final View view) {
if (mSwipeTouchListener != null) {
if (mSwipeTouchListener instanceof SwipeUndoTouchListener) {
((SwipeUndoTouchListener) mSwipeTouchListener).undo(view);
} else {
throw new IllegalStateException("Enabled swipe functionality does not support undo");
}
}
}
private class MyOnScrollListener implements OnScrollListener {
private final Collection<OnScrollListener> mOnScrollListeners = new HashSet<>();
@Override
public void onScrollStateChanged(final AbsListView view, final int scrollState) {
for (OnScrollListener onScrollListener : mOnScrollListeners) {
onScrollListener.onScrollStateChanged(view, scrollState);
}
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
if (mSwipeTouchListener instanceof SwipeUndoTouchListener) {
((SwipeUndoTouchListener) mSwipeTouchListener).dimissPending();
}
}
}
@Override
public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) {
for (OnScrollListener onScrollListener : mOnScrollListeners) {
onScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
}
public void addOnScrollListener(final OnScrollListener onScrollListener) {
mOnScrollListeners.add(onScrollListener);
}
}
}
| |
package org.java_websocket.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import org.java_websocket.SocketChannelIOHelper;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocket.READYSTATE;
import org.java_websocket.WebSocketAdapter;
import org.java_websocket.WebSocketFactory;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.WrappedByteChannel;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.exceptions.InvalidHandshakeException;
import org.java_websocket.framing.CloseFrame;
import org.java_websocket.handshake.HandshakeImpl1Client;
import org.java_websocket.handshake.Handshakedata;
import org.java_websocket.handshake.ServerHandshake;
/**
* The <tt>WebSocketClient</tt> is an abstract class that expects a valid
* "ws://" URI to connect to. When connected, an instance recieves important
* events related to the life of the connection. A subclass must implement
* <var>onOpen</var>, <var>onClose</var>, and <var>onMessage</var> to be
* useful. An instance can send messages to it's connected server via the
* <var>send</var> method.
*
* @author Nathan Rajlich
*/
public abstract class WebSocketClient extends WebSocketAdapter implements Runnable {
/**
* The URI this channel is supposed to connect to.
*/
protected URI uri = null;
private WebSocketImpl conn = null;
/**
* The SocketChannel instance this channel uses.
*/
private SocketChannel channel = null;
private ByteChannel wrappedchannel = null;
private Thread writethread;
private Thread readthread;
private Draft draft;
private Map<String,String> headers;
private CountDownLatch connectLatch = new CountDownLatch( 1 );
private CountDownLatch closeLatch = new CountDownLatch( 1 );
private int timeout = 0;
private WebSocketClientFactory wsfactory = new DefaultWebSocketClientFactory( this );
private InetSocketAddress proxyAddress = null;
public WebSocketClient( URI serverURI ) {
this( serverURI, new Draft_10() );
}
/**
* Constructs a WebSocketClient instance and sets it to the connect to the
* specified URI. The channel does not attampt to connect automatically. You
* must call <var>connect</var> first to initiate the socket connection.
*/
public WebSocketClient( URI serverUri , Draft draft ) {
this( serverUri, draft, null, 0 );
}
public WebSocketClient( URI serverUri , Draft draft , Map<String,String> headers , int connecttimeout ) {
if( serverUri == null ) {
throw new IllegalArgumentException();
}
if( draft == null ) {
throw new IllegalArgumentException( "null as draft is permitted for `WebSocketServer` only!" );
}
this.uri = serverUri;
this.draft = draft;
this.headers = headers;
this.timeout = connecttimeout;
try {
channel = SelectorProvider.provider().openSocketChannel();
channel.configureBlocking( true );
} catch ( IOException e ) {
channel = null;
onWebsocketError( null, e );
}
if(channel == null){
conn = (WebSocketImpl) wsfactory.createWebSocket( this, draft, null );
conn.close( CloseFrame.NEVER_CONNECTED, "Failed to create or configure SocketChannel." );
}
else{
conn = (WebSocketImpl) wsfactory.createWebSocket( this, draft, channel.socket() );
}
}
/**
* Gets the URI that this WebSocketClient is connected to.
*
* @return The <tt>URI</tt> for this WebSocketClient.
*/
public URI getURI() {
return uri;
}
/** Returns the protocol version this channel uses. */
public Draft getDraft() {
return draft;
}
/**
* Starts a background thread that attempts and maintains a WebSocket
* connection to the URI specified in the constructor or via <var>setURI</var>.
* <var>setURI</var>.
*/
public void connect() {
if( writethread != null )
throw new IllegalStateException( "WebSocketClient objects are not reuseable" );
writethread = new Thread( this );
writethread.start();
}
/**
* Same as connect but blocks until the websocket connected or failed to do so.<br>
* Returns whether it succeeded or not.
**/
public boolean connectBlocking() throws InterruptedException {
connect();
connectLatch.await();
return conn.isOpen();
}
public void close() {
if( writethread != null ) {
conn.close( CloseFrame.NORMAL );
}
}
public void closeBlocking() throws InterruptedException {
close();
closeLatch.await();
}
/**
* Sends <var>text</var> to the connected WebSocket server.
*
* @param text
* The String to send to the WebSocket server.
*/
public void send( String text ) throws NotYetConnectedException {
conn.send( text );
}
/**
* Sends <var>data</var> to the connected WebSocket server.
*
* @param data
* The Byte-Array of data to send to the WebSocket server.
*/
public void send( byte[] data ) throws NotYetConnectedException {
conn.send( data );
}
// Runnable IMPLEMENTATION /////////////////////////////////////////////////
public void run() {
if( writethread == null )
writethread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
}
private final void interruptableRun() {
if( channel == null ) {
return;// channel will be initialized in the constructor and only be null if no socket channel could be created or if blocking mode could be established
}
boolean waitConnectProxy = false ; //CF++
try {
String host;
int port ;
if( proxyAddress != null ) {
host = proxyAddress.getHostName();
port = proxyAddress.getPort();
waitConnectProxy = true ; //CF++
} else {
host = uri.getHost();
port = getPort();
}
channel.connect( new InetSocketAddress( host, port ) );
conn.channel = wrappedchannel = createProxyChannel( wsfactory.wrapChannel( channel, null, host, port ) );
timeout = 0; // since connect is over
sendHandshake();
readthread = new Thread( new WebsocketWriteThread() );
readthread.start();
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( /*IOException | SecurityException | UnresolvedAddressException*/Exception e ) {//
onWebsocketError( conn, e );
conn.closeConnection( CloseFrame.NEVER_CONNECTED, e.getMessage() );
return;
}
ByteBuffer buff = ByteBuffer.allocate( WebSocketImpl.RCVBUF );
try/*IO*/{
while ( channel.isOpen() ) {
if( SocketChannelIOHelper.read( buff, this.conn, wrappedchannel ) ) {
//CF++
if (waitConnectProxy) {
waitConnectProxy = false ;
// String str = new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() );
// if (str.toLowerCase().contains("200 connection established")) { //http Proxy
// return ;
// }
continue ;
}
//CF--
conn.decode( buff );
} else {
conn.eot();
}
if( wrappedchannel instanceof WrappedByteChannel ) {
WrappedByteChannel w = (WrappedByteChannel) wrappedchannel;
if( w.isNeedRead() ) {
while ( SocketChannelIOHelper.readMore( buff, conn, w ) ) {
conn.decode( buff );
}
conn.decode( buff );
}
}
}
} catch ( CancelledKeyException e ) {
conn.eot();
} catch ( IOException e ) {
conn.eot();
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, e.getMessage() );
}
}
private int getPort() {
int port = uri.getPort();
if( port == -1 ) {
String scheme = uri.getScheme();
if( scheme.equals( "wss" ) ) {
return WebSocket.DEFAULT_WSS_PORT;
} else if( scheme.equals( "ws" ) ) {
return WebSocket.DEFAULT_PORT;
} else {
throw new RuntimeException( "unkonow scheme" + scheme );
}
}
return port;
}
private void sendHandshake() throws InvalidHandshakeException {
String path;
String part1 = uri.getPath();
String part2 = uri.getQuery();
if( part1 == null || part1.length() == 0 )
path = "/";
else
path = part1;
if( part2 != null )
path += "?" + part2;
int port = getPort();
String host = uri.getHost() + ( port != WebSocket.DEFAULT_PORT ? ":" + port : "" );
HandshakeImpl1Client handshake = new HandshakeImpl1Client();
handshake.setResourceDescriptor( path );
handshake.put( "Host", host );
if( headers != null ) {
for( Map.Entry<String,String> kv : headers.entrySet() ) {
handshake.put( kv.getKey(), kv.getValue() );
}
}
conn.startHandshake( handshake );
}
/**
* This represents the state of the connection.
* You can use this method instead of
*/
public READYSTATE getReadyState() {
return conn.getReadyState();
}
/**
* Calls subclass' implementation of <var>onMessage</var>.
*
* @param conn
* @param message
*/
@Override
public final void onWebsocketMessage( WebSocket conn, String message ) {
onMessage( message );
}
@Override
public final void onWebsocketMessage( WebSocket conn, ByteBuffer blob ) {
onMessage( blob );
}
/**
* Calls subclass' implementation of <var>onOpen</var>.
*
* @param conn
*/
@Override
public final void onWebsocketOpen( WebSocket conn, Handshakedata handshake ) {
connectLatch.countDown();
onOpen( (ServerHandshake) handshake );
}
/**
* Calls subclass' implementation of <var>onClose</var>.
*
* @param conn
*/
@Override
public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) {
connectLatch.countDown();
closeLatch.countDown();
if( readthread != null )
readthread.interrupt();
onClose( code, reason, remote );
}
/**
* Calls subclass' implementation of <var>onIOError</var>.
*
* @param conn
*/
@Override
public final void onWebsocketError( WebSocket conn, Exception ex ) {
onError( ex );
}
@Override
public final void onWriteDemand( WebSocket conn ) {
// nothing to do
}
@Override
public void onWebsocketCloseInitiated( WebSocket conn, int code, String reason ) {
onCloseInitiated( code, reason );
}
@Override
public void onWebsocketClosing( WebSocket conn, int code, String reason, boolean remote ) {
onClosing( code, reason, remote );
}
public void onCloseInitiated( int code, String reason ) {
}
public void onClosing( int code, String reason, boolean remote ) {
}
public WebSocket getConnection() {
return conn;
}
public final void setWebSocketFactory( WebSocketClientFactory wsf ) {
this.wsfactory = wsf;
}
public final WebSocketFactory getWebSocketFactory() {
return wsfactory;
}
@Override
public InetSocketAddress getLocalSocketAddress( WebSocket conn ) {
if( channel != null )
return (InetSocketAddress) channel.socket().getLocalSocketAddress();
return null;
}
@Override
public InetSocketAddress getRemoteSocketAddress( WebSocket conn ) {
if( channel != null )
return (InetSocketAddress) channel.socket().getLocalSocketAddress();
return null;
}
// ABTRACT METHODS /////////////////////////////////////////////////////////
public abstract void onOpen( ServerHandshake handshakedata );
public abstract void onMessage( String message );
public abstract void onClose( int code, String reason, boolean remote );
public abstract void onError( Exception ex );
public void onMessage( ByteBuffer bytes ) {
};
public class DefaultClientProxyChannel extends AbstractClientProxyChannel {
public DefaultClientProxyChannel( ByteChannel towrap ) {
super( towrap );
}
/*
@Override
public String buildHandShake() {
StringBuilder b = new StringBuilder();
String host = uri.getHost();
b.append( "CONNECT " );
b.append( host );
b.append( ":" );
b.append( getPort() );
b.append( " HTTP/1.1\n" );
b.append( "Host: " );
b.append( host );
b.append( "\n" );
return b.toString();
}
*/
//CF++
@Override
public String buildHandShake() {
StringBuilder b = new StringBuilder();
String host = uri.getHost();
b.append( "CONNECT " );
b.append( host );
b.append( ":" );
b.append( getPort() );
b.append( " HTTP/1.1\r\n" );
b.append( "Host: " );
b.append( host );
b.append( "Proxy-Connection: Keep-Alive\r\n" );
b.append( "\r\n\r\n" );
return b.toString();
}
//CF--
}
public interface WebSocketClientFactory extends WebSocketFactory {
public ByteChannel wrapChannel( SocketChannel channel, SelectionKey key, String host, int port ) throws IOException;
}
private class WebsocketWriteThread implements Runnable {
@Override
public void run() {
Thread.currentThread().setName( "WebsocketWriteThread" );
try {
while ( !Thread.interrupted() ) {
SocketChannelIOHelper.writeBlocking( conn, wrappedchannel );
}
} catch ( IOException e ) {
conn.eot();
} catch ( InterruptedException e ) {
// this thread is regularly terminated via an interrupt
}
}
}
public ByteChannel createProxyChannel( ByteChannel towrap ) {
if( proxyAddress != null ){
return new DefaultClientProxyChannel( towrap );
}
return towrap;//no proxy in use
}
public void setProxy( InetSocketAddress proxyaddress ) {
proxyAddress = proxyaddress;
}
}
| |
/*
* Copyright (c) 2018 Cybernetic Frontiers LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.cyberfront.crdt;
import java.util.Collection;
import java.util.TreeSet;
import com.cyberfront.crdt.operation.Operation.OperationType;
import com.cyberfront.crdt.operation.Operation;
import com.cyberfront.crdt.support.Support;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* This is an abstract class which defines a Two Set CRDT. One set contains operations to use, called an ADD set, and the other contains
* a set of operations which must not be used, called a REMOVE set. Elements in the REMOVE set have precedence over those in the ADD set.
* That is, if an element is contained in the REMOVE set it will not be used if it is in the ADD set, regardless of when it was added to the
* ADD set.
*/
public abstract class OperationTwoSet extends AbstractCRDT {
/** Property label for the add set property */
protected static final String ADDSET = "addset";
/** Property label for the remove set property */
protected static final String REMSET = "remset";
/** The ADD set. */
@JsonProperty(ADDSET)
private Collection<Operation> addSet;
/** The REMOVE set. */
private Collection<Operation> remSet;
/** Default constructor for the two set instance... no fields are initialized */
public OperationTwoSet() { }
/**
* Copy constructor which duplicates the state of the given CRDT instance
* @param src Source CRDT to copy
*/
public OperationTwoSet(OperationTwoSet src) {
this(src.getAddSet(), src.getRemSet());
}
/**
* COnstructor to specifically define the add and remove sets
* @param addset Add set to use in the constructed CRDT
* @param remset Remove set to use in the constructed CRDT
*/
@JsonCreator
public OperationTwoSet(@JsonProperty(ADDSET) Collection<Operation> addset,
@JsonProperty(REMSET) Collection<Operation> remset) {
this.getAddSet().addAll(addset);
this.getRemSet().addAll(remset);
}
/**
* This method retrieved the ADD set.
*
* @return the ADD set
*/
private Collection<Operation> getAddSet() {
if (null == this.addSet) {
this.addSet = new TreeSet<>();
}
return this.addSet;
}
/**
* This method retrieved the REMOVE set.
*
* @return the REMOVE set
*/
private Collection<Operation> getRemSet() {
if (null == this.remSet) {
this.remSet = new TreeSet<>();
}
return this.remSet;
}
/**
* Generate and retrieve a copy of the add set for public consumption
* @return A copy of the add set
*/
@JsonProperty(ADDSET)
public Collection<Operation> copyAddSet() {
return Operation.copy(this.getAddSet());
}
/**
* Generate and retrieve a copy of the remove set for public consumption
* @return A copy of the remove set
*/
@JsonProperty(REMSET)
public Collection<Operation> copyRemSet() {
return Operation.copy(this.getRemSet());
}
/**
* Retrieve the number of elements in the Add Set
*
* @return The number of elements in the Add Set
*/
@JsonIgnore
public long getAddCount() {
return this.getAddSet().size();
}
/**
* Retrieve the number of elements in the Remove Set
*
* @return The number of elements in the Remove Set
*/
@JsonIgnore
public long getRemCount() {
return this.getRemSet().size();
}
/**
* Retrieve the number of elements in the final operation set
*
* @return The number of elements in the Remove Set
*/
@JsonIgnore
public long getOperationCount() {
return this.getOpsSet().size();
}
/**
* Insert an operation to the ADD set
*
* @param op The operation to add to the ADD set
*/
protected void addOperation(Operation op) {
this.getAddSet().add(op);
}
/**
* Insert an operation to the REMOVE set
*
* @param op The operation to add to the REMOVE set
*/
protected void remOperation(Operation op) {
this.getRemSet().add(op);
}
/**
* This private static function returns a set resulting from removing all of the elements on the RHS from the set on the LHS
*
* @param lhs The left hand side of the difference operator
* @param rhs The right hand side of the difference operator
* @return The set of elements resulting from removing all of the elements in RHS from LHS
*/
private static Collection<Operation> diff(Collection<Operation> lhs, Collection<Operation> rhs) {
Collection<Operation> rv = new TreeSet<>();
rv.addAll(lhs);
rv.removeAll(rhs);
return rv;
}
/**
* This method returns the collection of elements in the ADD set after those in the REMOVE set have been
* removed.
*
* @return The operations which are active in this Two Set CRDT
*/
@JsonIgnore
public Collection<Operation> getOpsSet() {
return diff(this.getAddSet(), this.getRemSet());
}
/**
* This method removes all elements in both the ADD and REMOVE sets, effectively reseting them to empty.
*/
public void clear() {
this.getAddSet().clear();
this.getRemSet().clear();
}
/**
* This method determines the state of the CRDT. If both the ADD and REMOVE sets are empty, then this is empty. Alternatively if the ADD
* set is s subset of the REMOVE set, this will also result in this indicating that there are no operations, resulting in this being an
* empty set.
*
* @return True exactly when the set of active operations is empty
*/
@JsonIgnore
public boolean isEmpty() {
return (this.getAddSet().isEmpty() && this.getRemSet().isEmpty()) || this.getOpsSet().isEmpty();
}
/**
* Look in a collection of operations to determine if at least one element has the given OperationType
* @param operations List of operations to search for the given OperationType
* @param type OperationType to search for in the given collection
* @return True exactly when there is an operation of the given OperationType in the collection of operations; false otherwise
*/
protected static boolean doesTypeExist(final Collection<Operation> operations, final OperationType type) {
for (Operation operation : operations) {
if (type.equals(operation.getType())) {
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see com.cyberfront.cmrdt.manager.AbstractCRDT#isCreated()
*/
@Override
@JsonIgnore
public boolean isCreated() {
return doesTypeExist(this.getOpsSet(), OperationType.CREATE);
}
/* (non-Javadoc)
* @see com.cyberfront.cmrdt.manager.AbstractCRDT#isRead()
*/
@Override
@JsonIgnore
public boolean isRead() {
return doesTypeExist(this.getOpsSet(), OperationType.READ);
}
/* (non-Javadoc)
* @see com.cyberfront.cmrdt.manager.AbstractCRDT#isUpdated()
*/
@Override
@JsonIgnore
public boolean isUpdated() {
return doesTypeExist(this.getOpsSet(), OperationType.UPDATE);
}
/* (non-Javadoc)
* @see com.cyberfront.cmrdt.manager.AbstractCRDT#isDeleted()
*/
@Override
@JsonIgnore
public boolean isDeleted() {
return doesTypeExist(this.getOpsSet(), OperationType.DELETE);
}
/**
* This static method counts the number of NewBaseOperation instances of the type given which are in the
* collection provided
*
* @param ops Collection of BaseOperations to search for operations of the specified type
* @param opType Type to look for in the collection of BaseOperations
* @return Number of NewBaseOperation instances with the given type
*/
protected static long countOperations(Collection<Operation> ops, OperationType opType) {
long rv = 0;
for (Operation op : ops) {
if (opType.equals(op.getType())) {
++rv;
}
}
return rv;
}
/* (non-Javadoc)
* @see com.cyberfront.crdt.AbstractCRDT#countCreated()
*/
@Override
public long countCreated() {
return countOperations(this.getOpsSet(), OperationType.CREATE);
}
/* (non-Javadoc)
* @see com.cyberfront.crdt.AbstractCRDT#countRead()
*/
@Override
public long countRead() {
return countOperations(this.getOpsSet(), OperationType.READ);
}
/* (non-Javadoc)
* @see com.cyberfront.crdt.AbstractCRDT#countUpdate()
*/
@Override
public long countUpdate() {
return countOperations(this.getOpsSet(), OperationType.UPDATE);
}
/* (non-Javadoc)
* @see com.cyberfront.crdt.AbstractCRDT#countDelete()
*/
@Override
public long countDelete() {
return countOperations(this.getOpsSet(), OperationType.DELETE);
}
/* (non-Javadoc)
* @see com.cyberfront.cmrdt.manager.AbstractCRDT#getSegment()
*/
@Override
protected String getSegment() {
StringBuilder sb = new StringBuilder();
sb.append(super.getSegment() + ",");
sb.append("\"addSet\":" + Support.convert(this.getAddSet()) + ",");
sb.append("\"remSet\":" + Support.convert(this.getRemSet()) + ",");
sb.append("\"opSet\":" + Support.convert(this.getOpsSet()));
return sb.toString();
}
}
| |
package com.luboganev.handdrawn;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.os.Build;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class DrawingView extends View {
private List<TimedPoint> mTimedPoints = new LinkedList<>();
private Path mDrawPath;
private Paint mDrawPaint, mCanvasPaint;
// If path should be reset in onDraw
private boolean mResetPath = false;
// If canvas should be cleared in onDraw
private boolean mClear = false;
private Canvas mDrawCanvas;
private Bitmap mCanvasBitmap;
public static final int MODE_DRAW = 1;
public static final int MODE_PRESENT = 2;
private int mMode = MODE_DRAW;
/**
* Changes the mode of the view between touch
* drawing and presenting saved timedpoints
*
* @param mode
*/
public void setMode(int mode) {
if (mMode == mode) {
return;
}
switch (mode) {
case MODE_DRAW:
clearCanvas();
mMode = mode;
break;
case MODE_PRESENT:
mMode = mode;
break;
}
}
public void setTimedPoints(List<TimedPoint> timedPoints) {
if (mMode == MODE_PRESENT) {
mTimedPoints = timedPoints;
presentPointsRange(0, timedPoints.size() - 1);
}
}
public List<TimedPoint> getTimedPointsCopy() {
ArrayList<TimedPoint> copyPoints = new ArrayList<>();
copyPoints.addAll(mTimedPoints);
return copyPoints;
}
public DrawingView(Context context) {
super(context);
initView();
}
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public DrawingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public DrawingView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView();
}
private void initView() {
mDrawPath = new Path();
mDrawPaint = new Paint();
int mPaintColor = 0xFF000000;
mDrawPaint.setColor(mPaintColor);
mDrawPaint.setAntiAlias(true);
mDrawPaint.setStrokeWidth(20);
mDrawPaint.setStyle(Paint.Style.STROKE);
mDrawPaint.setStrokeJoin(Paint.Join.ROUND);
mDrawPaint.setStrokeCap(Paint.Cap.ROUND);
mCanvasPaint = new Paint(Paint.DITHER_FLAG);
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
if (mMode != MODE_DRAW) {
return false;
}
float touchX = event.getX();
float touchY = event.getY();
mTimedPoints.add(new TimedPoint(touchX, touchY, event.getAction(), System.currentTimeMillis()));
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mDrawPath.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
mDrawPath.lineTo(touchX, touchY);
break;
case MotionEvent.ACTION_UP:
mDrawCanvas.drawPath(mDrawPath, mDrawPaint);
mDrawPath.reset();
break;
default:
return false;
}
invalidate();
return true;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mCanvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mDrawCanvas = new Canvas(mCanvasBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
if (mClear) {
mDrawCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
mClear = false;
}
if (mResetPath) {
mDrawPath.reset();
mResetPath = false;
}
canvas.drawBitmap(mCanvasBitmap, 0, 0, mCanvasPaint);
canvas.drawPath(mDrawPath, mDrawPaint);
}
/**
* Clears the canvas and all saved timed points
*/
public void clearCanvas() {
mClear = true;
mResetPath = true;
mTimedPoints.clear();
invalidate();
}
/**
* Drawns a range of the saved timed points on the screen. The view needs to be in
* present mode to do this.
*
* @param startIndex
* @param endIndex
*/
public void presentPointsRange(int startIndex, int endIndex) {
if (mMode != MODE_PRESENT) {
return;
}
if (startIndex >= endIndex) {
return;
}
if (startIndex < 0) {
return;
}
if (endIndex >= mTimedPoints.size()) {
return;
}
mClear = true;
Path path = new Path();
for (int i = startIndex; i < endIndex; i++) {
TimedPoint p = mTimedPoints.get(i);
if (i == startIndex) {
path.moveTo(p.getTouchX(), p.getTouchY());
}
switch (p.getTouchEventAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(p.getTouchX(), p.getTouchY());
break;
case MotionEvent.ACTION_MOVE:
path.lineTo(p.getTouchX(), p.getTouchY());
break;
}
}
mDrawPath = path;
invalidate();
}
public int getMode() {
return mMode;
}
}
| |
package org.cyclops.cyclopscore.ingredient.collection;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.cyclops.commoncapabilities.api.ingredient.IngredientInstanceWrapper;
import org.cyclops.cyclopscore.ingredient.IngredientComponentStubs;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
@RunWith(Parameterized.class)
public class TestIngredientMapSimple {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ new IngredientHashMap<>(IngredientComponentStubs.SIMPLE) },
{ new IngredientHashMap<>(IngredientComponentStubs.SIMPLE, 3) },
{ new IngredientHashMap<>(IngredientComponentStubs.SIMPLE, new IngredientHashMap<>(IngredientComponentStubs.SIMPLE)) },
{ new IngredientHashMap<>(IngredientComponentStubs.SIMPLE, Maps.newHashMap()) },
{ new IngredientTreeMap<>(IngredientComponentStubs.SIMPLE) },
{ new IngredientTreeMap<>(IngredientComponentStubs.SIMPLE, new IngredientTreeMap<>(IngredientComponentStubs.SIMPLE)) },
{ new IngredientTreeMap<>(IngredientComponentStubs.SIMPLE, Maps.newTreeMap()) },
});
}
@Parameterized.Parameter
public IIngredientMapMutable<Integer, Boolean, Integer> collection;
@Before
public void beforeEach() {
collection.clear();
collection.put(0, 0);
collection.put(1, 10);
collection.put(2, 20);
}
@Test
public void testEquals() {
assertThat(collection.equals(collection), is(true));
assertThat(collection.equals("abc"), is(false));
assertThat(collection.equals(new IngredientHashMap<>(IngredientComponentStubs.COMPLEX)), is(false));
assertThat(collection.equals(null), is(false));
HashMap<IngredientInstanceWrapper<Integer, Boolean>, Integer> subMap0 = Maps.newHashMap();
subMap0.put(new IngredientInstanceWrapper<>(IngredientComponentStubs.SIMPLE, 0), 0);
subMap0.put(new IngredientInstanceWrapper<>(IngredientComponentStubs.SIMPLE, 1), 10);
subMap0.put(new IngredientInstanceWrapper<>(IngredientComponentStubs.SIMPLE, 2), 20);
assertThat(collection.equals(new IngredientHashMap<>(IngredientComponentStubs.SIMPLE, subMap0)), is(true));
HashMap<IngredientInstanceWrapper<Integer, Boolean>, Integer> subMap1 = Maps.newHashMap();
subMap1.put(new IngredientInstanceWrapper<>(IngredientComponentStubs.SIMPLE, 0), 0);
subMap1.put(new IngredientInstanceWrapper<>(IngredientComponentStubs.SIMPLE, 1), 10);
subMap1.put(new IngredientInstanceWrapper<>(IngredientComponentStubs.SIMPLE, 3), 30);
assertThat(collection.equals(new IngredientHashMap<>(IngredientComponentStubs.SIMPLE, subMap1)), is(false));
HashMap<IngredientInstanceWrapper<Integer, Boolean>, Integer> subMap2 = Maps.newHashMap();
subMap2.put(new IngredientInstanceWrapper<>(IngredientComponentStubs.SIMPLE, 0), 0);
subMap2.put(new IngredientInstanceWrapper<>(IngredientComponentStubs.SIMPLE, 1), 10);
assertThat(collection.equals(new IngredientHashMap<>(IngredientComponentStubs.SIMPLE, subMap2)), is(false));
assertThat(collection.equals(new IngredientHashMap<>(IngredientComponentStubs.COMPLEX)), is(false));
}
@Test
public void testHashCode() {
assertThat(collection.hashCode(), is(collection.hashCode()));
assertThat(collection.hashCode(), not(is(new IngredientHashMap<>(IngredientComponentStubs.COMPLEX).hashCode())));
IngredientHashMap<Integer, Boolean, Integer> simpleMap = new IngredientHashMap<>(IngredientComponentStubs.SIMPLE);
simpleMap.put(0, 0);
simpleMap.put(1, 10);
simpleMap.put(2, 20);
assertThat(collection.hashCode(), is(simpleMap.hashCode()));
assertThat(collection.hashCode(), not(is(new IngredientArrayList<>(IngredientComponentStubs.COMPLEX).hashCode())));
}
@Test
public void testIteratorNext() {
Iterator<Map.Entry<Integer, Integer>> it = collection.iterator(0, true);
assertThat(it.hasNext(), is(true));
assertThat(it.next(), is(new AbstractMap.SimpleEntry<>(0, 0)));
assertThat(it.hasNext(), is(false));
}
@Test(expected = NoSuchElementException.class)
public void testIteratorNextTooMany() {
Iterator<Map.Entry<Integer, Integer>> it = collection.iterator(0, true);
assertThat(it.next(), is(new AbstractMap.SimpleEntry<>(0, 0)));
it.next();
}
@Test
public void testIteratorRemove() {
Iterator<Map.Entry<Integer, Integer>> it = collection.iterator(0, true);
assertThat(it.next(), is(new AbstractMap.SimpleEntry<>(0, 0)));
it.remove();
assertThat(collection.containsKey(0), is(false));
}
@Test(expected = IllegalStateException.class)
public void testIteratorRemoveTooMany() {
Iterator<Map.Entry<Integer, Integer>> it = collection.iterator(0, true);
assertThat(it.next(), is(new AbstractMap.SimpleEntry<>(0, 0)));
it.remove();
it.remove();
}
@Test
public void testIteratorEmpty() {
Iterator<Map.Entry<Integer, Integer>> it = collection.iterator(4, true);
assertThat(it.hasNext(), is(false));
}
@Test(expected = RuntimeException.class)
public void testIteratorNextEmpty() {
Iterator<Map.Entry<Integer, Integer>> it = collection.iterator(4, true);
it.next();
}
@Test(expected = RuntimeException.class)
public void testIteratorRemoveEmpty() {
Iterator<Map.Entry<Integer, Integer>> it = collection.iterator(4, true);
it.remove();
}
@Test(expected = RuntimeException.class)
public void testIteratorRemoveNoNext() {
Iterator<Map.Entry<Integer, Integer>> it = collection.iterator(0, true);
it.remove();
}
@Test
public void testContainsMatch() {
assertThat(collection.containsKey(0, true), is(true));
assertThat(collection.containsKey(1, true), is(true));
assertThat(collection.containsKey(2, true), is(true));
assertThat(collection.containsKey(3, true), is(false));
}
@Test
public void testCount() {
assertThat(collection.countKey(0, true), is(1));
assertThat(collection.countKey(1, true), is(1));
assertThat(collection.countKey(2, true), is(1));
assertThat(collection.countKey(3, true), is(0));
}
@Test
public void testIteratorMatch() {
assertThat(Lists.newArrayList(collection.iterator(0, true)), is(Lists.newArrayList(new AbstractMap.SimpleEntry<>(0, 0))));
assertThat(Lists.newArrayList(collection.iterator(1, true)), is(Lists.newArrayList(new AbstractMap.SimpleEntry<>(1, 10))));
assertThat(Lists.newArrayList(collection.iterator(2, true)), is(Lists.newArrayList(new AbstractMap.SimpleEntry<>(2, 20))));
assertThat(Lists.newArrayList(collection.iterator(3, true)), is(Lists.newArrayList()));
}
@Test
public void testToString() {
assertThat(collection.toString(), equalTo("[{0,0}, {1,10}, {2,20}]"));
}
@Test
public void testRemoveAll() {
Assert.assertThat(collection.size(), is(3));
assertThat(collection.removeAll(3, true), is(0));
Assert.assertThat(collection.size(), is(3));
assertThat(collection.removeAll(2, true), is(1));
Assert.assertThat(collection.size(), is(2));
assertThat(collection.removeAll(1, true), is(1));
Assert.assertThat(collection.size(), is(1));
assertThat(collection.removeAll(0, true), is(1));
Assert.assertThat(collection.size(), is(0));
}
@Test
public void testRemoveAllAny() {
Assert.assertThat(collection.size(), is(3));
assertThat(collection.removeAll(3, false), is(3));
Assert.assertThat(collection.size(), is(0));
}
@Test
public void testRemoveAllIterable() {
Assert.assertThat(collection.size(), is(3));
assertThat(collection.removeAll(Lists.newArrayList(0, 1, 2, 3), true), is(3));
Assert.assertThat(collection.size(), is(0));
}
@Test
public void testRemoveAllIterableAny() {
Assert.assertThat(collection.size(), is(3));
assertThat(collection.removeAll(Lists.newArrayList(0, 1), false), is(3));
Assert.assertThat(collection.size(), is(0));
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.percolator;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.percolate.MultiPercolateRequestBuilder;
import org.elasticsearch.action.percolate.MultiPercolateResponse;
import org.elasticsearch.action.percolate.PercolateRequestBuilder;
import org.elasticsearch.action.percolate.PercolateResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Predicate;
import static org.elasticsearch.action.percolate.PercolateSourceBuilder.docBuilder;
import static org.elasticsearch.client.Requests.clusterHealthRequest;
import static org.elasticsearch.common.settings.Settings.settingsBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.percolator.PercolatorTestUtil.convertFromTextArray;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertMatchCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
@ClusterScope(scope = Scope.TEST, numDataNodes = 0, numClientNodes = 0, transportClientRatio = 0)
public class RecoveryPercolatorIT extends ESIntegTestCase {
@Override
protected int numberOfShards() {
return 1;
}
public void testRestartNodePercolator1() throws Exception {
internalCluster().startNode();
assertAcked(prepareCreate("test").addMapping("type1", "field1", "type=string").addMapping(PercolatorService.TYPE_NAME, "color", "type=string"));
logger.info("--> register a query");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "kuku")
.setSource(jsonBuilder().startObject()
.field("color", "blue")
.field("query", termQuery("field1", "value1"))
.endObject())
.setRefresh(true)
.get();
PercolateResponse percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc")
.field("field1", "value1")
.endObject().endObject())
.get();
assertThat(percolate.getMatches(), arrayWithSize(1));
internalCluster().rollingRestart();
logger.info("Running Cluster Health (wait for the shards to startup)");
ensureYellow();
percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc")
.field("field1", "value1")
.endObject().endObject())
.get();
assertMatchCount(percolate, 1l);
assertThat(percolate.getMatches(), arrayWithSize(1));
}
public void testRestartNodePercolator2() throws Exception {
internalCluster().startNode();
assertAcked(prepareCreate("test").addMapping("type1", "field1", "type=string").addMapping(PercolatorService.TYPE_NAME, "color", "type=string"));
logger.info("--> register a query");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "kuku")
.setSource(jsonBuilder().startObject()
.field("color", "blue")
.field("query", termQuery("field1", "value1"))
.endObject())
.setRefresh(true)
.get();
assertThat(client().prepareSearch().setSize(0).setTypes(PercolatorService.TYPE_NAME).setQuery(matchAllQuery()).get().getHits().totalHits(), equalTo(1l));
PercolateResponse percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc")
.field("field1", "value1")
.endObject().endObject())
.get();
assertMatchCount(percolate, 1l);
assertThat(percolate.getMatches(), arrayWithSize(1));
internalCluster().rollingRestart();
logger.info("Running Cluster Health (wait for the shards to startup)");
ClusterHealthResponse clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForYellowStatus().waitForActiveShards(1)).actionGet();
logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
assertThat(clusterHealth.isTimedOut(), equalTo(false));
SearchResponse countResponse = client().prepareSearch().setSize(0).setTypes(PercolatorService.TYPE_NAME).setQuery(matchAllQuery()).get();
assertHitCount(countResponse, 1l);
DeleteIndexResponse actionGet = client().admin().indices().prepareDelete("test").get();
assertThat(actionGet.isAcknowledged(), equalTo(true));
assertAcked(prepareCreate("test").addMapping("type1", "field1", "type=string").addMapping(PercolatorService.TYPE_NAME, "color", "type=string"));
clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForYellowStatus().waitForActiveShards(1)).actionGet();
logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
assertThat(clusterHealth.isTimedOut(), equalTo(false));
assertThat(client().prepareSearch().setSize(0).setTypes(PercolatorService.TYPE_NAME).setQuery(matchAllQuery()).get().getHits().totalHits(), equalTo(0l));
percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc")
.field("field1", "value1")
.endObject().endObject())
.get();
assertMatchCount(percolate, 0l);
assertThat(percolate.getMatches(), emptyArray());
logger.info("--> register a query");
client().prepareIndex("test", PercolatorService.TYPE_NAME, "kuku")
.setSource(jsonBuilder().startObject()
.field("color", "blue")
.field("query", termQuery("field1", "value1"))
.endObject())
.setRefresh(true)
.get();
assertThat(client().prepareSearch().setSize(0).setTypes(PercolatorService.TYPE_NAME).setQuery(matchAllQuery()).get().getHits().totalHits(), equalTo(1l));
percolate = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc")
.field("field1", "value1")
.endObject().endObject())
.get();
assertMatchCount(percolate, 1l);
assertThat(percolate.getMatches(), arrayWithSize(1));
}
public void testLoadingPercolateQueriesDuringCloseAndOpen() throws Exception {
internalCluster().startNode();
internalCluster().startNode();
assertAcked(client().admin().indices().prepareCreate("test")
.setSettings(settingsBuilder().put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 2)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)));
ensureGreen();
logger.info("--> Add dummy docs");
client().prepareIndex("test", "type1", "1").setSource("field1", 0).get();
client().prepareIndex("test", "type2", "1").setSource("field1", 1).get();
logger.info("--> register a queries");
for (int i = 1; i <= 100; i++) {
client().prepareIndex("test", PercolatorService.TYPE_NAME, Integer.toString(i))
.setSource(jsonBuilder().startObject()
.field("query", rangeQuery("field1").from(0).to(i))
.endObject())
.get();
}
refresh();
logger.info("--> Percolate doc with field1=95");
PercolateResponse response = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", 95).endObject().endObject())
.get();
assertMatchCount(response, 6l);
assertThat(response.getMatches(), arrayWithSize(6));
assertThat(convertFromTextArray(response.getMatches(), "test"), arrayContainingInAnyOrder("95", "96", "97", "98", "99", "100"));
logger.info("--> Close and open index to trigger percolate queries loading...");
assertAcked(client().admin().indices().prepareClose("test"));
assertAcked(client().admin().indices().prepareOpen("test"));
ensureGreen();
logger.info("--> Percolate doc with field1=100");
response = client().preparePercolate()
.setIndices("test").setDocumentType("type1")
.setSource(jsonBuilder().startObject().startObject("doc").field("field1", 100).endObject().endObject()).get();
assertMatchCount(response, 1l);
assertThat(response.getMatches(), arrayWithSize(1));
assertThat(response.getMatches()[0].getId().string(), equalTo("100"));
}
public void testPercolatorRecovery() throws Exception {
// 3 nodes, 2 primary + 2 replicas per primary, so each node should have a copy of the data.
// We only start and stop nodes 2 and 3, so all requests should succeed and never be partial.
internalCluster().startNode(settingsBuilder().put("node.stay", true));
internalCluster().startNode(settingsBuilder().put("node.stay", false));
internalCluster().startNode(settingsBuilder().put("node.stay", false));
ensureGreen();
client().admin().indices().prepareCreate("test")
.setSettings(settingsBuilder()
.put("index.number_of_shards", 2)
.put("index.number_of_replicas", 2)
)
.get();
ensureGreen();
final Client client = internalCluster().client(input -> input.getAsBoolean("node.stay", true));
final int numQueries = randomIntBetween(50, 100);
logger.info("--> register a queries");
for (int i = 0; i < numQueries; i++) {
client.prepareIndex("test", PercolatorService.TYPE_NAME, Integer.toString(i))
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.get();
}
refresh();
final String document = "{\"field\" : \"a\"}";
client.prepareIndex("test", "type", "1")
.setSource(document)
.get();
final Lock lock = new ReentrantLock();
final AtomicBoolean run = new AtomicBoolean(true);
final AtomicReference<Throwable> error = new AtomicReference<>();
Runnable r = () -> {
try {
while (run.get()) {
PercolateRequestBuilder percolateBuilder = client.preparePercolate()
.setIndices("test").setDocumentType("type").setSize(numQueries);
if (randomBoolean()) {
percolateBuilder.setPercolateDoc(docBuilder().setDoc(document));
} else {
percolateBuilder.setGetRequest(Requests.getRequest("test").type("type").id("1"));
}
PercolateResponse response;
try {
lock.lock();
response = percolateBuilder.get();
} finally {
lock.unlock();
}
assertNoFailures(response);
assertThat(response.getSuccessfulShards(), equalTo(response.getTotalShards()));
assertThat(response.getCount(), equalTo((long) numQueries));
assertThat(response.getMatches().length, equalTo(numQueries));
}
} catch (Throwable t) {
logger.info("Error in percolate thread...", t);
run.set(false);
error.set(t);
}
};
Thread t = new Thread(r);
t.start();
Predicate<Settings> nodePredicate = input -> !input.getAsBoolean("node.stay", false);
try {
// 1 index, 2 primaries, 2 replicas per primary
for (int i = 0; i < 4; i++) {
try {
lock.lock();
internalCluster().stopRandomNode(nodePredicate);
} finally {
lock.unlock();
}
client.admin().cluster().prepareHealth("test")
.setWaitForEvents(Priority.LANGUID)
.setTimeout(TimeValue.timeValueMinutes(2))
.setWaitForYellowStatus()
.setWaitForActiveShards(4) // 2 nodes, so 4 shards (2 primaries, 2 replicas)
.get();
assertThat(error.get(), nullValue());
try {
lock.lock();
internalCluster().stopRandomNode(nodePredicate);
} finally {
lock.unlock();
}
client.admin().cluster().prepareHealth("test")
.setWaitForEvents(Priority.LANGUID)
.setTimeout(TimeValue.timeValueMinutes(2))
.setWaitForYellowStatus()
.setWaitForActiveShards(2) // 1 node, so 2 shards (2 primaries, 0 replicas)
.get();
assertThat(error.get(), nullValue());
internalCluster().startNode(settingsBuilder().put("node.stay", false));
client.admin().cluster().prepareHealth("test")
.setWaitForEvents(Priority.LANGUID)
.setTimeout(TimeValue.timeValueMinutes(2))
.setWaitForYellowStatus()
.setWaitForActiveShards(4) // 2 nodes, so 4 shards (2 primaries, 2 replicas)
.get();
assertThat(error.get(), nullValue());
internalCluster().startNode(settingsBuilder().put("node.stay", false));
client.admin().cluster().prepareHealth("test")
.setWaitForEvents(Priority.LANGUID)
.setTimeout(TimeValue.timeValueMinutes(2))
.setWaitForGreenStatus() // We're confirm the shard settings, so green instead of yellow
.setWaitForActiveShards(6) // 3 nodes, so 6 shards (2 primaries, 4 replicas)
.get();
assertThat(error.get(), nullValue());
}
} finally {
run.set(false);
}
t.join();
assertThat(error.get(), nullValue());
}
}
| |
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.facelets.tag.jsf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import com.sun.facelets.FaceletContext;
import com.sun.facelets.FaceletHandler;
import com.sun.facelets.tag.TagAttribute;
import com.sun.facelets.tag.TagAttributeException;
/**
*
* @author Jacob Hookom
* @version $Id: ComponentSupport.java,v 1.8 2008/07/13 19:01:46 rlubke Exp $
*/
public final class ComponentSupport {
private final static String MARK_DELETED = "com.sun.facelets.MARK_DELETED";
public final static String MARK_CREATED = "com.sun.facelets.MARK_ID";
/**
* Used in conjunction with markForDeletion where any UIComponent marked
* will be removed.
*
* @param c
* UIComponent to finalize
*/
public static final void finalizeForDeletion(UIComponent c) {
// remove any existing marks of deletion
c.getAttributes().remove(MARK_DELETED);
// finally remove any children marked as deleted
int sz = c.getChildCount();
if (sz > 0) {
UIComponent cc = null;
List cl = c.getChildren();
while (--sz >= 0) {
cc = (UIComponent) cl.get(sz);
if (cc.getAttributes().containsKey(MARK_DELETED)) {
cl.remove(sz);
}
}
}
// remove any facets marked as deleted
if (c.getFacets().size() > 0) {
Collection col = c.getFacets().values();
UIComponent fc;
for (Iterator itr = col.iterator(); itr.hasNext();) {
fc = (UIComponent) itr.next();
if (fc.getAttributes().containsKey(MARK_DELETED)) {
itr.remove();
}
}
}
}
/**
* A lighter-weight version of UIComponent's findChild.
*
* @param parent
* parent to start searching from
* @param id
* to match to
* @return UIComponent found or null
*/
public static final UIComponent findChild(UIComponent parent, String id) {
int sz = parent.getChildCount();
if (sz > 0) {
UIComponent c = null;
List cl = parent.getChildren();
while (--sz >= 0) {
c = (UIComponent) cl.get(sz);
if (id.equals(c.getId())) {
return c;
}
}
}
return null;
}
/**
* By TagId, find Child
* @param parent
* @param id
* @return
*/
public static final UIComponent findChildByTagId(UIComponent parent, String id) {
Iterator itr = parent.getFacetsAndChildren();
UIComponent c = null;
String cid = null;
while (itr.hasNext()) {
c = (UIComponent) itr.next();
cid = (String) c.getAttributes().get(MARK_CREATED);
if (id.equals(cid)) {
return c;
}
}
// int sz = parent.getChildCount();
// if (sz > 0) {
// UIComponent c = null;
// List cl = parent.getChildren();
// String cid = null;
// while (--sz >= 0) {
// c = (UIComponent) cl.get(sz);
// cid = (String) c.getAttributes().get(MARK_CREATED);
// if (id.equals(cid)) {
// return c;
// }
// }
// }
return null;
}
/**
* According to JSF 1.2 tag specs, this helper method will use the
* TagAttribute passed in determining the Locale intended.
*
* @param ctx
* FaceletContext to evaluate from
* @param attr
* TagAttribute representing a Locale
* @return Locale found
* @throws TagAttributeException
* if the Locale cannot be determined
*/
public static final Locale getLocale(FaceletContext ctx, TagAttribute attr)
throws TagAttributeException {
Object obj = attr.getObject(ctx);
if (obj instanceof Locale) {
return (Locale) obj;
}
if (obj instanceof String) {
String s = (String) obj;
if (s.length() == 2) {
return new Locale(s);
}
if (s.length() == 5) {
return new Locale(s.substring(0, 2), s.substring(3, 5)
.toUpperCase());
}
if (s.length() >= 7) {
return new Locale(s.substring(0, 2), s.substring(3, 5)
.toUpperCase(), s.substring(6, s.length()));
}
throw new TagAttributeException(attr, "Invalid Locale Specified: "
+ s);
} else {
throw new TagAttributeException(attr,
"Attribute did not evaluate to a String or Locale: " + obj);
}
}
/**
* Tries to walk up the parent to find the UIViewRoot, if not found, then go
* to FaceletContext's FacesContext for the view root.
*
* @param ctx
* FaceletContext
* @param parent
* UIComponent to search from
* @return UIViewRoot instance for this evaluation
*/
public static final UIViewRoot getViewRoot(FaceletContext ctx,
UIComponent parent) {
UIComponent c = parent;
do {
if (c instanceof UIViewRoot) {
return (UIViewRoot) c;
} else {
c = c.getParent();
}
} while (c != null);
return ctx.getFacesContext().getViewRoot();
}
/**
* Marks all direct children and Facets with an attribute for deletion.
*
* @see #finalizeForDeletion(UIComponent)
* @param c
* UIComponent to mark
*/
public static final void markForDeletion(UIComponent c) {
// flag this component as deleted
c.getAttributes().put(MARK_DELETED, Boolean.TRUE);
// mark all children to be deleted
int sz = c.getChildCount();
if (sz > 0) {
UIComponent cc = null;
List cl = c.getChildren();
while (--sz >= 0) {
cc = (UIComponent) cl.get(sz);
if (cc.getAttributes().containsKey(MARK_CREATED)) {
cc.getAttributes().put(MARK_DELETED, Boolean.TRUE);
}
}
}
// mark all facets to be deleted
if (c.getFacets().size() > 0) {
Collection col = c.getFacets().values();
UIComponent fc;
for (Iterator itr = col.iterator(); itr.hasNext();) {
fc = (UIComponent) itr.next();
if (fc.getAttributes().containsKey(MARK_CREATED)) {
fc.getAttributes().put(MARK_DELETED, Boolean.TRUE);
}
}
}
}
public final static void encodeRecursive(FacesContext context,
UIComponent viewToRender) throws IOException, FacesException {
if (viewToRender.isRendered()) {
viewToRender.encodeBegin(context);
if (viewToRender.getRendersChildren()) {
viewToRender.encodeChildren(context);
} else if (viewToRender.getChildCount() > 0) {
Iterator kids = viewToRender.getChildren().iterator();
while (kids.hasNext()) {
UIComponent kid = (UIComponent) kids.next();
encodeRecursive(context, kid);
}
}
viewToRender.encodeEnd(context);
}
}
public static void removeTransient(UIComponent c) {
UIComponent d, e;
if (c.getChildCount() > 0) {
for (Iterator itr = c.getChildren().iterator(); itr.hasNext();) {
d = (UIComponent) itr.next();
if (d.getFacets().size() > 0) {
for (Iterator jtr = d.getFacets().values().iterator(); jtr
.hasNext();) {
e = (UIComponent) jtr.next();
if (e.isTransient()) {
jtr.remove();
} else {
removeTransient(e);
}
}
}
if (d.isTransient()) {
itr.remove();
} else {
removeTransient(d);
}
}
}
if (c.getFacets().size() > 0) {
for (Iterator itr = c.getFacets().values().iterator(); itr
.hasNext();) {
d = (UIComponent) itr.next();
if (d.isTransient()) {
itr.remove();
} else {
removeTransient(d);
}
}
}
}
/**
* Determine if the passed component is not null and if it's new
* to the tree. This operation can be used for determining if attributes
* should be wired to the component.
*
* @param component the component you wish to modify
* @return true if it's new
*/
public final static boolean isNew(UIComponent component) {
return component != null && component.getParent() == null;
}
}
| |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.data.input.impl;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import io.druid.java.util.common.parsers.ParserUtils;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DimensionsSpec
{
private final List<DimensionSchema> dimensions;
private final Set<String> dimensionExclusions;
private final Map<String, DimensionSchema> dimensionSchemaMap;
public static DimensionsSpec ofEmpty()
{
return new DimensionsSpec(null, null, null);
}
public static List<DimensionSchema> getDefaultSchemas(List<String> dimNames)
{
return getDefaultSchemas(dimNames, DimensionSchema.MultiValueHandling.ofDefault());
}
public static List<DimensionSchema> getDefaultSchemas(
final List<String> dimNames,
final DimensionSchema.MultiValueHandling multiValueHandling
)
{
return Lists.transform(
dimNames,
new Function<String, DimensionSchema>()
{
@Override
public DimensionSchema apply(String input)
{
return new StringDimensionSchema(input, multiValueHandling);
}
}
);
}
public static DimensionSchema convertSpatialSchema(SpatialDimensionSchema spatialSchema)
{
return new NewSpatialDimensionSchema(spatialSchema.getDimName(), spatialSchema.getDims());
}
@JsonCreator
public DimensionsSpec(
@JsonProperty("dimensions") List<DimensionSchema> dimensions,
@JsonProperty("dimensionExclusions") List<String> dimensionExclusions,
@Deprecated @JsonProperty("spatialDimensions") List<SpatialDimensionSchema> spatialDimensions
)
{
this.dimensions = dimensions == null
? Lists.<DimensionSchema>newArrayList()
: Lists.newArrayList(dimensions);
this.dimensionExclusions = (dimensionExclusions == null)
? Sets.<String>newHashSet()
: Sets.newHashSet(dimensionExclusions);
List<SpatialDimensionSchema> spatialDims = (spatialDimensions == null)
? Lists.<SpatialDimensionSchema>newArrayList()
: spatialDimensions;
verify(spatialDims);
// Map for easy dimension name-based schema lookup
this.dimensionSchemaMap = new HashMap<>();
for (DimensionSchema schema : this.dimensions) {
dimensionSchemaMap.put(schema.getName(), schema);
}
for(SpatialDimensionSchema spatialSchema : spatialDims) {
DimensionSchema newSchema = DimensionsSpec.convertSpatialSchema(spatialSchema);
this.dimensions.add(newSchema);
dimensionSchemaMap.put(newSchema.getName(), newSchema);
}
}
@JsonProperty
public List<DimensionSchema> getDimensions()
{
return dimensions;
}
@JsonProperty
public Set<String> getDimensionExclusions()
{
return dimensionExclusions;
}
@Deprecated @JsonIgnore
public List<SpatialDimensionSchema> getSpatialDimensions()
{
Iterable<NewSpatialDimensionSchema> filteredList = Iterables.filter(
dimensions, NewSpatialDimensionSchema.class
);
Iterable<SpatialDimensionSchema> transformedList = Iterables.transform(
filteredList,
new Function<NewSpatialDimensionSchema, SpatialDimensionSchema>()
{
@Nullable
@Override
public SpatialDimensionSchema apply(NewSpatialDimensionSchema input)
{
return new SpatialDimensionSchema(input.getName(), input.getDims());
}
}
);
return Lists.newArrayList(transformedList);
}
@JsonIgnore
public List<String> getDimensionNames()
{
return Lists.transform(
dimensions,
new Function<DimensionSchema, String>()
{
@Override
public String apply(DimensionSchema input)
{
return input.getName();
}
}
);
}
public DimensionSchema getSchema(String dimension)
{
return dimensionSchemaMap.get(dimension);
}
public boolean hasCustomDimensions()
{
return !(dimensions == null || dimensions.isEmpty());
}
public DimensionsSpec withDimensions(List<DimensionSchema> dims)
{
return new DimensionsSpec(dims, ImmutableList.copyOf(dimensionExclusions), null);
}
public DimensionsSpec withDimensionExclusions(Set<String> dimExs)
{
return new DimensionsSpec(
dimensions,
ImmutableList.copyOf(Sets.union(dimensionExclusions, dimExs)),
null
);
}
@Deprecated
public DimensionsSpec withSpatialDimensions(List<SpatialDimensionSchema> spatials)
{
return new DimensionsSpec(dimensions, ImmutableList.copyOf(dimensionExclusions), spatials);
}
private void verify(List<SpatialDimensionSchema> spatialDimensions)
{
List<String> dimNames = getDimensionNames();
Preconditions.checkArgument(
Sets.intersection(this.dimensionExclusions, Sets.newHashSet(dimNames)).isEmpty(),
"dimensions and dimensions exclusions cannot overlap"
);
ParserUtils.validateFields(dimNames);
ParserUtils.validateFields(dimensionExclusions);
List<String> spatialDimNames = Lists.transform(
spatialDimensions,
new Function<SpatialDimensionSchema, String>()
{
@Override
public String apply(SpatialDimensionSchema input)
{
return input.getDimName();
}
}
);
// Don't allow duplicates between main list and deprecated spatial list
ParserUtils.validateFields(Iterables.concat(dimNames, spatialDimNames));
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DimensionsSpec that = (DimensionsSpec) o;
if (!dimensions.equals(that.dimensions)) {
return false;
}
return dimensionExclusions.equals(that.dimensionExclusions);
}
@Override
public int hashCode()
{
int result = dimensions.hashCode();
result = 31 * result + dimensionExclusions.hashCode();
return result;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.core.io.nio;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import io.netty.buffer.ByteBuf;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQExceptionType;
import org.apache.activemq.artemis.api.core.ActiveMQIOErrorException;
import org.apache.activemq.artemis.api.core.ActiveMQIllegalStateException;
import org.apache.activemq.artemis.core.io.AbstractSequentialFile;
import org.apache.activemq.artemis.core.io.DelegateCallback;
import org.apache.activemq.artemis.core.io.IOCallback;
import org.apache.activemq.artemis.core.io.SequentialFile;
import org.apache.activemq.artemis.core.io.SequentialFileFactory;
import org.apache.activemq.artemis.core.io.buffer.TimedBufferObserver;
import org.apache.activemq.artemis.journal.ActiveMQJournalBundle;
import org.apache.activemq.artemis.journal.ActiveMQJournalLogger;
import org.apache.activemq.artemis.utils.Env;
public class NIOSequentialFile extends AbstractSequentialFile {
private static final boolean DEBUG_OPENS = false;
/* This value has been tuned just to reduce the memory footprint
of read/write of the whole file size: given that this value
is > 8192, RandomAccessFile JNI code will use malloc/free instead
of using a copy on the stack, but it has been proven to NOT be
a bottleneck.
Instead of reading the whole content in a single operation, this will read in smaller chunks.
*/
private static final int CHUNK_SIZE = 2 * 1024 * 1024;
private FileChannel channel;
private RandomAccessFile rfile;
private final int maxIO;
public NIOSequentialFile(final SequentialFileFactory factory,
final File directory,
final String file,
final int maxIO,
final Executor writerExecutor) {
super(directory, file, factory, writerExecutor);
this.maxIO = maxIO;
}
@Override
protected TimedBufferObserver createTimedBufferObserver() {
return new SyncLocalBufferObserver();
}
@Override
public int calculateBlockStart(final int position) {
return position;
}
@Override
public synchronized boolean isOpen() {
return channel != null;
}
/**
* this.maxIO represents the default maxIO.
* Some operations while initializing files on the journal may require a different maxIO
*/
@Override
public synchronized void open() throws IOException {
open(maxIO, true);
}
@Override
public ByteBuffer map(int position, long size) throws IOException {
return channel.map(FileChannel.MapMode.READ_ONLY, 0, size);
}
public static void clearDebug() {
counters.clear();
}
public static void printDebug() {
for (Map.Entry<String, AtomicInteger> entry : counters.entrySet()) {
System.out.println(entry.getValue() + " " + entry.getKey());
}
}
public static AtomicInteger getDebugCounter(Exception location) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
location.printStackTrace(printWriter);
String strLocation = writer.toString();
return getDebugCounter(strLocation);
}
public static AtomicInteger getDebugCounter(String strLocation) {
AtomicInteger value = counters.get(strLocation);
if (value == null) {
value = new AtomicInteger(0);
AtomicInteger oldvalue = counters.putIfAbsent(strLocation, value);
if (oldvalue != null) {
value = oldvalue;
}
}
return value;
}
private static Map<String, AtomicInteger> counters = new ConcurrentHashMap<>();
@Override
public void open(final int maxIO, final boolean useExecutor) throws IOException {
try {
rfile = new RandomAccessFile(getFile(), "rw");
channel = rfile.getChannel();
fileSize = channel.size();
if (DEBUG_OPENS) {
getDebugCounter(new Exception("open")).incrementAndGet();
getDebugCounter("open").incrementAndGet();
}
} catch (ClosedChannelException e) {
throw e;
} catch (IOException e) {
factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this);
throw e;
}
}
@Override
public void fill(final int size) throws IOException {
try {
//uses the most common OS page size to match the Page Cache entry size and reduce JVM memory footprint
final int zeroPageCapacity = Env.osPageSize();
final ByteBuffer zeroPage = this.factory.newBuffer(zeroPageCapacity);
try {
int bytesToWrite = size;
long writePosition = 0;
while (bytesToWrite > 0) {
zeroPage.clear();
final int zeroPageLimit = Math.min(bytesToWrite, zeroPageCapacity);
zeroPage.limit(zeroPageLimit);
//use the cheaper pwrite instead of fseek + fwrite
final int writtenBytes = channel.write(zeroPage, writePosition);
bytesToWrite -= writtenBytes;
writePosition += writtenBytes;
}
if (factory.isDatasync()) {
channel.force(true);
}
//set the position to 0 to match the fill contract
channel.position(0);
fileSize = channel.size();
} finally {
//return it to the factory
this.factory.releaseBuffer(zeroPage);
}
} catch (ClosedChannelException e) {
throw e;
} catch (IOException e) {
factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this);
throw e;
}
}
@Override
public synchronized void close() throws IOException, InterruptedException, ActiveMQException {
close(true);
}
@Override
public synchronized void close(boolean waitSync) throws IOException, InterruptedException, ActiveMQException {
super.close();
if (DEBUG_OPENS) {
getDebugCounter(new Exception("Close")).incrementAndGet();
getDebugCounter("close").incrementAndGet();
}
try {
try {
if (channel != null) {
if (waitSync && factory.isDatasync())
channel.force(false);
channel.close();
}
} finally {
if (rfile != null) {
rfile.close();
}
}
} catch (ClosedChannelException e) {
throw e;
} catch (IOException e) {
factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this);
throw e;
} finally {
channel = null;
rfile = null;
}
notifyAll();
}
@Override
public int read(final ByteBuffer bytes) throws Exception {
return read(bytes, null);
}
private static int readRafInChunks(RandomAccessFile raf, byte[] b, int off, int len) throws IOException {
int remaining = len;
int offset = off;
while (remaining > 0) {
final int chunkSize = Math.min(CHUNK_SIZE, remaining);
final int read = raf.read(b, offset, chunkSize);
assert read != 0;
if (read == -1) {
if (len == remaining) {
return -1;
}
break;
}
offset += read;
remaining -= read;
}
return len - remaining;
}
private static void writeRafInChunks(RandomAccessFile raf, byte[] b, int off, int len) throws IOException {
int remaining = len;
int offset = off;
while (remaining > 0) {
final int chunkSize = Math.min(CHUNK_SIZE, remaining);
raf.write(b, offset, chunkSize);
offset += chunkSize;
remaining -= chunkSize;
}
}
@Override
public synchronized int read(final ByteBuffer bytes,
final IOCallback callback) throws IOException, ActiveMQIllegalStateException {
try {
if (channel == null) {
throw new ActiveMQIllegalStateException("File " + this.getFileName() + " has a null channel");
}
final int bytesRead;
if (bytes.hasArray()) {
if (bytes.remaining() > CHUNK_SIZE) {
bytesRead = readRafInChunks(rfile, bytes.array(), bytes.arrayOffset() + bytes.position(), bytes.remaining());
} else {
bytesRead = rfile.read(bytes.array(), bytes.arrayOffset() + bytes.position(), bytes.remaining());
}
if (bytesRead > 0) {
bytes.position(bytes.position() + bytesRead);
}
} else {
bytesRead = channel.read(bytes);
}
if (callback != null) {
callback.done();
}
bytes.flip();
return bytesRead;
} catch (ClosedChannelException e) {
throw e;
} catch (IOException e) {
if (callback != null) {
callback.onError(ActiveMQExceptionType.IO_ERROR.getCode(), e.getLocalizedMessage());
}
factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this);
throw e;
}
}
@Override
public void sync() throws IOException {
if (factory.isDatasync() && channel != null) {
try {
channel.force(false);
} catch (ClosedChannelException e) {
throw e;
} catch (IOException e) {
factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this);
throw e;
}
}
}
@Override
public long size() throws IOException {
if (channel == null) {
return getFile().length();
}
try {
return channel.size();
} catch (ClosedChannelException e) {
throw e;
} catch (IOException e) {
factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this);
throw e;
}
}
@Override
public void position(final long pos) throws IOException {
try {
super.position(pos);
channel.position(pos);
} catch (ClosedChannelException e) {
throw e;
} catch (IOException e) {
factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this);
throw e;
}
}
@Override
public String toString() {
return "NIOSequentialFile " + getFile();
}
@Override
public SequentialFile cloneFile() {
return new NIOSequentialFile(factory, directory, getFileName(), maxIO, null);
}
@Override
public void writeDirect(final ByteBuffer bytes, final boolean sync, final IOCallback callback) {
if (callback == null) {
throw new NullPointerException("callback parameter need to be set");
}
try {
internalWrite(bytes, sync, callback, true);
} catch (Exception e) {
callback.onError(ActiveMQExceptionType.GENERIC_EXCEPTION.getCode(), e.getMessage());
}
}
@Override
public void writeDirect(final ByteBuffer bytes, final boolean sync) throws Exception {
internalWrite(bytes, sync, null, true);
}
@Override
public void blockingWriteDirect(ByteBuffer bytes,boolean sync, boolean releaseBuffer) throws Exception {
internalWrite(bytes, sync, null, releaseBuffer);
}
private void internalWrite(final ByteBuffer bytes,
final boolean sync,
final IOCallback callback,
boolean releaseBuffer) throws IOException, ActiveMQIOErrorException, InterruptedException {
if (!isOpen()) {
if (callback != null) {
callback.onError(ActiveMQExceptionType.IO_ERROR.getCode(), "File not opened");
} else {
throw ActiveMQJournalBundle.BUNDLE.fileNotOpened();
}
return;
}
position.addAndGet(bytes.limit());
try {
doInternalWrite(bytes, sync, callback, releaseBuffer);
} catch (ClosedChannelException e) {
throw e;
} catch (IOException e) {
factory.onIOError(new ActiveMQIOErrorException(e.getMessage(), e), e.getMessage(), this);
}
}
/**
* @param bytes
* @param sync
* @param callback
* @throws IOException
* @throws Exception
*/
private void doInternalWrite(final ByteBuffer bytes,
final boolean sync,
final IOCallback callback,
boolean releaseBuffer) throws IOException {
try {
if (bytes.hasArray()) {
if (bytes.remaining() > CHUNK_SIZE) {
writeRafInChunks(rfile, bytes.array(), bytes.arrayOffset() + bytes.position(), bytes.remaining());
} else {
rfile.write(bytes.array(), bytes.arrayOffset() + bytes.position(), bytes.remaining());
}
bytes.position(bytes.limit());
} else {
channel.write(bytes);
}
if (sync) {
sync();
}
if (callback != null) {
callback.done();
}
} finally {
if (releaseBuffer) {
//release it to recycle the write buffer if big enough
this.factory.releaseBuffer(bytes);
}
}
}
@Override
public void copyTo(SequentialFile dstFile) throws IOException {
if (ActiveMQJournalLogger.LOGGER.isDebugEnabled()) {
ActiveMQJournalLogger.LOGGER.debug("Copying " + this + " as " + dstFile);
}
if (isOpen()) {
throw new IllegalStateException("File opened!");
}
if (dstFile.isOpen()) {
throw new IllegalArgumentException("dstFile must be closed too");
}
SequentialFile.appendTo(getFile().toPath(), dstFile.getJavaFile().toPath());
}
private class SyncLocalBufferObserver extends LocalBufferObserver {
@Override
public void flushBuffer(ByteBuf byteBuf, boolean requestedSync, List<IOCallback> callbacks) {
//maybe no need to perform any copy
final int bytes = byteBuf.readableBytes();
if (bytes == 0) {
IOCallback.done(callbacks);
} else {
//enable zero copy case
if (byteBuf.nioBufferCount() == 1 && byteBuf.isDirect()) {
final ByteBuffer buffer = byteBuf.internalNioBuffer(byteBuf.readerIndex(), bytes);
final IOCallback callback = new DelegateCallback(callbacks);
try {
//no need to pool the buffer and don't care if the NIO buffer got modified
internalWrite(buffer, requestedSync, callback, false);
} catch (Exception e) {
callback.onError(ActiveMQExceptionType.GENERIC_EXCEPTION.getCode(), e.getMessage());
}
} else {
super.flushBuffer(byteBuf, requestedSync, callbacks);
}
}
}
}
}
| |
package swoop.pipeline;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import swoop.util.New;
public class PipelineBuilderTest {
private static Logger logger = LoggerFactory.getLogger(PipelineBuilderTest.class);
private List<PathMatcher> matchers;
@BeforeMethod
public void setUp () {
matchers = New.arrayList();
}
@Test
public void usecase_notThreaded() {
PipelineBuilder builder = new PipelineBuilder();
builder.handler(e(new Filter("time"))) //
.handler(e(new Downstream("auth"))) //
.handler(e(new Downstream("prepare"))) //
.handler(e(new Upstream("gzip"))) //
.handler(e(new Target("bob")))//
;
Pipeline pipeline = builder.buildPipeline().with(StringBuilder.class, new StringBuilder());
pipeline.invokeNext();
String string = pipeline.get(StringBuilder.class).toString();
assertThat(string, equalTo("<time><auth><prepare><bob><<bob>></bob></gzip></time>"));
}
private HandlerEntry e(Handler target) {
return new HandlerEntry(pathMatcherMock(), target);
}
private PathMatcher pathMatcherMock() {
PathMatcher pathMatcher = Mockito.mock(PathMatcher.class);
matchers.add(pathMatcher);
return pathMatcher;
}
@Test
public void usecase_threaded() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
PipelineBuilder builder = new PipelineBuilder();
builder.executor(Pipelines.threadedExecutor())//
.handler(e(new UpstreamLatch(latch)))//
.handler(e(new Filter("time"))) //
.handler(e(new Downstream("auth"))) //
.handler(e(new Downstream("prepare"))) //
.handler(e(new Upstream("gzip"))) //
.handler(e(new Target("bob")))//
;
Pipeline pipeline = builder.buildPipeline().with(StringBuilder.class, new StringBuilder());
pipeline.invokeNext();
latch.await();
String string = pipeline.get(StringBuilder.class).toString();
assertThat(string, equalTo("<time><auth><prepare><bob><<bob>></bob></gzip></time>"));
}
@Test
public void usecase_threaded_withAsyncJob() throws InterruptedException {
ExecutorService backgroundExecutor = Executors.newFixedThreadPool(2);
CountDownLatch latch = new CountDownLatch(1);
PipelineBuilder builder = new PipelineBuilder();
builder.executor(Pipelines.threadedExecutor())//
.handler(e(new UpstreamLatch(latch)))//
.handler(e(new Perf()))//
.handler(e(new Filter("time"))) //
.handler(e(new Downstream("auth"))) //
.handler(e(new Downstream("prepare"))) //
.handler(e(new Upstream("gzip"))) //
.handler(e(new Async("bob", backgroundExecutor)))//
;
Pipeline pipeline = builder.buildPipeline().with(StringBuilder.class, new StringBuilder());
pipeline.invokeNext();
latch.await();
String string = pipeline.get(StringBuilder.class).toString();
assertThat(string, equalTo("<time><auth><prepare><<bob>></gzip></time>"));
}
public static class Perf implements PipelineDownstreamHandler, PipelineUpstreamHandler {
@Override
public void handleDownstream(Pipeline pipeline) {
pipeline.with(new Chrono().start()).invokeNext();
}
@Override
public void handleUpstream(Pipeline pipeline) {
Chrono chrono = pipeline.get(Chrono.class).end();
logger.info(chrono.elapsed() + "ms");
pipeline.invokeNext();
}
}
static class Chrono {
long start, end;
public Chrono start() {
this.start = System.currentTimeMillis();
return this;
}
public Chrono end() {
this.end = System.currentTimeMillis();
return this;
}
public long elapsed() {
return (end - start);
}
}
public static class Async implements PipelineTargetHandler {
private String token;
private Executor backgroundThread;
public Async(String token, Executor backgroundThread) {
super();
this.token = token;
this.backgroundThread = backgroundThread;
}
@Override
public void handleTarget(final Pipeline pipeline) {
backgroundThread.execute(new Runnable() {
@Override
public void run() {
logger.info("Async:Target [" + token + "]");
pipeline.get(StringBuilder.class).append("<<").append(token).append(">>");
// some jobs...
pipeline.invokeNext();
}
});
}
}
public static class Filter implements PipelineDownstreamHandler, PipelineUpstreamHandler {
private String token;
public Filter(String token) {
super();
this.token = token;
}
@Override
public void handleDownstream(Pipeline pipeline) {
logger.info("Filter vvv{}", token);
pipeline.get(StringBuilder.class).append("<").append(token).append(">");
pipeline.invokeNext();
}
@Override
public void handleUpstream(Pipeline pipeline) {
logger.info("Filter ^^^{}", token);
pipeline.get(StringBuilder.class).append("</").append(token).append(">");
pipeline.invokeNext();
}
}
public static class Target implements PipelineDownstreamHandler, PipelineUpstreamHandler, PipelineTargetHandler {
private String token;
public Target(String token) {
super();
this.token = token;
}
@Override
public void handleTarget(Pipeline pipeline) {
logger.info("Target {}", token);
pipeline.get(StringBuilder.class).append("<<").append(token).append(">>");
pipeline.invokeNext();
}
@Override
public void handleDownstream(Pipeline pipeline) {
logger.info("Target vvv{}", token);
pipeline.get(StringBuilder.class).append("<").append(token).append(">");
pipeline.invokeNext();
}
@Override
public void handleUpstream(Pipeline pipeline) {
logger.info("Target ^^^{}", token);
pipeline.get(StringBuilder.class).append("</").append(token).append(">");
pipeline.invokeNext();
}
}
public static class Downstream implements PipelineDownstreamHandler {
private String token;
public Downstream(String token) {
super();
this.token = token;
}
@Override
public void handleDownstream(Pipeline pipeline) {
logger.info("Downstream vvv{}", token);
pipeline.get(StringBuilder.class).append("<").append(token).append(">");
pipeline.invokeNext();
}
}
public static class Upstream implements PipelineUpstreamHandler {
private String token;
public Upstream(String token) {
super();
this.token = token;
}
@Override
public void handleUpstream(Pipeline pipeline) {
logger.info("Upstream ^^^{}", token);
pipeline.get(StringBuilder.class).append("</").append(token).append(">");
pipeline.invokeNext();
}
}
public static class UpstreamLatch implements PipelineUpstreamHandler {
private CountDownLatch latch;
public UpstreamLatch(CountDownLatch latch) {
super();
this.latch = latch;
}
@Override
public void handleUpstream(Pipeline pipeline) {
logger.info("Upstream ^^^ latch");
latch.countDown();
pipeline.invokeNext();
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* AdGroupCriterion.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.adwords.axis.v201809.cm;
/**
* Represents a criterion in an ad group, used with AdGroupCriterionService.
*/
public class AdGroupCriterion implements java.io.Serializable {
/* The ad group this criterion is in.
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span> */
private java.lang.Long adGroupId;
/* <span class="constraint ReadOnly">This field is read only and
* will be ignored when sent to the API.</span> */
private com.google.api.ads.adwords.axis.v201809.cm.CriterionUse criterionUse;
/* The criterion part of the ad group criterion.
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span> */
private com.google.api.ads.adwords.axis.v201809.cm.Criterion criterion;
/* Labels that are attached to the AdGroupCriterion. To associate
* an existing {@link Label} to an
* existing {@link AdGroupCriterion}, use {@link AdGroupCriterionService#mutateLabel}
* with ADD
* operator. To remove an associated {@link Label} from
* the {@link AdGroupCriterion}, use
* {@link AdGroupCriterionService#mutateLabel} with REMOVE
* operator. To filter on {@link Label}s,
* use one of {@link Predicate.Operator#CONTAINS_ALL},
* {@link Predicate.Operator#CONTAINS_ANY},
* {@link Predicate.Operator#CONTAINS_NONE} operators
* with a list of {@link Label} ids.
* <span class="constraint CampaignType">This field may
* not be set for campaign channel subtype UNIVERSAL_APP_CAMPAIGN.</span>
* <span class="constraint ReadOnly">This field is read only and will
* be ignored when sent to the API for the following {@link Operator}s:
* REMOVE and SET.</span> */
private com.google.api.ads.adwords.axis.v201809.cm.Label[] labels;
/* This Map provides a place to put new features and settings
* in older versions
* of the AdWords API in the rare instance we need to
* introduce a new feature in
* an older version.
*
* It is presently unused. Do not set a value. */
private com.google.api.ads.adwords.axis.v201809.cm.String_StringMapEntry[] forwardCompatibilityMap;
/* ID of the base campaign from which this draft/trial ad group
* criterion was created.
* This field is only returned on get requests.
* <span class="constraint ReadOnly">This field is read
* only and will be ignored when sent to the API.</span> */
private java.lang.Long baseCampaignId;
/* ID of the base ad group from which this draft/trial ad group
* criterion was created. For
* base ad groups this is equal to the ad group ID.
* If the ad group was created
* in the draft or trial and has no corresponding base
* ad group, this field is null.
* This field is only returned on get requests.
* <span class="constraint ReadOnly">This field is read
* only and will be ignored when sent to the API.</span> */
private java.lang.Long baseAdGroupId;
/* Indicates that this instance is a subtype of AdGroupCriterion.
* Although this field is returned in the response, it is ignored on
* input
* and cannot be selected. Specify xsi:type instead. */
private java.lang.String adGroupCriterionType;
public AdGroupCriterion() {
}
public AdGroupCriterion(
java.lang.Long adGroupId,
com.google.api.ads.adwords.axis.v201809.cm.CriterionUse criterionUse,
com.google.api.ads.adwords.axis.v201809.cm.Criterion criterion,
com.google.api.ads.adwords.axis.v201809.cm.Label[] labels,
com.google.api.ads.adwords.axis.v201809.cm.String_StringMapEntry[] forwardCompatibilityMap,
java.lang.Long baseCampaignId,
java.lang.Long baseAdGroupId,
java.lang.String adGroupCriterionType) {
this.adGroupId = adGroupId;
this.criterionUse = criterionUse;
this.criterion = criterion;
this.labels = labels;
this.forwardCompatibilityMap = forwardCompatibilityMap;
this.baseCampaignId = baseCampaignId;
this.baseAdGroupId = baseAdGroupId;
this.adGroupCriterionType = adGroupCriterionType;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("adGroupCriterionType", getAdGroupCriterionType())
.add("adGroupId", getAdGroupId())
.add("baseAdGroupId", getBaseAdGroupId())
.add("baseCampaignId", getBaseCampaignId())
.add("criterion", getCriterion())
.add("criterionUse", getCriterionUse())
.add("forwardCompatibilityMap", getForwardCompatibilityMap())
.add("labels", getLabels())
.toString();
}
/**
* Gets the adGroupId value for this AdGroupCriterion.
*
* @return adGroupId * The ad group this criterion is in.
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span>
*/
public java.lang.Long getAdGroupId() {
return adGroupId;
}
/**
* Sets the adGroupId value for this AdGroupCriterion.
*
* @param adGroupId * The ad group this criterion is in.
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span>
*/
public void setAdGroupId(java.lang.Long adGroupId) {
this.adGroupId = adGroupId;
}
/**
* Gets the criterionUse value for this AdGroupCriterion.
*
* @return criterionUse * <span class="constraint ReadOnly">This field is read only and
* will be ignored when sent to the API.</span>
*/
public com.google.api.ads.adwords.axis.v201809.cm.CriterionUse getCriterionUse() {
return criterionUse;
}
/**
* Sets the criterionUse value for this AdGroupCriterion.
*
* @param criterionUse * <span class="constraint ReadOnly">This field is read only and
* will be ignored when sent to the API.</span>
*/
public void setCriterionUse(com.google.api.ads.adwords.axis.v201809.cm.CriterionUse criterionUse) {
this.criterionUse = criterionUse;
}
/**
* Gets the criterion value for this AdGroupCriterion.
*
* @return criterion * The criterion part of the ad group criterion.
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span>
*/
public com.google.api.ads.adwords.axis.v201809.cm.Criterion getCriterion() {
return criterion;
}
/**
* Sets the criterion value for this AdGroupCriterion.
*
* @param criterion * The criterion part of the ad group criterion.
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span>
*/
public void setCriterion(com.google.api.ads.adwords.axis.v201809.cm.Criterion criterion) {
this.criterion = criterion;
}
/**
* Gets the labels value for this AdGroupCriterion.
*
* @return labels * Labels that are attached to the AdGroupCriterion. To associate
* an existing {@link Label} to an
* existing {@link AdGroupCriterion}, use {@link AdGroupCriterionService#mutateLabel}
* with ADD
* operator. To remove an associated {@link Label} from
* the {@link AdGroupCriterion}, use
* {@link AdGroupCriterionService#mutateLabel} with REMOVE
* operator. To filter on {@link Label}s,
* use one of {@link Predicate.Operator#CONTAINS_ALL},
* {@link Predicate.Operator#CONTAINS_ANY},
* {@link Predicate.Operator#CONTAINS_NONE} operators
* with a list of {@link Label} ids.
* <span class="constraint CampaignType">This field may
* not be set for campaign channel subtype UNIVERSAL_APP_CAMPAIGN.</span>
* <span class="constraint ReadOnly">This field is read only and will
* be ignored when sent to the API for the following {@link Operator}s:
* REMOVE and SET.</span>
*/
public com.google.api.ads.adwords.axis.v201809.cm.Label[] getLabels() {
return labels;
}
/**
* Sets the labels value for this AdGroupCriterion.
*
* @param labels * Labels that are attached to the AdGroupCriterion. To associate
* an existing {@link Label} to an
* existing {@link AdGroupCriterion}, use {@link AdGroupCriterionService#mutateLabel}
* with ADD
* operator. To remove an associated {@link Label} from
* the {@link AdGroupCriterion}, use
* {@link AdGroupCriterionService#mutateLabel} with REMOVE
* operator. To filter on {@link Label}s,
* use one of {@link Predicate.Operator#CONTAINS_ALL},
* {@link Predicate.Operator#CONTAINS_ANY},
* {@link Predicate.Operator#CONTAINS_NONE} operators
* with a list of {@link Label} ids.
* <span class="constraint CampaignType">This field may
* not be set for campaign channel subtype UNIVERSAL_APP_CAMPAIGN.</span>
* <span class="constraint ReadOnly">This field is read only and will
* be ignored when sent to the API for the following {@link Operator}s:
* REMOVE and SET.</span>
*/
public void setLabels(com.google.api.ads.adwords.axis.v201809.cm.Label[] labels) {
this.labels = labels;
}
public com.google.api.ads.adwords.axis.v201809.cm.Label getLabels(int i) {
return this.labels[i];
}
public void setLabels(int i, com.google.api.ads.adwords.axis.v201809.cm.Label _value) {
this.labels[i] = _value;
}
/**
* Gets the forwardCompatibilityMap value for this AdGroupCriterion.
*
* @return forwardCompatibilityMap * This Map provides a place to put new features and settings
* in older versions
* of the AdWords API in the rare instance we need to
* introduce a new feature in
* an older version.
*
* It is presently unused. Do not set a value.
*/
public com.google.api.ads.adwords.axis.v201809.cm.String_StringMapEntry[] getForwardCompatibilityMap() {
return forwardCompatibilityMap;
}
/**
* Sets the forwardCompatibilityMap value for this AdGroupCriterion.
*
* @param forwardCompatibilityMap * This Map provides a place to put new features and settings
* in older versions
* of the AdWords API in the rare instance we need to
* introduce a new feature in
* an older version.
*
* It is presently unused. Do not set a value.
*/
public void setForwardCompatibilityMap(com.google.api.ads.adwords.axis.v201809.cm.String_StringMapEntry[] forwardCompatibilityMap) {
this.forwardCompatibilityMap = forwardCompatibilityMap;
}
public com.google.api.ads.adwords.axis.v201809.cm.String_StringMapEntry getForwardCompatibilityMap(int i) {
return this.forwardCompatibilityMap[i];
}
public void setForwardCompatibilityMap(int i, com.google.api.ads.adwords.axis.v201809.cm.String_StringMapEntry _value) {
this.forwardCompatibilityMap[i] = _value;
}
/**
* Gets the baseCampaignId value for this AdGroupCriterion.
*
* @return baseCampaignId * ID of the base campaign from which this draft/trial ad group
* criterion was created.
* This field is only returned on get requests.
* <span class="constraint ReadOnly">This field is read
* only and will be ignored when sent to the API.</span>
*/
public java.lang.Long getBaseCampaignId() {
return baseCampaignId;
}
/**
* Sets the baseCampaignId value for this AdGroupCriterion.
*
* @param baseCampaignId * ID of the base campaign from which this draft/trial ad group
* criterion was created.
* This field is only returned on get requests.
* <span class="constraint ReadOnly">This field is read
* only and will be ignored when sent to the API.</span>
*/
public void setBaseCampaignId(java.lang.Long baseCampaignId) {
this.baseCampaignId = baseCampaignId;
}
/**
* Gets the baseAdGroupId value for this AdGroupCriterion.
*
* @return baseAdGroupId * ID of the base ad group from which this draft/trial ad group
* criterion was created. For
* base ad groups this is equal to the ad group ID.
* If the ad group was created
* in the draft or trial and has no corresponding base
* ad group, this field is null.
* This field is only returned on get requests.
* <span class="constraint ReadOnly">This field is read
* only and will be ignored when sent to the API.</span>
*/
public java.lang.Long getBaseAdGroupId() {
return baseAdGroupId;
}
/**
* Sets the baseAdGroupId value for this AdGroupCriterion.
*
* @param baseAdGroupId * ID of the base ad group from which this draft/trial ad group
* criterion was created. For
* base ad groups this is equal to the ad group ID.
* If the ad group was created
* in the draft or trial and has no corresponding base
* ad group, this field is null.
* This field is only returned on get requests.
* <span class="constraint ReadOnly">This field is read
* only and will be ignored when sent to the API.</span>
*/
public void setBaseAdGroupId(java.lang.Long baseAdGroupId) {
this.baseAdGroupId = baseAdGroupId;
}
/**
* Gets the adGroupCriterionType value for this AdGroupCriterion.
*
* @return adGroupCriterionType * Indicates that this instance is a subtype of AdGroupCriterion.
* Although this field is returned in the response, it is ignored on
* input
* and cannot be selected. Specify xsi:type instead.
*/
public java.lang.String getAdGroupCriterionType() {
return adGroupCriterionType;
}
/**
* Sets the adGroupCriterionType value for this AdGroupCriterion.
*
* @param adGroupCriterionType * Indicates that this instance is a subtype of AdGroupCriterion.
* Although this field is returned in the response, it is ignored on
* input
* and cannot be selected. Specify xsi:type instead.
*/
public void setAdGroupCriterionType(java.lang.String adGroupCriterionType) {
this.adGroupCriterionType = adGroupCriterionType;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof AdGroupCriterion)) return false;
AdGroupCriterion other = (AdGroupCriterion) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.adGroupId==null && other.getAdGroupId()==null) ||
(this.adGroupId!=null &&
this.adGroupId.equals(other.getAdGroupId()))) &&
((this.criterionUse==null && other.getCriterionUse()==null) ||
(this.criterionUse!=null &&
this.criterionUse.equals(other.getCriterionUse()))) &&
((this.criterion==null && other.getCriterion()==null) ||
(this.criterion!=null &&
this.criterion.equals(other.getCriterion()))) &&
((this.labels==null && other.getLabels()==null) ||
(this.labels!=null &&
java.util.Arrays.equals(this.labels, other.getLabels()))) &&
((this.forwardCompatibilityMap==null && other.getForwardCompatibilityMap()==null) ||
(this.forwardCompatibilityMap!=null &&
java.util.Arrays.equals(this.forwardCompatibilityMap, other.getForwardCompatibilityMap()))) &&
((this.baseCampaignId==null && other.getBaseCampaignId()==null) ||
(this.baseCampaignId!=null &&
this.baseCampaignId.equals(other.getBaseCampaignId()))) &&
((this.baseAdGroupId==null && other.getBaseAdGroupId()==null) ||
(this.baseAdGroupId!=null &&
this.baseAdGroupId.equals(other.getBaseAdGroupId()))) &&
((this.adGroupCriterionType==null && other.getAdGroupCriterionType()==null) ||
(this.adGroupCriterionType!=null &&
this.adGroupCriterionType.equals(other.getAdGroupCriterionType())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getAdGroupId() != null) {
_hashCode += getAdGroupId().hashCode();
}
if (getCriterionUse() != null) {
_hashCode += getCriterionUse().hashCode();
}
if (getCriterion() != null) {
_hashCode += getCriterion().hashCode();
}
if (getLabels() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getLabels());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getLabels(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getForwardCompatibilityMap() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getForwardCompatibilityMap());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getForwardCompatibilityMap(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getBaseCampaignId() != null) {
_hashCode += getBaseCampaignId().hashCode();
}
if (getBaseAdGroupId() != null) {
_hashCode += getBaseAdGroupId().hashCode();
}
if (getAdGroupCriterionType() != null) {
_hashCode += getAdGroupCriterionType().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(AdGroupCriterion.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "AdGroupCriterion"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("adGroupId");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "adGroupId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("criterionUse");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "criterionUse"));
elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "CriterionUse"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("criterion");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "criterion"));
elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "Criterion"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("labels");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "labels"));
elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "Label"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("forwardCompatibilityMap");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "forwardCompatibilityMap"));
elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "String_StringMapEntry"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("baseCampaignId");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "baseCampaignId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("baseAdGroupId");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "baseAdGroupId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("adGroupCriterionType");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "AdGroupCriterion.Type"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| |
/**
* Copyright Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.azure.storage.core;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import com.microsoft.azure.storage.Constants;
import com.microsoft.azure.storage.OperationContext;
import com.microsoft.azure.storage.RequestOptions;
import com.microsoft.azure.storage.StorageException;
/**
* RESERVED FOR INTERNAL USE. The Base Request class for the protocol layer.
*/
public final class BaseRequest {
private static final String METADATA = "metadata";
private static final String SERVICE = "service";
private static final String STATS = "stats";
private static final String TIMEOUT = "timeout";
/**
* Stores the user agent to send over the wire to identify the client.
*/
private static String userAgent;
/**
* Adds the metadata.
*
* @param request
* The request.
* @param metadata
* The metadata.
*/
public static void addMetadata(final HttpURLConnection request, final Map<String, String> metadata,
final OperationContext opContext) {
if (metadata != null) {
for (final Entry<String, String> entry : metadata.entrySet()) {
addMetadata(request, entry.getKey(), entry.getValue(), opContext);
}
}
}
/**
* Adds the metadata.
*
* @param opContext
* an object used to track the execution of the operation
* @param request
* The request.
* @param name
* The metadata name.
* @param value
* The metadata value.
*/
private static void addMetadata(final HttpURLConnection request, final String name, final String value,
final OperationContext opContext) {
if (Utility.isNullOrEmptyOrWhitespace(name)) {
throw new IllegalArgumentException(SR.METADATA_KEY_INVALID);
}
else if (Utility.isNullOrEmptyOrWhitespace(value)) {
throw new IllegalArgumentException(SR.METADATA_VALUE_INVALID);
}
request.setRequestProperty(Constants.HeaderConstants.PREFIX_FOR_STORAGE_METADATA + name, value);
}
/**
* Adds the optional header.
*
* @param request
* a HttpURLConnection for the operation.
* @param name
* the metadata name.
* @param value
* the metadata value.
*/
public static void addOptionalHeader(final HttpURLConnection request, final String name, final String value) {
if (value != null && !value.equals(Constants.EMPTY_STRING)) {
request.setRequestProperty(name, value);
}
}
/**
* Creates the specified resource. Note request is set to setFixedLengthStreamingMode(0); Sign with 0 length.
*
* @param uri
* the request Uri.
* @param options
* A {@link RequestOptions} object that specifies execution options such as retry policy and timeout
* settings for the operation.
* @param builder
* the UriQueryBuilder for the request
* @param opContext
* an object used to track the execution of the operation
*
* @return a HttpURLConnection to perform the operation.
* @throws IOException
* if there is an error opening the connection
* @throws URISyntaxException
* if there is an improperly formated URI
* @throws StorageException
* @throws IllegalArgumentException
*/
public static HttpURLConnection create(final URI uri, final RequestOptions options, UriQueryBuilder builder,
final OperationContext opContext) throws IOException, URISyntaxException, StorageException {
if (builder == null) {
builder = new UriQueryBuilder();
}
final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext);
retConnection.setFixedLengthStreamingMode(0);
retConnection.setDoOutput(true);
retConnection.setRequestMethod(Constants.HTTP_PUT);
return retConnection;
}
/**
* Creates the web request.
*
* @param uri
* the request Uri.
* @param options
* A {@link RequestOptions} object that specifies execution options such as retry policy and timeout
* settings for the operation. This parameter is unused.
* @param builder
* the UriQueryBuilder for the request
* @param opContext
* an object used to track the execution of the operation
* @return a HttpURLConnection to perform the operation.
* @throws IOException
* if there is an error opening the connection
* @throws URISyntaxException
* if there is an improperly formated URI
* @throws StorageException
*/
public static HttpURLConnection createURLConnection(final URI uri, final RequestOptions options,
UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException,
StorageException {
if (builder == null) {
builder = new UriQueryBuilder();
}
if (options.getTimeoutIntervalInMs() != null && options.getTimeoutIntervalInMs() != 0) {
builder.add(TIMEOUT, String.valueOf(options.getTimeoutIntervalInMs() / 1000));
}
final URL resourceUrl = builder.addToURI(uri).toURL();
// Get the proxy settings
Proxy proxy = OperationContext.getDefaultProxy();
if (opContext != null && opContext.getProxy() != null) {
proxy = opContext.getProxy();
}
// Set up connection, optionally with proxy settings
final HttpURLConnection retConnection;
if (proxy != null) {
retConnection = (HttpURLConnection) resourceUrl.openConnection(proxy);
}
else {
retConnection = (HttpURLConnection) resourceUrl.openConnection();
}
/*
* ReadTimeout must be explicitly set to avoid a bug in JDK 6. In certain cases, this bug causes an immediate
* read timeout exception to be thrown even if ReadTimeout is not set.
*
* Both connect and read timeout are set to the same value as we have no way of knowing how to partition
* the remaining time between these operations. The user can override these timeouts using the SendingRequest
* event handler if more control is desired.
*/
int timeout = Utility.getRemainingTimeout(options.getOperationExpiryTimeInMs(), options.getTimeoutIntervalInMs());
retConnection.setReadTimeout(timeout);
retConnection.setConnectTimeout(timeout);
// Note : by default sends Accept behavior as text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT, Constants.HeaderConstants.XML_TYPE);
retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT_CHARSET, Constants.UTF8_CHARSET);
// Note: by default sends Accept-Encoding as gzip
retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT_ENCODING, Constants.EMPTY_STRING);
// Note : by default sends Content-type behavior as application/x-www-form-urlencoded for posts.
retConnection.setRequestProperty(Constants.HeaderConstants.CONTENT_TYPE, Constants.EMPTY_STRING);
retConnection.setRequestProperty(Constants.HeaderConstants.STORAGE_VERSION_HEADER,
Constants.HeaderConstants.TARGET_STORAGE_VERSION);
retConnection.setRequestProperty(Constants.HeaderConstants.USER_AGENT, getUserAgent());
retConnection.setRequestProperty(Constants.HeaderConstants.CLIENT_REQUEST_ID_HEADER,
opContext.getClientRequestID());
return retConnection;
}
/**
* Deletes the specified resource. Sign with no length specified.
*
* @param uri
* the request Uri.
* @param timeout
* the timeout for the request
* @param builder
* the UriQueryBuilder for the request
* @param opContext
* an object used to track the execution of the operation
* @return a HttpURLConnection to perform the operation.
* @throws IOException
* if there is an error opening the connection
* @throws URISyntaxException
* if there is an improperly formated URI
* @throws StorageException
*/
public static HttpURLConnection delete(final URI uri, final RequestOptions options, UriQueryBuilder builder,
final OperationContext opContext) throws IOException, URISyntaxException, StorageException {
if (builder == null) {
builder = new UriQueryBuilder();
}
final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext);
retConnection.setRequestMethod(Constants.HTTP_DELETE);
return retConnection;
}
/**
* Gets a {@link UriQueryBuilder} for listing.
*
* @param listingContext
* A {@link ListingContext} object that specifies parameters for
* the listing operation, if any. May be <code>null</code>.
*
* @throws StorageException
* If a storage service error occurred during the operation.
*/
public static UriQueryBuilder getListUriQueryBuilder(final ListingContext listingContext) throws StorageException {
final UriQueryBuilder builder = new UriQueryBuilder();
builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.LIST);
if (listingContext != null) {
if (!Utility.isNullOrEmpty(listingContext.getPrefix())) {
builder.add(Constants.QueryConstants.PREFIX, listingContext.getPrefix());
}
if (!Utility.isNullOrEmpty(listingContext.getMarker())) {
builder.add(Constants.QueryConstants.MARKER, listingContext.getMarker());
}
if (listingContext.getMaxResults() != null && listingContext.getMaxResults() > 0) {
builder.add(Constants.QueryConstants.MAX_RESULTS, listingContext.getMaxResults().toString());
}
}
return builder;
}
/**
* Gets the properties. Sign with no length specified.
*
* @param uri
* The Uri to query.
* @param timeout
* The timeout.
* @param builder
* The builder.
* @param opContext
* an object used to track the execution of the operation
* @return a web request for performing the operation.
* @throws StorageException
* @throws URISyntaxException
* @throws IOException
* */
public static HttpURLConnection getProperties(final URI uri, final RequestOptions options, UriQueryBuilder builder,
final OperationContext opContext) throws IOException, URISyntaxException, StorageException {
if (builder == null) {
builder = new UriQueryBuilder();
}
final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext);
retConnection.setRequestMethod(Constants.HTTP_HEAD);
return retConnection;
}
/**
* Creates a HttpURLConnection used to retrieve the Analytics service properties from the storage service.
*
* @param uri
* The service endpoint.
* @param timeout
* The timeout.
* @param builder
* The builder.
* @param opContext
* an object used to track the execution of the operation
* @return a web request for performing the operation.
* @throws IOException
* @throws URISyntaxException
* @throws StorageException
*/
public static HttpURLConnection getServiceProperties(final URI uri, final RequestOptions options,
UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException,
StorageException {
if (builder == null) {
builder = new UriQueryBuilder();
}
builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.PROPERTIES);
builder.add(Constants.QueryConstants.RESOURCETYPE, SERVICE);
final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext);
retConnection.setRequestMethod(Constants.HTTP_GET);
return retConnection;
}
/**
* Creates a web request to get the stats of the service.
*
* @param uri
* The service endpoint.
* @param timeout
* The timeout.
* @param builder
* The builder.
* @param opContext
* an object used to track the execution of the operation
* @return a web request for performing the operation.
* @throws IOException
* @throws URISyntaxException
* @throws StorageException
*/
public static HttpURLConnection getServiceStats(final URI uri, final RequestOptions options,
UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException,
StorageException {
if (builder == null) {
builder = new UriQueryBuilder();
}
builder.add(Constants.QueryConstants.COMPONENT, STATS);
builder.add(Constants.QueryConstants.RESOURCETYPE, SERVICE);
final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext);
retConnection.setRequestMethod("GET");
return retConnection;
}
/**
* Gets the user agent to send over the wire to identify the client.
*
* @return the user agent to send over the wire to identify the client.
*/
public static String getUserAgent() {
if (userAgent == null) {
String userAgentComment = String.format(Utility.LOCALE_US, "(Android %s; %s; %s)",
android.os.Build.VERSION.RELEASE, android.os.Build.BRAND, android.os.Build.MODEL);
userAgent = String.format("%s/%s %s", Constants.HeaderConstants.USER_AGENT_PREFIX,
Constants.HeaderConstants.USER_AGENT_VERSION, userAgentComment);
}
return userAgent;
}
/**
* Sets the metadata. Sign with 0 length.
*
* @param uri
* The blob Uri.
* @param timeout
* The timeout.
* @param builder
* The builder.
* @param opContext
* an object used to track the execution of the operation
* @return a web request for performing the operation.
* @throws StorageException
* @throws URISyntaxException
* @throws IOException
* */
public static HttpURLConnection setMetadata(final URI uri, final RequestOptions options, UriQueryBuilder builder,
final OperationContext opContext) throws IOException, URISyntaxException, StorageException {
if (builder == null) {
builder = new UriQueryBuilder();
}
builder.add(Constants.QueryConstants.COMPONENT, METADATA);
final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext);
retConnection.setFixedLengthStreamingMode(0);
retConnection.setDoOutput(true);
retConnection.setRequestMethod(Constants.HTTP_PUT);
return retConnection;
}
/**
* Creates a HttpURLConnection used to set the Analytics service properties on the storage service.
*
* @param uri
* The service endpoint.
* @param timeout
* The timeout.
* @param builder
* The builder.
* @param opContext
* an object used to track the execution of the operation
* @return a web request for performing the operation.
* @throws IOException
* @throws URISyntaxException
* @throws StorageException
*/
public static HttpURLConnection setServiceProperties(final URI uri, final RequestOptions options,
UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException,
StorageException {
if (builder == null) {
builder = new UriQueryBuilder();
}
builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.PROPERTIES);
builder.add(Constants.QueryConstants.RESOURCETYPE, SERVICE);
final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext);
retConnection.setDoOutput(true);
retConnection.setRequestMethod(Constants.HTTP_PUT);
return retConnection;
}
/**
* A private default constructor. All methods of this class are static so no instances of it should ever be created.
*/
private BaseRequest() {
// No op
}
}
| |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.commands;
import com.intellij.ide.passwordSafe.MasterPasswordUnavailableException;
import com.intellij.ide.passwordSafe.PasswordSafe;
import com.intellij.ide.passwordSafe.PasswordSafeException;
import com.intellij.ide.passwordSafe.impl.PasswordSafeImpl;
import com.intellij.ide.passwordSafe.ui.PasswordSafePromptDialog;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.AuthData;
import com.intellij.util.ObjectUtils;
import com.intellij.util.UriUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.URLUtil;
import com.intellij.vcsUtil.AuthDialog;
import git4idea.remote.GitHttpAuthDataProvider;
import git4idea.remote.GitRememberedInputs;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* <p>Handles "ask username" and "ask password" requests from Git:
* shows authentication dialog in the GUI, waits for user input and returns the credentials supplied by the user.</p>
* <p>If user cancels the dialog, empty string is returned.</p>
* <p>If no username is specified in the URL, Git queries for the username and for the password consecutively.
* In this case to avoid showing dialogs twice, the component asks for both credentials at once,
* and remembers the password to provide it to the Git process during the next request without requiring user interaction.</p>
* <p>New instance of the GitAskPassGuiHandler should be created for each session, i. e. for each remote operation call.</p>
*
* @author Kirill Likhodedov
*/
class GitHttpGuiAuthenticator implements GitHttpAuthenticator {
private static final Logger LOG = Logger.getInstance(GitHttpGuiAuthenticator.class);
private static final Class<GitHttpAuthenticator> PASS_REQUESTER = GitHttpAuthenticator.class;
@NotNull private final Project myProject;
@NotNull private final String myTitle;
@NotNull private final Collection<String> myUrlsFromCommand;
@Nullable private String myPassword;
@Nullable private String myPasswordKey;
@Nullable private String myUnifiedUrl;
@Nullable private String myLogin;
private boolean mySaveOnDisk;
@Nullable private GitHttpAuthDataProvider myDataProvider;
private boolean myWasCancelled;
GitHttpGuiAuthenticator(@NotNull Project project, @NotNull GitCommand command, @NotNull Collection<String> url) {
myProject = project;
myTitle = "Git " + StringUtil.capitalize(command.name());
myUrlsFromCommand = url;
}
@Override
@NotNull
public String askPassword(@NotNull String url) {
if (myPassword != null) { // already asked in askUsername
return myPassword;
}
if (myWasCancelled) { // already pressed cancel in askUsername
return "";
}
Pair<GitHttpAuthDataProvider, AuthData> authData = findBestAuthData(getUnifiedUrl(url));
if (authData != null && authData.second.getPassword() != null) {
String password = authData.second.getPassword();
myDataProvider = authData.first;
myPassword = password;
return password;
}
myPasswordKey = getUnifiedUrl(url);
String password = PasswordSafePromptDialog.askPassword(myProject, myTitle, "Enter the password for " + getDisplayableUrl(url),
PASS_REQUESTER, myPasswordKey, false, null);
if (password == null) {
myWasCancelled = true;
return "";
}
// Password is stored in the safe in PasswordSafePromptDialog.askPassword,
// but it is not the right behavior (incorrect password is stored too because of that) and should be fixed separately.
// We store it here manually, to let it work after that behavior is fixed.
myPassword = password;
myDataProvider = new GitDefaultHttpAuthDataProvider(); // workaround: askPassword remembers the password even it is not correct
return password;
}
@Override
@NotNull
public String askUsername(@NotNull String url) {
Pair<GitHttpAuthDataProvider, AuthData> authData = findBestAuthData(getUnifiedUrl(url));
String login = null;
String password = null;
if (authData != null) {
login = authData.second.getLogin();
password = authData.second.getPassword();
myDataProvider = authData.first;
}
if (login != null && password != null) {
myPassword = password;
return login;
}
AuthDialog dialog = showAuthDialog(getDisplayableUrl(url), login);
if (dialog == null || !dialog.isOK()) {
myWasCancelled = true;
return "";
}
// remember values to store in the database afterwards, if authentication succeeds
myPassword = dialog.getPassword();
myLogin = dialog.getUsername();
myUnifiedUrl = getUnifiedUrl(url);
mySaveOnDisk = dialog.isRememberPassword();
myPasswordKey = makeKey(myUnifiedUrl, myLogin);
return myLogin;
}
@Nullable
private AuthDialog showAuthDialog(final String url, final String login) {
final Ref<AuthDialog> dialog = Ref.create();
ApplicationManager.getApplication().invokeAndWait(new Runnable() {
@Override
public void run() {
dialog.set(new AuthDialog(myProject, myTitle, "Enter credentials for " + url, login, null, true));
dialog.get().show();
}
}, ModalityState.any());
return dialog.get();
}
@Override
public void saveAuthData() {
// save login and url
if (myUnifiedUrl != null && myLogin != null) {
GitRememberedInputs.getInstance().addUrl(myUnifiedUrl, myLogin);
}
// save password
if (myPasswordKey != null && myPassword != null) {
PasswordSafeImpl passwordSafe = (PasswordSafeImpl)PasswordSafe.getInstance();
try {
passwordSafe.getMemoryProvider().storePassword(myProject, PASS_REQUESTER, myPasswordKey, myPassword);
if (mySaveOnDisk) {
passwordSafe.getMasterKeyProvider().storePassword(myProject, PASS_REQUESTER, myPasswordKey, myPassword);
}
}
catch (MasterPasswordUnavailableException ignored) {
}
catch (PasswordSafeException e) {
LOG.error("Couldn't remember password for " + myPasswordKey, e);
}
}
}
@Override
public void forgetPassword() {
if (myDataProvider != null && myUnifiedUrl != null) {
myDataProvider.forgetPassword(myUnifiedUrl);
}
}
@Override
public boolean wasCancelled() {
return myWasCancelled;
}
/**
* Get the URL to display to the user in the authentication dialog.
*/
@NotNull
private String getDisplayableUrl(@Nullable String urlFromGit) {
return !StringUtil.isEmptyOrSpaces(urlFromGit) ? urlFromGit : findPresetHttpUrl();
}
/**
* Get the URL to be used as the authentication data identifier in the password safe and the settings.
*/
@NotNull
private String getUnifiedUrl(@Nullable String urlFromGit) {
return changeHttpsToHttp(StringUtil.isEmptyOrSpaces(urlFromGit) ? findPresetHttpUrl() : urlFromGit);
}
@NotNull
private String findPresetHttpUrl() {
return ObjectUtils.chooseNotNull(ContainerUtil.find(myUrlsFromCommand, new Condition<String>() {
@Override
public boolean value(String url) {
String scheme = UriUtil.splitScheme(url).getFirst();
return scheme.startsWith("http");
}
}), ContainerUtil.getFirstItem(myUrlsFromCommand));
}
/**
* If the url scheme is HTTPS, store it as HTTP in the database, not to make user enter and remember same credentials twice.
*/
@NotNull
private static String changeHttpsToHttp(@NotNull String url) {
String prefix = "https";
if (url.startsWith(prefix)) {
return "http" + url.substring(prefix.length());
}
return url;
}
// return the first that knows username + password; otherwise return the first that knows just the username
@Nullable
private Pair<GitHttpAuthDataProvider, AuthData> findBestAuthData(@NotNull String url) {
Pair<GitHttpAuthDataProvider, AuthData> candidate = null;
for (GitHttpAuthDataProvider provider : getProviders()) {
AuthData data = provider.getAuthData(url);
if (data != null) {
Pair<GitHttpAuthDataProvider, AuthData> pair = Pair.create(provider, data);
if (data.getPassword() != null) {
return pair;
}
if (candidate == null) {
candidate = pair;
}
}
}
return candidate;
}
@NotNull
private List<GitHttpAuthDataProvider> getProviders() {
List<GitHttpAuthDataProvider> providers = ContainerUtil.newArrayList();
providers.add(new GitDefaultHttpAuthDataProvider());
providers.addAll(Arrays.asList(GitHttpAuthDataProvider.EP_NAME.getExtensions()));
return providers;
}
/**
* Makes the password database key for the URL: inserts the login after the scheme: http://login@url.
*/
@NotNull
private static String makeKey(@NotNull String url, @Nullable String login) {
if (login == null) {
return url;
}
Couple<String> pair = UriUtil.splitScheme(url);
String scheme = pair.getFirst();
if (!StringUtil.isEmpty(scheme)) {
return scheme + URLUtil.SCHEME_SEPARATOR + login + "@" + pair.getSecond();
}
return login + "@" + url;
}
public class GitDefaultHttpAuthDataProvider implements GitHttpAuthDataProvider {
@Nullable
@Override
public AuthData getAuthData(@NotNull String url) {
String userName = getUsername(url);
String key = makeKey(url, userName);
final PasswordSafe passwordSafe = PasswordSafe.getInstance();
try {
String password = passwordSafe.getPassword(myProject, PASS_REQUESTER, key);
return new AuthData(StringUtil.notNullize(userName), password);
}
catch (PasswordSafeException e) {
LOG.info("Couldn't get the password for key [" + key + "]", e);
return null;
}
}
@Nullable
private String getUsername(@NotNull String url) {
return GitRememberedInputs.getInstance().getUserNameForUrl(url);
}
@Override
public void forgetPassword(@NotNull String url) {
String key = myPasswordKey != null ? myPasswordKey : makeKey(url, getUsername(url));
try {
PasswordSafe.getInstance().removePassword(myProject, PASS_REQUESTER, key);
}
catch (PasswordSafeException e) {
LOG.info("Couldn't forget the password for " + myPasswordKey);
}
}
}
}
| |
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.loader.data;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
/**
* {@link RandomAccessData} implementation backed by a {@link RandomAccessFile}.
*
* @author Phillip Webb
*/
public class RandomAccessDataFile implements RandomAccessData {
private static final int DEFAULT_CONCURRENT_READS = 4;
private final File file;
private final FilePool filePool;
private final long offset;
private final long length;
/**
* Create a new {@link RandomAccessDataFile} backed by the specified file.
* @param file the underlying file
* @throws IllegalArgumentException if the file is null or does not exist
* @see #RandomAccessDataFile(File, int)
*/
public RandomAccessDataFile(File file) {
this(file, DEFAULT_CONCURRENT_READS);
}
/**
* Create a new {@link RandomAccessDataFile} backed by the specified file.
* @param file the underlying file
* @param concurrentReads the maximum number of concurrent reads allowed on the
* underlying file before blocking
* @throws IllegalArgumentException if the file is null or does not exist
* @see #RandomAccessDataFile(File)
*/
public RandomAccessDataFile(File file, int concurrentReads) {
if (file == null) {
throw new IllegalArgumentException("File must not be null");
}
if (!file.exists()) {
throw new IllegalArgumentException("File must exist");
}
this.file = file;
this.filePool = new FilePool(concurrentReads);
this.offset = 0L;
this.length = file.length();
}
/**
* Private constructor used to create a {@link #getSubsection(long, long) subsection}.
* @param file the underlying file
* @param pool the underlying pool
* @param offset the offset of the section
* @param length the length of the section
*/
private RandomAccessDataFile(File file, FilePool pool, long offset, long length) {
this.file = file;
this.filePool = pool;
this.offset = offset;
this.length = length;
}
/**
* Returns the underlying File.
* @return the underlying file
*/
public File getFile() {
return this.file;
}
@Override
public InputStream getInputStream(ResourceAccess access) throws IOException {
return new DataInputStream(access);
}
@Override
public RandomAccessData getSubsection(long offset, long length) {
if (offset < 0 || length < 0 || offset + length > this.length) {
throw new IndexOutOfBoundsException();
}
return new RandomAccessDataFile(this.file, this.filePool, this.offset + offset,
length);
}
@Override
public long getSize() {
return this.length;
}
public void close() throws IOException {
this.filePool.close();
}
/**
* {@link RandomAccessDataInputStream} implementation for the
* {@link RandomAccessDataFile}.
*/
private class DataInputStream extends InputStream {
private RandomAccessFile file;
private int position;
DataInputStream(ResourceAccess access) throws IOException {
if (access == ResourceAccess.ONCE) {
this.file = new RandomAccessFile(RandomAccessDataFile.this.file, "r");
this.file.seek(RandomAccessDataFile.this.offset);
}
}
@Override
public int read() throws IOException {
return doRead(null, 0, 1);
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b == null ? 0 : b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException("Bytes must not be null");
}
return doRead(b, off, len);
}
/**
* Perform the actual read.
* @param b the bytes to read or {@code null} when reading a single byte
* @param off the offset of the byte array
* @param len the length of data to read
* @return the number of bytes read into {@code b} or the actual read byte if
* {@code b} is {@code null}. Returns -1 when the end of the stream is reached
* @throws IOException in case of I/O errors
*/
public int doRead(byte[] b, int off, int len) throws IOException {
if (len == 0) {
return 0;
}
int cappedLen = cap(len);
if (cappedLen <= 0) {
return -1;
}
RandomAccessFile file = this.file;
if (file == null) {
file = RandomAccessDataFile.this.filePool.acquire();
file.seek(RandomAccessDataFile.this.offset + this.position);
}
try {
if (b == null) {
int rtn = file.read();
moveOn(rtn == -1 ? 0 : 1);
return rtn;
}
else {
return (int) moveOn(file.read(b, off, cappedLen));
}
}
finally {
if (this.file == null) {
RandomAccessDataFile.this.filePool.release(file);
}
}
}
@Override
public long skip(long n) throws IOException {
return (n <= 0 ? 0 : moveOn(cap(n)));
}
@Override
public void close() throws IOException {
if (this.file != null) {
this.file.close();
}
}
/**
* Cap the specified value such that it cannot exceed the number of bytes
* remaining.
* @param n the value to cap
* @return the capped value
*/
private int cap(long n) {
return (int) Math.min(RandomAccessDataFile.this.length - this.position, n);
}
/**
* Move the stream position forwards the specified amount.
* @param amount the amount to move
* @return the amount moved
*/
private long moveOn(int amount) {
this.position += amount;
return amount;
}
}
/**
* Manage a pool that can be used to perform concurrent reads on the underlying
* {@link RandomAccessFile}.
*/
private class FilePool {
private final int size;
private final Semaphore available;
private final Queue<RandomAccessFile> files;
FilePool(int size) {
this.size = size;
this.available = new Semaphore(size);
this.files = new ConcurrentLinkedQueue<RandomAccessFile>();
}
public RandomAccessFile acquire() throws IOException {
try {
this.available.acquire();
RandomAccessFile file = this.files.poll();
return (file == null
? new RandomAccessFile(RandomAccessDataFile.this.file, "r")
: file);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new IOException(ex);
}
}
public void release(RandomAccessFile file) {
this.files.add(file);
this.available.release();
}
public void close() throws IOException {
try {
this.available.acquire(this.size);
try {
RandomAccessFile file = this.files.poll();
while (file != null) {
file.close();
file = this.files.poll();
}
}
finally {
this.available.release(this.size);
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new IOException(ex);
}
}
}
}
| |
/*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.i18n;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSelectInfo;
import org.apache.commons.vfs.FileSelector;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.fileinput.FileInputList;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This class takes care of crawling through the source code
*
* @author matt
*
*/
public class MessagesSourceCrawler {
private String scanPhrases[];
/**
* The source directories to crawl through
*/
private List<String> sourceDirectories;
/**
* Source folder - package name - all the key occurrences in there
*/
private Map<String, Map<String, List<KeyOccurrence>>> sourcePackageOccurrences;
/**
* The file names to avoid (base names)
*/
private List<String> filesToAvoid;
private String singleMessagesFile;
/**
* The folders with XML files to scan for keys in
*/
private List<SourceCrawlerXMLFolder> xmlFolders;
private Pattern packagePattern;
private Pattern importPattern;
private Pattern importMessagesPattern;
private Pattern stringPkgPattern;
private Pattern classPkgPattern;
private LogChannelInterface log;
/**
* @param sourceDirectories
* The source directories to crawl through
* @param singleMessagesFile
* the messages file if there is only one, otherwise: null
*/
public MessagesSourceCrawler(LogChannelInterface log, List<String> sourceDirectories, String singleMessagesFile, List<SourceCrawlerXMLFolder> xmlFolders) {
super();
this.log = log;
this.sourceDirectories = sourceDirectories;
this.singleMessagesFile = singleMessagesFile;
this.filesToAvoid = new ArrayList<String>();
this.xmlFolders = xmlFolders;
this.sourcePackageOccurrences = new HashMap<String, Map<String, List<KeyOccurrence>>>();
packagePattern = Pattern.compile("^\\s*package .*;[ \t]*$");
importPattern = Pattern.compile("^\\s*import [a-z\\._0-9]*\\.[A-Z].*;[ \t]*$");
importMessagesPattern = Pattern.compile("^\\s*import [a-z\\._0-9]*\\.Messages;[ \t]*$");
stringPkgPattern = Pattern.compile("^.*private static String PKG.*=.*$");
classPkgPattern = Pattern.compile("^.*private static Class.*\\sPKG\\s*=.*$");
}
/**
* @return The source directories to crawl through
*/
public List<String> getSourceDirectories() {
return sourceDirectories;
}
/**
* @param sourceDirectories
* The source directories to crawl through
*/
public void setSourceDirectories(List<String> sourceDirectories) {
this.sourceDirectories = sourceDirectories;
}
/**
* @return the files to avoid
*/
public List<String> getFilesToAvoid() {
return filesToAvoid;
}
/**
* @param filesToAvoid
* the files to avoid
*/
public void setFilesToAvoid(List<String> filesToAvoid) {
this.filesToAvoid = filesToAvoid;
}
/**
* Add a key occurrence to the list of occurrences. The list is kept sorted
* on key and message package. If the key already exists, we increment the
* number of occurrences.
*
* @param occ
* The key occurrence to add
*/
public void addKeyOccurrence(KeyOccurrence occ) {
// System.out.println("Adding key occurrence : folder="+occ.getSourceFolder()+", pkg="+occ.getMessagesPackage()+", key="+occ.getKey());
String sourceFolder = occ.getSourceFolder();
if (sourceFolder==null) {
throw new RuntimeException("No source folder found for key: "+occ.getKey()+" in package "+occ.getMessagesPackage());
}
String messagesPackage = occ.getMessagesPackage();
// Do we have a map for the source folders?
// If not, add one...
//
Map<String, List<KeyOccurrence>> packageOccurrences = sourcePackageOccurrences.get(sourceFolder);
if (packageOccurrences==null) {
packageOccurrences=new HashMap<String, List<KeyOccurrence>>();
sourcePackageOccurrences.put(sourceFolder, packageOccurrences);
}
// Do we have a map entry for the occurrences list in the source folder?
// If not, add a list for the messages package
//
List<KeyOccurrence> occurrences = packageOccurrences.get(messagesPackage);
if (occurrences==null) {
occurrences = new ArrayList<KeyOccurrence>();
occurrences.add(occ);
packageOccurrences.put(messagesPackage, occurrences);
} else {
int index = Collections.binarySearch(occurrences, occ);
if (index < 0) {
// Add it to the list, keep it sorted...
//
occurrences.add(-index - 1, occ);
}
}
}
public void crawl() throws Exception {
for (final String sourceDirectory : sourceDirectories) {
FileObject folder = KettleVFS.getFileObject(sourceDirectory);
FileObject[] javaFiles = folder.findFiles(new FileSelector() {
@Override
public boolean traverseDescendents(FileSelectInfo info) throws Exception {
return true;
}
@Override
public boolean includeFile(FileSelectInfo info) throws Exception {
return info.getFile().getName().getExtension().equals("java");
}
} );
for (FileObject javaFile : javaFiles) {
/**
* We don't want the Messages.java files, there is nothing in there for
* us.
*/
boolean skip=false;
for (String filename : filesToAvoid) {
if (javaFile.getName().getBaseName().equals(filename)) {
skip=true;
}
}
if (skip) {
continue; // don't process this file.
}
// For each of these files we look for keys...
//
lookForOccurrencesInFile(sourceDirectory, javaFile);
}
}
// Also search for keys in the XUL files...
//
for (SourceCrawlerXMLFolder xmlFolder : xmlFolders) {
String[] xmlDirs = { xmlFolder.getFolder(), };
String[] xmlMasks = { xmlFolder.getWildcard(), };
String[] xmlReq = { "N", };
boolean[] xmlSubdirs = { true, }; // search sub-folders too
FileInputList xulFileInputList = FileInputList.createFileList(
new Variables(), xmlDirs, xmlMasks, xmlReq, xmlSubdirs);
for (FileObject fileObject : xulFileInputList.getFiles()) {
try {
Document doc = XMLHandler.loadXMLFile(fileObject);
// Scan for elements and tags in this file...
//
for (SourceCrawlerXMLElement xmlElement : xmlFolder.getElements()) {
addLabelOccurrences(
xmlFolder.getDefaultSourceFolder(),
fileObject,
doc.getElementsByTagName(xmlElement.getSearchElement()),
xmlFolder.getKeyPrefix(),
xmlElement.getKeyTag(),
xmlElement.getKeyAttribute(),
xmlFolder.getDefaultPackage(),
xmlFolder.getPackageExceptions()
);
}
} catch (KettleXMLException e) {
log.logError("Unable to open XUL / XML document: " + fileObject);
}
}
}
}
private void addLabelOccurrences(String sourceFolder, FileObject fileObject, NodeList nodeList,
String keyPrefix, String tag, String attribute,
String defaultPackage,
List<SourceCrawlerPackageException> packageExcpeptions)
throws Exception {
if (nodeList == null)
return;
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
String labelString = null;
if (!Const.isEmpty(attribute)) {
labelString = XMLHandler.getTagAttribute(node, attribute);
} else if (!Const.isEmpty(tag)) {
labelString = XMLHandler.getTagValue(node, tag);
}
// TODO : Set the prefix in the right place
keyPrefix="$";
if (labelString != null && labelString.startsWith(keyPrefix)) {
String key = labelString.substring(1);
// TODO : maybe not the right place ...
// just removed ${} around the key
key=labelString.substring(2, labelString.length()-1).trim();
String messagesPackage = defaultPackage;
for (SourceCrawlerPackageException packageException : packageExcpeptions) {
if (key.startsWith(packageException.getStartsWith()))
messagesPackage = packageException.getPackageName();
}
StringWriter bodyXML = new StringWriter();
transformer.transform(new DOMSource(node), new StreamResult(bodyXML));
String xml = bodyXML.getBuffer().toString();
KeyOccurrence keyOccurrence = new KeyOccurrence(fileObject, sourceFolder, messagesPackage, -1, -1, key, "?", xml);
addKeyOccurrence(keyOccurrence);
}
}
}
/**
* Look for additional occurrences of keys in the specified file.
* @param sourceFolder The folder the java file and messages files live in
*
* @param javaFile
* The java source file to examine
* @throws IOException
* In case there is a problem accessing the specified source
* file.
*/
public void lookForOccurrencesInFile(String sourceFolder, FileObject javaFile)
throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader( KettleVFS.getInputStream(javaFile)));
String messagesPackage = null;
int row = 0;
String classPackage = null;
Map<String, String> importedClasses = new Hashtable<String, String>(); // Remember the imports we do...
String line = reader.readLine();
while (line != null) {
row++;
String line2=line;
boolean extraLine;
do {
extraLine = false;
for (String scanPhrase : scanPhrases) {
if (line2.endsWith(scanPhrase)) {
extraLine=true;
break;
}
}
if (extraLine) {
line2 = reader.readLine();
line+=line2;
}
} while (extraLine);
// Examine the line...
// What we first look for is the import of the messages package.
//
// "package org.pentaho.di.trans.steps.sortedmerge;"
//
if (packagePattern.matcher(line).matches()) {
int beginIndex = line.indexOf("org.pentaho.");
int endIndex = line.indexOf(';');
if (beginIndex>=0 && endIndex>=0) {
messagesPackage = line.substring(beginIndex, endIndex); // this is the default
classPackage = messagesPackage;
}
}
// Remember all the imports...
//
if (importPattern.matcher(line).matches()) {
int beginIndex = line.indexOf("import")+"import".length()+1;
int endIndex = line.indexOf(";", beginIndex);
String expression = line.substring(beginIndex, endIndex);
// The last word is the Class imported...
// If it's * we ignore it.
//
int lastDotIndex = expression.lastIndexOf('.');
if (lastDotIndex>0) {
String packageName = expression.substring(0, lastDotIndex);
String className = expression.substring(lastDotIndex+1);
if (!"*".equals(className)) {
importedClasses.put(className, packageName);
}
}
}
// This is the alternative location of the messages package:
//
// "import org.pentaho.di.trans.steps.sortedmerge.Messages;"
//
if (importMessagesPattern.matcher(line).matches()) {
int beginIndex = line.indexOf("org.pentaho.");
int endIndex = line.indexOf(".Messages;");
messagesPackage = line.substring(beginIndex, endIndex); // if there is any specified, we take this one.
}
// Look for the value of the PKG value...
//
// private static String PKG = "org.pentaho.foo.bar.somepkg";
//
if (stringPkgPattern.matcher(line).matches()) {
int beginIndex = line.indexOf('"')+1;
int endIndex = line.indexOf('"', beginIndex);
messagesPackage = line.substring(beginIndex, endIndex);
}
// Look for the value of the PKG value as a fully qualified class...
//
// private static Class<?> PKG = Abort.class;
//
if (classPackage!=null && classPkgPattern.matcher(line).matches()) {
int fromIndex=line.indexOf('=')+1;
int toIndex=line.indexOf(".class", fromIndex);
String expression = Const.trim(line.substring(fromIndex, toIndex));
// System.out.println("expression : "+expression);
// If the expression doesn't contain any package, we'll look up the package in the imports. If not found there, it's a local package.
//
if (expression.contains(".")) {
int lastDotIndex = expression.lastIndexOf('.');
messagesPackage = expression.substring(0, lastDotIndex);
} else {
String packageName = importedClasses.get(expression);
if (packageName==null) {
messagesPackage = classPackage; // Local package
} else {
messagesPackage = packageName; // imported
}
}
}
// Now look for occurrences of "Messages.getString(", "BaseMessages.getString(PKG", ...
//
for (String scanPhrase : scanPhrases) {
int index = line.indexOf(scanPhrase);
while (index >= 0) {
// see if there's a character [a-z][A-Z] before the search string...
// Otherwise we're looking at BaseMessages.getString(), etc.
//
if (index==0 || (index>0 & !Character.isJavaIdentifierPart(line.charAt(index-1)))) {
addLineOccurrence(sourceFolder, javaFile, messagesPackage, line, row, index, scanPhrase);
}
index = line.indexOf(scanPhrase, index + 1);
}
}
line = reader.readLine();
}
reader.close();
}
/**
* Extract the needed information from the line and the index on which
* Messages.getString() occurs.
* @param sourceFolder The source folder the messages and java files live in
*
* @param fileObject
* the file we're reading
* @param messagesPackage
* the messages package
* @param line
* the line
* @param row
* the row number
* @param index
* the index in the line on which "Messages.getString(" is
* located.
*/
private void addLineOccurrence(String sourceFolder, FileObject fileObject,
String messagesPackage, String line, int row, int index, String scanPhrase) {
// Right after the "Messages.getString(" string is the key, quoted (")
// until the next comma...
//
int column = index + scanPhrase.length();
String arguments = "";
// we start at the double quote...
//
int startKeyIndex = line.indexOf('"', column) + 1;
int endKeyIndex = line.indexOf('"', startKeyIndex);
String key;
if (endKeyIndex >= 0) {
key = line.substring(startKeyIndex, endKeyIndex);
// Can we also determine the arguments?
// No, not always: only if the arguments are all on the same line.
//
// Look for the next closing bracket...
//
int bracketIndex = endKeyIndex;
int nrOpen = 1;
while (bracketIndex < line.length() && nrOpen != 0) {
int c = line.charAt(bracketIndex);
if (c == '(')
nrOpen++;
if (c == ')')
nrOpen--;
bracketIndex++;
}
if (bracketIndex + 1 < line.length()) {
arguments = line.substring(endKeyIndex + 1, bracketIndex);
} else {
arguments = line.substring(endKeyIndex + 1);
}
} else {
key = line.substring(startKeyIndex);
}
// Sanity check...
//
if (key.contains("\t") || key.contains(" ")) {
System.out.println("Suspect key found: [" + key + "] in file ["
+ fileObject + "]");
}
// OK, add the occurrence to the list...
//
// Make sure we pass the System key occurrences to the correct package.
//
if (key.startsWith("System.")) {
String i18nPackage = BaseMessages.class.getPackage().getName();
KeyOccurrence keyOccurrence = new KeyOccurrence(fileObject, sourceFolder, i18nPackage, row, column, key, arguments, line);
// If we just add this key, we'll get doubles in the i18n package
//
KeyOccurrence lookup = getKeyOccurrence(key, i18nPackage);
if (lookup == null) {
addKeyOccurrence(keyOccurrence);
} else {
// Adjust the line of code...
//
lookup.setSourceLine(lookup.getSourceLine() + Const.CR + keyOccurrence.getSourceLine());
lookup.incrementOccurrences();
}
} else {
KeyOccurrence keyOccurrence = new KeyOccurrence(fileObject, sourceFolder, messagesPackage, row, column, key, arguments, line);
addKeyOccurrence(keyOccurrence);
}
}
/**
* @return A sorted list of distinct occurrences of the used message package names
*/
public List<String> getMessagesPackagesList(String sourceFolder) {
Map<String, List<KeyOccurrence>> packageOccurrences = sourcePackageOccurrences.get(sourceFolder);
List<String> list = new ArrayList<String>(packageOccurrences.keySet());
Collections.sort(list);
return list;
}
/**
* Get all the key occurrences for a certain messages package.
*
* @param sourceFolder the source folder to reference
* @param messagesPackage the package to hunt for
* @return all the key occurrences for a certain messages package.
*/
public List<KeyOccurrence> getOccurrencesForPackage(String messagesPackage) {
List<KeyOccurrence> list = new ArrayList<KeyOccurrence>();
for (String sourceFolder : sourcePackageOccurrences.keySet()) {
Map<String, List<KeyOccurrence>> po = sourcePackageOccurrences.get(sourceFolder);
List<KeyOccurrence> occurrences = po.get(messagesPackage);
if (occurrences!=null) {
list.addAll(occurrences);
}
}
return list;
}
public KeyOccurrence getKeyOccurrence(String key, String selectedMessagesPackage) {
for (String sourceFolder : sourcePackageOccurrences.keySet()) {
Map<String, List<KeyOccurrence>> po = sourcePackageOccurrences.get(sourceFolder);
if (po!=null) {
List<KeyOccurrence> occurrences = po.get(selectedMessagesPackage);
if (occurrences!=null) {
for (KeyOccurrence keyOccurrence : occurrences) {
if (keyOccurrence.getKey().equals(key) &&
keyOccurrence.getMessagesPackage().equals(selectedMessagesPackage)) {
return keyOccurrence;
}
}
}
}
}
return null;
}
/**
* @return the singleMessagesFile
*/
public String getSingleMessagesFile() {
return singleMessagesFile;
}
/**
* @param singleMessagesFile
* the singleMessagesFile to set
*/
public void setSingleMessagesFile(String singleMessagesFile) {
this.singleMessagesFile = singleMessagesFile;
}
/**
* @return the scanPhrases
*/
public String[] getScanPhrases() {
return scanPhrases;
}
/**
* @param scanPhrases the scanPhrases to set
*/
public void setScanPhrases(String[] scanPhrases) {
this.scanPhrases = scanPhrases;
}
public Map<String, Map<String, List<KeyOccurrence>>> getSourcePackageOccurrences() {
return sourcePackageOccurrences;
}
public void setSourcePackageOccurrences(Map<String, Map<String, List<KeyOccurrence>>> sourcePackageOccurrences) {
this.sourcePackageOccurrences = sourcePackageOccurrences;
}
/**
* Get the unique package-key
* @param sourceFolder
*/
public List<KeyOccurrence> getKeyOccurrences(String sourceFolder) {
Map<String, KeyOccurrence> map = new HashMap<String, KeyOccurrence>();
Map<String, List<KeyOccurrence>> po = sourcePackageOccurrences.get(sourceFolder);
if (po!=null) {
for (List<KeyOccurrence> keyOccurrences : po.values()) {
for (KeyOccurrence keyOccurrence : keyOccurrences) {
String key = keyOccurrence.getMessagesPackage() + " - " + keyOccurrence.getKey();
map.put(key, keyOccurrence);
}
}
}
return new ArrayList<KeyOccurrence>(map.values());
}
}
| |
package com.pgmacdesign.pgmactips.networkclasses.retrofitutilities;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.pgmacdesign.pgmactips.utilities.L;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Type;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import okhttp3.Request;
import okio.Timeout;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Retry Call Adapter Factory to be used in the {@link RetrofitClient} class
* Code pulled from MORRIS at this link: https://androidwave.com/retrying-request-with-retrofit-android/
*/
public class RetryCallAdapterFactory extends CallAdapter.Factory {
//region Interface
/**
* Retry Interface. Defaults to 3 attempts
*/
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface Retry {
int max() default 3;
}
//endregion
/**
* Customizable number of retry attempts set
*/
private int retryAttempts;
//region Constructor
private RetryCallAdapterFactory(){
this.retryAttempts = 3;
}
private RetryCallAdapterFactory(int retryAttempts){
this.retryAttempts = retryAttempts;
}
//endregion
/**
* Static Instance Generator
* @return
*/
public static RetryCallAdapterFactory create() {
return new RetryCallAdapterFactory();
}
/**
* Static Instance Generator
* @return
*/
public static RetryCallAdapterFactory create(@IntRange (from = 0) int retryCount) {
return new RetryCallAdapterFactory(retryCount);
}
/**
* Constructor for the Call Adapter
* @param returnType
* @param annotations
* @param retrofit
* @return
*/
@Nullable
@Override
public CallAdapter<?, ?> get(@NonNull Type returnType, @NonNull Annotation[] annotations,
@NonNull Retrofit retrofit) {
/**
* You can setup a default max retry count for all connections.
*/
int itShouldRetry = 0;
final Retry retry = getRetry(annotations);
if (retry != null) {
itShouldRetry = retry.max();
} else {
itShouldRetry = this.retryAttempts;
}
return new RetryCallAdapter<>(
retrofit.nextCallAdapter(this, returnType, annotations), itShouldRetry
);
}
/**
* Simple getter method to return the interface defined above
* @param annotations
* @return
*/
private Retry getRetry(@NonNull Annotation[] annotations) {
for (Annotation annotation : annotations) {
if (annotation instanceof Retry) {
return (Retry) annotation;
}
}
return null;
}
/**
* The Call Adapter
* @param <R>
* @param <T>
*/
static final class RetryCallAdapter<R, T> implements CallAdapter<R, T> {
private final CallAdapter<R, T> delegated;
private final int maxRetries;
public RetryCallAdapter(CallAdapter<R, T> delegated, int maxRetries) {
this.delegated = delegated;
this.maxRetries = maxRetries;
}
@Override
public Type responseType() {
return this.delegated.responseType();
}
@Override
public T adapt(final Call<R> call) {
return this.delegated.adapt(this.maxRetries > 0 ? new RetryingCall<>(call, this.maxRetries) : call);
}
}
/**
* Method for retrying the call
* @param <R>
*/
static final class RetryingCall<R> implements Call<R> {
private final Call<R> delegated;
private final int maxRetries;
public RetryingCall(Call<R> delegated, int maxRetries) {
this.delegated = delegated;
this.maxRetries = maxRetries;
}
@Override
public Response<R> execute() throws IOException {
return this.delegated.execute();
}
@Override
public void enqueue(@NonNull Callback<R> callback) {
this.delegated.enqueue(new RetryCallback<>(this.delegated, callback, this.maxRetries));
}
@Override
public boolean isExecuted() {
return this.delegated.isExecuted();
}
@Override
public void cancel() {
this.delegated.cancel();
}
@Override
public boolean isCanceled() {
return this.delegated.isCanceled();
}
@Override
public Call<R> clone() {
return new RetryingCall<>(this.delegated.clone(), this.maxRetries);
}
@Override
public Request request() {
return this.delegated.request();
}
@Override
public Timeout timeout() {
return this.delegated.timeout();
}
}
/**
* Retry Callback
* @param <T>
*/
static final class RetryCallback<T> implements Callback<T> {
private final Call<T> call;
private final Callback<T> callback;
private final int maxRetries;
public RetryCallback(Call<T> call, Callback<T> callback, int maxRetries) {
this.call = call;
this.callback = callback;
this.maxRetries = maxRetries;
}
private final AtomicInteger retryCount = new AtomicInteger(0);
@Override
public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
if(this.maxRetries <= 0){
this.callback.onResponse(call, response);
return;
}
if (!response.isSuccessful() && (this.retryCount.incrementAndGet() <= this.maxRetries)) {
retryCall();
} else {
this.callback.onResponse(call, response);
}
}
@Override
public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
int x = this.retryCount.incrementAndGet();
if(this.maxRetries <= 0){
this.callback.onFailure(call, t);
return;
}
if (x <= this.maxRetries) {
retryCall();
} else if (this.maxRetries > 0) {
this.callback.onFailure(call,
new TimeoutException(String.format("Call failed after %s attempts.", this.maxRetries)));
} else {
this.callback.onFailure(call, t);
}
}
private void retryCall() {
L.m("" + this.retryCount.get() + "/" + this.maxRetries + " " + " Retrying...");
this.call.clone().enqueue(this);
}
}
}
| |
/*
Copyright 2013 Philipp Leitner
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package at.ac.tuwien.infosys.jcloudscale.vm;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;
import at.ac.tuwien.infosys.jcloudscale.annotations.JCloudScaleConfigurationProvider;
import at.ac.tuwien.infosys.jcloudscale.configuration.JCloudScaleConfiguration;
import at.ac.tuwien.infosys.jcloudscale.configuration.JCloudScaleConfigurationBuilder;
import at.ac.tuwien.infosys.jcloudscale.exception.JCloudScaleException;
import at.ac.tuwien.infosys.jcloudscale.logging.LogReceiver;
import at.ac.tuwien.infosys.jcloudscale.logging.SysoutputReceiver;
import at.ac.tuwien.infosys.jcloudscale.management.CloudManager;
import at.ac.tuwien.infosys.jcloudscale.management.JCloudScaleReferenceManager;
import at.ac.tuwien.infosys.jcloudscale.messaging.MQWrapper;
import at.ac.tuwien.infosys.jcloudscale.monitoring.EventCorrelationEngine;
import at.ac.tuwien.infosys.jcloudscale.server.messaging.MonitoringMQHelper;
/**
* The main JCloudScale class in the client-side code.
*/
public class JCloudScaleClient implements Closeable
{
/**
* In case configuration was not specified explicitly, JCloudScale will check this property
* in System Properties to load configuration. If it won't be specified as well, default configuration will be used.
*/
public static final String JCLOUDSCALE_CONFIGURATION_PROPERTY = "jcloudscale.configuration";
//------------------------------------------------------------------
private static JCloudScaleClient instance = null;
private static volatile JCloudScaleConfiguration configuration = null;
private LogReceiver serverLogReceiver;
private SysoutputReceiver serverOutputReceiver;
private Closeable classProvider;
private Closeable riakPublisher;
private Closeable mqPublisher;
private AutoCloseable mqServer;
private Map<UUID, VirtualHostProxy> hostProxies = new HashMap<>();
private Logger log;
private JCloudScaleClient()
{
this.log = JCloudScaleConfiguration.getLogger(this);
// Ensuring that Message Queue Is running
if(getConfiguration().common().communication().getStartMessageQueueServerAutomatically())
{
try
{
mqServer = getConfiguration().server()
.cloudPlatform().ensureCommunicationServerRunning();
} catch (Exception ex)
{
log.warning("Failed to ensure that Message Queue is running: "+ex);
}
}
this.serverLogReceiver = new LogReceiver();
this.serverOutputReceiver = new SysoutputReceiver();
this.classProvider = getConfiguration().common()
.classLoader()
.createClassProvider();
// Publisher for MQ Server
if(getConfiguration().common().communication().startMulticastPublisher())
try
{
mqPublisher = getConfiguration().common().communication().createServerPublisher();
}
catch (IOException e)
{
log.warning("Failed to start Message Queue Multicast Publisher. "+ e);
}
}
/**
* Gets an instance of the JCloudScaleClient that manages all JCloudScale code on client.
* @return A singleton instance of the <b>JCloudScaleClient</b> class.
*/
public static synchronized JCloudScaleClient getClient()
{
if(instance == null)
instance = new JCloudScaleClient();
return instance;
}
/**
* Closes and cleansup all resources managed by the JCloudScale on the client-side.
*/
public static synchronized void closeClient() throws IOException
{
//TODO: consider if we need it here.
CloudManager.closeCloudManager();
MonitoringMQHelper.closeInstance();
EventCorrelationEngine.closeInstance();
JCloudScaleReferenceManager.closeInstance();
if(instance == null)
return;
instance.close();
instance = null;
}
//-----------------------------------------------------------------
/**
* Gets the client-instance of the JCloudScale Configuration.
* @return The instance of the current JCloudScale configuration.
*/
public static JCloudScaleConfiguration getConfiguration()
{
if(configuration == null)
ensureConfigurationSpecified();
return configuration;
}
/**
* Sets the JCloudScale configuration to be used during the application runtime.
* <b>WARNING:</b> to ensure that the configuration is same for all components,
* configuration has to be specified prior to any interaction with JCloudScale.
* @param cfg An instance of the <b>JCloudScaleConfiguration</b> class that declares
* the behavior and preferences of the JCloudScale.
*/
public static synchronized void setConfiguration(JCloudScaleConfiguration cfg)
{
if(configuration != null && instance != null)
{ //we already have configuration and running instance. The old one was used, let's inform user.
JCloudScaleConfiguration.getLogger(cfg, JCloudScaleClient.class).warning("JCloudScale configuration redefinition: Replacing configuration instance. Some components might be still using the previous version of the configuration.");
}
configuration = cfg;
JCloudScaleConfiguration.setServerContext(false);
}
//-------------------------------------------------------------------
public synchronized void addProxy(UUID id, VirtualHostProxy proxy)
{
//TODO: this method holds references to HostProxy to be able to close them all on shutdown. Like a safe-plan.
// Consider if this is actually required, as they are closed somewhere else.
if(hostProxies.containsKey(id))
hostProxies.get(id).close();
hostProxies.put(id, proxy);
}
@Override
public void close() throws IOException
{
this.serverLogReceiver.close();
this.serverOutputReceiver.close();
if(classProvider != null)
this.classProvider.close();
if(this.riakPublisher != null)
this.riakPublisher.close();
if(this.mqPublisher != null)
this.mqPublisher.close();
//closing all connections we have. Just to avoid bugs with not closed connection.
if(MQWrapper.shutdownAllConnections())
log.warning("JCloudScaleClient found that there are some MQ connections not closed. Consider fixing this.");
if(mqServer != null)
{
try
{
mqServer.close();
}
catch(Exception ex)
{
log.warning("Failed to close Message Queue Server: "+ex);
}
}
//just the cleanup, in case we forgot to close something.
for(VirtualHostProxy proxy : hostProxies.values())
proxy.close();
}
//-------------------------LOADING CONFIGURATION FROM PROPERTIES-----------------------
private static synchronized void ensureConfigurationSpecified()
{
if(configuration != null)
return;
String configurationLocation = System.getProperty(JCLOUDSCALE_CONFIGURATION_PROPERTY);
if(configurationLocation != null)
{
//checking if this is file
File configFile = new File(configurationLocation);
if(configFile.exists() && configFile.isFile())
setConfiguration(loadConfigurationFromFile(configFile));
else
{ // checking if this is the class.
try
{
Class<?> clazz = Class.forName(configurationLocation);
setConfiguration(loadConfigurationFromClass(clazz));
}
catch(ClassNotFoundException ex)
{// no, we could not detect what is this. We have to fail.
throw new JCloudScaleException(
String.format("Failed to load configuration from %s: " +
"neither file \"%s\" nor class \"%s\" exist.",
configurationLocation, configFile.getAbsolutePath(), configurationLocation));
}
}
JCloudScaleConfiguration.getLogger(configuration, JCloudScaleClient.class)
.info("JCloudScale successfully loaded configuration from "+configurationLocation);
}
else
{
JCloudScaleClient.setConfiguration(new JCloudScaleConfigurationBuilder().build());
JCloudScaleConfiguration.getLogger(configuration, JCloudScaleClient.class)
.info("No configuration specified; JCloudScale is using default configuration.");
}
}
private static JCloudScaleConfiguration loadConfigurationFromClass(Class<?> clazz)
{
final Class<? extends Annotation> annotationClass = JCloudScaleConfigurationProvider.class;
try
{
Method[] methods = clazz.getDeclaredMethods();
for(Method method : methods)
{
if(!method.isAnnotationPresent(annotationClass))
continue;
// checking return type
if(!method.getReturnType().equals(JCloudScaleConfiguration.class))
throw new JCloudScaleException(String.format(
"The method %s of class %s is annotated with %s " +
"annotation, but return type is %s instead of %s",
method.getName(), clazz.getName(),
annotationClass.getName(),
method.getReturnType().getName(),
JCloudScaleConfiguration.class.getName()));
// checking if it is static
if(!Modifier.isStatic(method.getModifiers()))
throw new JCloudScaleException(String.format(
"The method %s of class %s is annotated with %s " +
"annotation, but is not static.",
method.getName(), clazz.getName(),
annotationClass.getName()));
//checking parameters
if(method.getParameterTypes().length > 0)
throw new JCloudScaleException(String.format(
"The method %s of class %s is annotated with %s " +
"annotation, but has input parameters. Cannot get configuration from method with parameters.",
method.getName(), clazz.getName(),
annotationClass.getName()));
if(!method.isAccessible())
method.setAccessible(true);
try
{
return (JCloudScaleConfiguration)method.invoke(null);
}
catch(Exception ex)
{
throw new JCloudScaleException(ex, String.format("Failed to invoke method %s from class %s to retrieve configuration.", method.getName(), clazz.getName()));
}
}
throw new JCloudScaleException(String.format("The class %s is specified in %s property, " +
"but has no static methods annotated with %s",
clazz.getName(), JCLOUDSCALE_CONFIGURATION_PROPERTY,
annotationClass.getName()));
}
catch(Exception ex)
{
throw new JCloudScaleException(ex, "Failed to load configuration from the class "+clazz.getName());
}
}
private static JCloudScaleConfiguration loadConfigurationFromFile(File configFile)
{
try
{
return JCloudScaleConfiguration.load(configFile);
}
catch(Exception ex)
{
throw new JCloudScaleException(ex, "Failed to load configuration from the file "+configFile.getAbsolutePath());
}
}
}
| |
/*
* Generated from CrashDataHeaders.bond (https://github.com/Microsoft/bond)
*/
package com.microsoft.applicationinsights.contracts;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import com.microsoft.telemetry.ITelemetry;
import com.microsoft.telemetry.ITelemetryData;
import com.microsoft.telemetry.IContext;
import com.microsoft.telemetry.IJsonSerializable;
import com.microsoft.telemetry.Base;
import com.microsoft.telemetry.Data;
import com.microsoft.telemetry.Domain;
import com.microsoft.telemetry.Extension;
import com.microsoft.telemetry.JsonHelper;
/**
* Data contract class CrashDataHeaders.
*/
public class CrashDataHeaders
implements IJsonSerializable
{
/**
* Backing field for property Id.
*/
private String id;
/**
* Backing field for property Process.
*/
private String process;
/**
* Backing field for property ProcessId.
*/
private int processId;
/**
* Backing field for property ParentProcess.
*/
private String parentProcess;
/**
* Backing field for property ParentProcessId.
*/
private int parentProcessId;
/**
* Backing field for property CrashThread.
*/
private int crashThread;
/**
* Backing field for property ApplicationPath.
*/
private String applicationPath;
/**
* Backing field for property ApplicationIdentifier.
*/
private String applicationIdentifier;
/**
* Backing field for property ApplicationBuild.
*/
private String applicationBuild;
/**
* Backing field for property ExceptionType.
*/
private String exceptionType;
/**
* Backing field for property ExceptionCode.
*/
private String exceptionCode;
/**
* Backing field for property ExceptionAddress.
*/
private String exceptionAddress;
/**
* Backing field for property ExceptionReason.
*/
private String exceptionReason;
/**
* Initializes a new instance of the CrashDataHeaders class.
*/
public CrashDataHeaders()
{
this.InitializeFields();
}
/**
* Gets the Id property.
*/
public String getId() {
return this.id;
}
/**
* Sets the Id property.
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the Process property.
*/
public String getProcess() {
return this.process;
}
/**
* Sets the Process property.
*/
public void setProcess(String value) {
this.process = value;
}
/**
* Gets the ProcessId property.
*/
public int getProcessId() {
return this.processId;
}
/**
* Sets the ProcessId property.
*/
public void setProcessId(int value) {
this.processId = value;
}
/**
* Gets the ParentProcess property.
*/
public String getParentProcess() {
return this.parentProcess;
}
/**
* Sets the ParentProcess property.
*/
public void setParentProcess(String value) {
this.parentProcess = value;
}
/**
* Gets the ParentProcessId property.
*/
public int getParentProcessId() {
return this.parentProcessId;
}
/**
* Sets the ParentProcessId property.
*/
public void setParentProcessId(int value) {
this.parentProcessId = value;
}
/**
* Gets the CrashThread property.
*/
public int getCrashThread() {
return this.crashThread;
}
/**
* Sets the CrashThread property.
*/
public void setCrashThread(int value) {
this.crashThread = value;
}
/**
* Gets the ApplicationPath property.
*/
public String getApplicationPath() {
return this.applicationPath;
}
/**
* Sets the ApplicationPath property.
*/
public void setApplicationPath(String value) {
this.applicationPath = value;
}
/**
* Gets the ApplicationIdentifier property.
*/
public String getApplicationIdentifier() {
return this.applicationIdentifier;
}
/**
* Sets the ApplicationIdentifier property.
*/
public void setApplicationIdentifier(String value) {
this.applicationIdentifier = value;
}
/**
* Gets the ApplicationBuild property.
*/
public String getApplicationBuild() {
return this.applicationBuild;
}
/**
* Sets the ApplicationBuild property.
*/
public void setApplicationBuild(String value) {
this.applicationBuild = value;
}
/**
* Gets the ExceptionType property.
*/
public String getExceptionType() {
return this.exceptionType;
}
/**
* Sets the ExceptionType property.
*/
public void setExceptionType(String value) {
this.exceptionType = value;
}
/**
* Gets the ExceptionCode property.
*/
public String getExceptionCode() {
return this.exceptionCode;
}
/**
* Sets the ExceptionCode property.
*/
public void setExceptionCode(String value) {
this.exceptionCode = value;
}
/**
* Gets the ExceptionAddress property.
*/
public String getExceptionAddress() {
return this.exceptionAddress;
}
/**
* Sets the ExceptionAddress property.
*/
public void setExceptionAddress(String value) {
this.exceptionAddress = value;
}
/**
* Gets the ExceptionReason property.
*/
public String getExceptionReason() {
return this.exceptionReason;
}
/**
* Sets the ExceptionReason property.
*/
public void setExceptionReason(String value) {
this.exceptionReason = value;
}
/**
* Serializes the beginning of this object to the passed in writer.
* @param writer The writer to serialize this object to.
*/
@Override
public void serialize(Writer writer) throws IOException
{
if (writer == null)
{
throw new IllegalArgumentException("writer");
}
writer.write('{');
this.serializeContent(writer);
writer.write('}');
}
/**
* Serializes the beginning of this object to the passed in writer.
* @param writer The writer to serialize this object to.
*/
protected String serializeContent(Writer writer) throws IOException
{
String prefix = "";
writer.write(prefix + "\"id\":");
writer.write(JsonHelper.convert(this.id));
prefix = ",";
if (!(this.process == null))
{
writer.write(prefix + "\"process\":");
writer.write(JsonHelper.convert(this.process));
prefix = ",";
}
if (!(this.processId == 0))
{
writer.write(prefix + "\"processId\":");
writer.write(JsonHelper.convert(this.processId));
prefix = ",";
}
if (!(this.parentProcess == null))
{
writer.write(prefix + "\"parentProcess\":");
writer.write(JsonHelper.convert(this.parentProcess));
prefix = ",";
}
if (!(this.parentProcessId == 0))
{
writer.write(prefix + "\"parentProcessId\":");
writer.write(JsonHelper.convert(this.parentProcessId));
prefix = ",";
}
if (!(this.crashThread == 0))
{
writer.write(prefix + "\"crashThread\":");
writer.write(JsonHelper.convert(this.crashThread));
prefix = ",";
}
if (!(this.applicationPath == null))
{
writer.write(prefix + "\"applicationPath\":");
writer.write(JsonHelper.convert(this.applicationPath));
prefix = ",";
}
if (!(this.applicationIdentifier == null))
{
writer.write(prefix + "\"applicationIdentifier\":");
writer.write(JsonHelper.convert(this.applicationIdentifier));
prefix = ",";
}
if (!(this.applicationBuild == null))
{
writer.write(prefix + "\"applicationBuild\":");
writer.write(JsonHelper.convert(this.applicationBuild));
prefix = ",";
}
if (!(this.exceptionType == null))
{
writer.write(prefix + "\"exceptionType\":");
writer.write(JsonHelper.convert(this.exceptionType));
prefix = ",";
}
if (!(this.exceptionCode == null))
{
writer.write(prefix + "\"exceptionCode\":");
writer.write(JsonHelper.convert(this.exceptionCode));
prefix = ",";
}
if (!(this.exceptionAddress == null))
{
writer.write(prefix + "\"exceptionAddress\":");
writer.write(JsonHelper.convert(this.exceptionAddress));
prefix = ",";
}
if (!(this.exceptionReason == null))
{
writer.write(prefix + "\"exceptionReason\":");
writer.write(JsonHelper.convert(this.exceptionReason));
prefix = ",";
}
return prefix;
}
/**
* Optionally initializes fields for the current context.
*/
protected void InitializeFields() {
}
}
| |
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.tool.assessment.ui.listener.delivery;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.LearningResourceStoreService;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Actor;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Context;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Object;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Result;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Statement;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Verb;
import org.sakaiproject.event.api.LearningResourceStoreService.LRS_Verb.SAKAI_VERB;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData;
import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentAccessControlIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.PublishedAssessmentIfc;
import org.sakaiproject.tool.assessment.facade.AgentFacade;
import org.sakaiproject.tool.assessment.facade.PublishedAssessmentFacade;
import org.sakaiproject.tool.assessment.services.FinFormatException;
import org.sakaiproject.tool.assessment.services.GradebookServiceException;
import org.sakaiproject.tool.assessment.services.GradingService;
import org.sakaiproject.tool.assessment.services.ItemService;
import org.sakaiproject.tool.assessment.services.SaLengthException;
import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService;
import org.sakaiproject.tool.assessment.ui.bean.delivery.DeliveryBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.FinBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.ItemContentsBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.SectionContentsBean;
import org.sakaiproject.tool.assessment.ui.bean.shared.PersonBean;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
import org.sakaiproject.tool.assessment.util.TextFormat;
/**
* <p>
* Title: Samigo
* </p>
* <p>
* Purpose: This listener is called in delivery when the user clicks on submit,
* save, or previous, next, toc.... It calculates and saves scores in DB
*
* @version $Id: SubmitToGradingActionListener.java 11634 2006-07-06 17:35:54Z
* daisyf@stanford.edu $
*/
public class SubmitToGradingActionListener implements ActionListener {
private static Log log = LogFactory
.getLog(SubmitToGradingActionListener.class);
/**
* The publishedAssesmentService
*/
private PublishedAssessmentService publishedAssesmentService = new PublishedAssessmentService();
/**
* ACTION.
*
* @param ae
* @throws AbortProcessingException
*/
public void processAction(ActionEvent ae) throws AbortProcessingException, FinFormatException, SaLengthException {
try {
log.debug("SubmitToGradingActionListener.processAction() ");
// get managed bean
DeliveryBean delivery = (DeliveryBean) ContextUtil
.lookupBean("delivery");
if ((ContextUtil.lookupParam("showfeedbacknow") != null
&& "true"
.equals(ContextUtil.lookupParam("showfeedbacknow")) || delivery
.getActionMode() == DeliveryBean.PREVIEW_ASSESSMENT))
delivery.setForGrade(false);
// get assessment
PublishedAssessmentFacade publishedAssessment = null;
if (delivery.getPublishedAssessment() != null)
publishedAssessment = delivery.getPublishedAssessment();
else {
publishedAssessment = publishedAssesmentService
.getPublishedAssessment(delivery.getAssessmentId());
delivery.setPublishedAssessment(publishedAssessment);
}
HashMap invalidFINMap = new HashMap();
ArrayList invalidSALengthList = new ArrayList();
AssessmentGradingData adata = submitToGradingService(ae, publishedAssessment, delivery, invalidFINMap, invalidSALengthList);
// set AssessmentGrading in delivery
delivery.setAssessmentGrading(adata);
if (adata.getForGrade()) {
Event event = EventTrackingService.newEvent("", adata.getPublishedAssessmentTitle(), true);
LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager
.get("org.sakaiproject.event.api.LearningResourceStoreService");
if (null != lrss && lrss.getEventActor(event) != null) {
lrss.registerStatement(getStatementForGradedAssessment(adata, lrss.getEventActor(event), publishedAssessment),
"sakai.samigo");
}
}
// set url & confirmation after saving the record for grade
if (adata != null && delivery.getForGrade())
setConfirmation(adata, publishedAssessment, delivery);
if (isForGrade(adata) && !isUnlimited(publishedAssessment)) {
delivery.setSubmissionsRemaining(delivery
.getSubmissionsRemaining() - 1);
}
if (invalidFINMap.size() != 0) {
delivery.setIsAnyInvalidFinInput(true);
throw new FinFormatException ("Not a valid FIN input");
}
if (invalidSALengthList.size() != 0) {
delivery.setIsAnyInvalidFinInput(true);
throw new SaLengthException ("Short Answer input is too long");
}
delivery.setIsAnyInvalidFinInput(false);
} catch (GradebookServiceException ge) {
ge.printStackTrace();
FacesContext context = FacesContext.getCurrentInstance();
String err = (String) ContextUtil.getLocalizedString(
"org.sakaiproject.tool.assessment.bundle.AuthorMessages",
"gradebook_exception_error");
context.addMessage(null, new FacesMessage(err));
return;
}
}
private boolean isForGrade(AssessmentGradingData aData) {
if (aData != null)
return (Boolean.TRUE).equals(aData.getForGrade());
else
return false;
}
private boolean isUnlimited(PublishedAssessmentFacade publishedAssessment) {
return (Boolean.TRUE).equals(publishedAssessment
.getAssessmentAccessControl().getUnlimitedSubmissions());
}
/**
* This method set the url & confirmation string for submitted.jsp. The
* confirmation string =
* assessmentGradingId-publishedAssessmentId-agentId-submitteddate
*
* @param adata
* @param publishedAssessment
* @param delivery
*/
private void setConfirmation(AssessmentGradingData adata,
PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery) {
if (publishedAssessment.getAssessmentAccessControl() != null) {
setFinalPage(publishedAssessment, delivery);
setSubmissionMessage(publishedAssessment, delivery);
}
setConfirmationId(adata, publishedAssessment, delivery);
}
/**
* Set confirmationId which is AssessmentGradingId-TimeStamp.
*
* @param adata
* @param publishedAssessment
* @param delivery
*/
private void setConfirmationId(AssessmentGradingData adata,
PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery) {
delivery.setConfirmation(adata.getAssessmentGradingId() + "-"
+ publishedAssessment.getPublishedAssessmentId() + "-"
+ adata.getAgentId() + "-"
+ adata.getSubmittedDate().toString());
}
/**
* Set the submission message.
*
* @param publishedAssessment
* @param delivery
*/
private void setSubmissionMessage(
PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery) {
String submissionMessage = publishedAssessment
.getAssessmentAccessControl().getSubmissionMessage();
if (submissionMessage != null)
delivery.setSubmissionMessage(submissionMessage);
}
/**
* Set finalPage url in delivery bean.
*
* @param publishedAssessment
* @param delivery
*/
private void setFinalPage(PublishedAssessmentFacade publishedAssessment,
DeliveryBean delivery) {
String url = publishedAssessment.getAssessmentAccessControl()
.getFinalPageUrl();
if (url != null)
url = url.trim();
delivery.setUrl(url);
}
/**
* Invoke submission and return the grading data
*
* @param publishedAssessment
* @param delivery
* @return
*/
private synchronized AssessmentGradingData submitToGradingService(
ActionEvent ae, PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery, HashMap invalidFINMap, ArrayList invalidSALengthList) throws FinFormatException {
log.debug("****1a. inside submitToGradingService ");
String submissionId = "";
HashSet<ItemGradingData> itemGradingHash = new HashSet<ItemGradingData>();
// daisyf decoding: get page contents contains SectionContentsBean, a
// wrapper for SectionDataIfc
Iterator<SectionContentsBean> iter = delivery.getPageContents().getPartsContents()
.iterator();
log.debug("****1b. inside submitToGradingService, iter= " + iter);
HashSet<ItemGradingData> adds = new HashSet<ItemGradingData>();
HashSet<ItemGradingData> removes = new HashSet<ItemGradingData>();
// we go through all the answer collected from JSF form per each
// publsihedItem and
// work out which answer is an new addition and in cases like
// MC/MCMR/Survey, we will
// discard any existing one and just save the new one. For other
// question type, we
// simply modify the publishedText or publishedAnswer of the existing
// ones.
while (iter.hasNext()) {
SectionContentsBean part = iter.next();
log.debug("****1c. inside submitToGradingService, part " + part);
Iterator<ItemContentsBean> iter2 = part.getItemContents().iterator();
while (iter2.hasNext()) { // go through each item from form
ItemContentsBean item = iter2.next();
log.debug("****** before prepareItemGradingPerItem");
prepareItemGradingPerItem(ae, delivery, item, adds, removes);
log.debug("****** after prepareItemGradingPerItem");
}
}
AssessmentGradingData adata = persistAssessmentGrading(ae, delivery,
itemGradingHash, publishedAssessment, adds, removes, invalidFINMap, invalidSALengthList);
StringBuffer redrawAnchorName = new StringBuffer("p");
String tmpAnchorName = "";
Iterator<SectionContentsBean> iterPart = delivery.getPageContents().getPartsContents().iterator();
while (iterPart.hasNext()) {
SectionContentsBean part = iterPart.next();
String partSeq = part.getNumber();
Iterator<ItemContentsBean> iterItem = part.getItemContents().iterator();
while (iterItem.hasNext()) { // go through each item from form
ItemContentsBean item = iterItem.next();
String itemSeq = item.getSequence();
Long itemId = item.getItemData().getItemId();
if (item.getItemData().getTypeId() == 5) {
if (invalidSALengthList.contains(itemId)) {
item.setIsInvalidSALengthInput(true);
redrawAnchorName.append(partSeq);
redrawAnchorName.append("q");
redrawAnchorName.append(itemSeq);
if (tmpAnchorName.equals("") || tmpAnchorName.compareToIgnoreCase(redrawAnchorName.toString()) > 0) {
tmpAnchorName = redrawAnchorName.toString();
}
}
else {
item.setIsInvalidSALengthInput(false);
}
}
else if (item.getItemData().getTypeId() == 11) {
if (invalidFINMap.containsKey(itemId)) {
item.setIsInvalidFinInput(true);
redrawAnchorName.append(partSeq);
redrawAnchorName.append("q");
redrawAnchorName.append(itemSeq);
if (tmpAnchorName.equals("") || tmpAnchorName.compareToIgnoreCase(redrawAnchorName.toString()) > 0) {
tmpAnchorName = redrawAnchorName.toString();
}
ArrayList list = (ArrayList) invalidFINMap.get(itemId);
List<FinBean> finArray = item.getFinArray();
Iterator<FinBean> iterFin = finArray.iterator();
while (iterFin.hasNext()) {
FinBean finBean = iterFin.next();
if (finBean.getItemGradingData() != null) {
Long itemGradingId = finBean.getItemGradingData().getItemGradingId();
if (list.contains(itemGradingId)) {
finBean.setIsCorrect(false);
}
}
}
}
else {
item.setIsInvalidFinInput(false);
}
}
}
}
if (tmpAnchorName != null && !tmpAnchorName.equals("")) {
delivery.setRedrawAnchorName(tmpAnchorName.toString());
}
else {
delivery.setRedrawAnchorName("");
}
delivery.setSubmissionId(submissionId);
delivery.setSubmissionTicket(submissionId);// is this the same thing?
// hmmmm
delivery.setSubmissionDate(new Date());
delivery.setSubmitted(true);
return adata;
}
private AssessmentGradingData persistAssessmentGrading(ActionEvent ae,
DeliveryBean delivery, HashSet<ItemGradingData> itemGradingHash,
PublishedAssessmentFacade publishedAssessment, HashSet<ItemGradingData> adds,
HashSet<ItemGradingData> removes, HashMap invalidFINMap, ArrayList invalidSALengthList) throws FinFormatException {
AssessmentGradingData adata = null;
if (delivery.getAssessmentGrading() != null) {
adata = delivery.getAssessmentGrading();
}
GradingService service = new GradingService();
log.debug("**adata=" + adata);
if (adata == null) { // <--- this shouldn't happened 'cos it should
// have been created by BeginDelivery
adata = makeNewAssessmentGrading(publishedAssessment, delivery,
itemGradingHash);
delivery.setAssessmentGrading(adata);
} else {
// 1. add all the new itemgrading for MC/Survey and discard any
// itemgrading for MC/Survey
// 2. add any modified SAQ/TF/FIB/Matching/MCMR/FIN
// 3. save any modified Mark for Review in FileUplaod/Audio
HashMap<Long, ItemDataIfc> fibMap = getFIBMap(publishedAssessment);
HashMap<Long, ItemDataIfc> finMap = getFINMap(publishedAssessment);
HashMap<Long, ItemDataIfc> calcQuestionMap = getCalcQuestionMap(publishedAssessment); // CALCULATED_QUESTION
HashMap<Long, ItemDataIfc> imagQuestionMap = getImagQuestionMap(publishedAssessment); // IMAGEMAP_QUESTION
HashMap<Long, ItemDataIfc> mcmrMap = getMCMRMap(publishedAssessment);
HashMap<Long, ItemDataIfc> emiMap = getEMIMap(publishedAssessment);
Set<ItemGradingData> itemGradingSet = adata.getItemGradingSet();
log.debug("*** 2a. before removal & addition " + (new Date()));
if (itemGradingSet != null) {
log.debug("*** 2aa. removing old itemGrading " + (new Date()));
itemGradingSet.removeAll(removes);
service.deleteAll(removes);
// refresh itemGradingSet & assessmentGrading after removal
log.debug("*** 2ab. reload itemGradingSet " + (new Date()));
itemGradingSet = service.getItemGradingSet(adata
.getAssessmentGradingId().toString());
log.debug("*** 2ac. load assessmentGarding " + (new Date()));
adata = service.load(adata.getAssessmentGradingId().toString(), false);
Iterator<ItemGradingData> iter = adds.iterator();
while (iter.hasNext()) {
iter.next().setAssessmentGradingId(adata
.getAssessmentGradingId());
}
// make update to old item and insert new item
// and we will only update item that has been changed
log
.debug("*** 2ad. set assessmentGrading with new/updated itemGrading "
+ (new Date()));
log
.debug("Submitforgrading: before calling .....................oldItemGradingSet.size = "
+ itemGradingSet.size());
log.debug("Submitforgrading: newItemGradingSet.size = "
+ adds.size());
HashSet<ItemGradingData> updateItemGradingSet = getUpdateItemGradingSet(
itemGradingSet, adds, fibMap, finMap, calcQuestionMap,imagQuestionMap,mcmrMap, emiMap, adata);
adata.setItemGradingSet(updateItemGradingSet);
}
}
adata.setSubmitFromTimeoutPopup(delivery.getsubmitFromTimeoutPopup());
adata.setIsLate(isLate(publishedAssessment, delivery.getsubmitFromTimeoutPopup()));
adata.setForGrade(Boolean.valueOf(delivery.getForGrade()));
// If this assessment grading data has been updated (comments or adj. score) by grader and then republic and allow student to resubmit
// when the student submit his answers, we update the status back to 0 and remove the grading entry/info.
if (AssessmentGradingData.ASSESSMENT_UPDATED_NEED_RESUBMIT.equals(adata.getStatus()) || AssessmentGradingData.ASSESSMENT_UPDATED.equals(adata.getStatus())) {
adata.setStatus(Integer.valueOf(0));
adata.setGradedBy(null);
adata.setGradedDate(null);
adata.setComments(null);
adata.setTotalOverrideScore(Double.valueOf(0d));
}
log.debug("*** 2b. before storingGrades, did all the removes and adds "
+ (new Date()));
if (delivery.getNavigation().equals("1") && ae != null && "showFeedback".equals(ae.getComponent().getId())) {
log.debug("Do not persist to db if it is linear access and the action is show feedback");
// 3. let's build three HashMap with (publishedItemId, publishedItem),
// (publishedItemTextId, publishedItem), (publishedAnswerId,
// publishedItem) to help with storing grades to adata only, not db
HashMap publishedItemHash = delivery.getPublishedItemHash();
HashMap publishedItemTextHash = delivery.getPublishedItemTextHash();
HashMap publishedAnswerHash = delivery.getPublishedAnswerHash();
service.storeGrades(adata, publishedAssessment, publishedItemHash, publishedItemTextHash, publishedAnswerHash, false, invalidFINMap, invalidSALengthList);
}
else {
log.debug("Persist to db otherwise");
// The following line seems redundant. I cannot see a reason why we need to save the adata here
// and then again in following service.storeGrades(). Comment it out.
//service.saveOrUpdateAssessmentGrading(adata);
log.debug("*** 3. before storingGrades, did all the removes and adds " + (new Date()));
// 3. let's build three HashMap with (publishedItemId, publishedItem),
// (publishedItemTextId, publishedItem), (publishedAnswerId,
// publishedItem) to help with storing grades to adata and then persist to DB
HashMap publishedItemHash = delivery.getPublishedItemHash();
HashMap publishedItemTextHash = delivery.getPublishedItemTextHash();
HashMap publishedAnswerHash = delivery.getPublishedAnswerHash();
service.storeGrades(adata, publishedAssessment, publishedItemHash, publishedItemTextHash, publishedAnswerHash, invalidFINMap, invalidSALengthList);
}
return adata;
}
private HashMap<Long, ItemDataIfc> getFIBMap(PublishedAssessmentIfc publishedAssessment) {
return publishedAssesmentService.prepareFIBItemHash(publishedAssessment);
}
private HashMap<Long, ItemDataIfc> getFINMap(PublishedAssessmentIfc publishedAssessment){
return publishedAssesmentService.prepareFINItemHash(publishedAssessment);
}
/**
* CALCULATED_QUESTION
* @param publishedAssessment
* @return map of calc items
*/
private HashMap<Long, ItemDataIfc> getCalcQuestionMap(PublishedAssessmentIfc publishedAssessment){
return (HashMap<Long, ItemDataIfc>) publishedAssesmentService.prepareCalcQuestionItemHash(publishedAssessment);
}
/**
* IMAGEMAP_QUESTION
* @param publishedAssessment
* @return map of image items
*/
private HashMap<Long, ItemDataIfc> getImagQuestionMap(PublishedAssessmentIfc publishedAssessment){
return (HashMap<Long, ItemDataIfc>) publishedAssesmentService.prepareImagQuestionItemHash(publishedAssessment);
}
private HashMap<Long, ItemDataIfc> getMCMRMap(PublishedAssessmentIfc publishedAssessment) {
return publishedAssesmentService.prepareMCMRItemHash(publishedAssessment);
}
private HashMap<Long, ItemDataIfc> getEMIMap(PublishedAssessmentIfc publishedAssessment) {
PublishedAssessmentService s = new PublishedAssessmentService();
return s.prepareEMIItemHash(publishedAssessment);
}
private HashSet<ItemGradingData> getUpdateItemGradingSet(Set oldItemGradingSet,
Set<ItemGradingData> newItemGradingSet, HashMap<Long, ItemDataIfc> fibMap, HashMap<Long, ItemDataIfc> finMap, HashMap<Long, ItemDataIfc> calcQuestionMap, HashMap<Long, ItemDataIfc> imagQuestionMap,HashMap<Long, ItemDataIfc> mcmrMap,
HashMap<Long, ItemDataIfc> emiMap, AssessmentGradingData adata) {
log.debug("Submitforgrading: oldItemGradingSet.size = "
+ oldItemGradingSet.size());
log.debug("Submitforgrading: newItemGradingSet.size = "
+ newItemGradingSet.size());
HashSet<ItemGradingData> updateItemGradingSet = new HashSet<ItemGradingData>();
Iterator iter = oldItemGradingSet.iterator();
HashMap<Long, ItemGradingData> map = new HashMap<Long, ItemGradingData>();
while (iter.hasNext()) { // create a map with old itemGrading
ItemGradingData item = (ItemGradingData) iter.next();
map.put(item.getItemGradingId(), item);
}
// go through new itemGrading
Iterator<ItemGradingData> iter1 = newItemGradingSet.iterator();
while (iter1.hasNext()) {
ItemGradingData newItem = iter1.next();
ItemGradingData oldItem = map.get(newItem
.getItemGradingId());
if (oldItem != null) {
// itemGrading exists and value has been change, then need
// update
Boolean oldReview = oldItem.getReview();
Boolean newReview = newItem.getReview();
Long oldAnswerId = oldItem.getPublishedAnswerId();
Long newAnswerId = newItem.getPublishedAnswerId();
String oldRationale = oldItem.getRationale();
String newRationale = TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, newItem.getRationale());
String oldAnswerText = oldItem.getAnswerText();
// Change to allow student submissions in rich-text [SAK-17021]
String newAnswerText = ContextUtil.stringWYSIWYG(newItem.getAnswerText());
if ((oldReview != null && !oldReview.equals(newReview))
|| (newReview!=null && !newReview.equals(oldReview))
|| (oldAnswerId != null && !oldAnswerId
.equals(newAnswerId))
|| (newAnswerId != null && !newAnswerId
.equals(oldAnswerId))
|| (oldRationale != null && !oldRationale
.equals(newRationale))
|| (newRationale != null && !newRationale
.equals(oldRationale))
|| (oldAnswerText != null && !oldAnswerText
.equals(newAnswerText))
|| (newAnswerText != null && !newAnswerText
.equals(oldAnswerText))
|| fibMap.get(oldItem.getPublishedItemId()) != null
|| emiMap.get(oldItem.getPublishedItemId()) != null
|| finMap.get(oldItem.getPublishedItemId())!=null
|| calcQuestionMap.get(oldItem.getPublishedItemId())!=null
|| imagQuestionMap.get(oldItem.getPublishedItemId())!=null
|| mcmrMap.get(oldItem.getPublishedItemId()) != null) {
oldItem.setReview(newItem.getReview());
oldItem.setPublishedAnswerId(newItem.getPublishedAnswerId());
oldItem.setRationale(newRationale);
oldItem.setAnswerText(newAnswerText);
oldItem.setSubmittedDate(new Date());
oldItem.setAutoScore(newItem.getAutoScore());
oldItem.setOverrideScore(newItem.getOverrideScore());
updateItemGradingSet.add(oldItem);
// log.debug("**** SubmitToGrading: need update
// "+oldItem.getItemGradingId());
}
} else { // itemGrading from new set doesn't exist, add to set in
// this case
// log.debug("**** SubmitToGrading: need add new item");
//a new item should always have the grading ID set to null
newItem.setItemGradingId(null);
newItem.setAgentId(adata.getAgentId());
updateItemGradingSet.add(newItem);
}
}
return updateItemGradingSet;
}
/**
* Make a new AssessmentGradingData object for delivery
*
* @param publishedAssessment
* the PublishedAssessmentFacade
* @param delivery
* the DeliveryBean
* @param itemGradingHash
* the item data
* @return
*/
private AssessmentGradingData makeNewAssessmentGrading(
PublishedAssessmentFacade publishedAssessment,
DeliveryBean delivery, HashSet<ItemGradingData> itemGradingHash) {
PersonBean person = (PersonBean) ContextUtil.lookupBean("person");
AssessmentGradingData adata = new AssessmentGradingData();
adata.setAgentId(person.getId());
adata.setPublishedAssessmentId(publishedAssessment
.getPublishedAssessmentId());
adata.setForGrade(Boolean.valueOf(delivery.getForGrade()));
adata.setItemGradingSet(itemGradingHash);
adata.setAttemptDate(new Date());
adata.setIsLate(Boolean.FALSE);
adata.setStatus(Integer.valueOf(0));
adata.setTotalOverrideScore(Double.valueOf(0));
adata.setTimeElapsed(Integer.valueOf("0"));
return adata;
}
/**
* This is specific to JSF - question for each type is layout differently in
* JSF and the answers submitted are being collected differently too. e.g.
* for each MC/Survey/MCMR, an itemgrading is associated with each choice.
* whereas there is only one itemgrading per each question for SAQ/TF/Audio,
* and one for each blank in FIB. To understand the logic in this method, it
* is best to study jsf/delivery/item/deliver*.jsp
*/
private void prepareItemGradingPerItem(ActionEvent ae, DeliveryBean delivery,
ItemContentsBean item, HashSet<ItemGradingData> adds, HashSet<ItemGradingData> removes) {
List<ItemGradingData> grading = item.getItemGradingDataArray();
int typeId = item.getItemData().getTypeId().intValue();
//no matter what kinds of type questions, if it marks as review, add it in.
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = grading.get(m);
if (itemgrading.getItemGradingId() == null && (itemgrading.getReview() != null && itemgrading.getReview().booleanValue()) == true) {
adds.addAll(grading);
break;
}
}
// 1. add all the new itemgrading for MC/Survey and discard any
// itemgrading for MC/Survey
// 2. add any modified SAQ/TF/FIB/Matching/MCMR/Audio/FIN
switch (typeId) {
case 1: // MC
case 12: // MC Single Selection
case 3: // Survey
boolean answerModified = false;
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = grading.get(m);
if (itemgrading.getItemGradingId() == null
|| itemgrading.getItemGradingId().intValue() <= 0) { // =>
// new answer
if (itemgrading.getPublishedAnswerId() != null || (itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
answerModified = true;
break;
}
}
}
// Click the Reset Selection link
if(item.getUnanswered()) {
answerModified = true;
}
if (answerModified) {
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = grading
.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
// remove all old answer for MC & Surevy
removes.add(itemgrading);
} else {
// add new answer
if (itemgrading.getPublishedAnswerId() != null
|| itemgrading.getAnswerText() != null
|| (itemgrading.getRationale() != null
&& !itemgrading.getRationale().trim().equals(""))) {
// null=> skipping this question
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
if (itemgrading.getRationale() != null && itemgrading.getRationale().length() > 0) {
itemgrading.setRationale(TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, itemgrading.getRationale()));
}
// the rest of the info is collected by
// ItemContentsBean via JSF form
adds.add(itemgrading);
}
}
}
}
else{
handleMarkForReview(grading, adds);
}
break;
case 4: // T/F
case 9: // Matching
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = grading.get(m);
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
}
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = grading.get(m);
if ((itemgrading.getItemGradingId() != null && itemgrading.getItemGradingId().intValue() > 0) ||
(itemgrading.getPublishedAnswerId() != null || itemgrading.getAnswerText() != null) ||
(itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
adds.addAll(grading);
break;
}
}
break;
case 5: // SAQ
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = grading.get(m);
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
}
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
adds.addAll(grading);
break;
} else if (itemgrading.getAnswerText() != null && !itemgrading.getAnswerText().equals("")) {
// Change to allow student submissions in rich-text [SAK-17021]
itemgrading.setAnswerText(ContextUtil.stringWYSIWYG(itemgrading.getAnswerText()));
adds.addAll(grading);
break;
}
}
break;
case 8: // FIB
case 15: // CALCULATED_QUESTION
case 16: //IMAGEMAP_QUESTION
case 11: // FIN
boolean addedToAdds = false;
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = grading.get(m);
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
}
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
adds.addAll(grading);
break;
} else if (itemgrading.getAnswerText() != null && !itemgrading.getAnswerText().equals("")) {
String s = itemgrading.getAnswerText();
log.debug("s = " + s);
// Change to allow student submissions in rich-text [SAK-17021]
itemgrading.setAnswerText(ContextUtil.stringWYSIWYG(s));
adds.addAll(grading);
if (!addedToAdds) {
adds.addAll(grading);
addedToAdds = true;
}
}
}
break;
case 2: // MCMR
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
// old answer, check which one to keep, not keeping null answer
if (itemgrading.getPublishedAnswerId() != null ||
(itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
adds.add(itemgrading);
} else {
removes.add(itemgrading);
}
} else {
// new answer
if (itemgrading.getPublishedAnswerId() != null ||
(itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
// new addition not accepting any new answer with null for MCMR
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
adds.add(itemgrading);
}
}
}
break;
case 14: // Extended Matching Item
Long assessmentGradingId = delivery.getAssessmentGrading().getAssessmentGradingId();
Long publishedItemId = item.getItemData().getItemId();
log.debug("Updating answer set for EMI question: publishedItemId=" + publishedItemId + " grading.size()=" + grading.size() +
" item id=" + item.getItemData().getItemId() + " assessmentGradingId=" + assessmentGradingId);
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
// old answer, check which one to keep, not keeping null answer
if (itemgrading.getPublishedAnswerId() != null) {
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
adds.add(itemgrading);
log.debug("adding answer: " + itemgrading.getItemGradingId());
} else {
removes.add(itemgrading);
log.debug("remove answer: " + itemgrading.getItemGradingId());
}
} else {
// new answer
if (itemgrading.getPublishedAnswerId() != null) {
// new addition not accepting any new answer with null for EMI
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
adds.add(itemgrading);
log.debug("adding new answer answer: " + itemgrading.getItemGradingId());
}
}
}
// We need to remove any answer (response) items in the storage that are not in the above lists
removes.addAll(identifyOrphanedEMIAnswers(grading, publishedItemId, assessmentGradingId));
break;
case 6: // File Upload
case 7: // Audio
handleMarkForReview(grading, adds);
break;
case 13: //Matrix Choices question
answerModified = false;
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = grading.get(m);
if (itemgrading != null) {
log.debug("\n:ItemId>>itemTextId>>answerId "+ itemgrading.getPublishedItemId()+itemgrading.getPublishedItemTextId()+itemgrading.getPublishedAnswerId()+"\n");
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
if (itemgrading.getRationale() != null && itemgrading.getRationale().length() > 0) {
itemgrading.setRationale(TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, itemgrading.getRationale()));
}
adds.add(itemgrading);
}
}
break;
}
// if it is linear access and there is not answer, we add an fake ItemGradingData
String actionCommand = "";
if (ae != null) {
actionCommand = ae.getComponent().getId();
log.debug("ae is not null, getActionCommand() = " + actionCommand);
}
else {
log.debug("ae is null");
}
if ("1".equals(delivery.getNavigation()) && adds.size() ==0 && !"showFeedback".equals(actionCommand)) {
log.debug("enter here");
Long assessmentGradingId = delivery.getAssessmentGrading().getAssessmentGradingId();
Long publishedItemId = item.getItemData().getItemId();
log.debug("assessmentGradingId = " + assessmentGradingId);
log.debug("publishedItemId = " + publishedItemId);
GradingService gradingService = new GradingService();
if (gradingService.getItemGradingData(assessmentGradingId.toString(), publishedItemId.toString()) == null) {
log.debug("Create a new (fake) ItemGradingData");
ItemGradingData itemGrading = new ItemGradingData();
itemGrading.setAssessmentGradingId(assessmentGradingId);
itemGrading.setAgentId(AgentFacade.getAgentString());
itemGrading.setPublishedItemId(publishedItemId);
ItemService itemService = new ItemService();
Long itemTextId = itemService.getItemTextId(publishedItemId);
log.debug("itemTextId = " + itemTextId);
if(itemTextId != -1){
itemGrading.setPublishedItemTextId(itemTextId);
adds.add(itemGrading);
}
}
else {
// For File Upload question, if user clicks on "Upload", a ItemGradingData will be created.
// Therefore, when user clicks on "Next", we shouldn't create it again.
// Same for Audio question, if user records anything, a ItemGradingData will be created.
// We don't create it again when user clicks on "Next".
if ((typeId == 6 || typeId == 7)) {
log.debug("File Upload or Audio! Do not create empty ItemGradingData if there exists one");
}
}
}
}
/**
* Identify the items in an EMI Answer that are orphaned
* @param grading
* @return a list of ItemGradings to be removed
*/
private Collection<ItemGradingData> identifyOrphanedEMIAnswers(List<ItemGradingData> grading, Long publishedItemId, Long assessmentGradingId) {
Set<ItemGradingData> ret = new HashSet<ItemGradingData>();
List<Long> itemsInGrading = new ArrayList<Long>();
for (int i = 0; i < grading.size(); i++) {
ItemGradingData data = grading.get(i);
itemsInGrading.add(data.getItemGradingId());
}
GradingService gradingService = new GradingService();
List<ItemGradingData> data = gradingService.getAllItemGradingDataForItemInGrading(assessmentGradingId, publishedItemId);
log.debug("got " + data.size() + " answers from storage");
log.debug("got " + grading.size() + " items in the grading object");
for (int i = 0; i < data.size(); i++) {
ItemGradingData item = data.get(i);
if (!itemsInGrading.contains(item.getItemGradingId())) {
log.debug("we will remove " + item.getItemGradingId());
ret.add(item);
}
}
return ret;
}
private void handleMarkForReview(List<ItemGradingData> grading, HashSet<ItemGradingData> adds){
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0
&& itemgrading.getReview() != null) {
// we will save itemgrading even though answer was not modified
// 'cos mark for review may have been modified
adds.add(itemgrading);
}
}
}
private Boolean isLate(PublishedAssessmentIfc pub, boolean submitFromTimeoutPopup) {
AssessmentAccessControlIfc a = pub.getAssessmentAccessControl();
// If submit from timeout popup, we don't record LATE
if(submitFromTimeoutPopup) {
return Boolean.FALSE;
}
if (a.getDueDate() != null && a.getDueDate().before(new Date()))
return Boolean.TRUE;
else
return Boolean.FALSE;
}
private LRS_Statement getStatementForGradedAssessment(AssessmentGradingData gradingData, LRS_Actor student,
PublishedAssessmentFacade publishedAssessment) {
LRS_Verb verb = new LRS_Verb(SAKAI_VERB.scored);
LRS_Object lrsObject = new LRS_Object(ServerConfigurationService.getPortalUrl() + "/assessment", "received-grade-assessment");
HashMap<String, String> nameMap = new HashMap<String, String>();
nameMap.put("en-US", "User received a grade");
lrsObject.setActivityName(nameMap);
HashMap<String, String> descMap = new HashMap<String, String>();
descMap.put("en-US", "User received a grade for their assessment: " + publishedAssessment.getTitle() + "; Submitted: "
+ (gradingData.getIsLate() ? "late" : "on time"));
lrsObject.setDescription(descMap);
LRS_Context context = new LRS_Context("other", "assessment");
LRS_Statement statement = new LRS_Statement(student, verb, lrsObject, getLRS_Result(gradingData, publishedAssessment), context);
return statement;
}
private LRS_Result getLRS_Result(AssessmentGradingData gradingData, PublishedAssessmentFacade publishedAssessment) {
double score = gradingData.getFinalScore();
LRS_Result result = new LRS_Result(new Double(score), new Double(0.0), new Double(publishedAssessment.getTotalScore()), null);
result.setCompletion(true);
return result;
}
}
| |
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2021 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.minio.http;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.minio.org.apache.commons.validator.routines.InetAddressValidator;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
/** HTTP utilities. */
public class HttpUtils {
public static final byte[] EMPTY_BODY = new byte[] {};
public static void validateNotNull(Object arg, String argName) {
if (arg == null) {
throw new IllegalArgumentException(argName + " must not be null.");
}
}
public static void validateNotEmptyString(String arg, String argName) {
validateNotNull(arg, argName);
if (arg.isEmpty()) {
throw new IllegalArgumentException(argName + " must be a non-empty string.");
}
}
public static void validateNullOrNotEmptyString(String arg, String argName) {
if (arg != null && arg.isEmpty()) {
throw new IllegalArgumentException(argName + " must be a non-empty string.");
}
}
public static void validateHostnameOrIPAddress(String endpoint) {
// Check endpoint is IPv4 or IPv6.
if (InetAddressValidator.getInstance().isValid(endpoint)) {
return;
}
// Check endpoint is a hostname.
// Refer https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
// why checks are done like below
if (endpoint.length() < 1 || endpoint.length() > 253) {
throw new IllegalArgumentException("invalid hostname");
}
for (String label : endpoint.split("\\.")) {
if (label.length() < 1 || label.length() > 63) {
throw new IllegalArgumentException("invalid hostname");
}
if (!(label.matches("^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$"))) {
throw new IllegalArgumentException("invalid hostname");
}
}
}
public static void validateUrl(HttpUrl url) {
if (!url.encodedPath().equals("/")) {
throw new IllegalArgumentException("no path allowed in endpoint " + url);
}
}
public static HttpUrl getBaseUrl(String endpoint) {
validateNotEmptyString(endpoint, "endpoint");
HttpUrl url = HttpUrl.parse(endpoint);
if (url == null) {
validateHostnameOrIPAddress(endpoint);
url = new HttpUrl.Builder().scheme("https").host(endpoint).build();
} else {
validateUrl(url);
}
return url;
}
public static String getHostHeader(HttpUrl url) {
// ignore port when port and service matches i.e HTTP -> 80, HTTPS -> 443
if ((url.scheme().equals("http") && url.port() == 80)
|| (url.scheme().equals("https") && url.port() == 443)) {
return url.host();
}
return url.host() + ":" + url.port();
}
/**
* copied logic from
* https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java
*/
public static OkHttpClient enableExternalCertificates(OkHttpClient httpClient, String filename)
throws GeneralSecurityException, IOException {
Collection<? extends Certificate> certificates = null;
try (FileInputStream fis = new FileInputStream(filename)) {
certificates = CertificateFactory.getInstance("X.509").generateCertificates(fis);
}
if (certificates == null || certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
char[] password = "password".toCharArray(); // Any password will work.
// Put the certificates a key store.
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
// By convention, 'null' creates an empty key store.
keyStore.load(null, password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = Integer.toString(index++);
keyStore.setCertificateEntry(certificateAlias, certificate);
}
// Use it to build an X509 trust manager.
KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
return httpClient
.newBuilder()
.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustManagers[0])
.build();
}
public static OkHttpClient newDefaultHttpClient(
long connectTimeout, long writeTimeout, long readTimeout) {
OkHttpClient httpClient =
new OkHttpClient()
.newBuilder()
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
.readTimeout(readTimeout, TimeUnit.MILLISECONDS)
.protocols(Arrays.asList(Protocol.HTTP_1_1))
.build();
String filename = System.getenv("SSL_CERT_FILE");
if (filename != null && !filename.isEmpty()) {
try {
httpClient = enableExternalCertificates(httpClient, filename);
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException(e);
}
}
return httpClient;
}
@SuppressFBWarnings(value = "SIC", justification = "Should not be used in production anyways.")
public static OkHttpClient disableCertCheck(OkHttpClient client)
throws KeyManagementException, NoSuchAlgorithmException {
final TrustManager[] trustAllCerts =
new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
};
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
return client
.newBuilder()
.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0])
.hostnameVerifier(
new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
})
.build();
}
public static OkHttpClient setTimeout(
OkHttpClient client, long connectTimeout, long writeTimeout, long readTimeout) {
return client
.newBuilder()
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
.readTimeout(readTimeout, TimeUnit.MILLISECONDS)
.build();
}
}
| |
package msee.sp3.cm.api;
import msee.sp3.cm.api.resources.*;
import msee.sp3.cm.api.resources.SearchByCriteria;
import msee.sp3.cm.beans.IFiwareMarketplaceBean;
import msee.sp3.cm.beans.IUserBean;
import msee.sp3.cm.domain.FiwareMarketplace;
import msee.sp3.cm.domain.ServiceProvider;
import msee.sp3.cm.domain.TrustedMarketplace;
import msee.sp3.cm.fiware.marketplaceri.client.StatefulMarketplaceClient;
import msee.sp3.cm.fiware.marketplaceri.client.exception.AuthenticationException;
import org.dozer.DozerBeanMapper;
import org.fiware.apps.marketplace.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.ws.rs.*;
import java.util.ArrayList;
import java.util.List;
/**
* Federated invocations to backend FI-WARE Marketplaces
*/
@Service("federationApi")
@Path("/fed")
public class FederationApi {
private Logger logger = LoggerFactory.getLogger(FederationApi.class);
@Resource
private DozerBeanMapper mapper;
@Resource
private IUserBean userBean;
@Resource(name = "fiwareMarketplaceBean")
private IFiwareMarketplaceBean fiwareBean;
/**
*
* @return a list of all Offering resources available on all of the user's trusted marketplaces.
*/
@GET
@Path("/{username}/offerings/all")
public List<OfferingResource> listOfferings(@PathParam("username") String username) {
ServiceProvider sp = userBean.getServiceProvider(username);
List<OfferingResource> toReturn = new ArrayList<OfferingResource>();
if ((sp.getTrustedMarketplaces() != null) && (!sp.getTrustedMarketplaces().isEmpty())) {
for (TrustedMarketplace tm : sp.getTrustedMarketplaces()) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm.getFiwareMarketplace(), username, sp.getPasswordHash());
if (smc != null) {
List<ServiceManifestation> allOfferings = smc.getAllServices();
if (allOfferings != null) {
for (ServiceManifestation sm : allOfferings) {
OfferingResource or = new OfferingResource();
mapper.map(sm, or);
or.setMarketplaceName(tm.getFiwareMarketplace().getName());
toReturn.add(or);
}
}
}
}
}
return toReturn;
}
/**
*
* @return a list of all Offering resources available on all of the user's trusted marketplaces.
*/
// @GET
// @Path("/{username}/offerings/{marketplace}")
// public List<OfferingResource> listOfferingsOfMarketplace(@PathParam("username") String username,
// @PathParam("marketplace") String marketplace) {
//
//
// }
@GET
@Path("/{username}/search/{searchTerm}")
public List<SearchResultEntryResource> search(@PathParam("username") String username, @PathParam("searchTerm") String searchTerm) {
ServiceProvider sp = userBean.getServiceProvider(username);
List<SearchResultEntryResource> toReturn = new ArrayList<SearchResultEntryResource>();
if ((sp.getTrustedMarketplaces() != null) && (!sp.getTrustedMarketplaces().isEmpty())) {
for (TrustedMarketplace tm : sp.getTrustedMarketplaces()) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm.getFiwareMarketplace(), username, sp.getPasswordHash());
if (smc != null) {
List<SearchResultEntry> searchResultEntries = smc.search(searchTerm);
if (searchResultEntries != null) {
for (SearchResultEntry sre : searchResultEntries) {
SearchResultEntryResource srer = new SearchResultEntryResource();
mapper.map(sre, srer);
FiwareMarketplaceResource fmr = new FiwareMarketplaceResource();
mapper.map(tm.getFiwareMarketplace(), fmr);
srer.setMarketplaceResource(fmr);
toReturn.add(srer);
}
}
}
}
}
return toReturn;
}
@GET
@Path("/search/{searchTerm}")
public List<SearchResultEntryResource> searchInAllMarketplaces(@PathParam("searchTerm") String searchTerm) {
List<FiwareMarketplace> marketplaces = fiwareBean.getFiwareMarketplaces(0, -1);
List<SearchResultEntryResource> toReturn = new ArrayList<SearchResultEntryResource>();
if ((marketplaces != null) && (!marketplaces.isEmpty())) {
for (FiwareMarketplace tm : marketplaces) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm, null, null);
if (smc != null) {
List<SearchResultEntry> searchResultEntries = smc.search(searchTerm);
if (searchResultEntries != null) {
for (SearchResultEntry sre : searchResultEntries) {
SearchResultEntryResource srer = new SearchResultEntryResource();
mapper.map(sre, srer);
FiwareMarketplaceResource fmr = new FiwareMarketplaceResource();
mapper.map(tm, fmr);
srer.setMarketplaceResource(fmr);
toReturn.add(srer);
}
}
}
}
}
return toReturn;
}
@POST
@Path("/search/criteria")
public List<OfferingResource> searchByCriteriaInAllMarketplaces(SearchByCriteria searchCriteria) {
List<FiwareMarketplace> marketplaces = fiwareBean.getFiwareMarketplaces(0, -1);
List<OfferingResource> toReturn = new ArrayList<OfferingResource>();
org.fiware.apps.marketplace.model.SearchByCriteria criteria = new org.fiware.apps.marketplace.model.SearchByCriteria();
mapper.map(searchCriteria, criteria);
if ((marketplaces != null) && (!marketplaces.isEmpty())) {
for (FiwareMarketplace tm : marketplaces) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm, null, null);
if (smc != null) {
SearchResultOffering searchResult = smc.findOfferingsByCriteria(criteria);
if (searchResult != null && searchResult.getOffering() != null && !searchResult.getOffering().isEmpty()) {
for (ServiceOffering offering : searchResult.getOffering()) {
OfferingResource offeringResource = new OfferingResource();
mapper.map(offering, offeringResource);
offeringResource.setMarketplaceName(tm.getName());
toReturn.add(offeringResource);
}
}
}
}
}
return toReturn;
}
/**
* List all stores for a user. We obtain the list of trusted marketplaces and then list each marketplace's stores.
* @return
*/
@GET
@Path("/{username}/allstores/")
public List<StoreResource> listAllStores(@PathParam("username") String username) {
ServiceProvider sp = userBean.getServiceProvider(username);
List<StoreResource> toReturn = new ArrayList<StoreResource>();
if ((sp.getTrustedMarketplaces() != null) && (!sp.getTrustedMarketplaces().isEmpty())) {
for (TrustedMarketplace tm : sp.getTrustedMarketplaces()) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm.getFiwareMarketplace(), username, sp.getPasswordHash());
if (smc != null) {
List<Store> fiStores = smc.findStores();
if (fiStores != null) {
for (Store s : fiStores) {
StoreResource sr = new StoreResource();
mapper.map(s, sr);
sr.setMarketplace(tm.getFiwareMarketplace().getName());
toReturn.add(sr);
}
}
}
}
}
return toReturn;
}
/**
* List all stores for a user. We obtain the list of trusted marketplaces and then list each marketplace's stores.
* @return
*/
@GET
@Path("/{username}/mystores")
public List<StoreResource> listMyStores(@PathParam("username") String username) {
ServiceProvider sp = userBean.getServiceProvider(username);
List<StoreResource> toReturn = new ArrayList<StoreResource>();
if ((sp.getTrustedMarketplaces() != null) && (!sp.getTrustedMarketplaces().isEmpty())) {
for (TrustedMarketplace tm : sp.getTrustedMarketplaces()) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm.getFiwareMarketplace(), username, sp.getPasswordHash());
if (smc != null) {
List<Store> fiStores = smc.findStores();
if (fiStores != null) {
for (Store s : fiStores) {
if (s.getCreator().getUsername().equals(username)) {
StoreResource sr = new StoreResource();
mapper.map(s, sr);
sr.setMarketplace(tm.getFiwareMarketplace().getName());
toReturn.add(sr);
}
}
}
}
}
}
return toReturn;
}
@PUT
@Path("/{username}/stores/{storename}")
@Consumes({"application/json", "application/xml"})
public void createNewStore(@PathParam("username") String username, @PathParam("storename") String storeName, StoreResource store) {
ServiceProvider sp = userBean.getServiceProvider(username);
if ((sp.getTrustedMarketplaces() != null) && (!sp.getTrustedMarketplaces().isEmpty())) {
for (TrustedMarketplace tm : sp.getTrustedMarketplaces()) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm.getFiwareMarketplace(), username, sp.getPasswordHash());
if (smc != null) {
Store fiStore = new Store();
mapper.map(store, fiStore);
smc.saveStore(fiStore);
}
}
}
}
@POST
@Path("/{username}/stores/{storename}")
@Consumes({"application/json", "application/xml"})
public void updateStore(@PathParam("username") String username, @PathParam("storename") String storeName, StoreResource store) {
ServiceProvider sp = userBean.getServiceProvider(username);
if ((sp.getTrustedMarketplaces() != null) && (!sp.getTrustedMarketplaces().isEmpty())) {
for (TrustedMarketplace tm : sp.getTrustedMarketplaces()) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm.getFiwareMarketplace(), username, sp.getPasswordHash());
if (smc != null) {
Store fiStore = new Store();
mapper.map(store, fiStore);
smc.updateStore(storeName, fiStore);
}
}
}
}
@DELETE
@Path("/{username}/stores/{storename}")
public void deleteStore(@PathParam("username") String username, @PathParam("storename") String storeName) {
ServiceProvider sp = userBean.getServiceProvider(username);
if ((sp.getTrustedMarketplaces() != null) && (!sp.getTrustedMarketplaces().isEmpty())) {
for (TrustedMarketplace tm : sp.getTrustedMarketplaces()) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm.getFiwareMarketplace(), username, sp.getPasswordHash());
if (smc != null) {
smc.deleteStore(storeName);
}
}
}
}
@GET
@Path("/{username}/stores/{storename}/allservices")
@Produces({"application/json", "application/xml"})
public List<ServiceResource> listServices(@PathParam("username") String username, @PathParam("storename") String storeName) {
List<ServiceResource> services = new ArrayList<ServiceResource>();
ServiceProvider sp = userBean.getServiceProvider(username);
if ((sp.getTrustedMarketplaces() != null) && (!sp.getTrustedMarketplaces().isEmpty())) {
for (TrustedMarketplace tm : sp.getTrustedMarketplaces()) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm.getFiwareMarketplace(), username, sp.getPasswordHash());
if (smc != null) {
List<org.fiware.apps.marketplace.model.Service> storeServices = smc.findServices(storeName);
for (org.fiware.apps.marketplace.model.Service s : storeServices) {
ServiceResource sr = new ServiceResource();
mapper.map(s, sr);
sr.setMarketplaceName(tm.getFiwareMarketplace().getName());
sr.setStoreName(storeName);
services.add(sr);
}
}
}
}
return services;
}
@GET
@Path("/{username}/stores/{storename}/service/{servicename}")
@Produces({"application/json", "application/xml"})
@Deprecated
public ServiceResource getService(@PathParam("username") String username, @PathParam("storename") String storeName,
@PathParam("servicename") String serviceName) {
ServiceProvider sp = userBean.getServiceProvider(username);
if ((sp.getTrustedMarketplaces() != null) && (!sp.getTrustedMarketplaces().isEmpty())) {
for (TrustedMarketplace tm : sp.getTrustedMarketplaces()) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm.getFiwareMarketplace(), username, sp.getPasswordHash());
if (smc != null) {
org.fiware.apps.marketplace.model.Service svc = smc.findService(storeName, serviceName);
ServiceResource sr = new ServiceResource();
mapper.map(svc, sr);
return sr;
}
}
}
return null;
}
@GET
@Path("/marketplaces/{marketplaceName}/stores/{storename}/service/{servicename}")
@Produces({"application/json", "application/xml"})
public List<OfferingResource> getServiceOfferings(@PathParam("marketplaceName") String marketplaceName,
@PathParam("storename") String storeName,
@PathParam("servicename") String serviceName) {
List<OfferingResource> toReturn = new ArrayList<OfferingResource>();
FiwareMarketplace fm = fiwareBean.getFiwareMarketplace(marketplaceName);
StatefulMarketplaceClient smc = obtainMarketplaceClient(fm, null, null);
if (smc != null) {
org.fiware.apps.marketplace.model.Service svc = smc.findService(storeName, serviceName);
for (ServiceOffering so : svc.getOfferings()) {
OfferingResource or = new OfferingResource();
mapper.map(so, or);
or.setMarketplaceName(fm.getName());
toReturn.add(or);
}
}
return toReturn;
}
@PUT
@Path("/{username}/stores/{storename}/service/{servicename}")
@Consumes({"application/json", "application/xml"})
public void createService(@PathParam("username") String username, @PathParam("storename") String storeName,
@PathParam("servicename") String serviceName, ServiceResource service) {
ServiceProvider sp = userBean.getServiceProvider(username);
if ((sp.getTrustedMarketplaces() != null) && (!sp.getTrustedMarketplaces().isEmpty())) {
for (TrustedMarketplace tm : sp.getTrustedMarketplaces()) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm.getFiwareMarketplace(), username, sp.getPasswordHash());
if (smc != null) {
org.fiware.apps.marketplace.model.Service svc = new org.fiware.apps.marketplace.model.Service();
mapper.map(service, svc);
logger.info("Service to be registered: {}", svc);
try {
smc.saveService(storeName, svc);
}
catch (Exception e) {
logger.error("Failed saving service {} to marketplace {}", service.getName());
}
}
}
}
else {
logger.warn("Could not create service {} for creator {}, no trusted marketplaces defined.");
}
}
@POST
@Path("/{username}/stores/{storename}/service/{servicename}")
@Consumes({"application/json", "application/xml"})
public void updateService(@PathParam("username") String username, @PathParam("storename") String storeName,
@PathParam("servicename") String serviceName, ServiceResource service) {
ServiceProvider sp = userBean.getServiceProvider(username);
if ((sp.getTrustedMarketplaces() != null) && (!sp.getTrustedMarketplaces().isEmpty())) {
for (TrustedMarketplace tm : sp.getTrustedMarketplaces()) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm.getFiwareMarketplace(), username, sp.getPasswordHash());
if (smc != null) {
org.fiware.apps.marketplace.model.Service svc = new org.fiware.apps.marketplace.model.Service();
mapper.map(service, svc);
logger.info("Service {} to be update to {}", serviceName, svc);
smc.updateService(storeName, serviceName, svc);
}
}
}
}
@DELETE
@Path("/{username}/stores/{storename}/service/{servicename}")
public void deleteService(@PathParam("username") String username, @PathParam("storename") String storeName,
@PathParam("servicename") String serviceName) {
ServiceProvider sp = userBean.getServiceProvider(username);
if ((sp.getTrustedMarketplaces() != null) && (!sp.getTrustedMarketplaces().isEmpty())) {
for (TrustedMarketplace tm : sp.getTrustedMarketplaces()) {
StatefulMarketplaceClient smc = obtainMarketplaceClient(tm.getFiwareMarketplace(), username, sp.getPasswordHash());
if (smc != null) {
smc.deleteService(storeName, serviceName);
}
}
}
}
/**
* helper method to obtain a configured, ready-to-use instance of fiware marketplace client
*/
private StatefulMarketplaceClient obtainMarketplaceClient(FiwareMarketplace fiMarketplace, String username, String password) {
StatefulMarketplaceClient smc = new StatefulMarketplaceClient();
if (username == null) {
try {
smc.startSessionWithBuiltinPrincipal(fiMarketplace.getUrl());
} catch (AuthenticationException e) {
logger.error("Failed to authenticate with marketplace at " + fiMarketplace.getUrl(), e);
return null;
}
}
else {
try {
smc.startSession(fiMarketplace.getUrl(), username, password);
} catch (AuthenticationException e) {
logger.error(String.format("Failed to authenticate as %s with marketplace at %s", username,
fiMarketplace.getUrl()), e);
return null;
}
}
return smc;
}
}
| |
package com.wa.sdk.cn.demo.tracking.fragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import com.wa.sdk.cn.demo.R;
import com.wa.sdk.cn.demo.Util;
import com.wa.sdk.cn.demo.WADemoConfig;
import com.wa.sdk.cn.demo.base.BaseFragment;
import com.wa.sdk.cn.demo.tracking.TrackingSendActivity;
import com.wa.sdk.cn.demo.widget.EventItemView;
import com.wa.sdk.common.utils.StringUtil;
import com.wa.sdk.track.WAEventType;
import java.util.HashMap;
import java.util.Set;
/**
* Created by yinglovezhuzhu@gmail.com on 2016/1/29.
*/
public class DefaultEventFragment extends BaseFragment {
private String mDefaultEventName;
private float mDefaultValue = 0.0f;
private HashMap<String, Object> mDefaultEventValues = new HashMap<String, Object>();
private LinearLayout mLlParamsContent;
private Button mBtnAddParameter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if(null != args) {
if(args.containsKey(WADemoConfig.EXTRA_EVENT_NAME)) {
mDefaultEventName = args.getString(WADemoConfig.EXTRA_EVENT_NAME);
}
if(args.containsKey(WADemoConfig.EXTRA_COUNT_VALUE)) {
mDefaultValue = args.getFloat(WADemoConfig.EXTRA_COUNT_VALUE, 0.0f);
}
if(args.containsKey(WADemoConfig.EXTRA_EVENT_VALUES)) {
HashMap<String, Object> values = (HashMap<String, Object>) args.getSerializable(WADemoConfig.EXTRA_EVENT_VALUES);
if(null == values || values.isEmpty()) {
return;
}
mDefaultEventValues.putAll(values);
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.fragment_send_event, container, false);
initView(contentView);
Set<String> valuesKey = mDefaultEventValues.keySet();
boolean isCustom = mDefaultEventName.startsWith(WAEventType.CUSTOM_EVENT_PREFIX);
for (String valueKey :valuesKey) {
addParameterItemView(valueKey, String.valueOf(mDefaultEventValues.get(valueKey)), isCustom, isCustom);
}
mBtnAddParameter.setEnabled(isCustom);
return contentView;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add_parameter:
addParameterItemView(null, null, true, true);
break;
default:
break;
}
}
private void initView(View contentView) {
EditText eventName = contentView.findViewById(R.id.et_event_name);
eventName.setEnabled(mDefaultEventName.startsWith(WAEventType.CUSTOM_EVENT_PREFIX));
EditText countValue = contentView.findViewById(R.id.et_event_count_value);
eventName.setText(mDefaultEventName);
countValue.setText(String.valueOf(mDefaultValue));
eventName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String newEventName = s.toString();
onEventNameChanged(mDefaultEventName, newEventName);
mDefaultEventName = newEventName;
}
});
countValue.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String newValue = s.toString();
try {
float value = 0;
if (! StringUtil.isEmpty(newValue))
value = Float.valueOf(newValue);
onEventValueChanged(mDefaultValue, value);
mDefaultValue = value;
} catch (Exception e) {
e.printStackTrace();
}
}
});
mLlParamsContent = contentView.findViewById(R.id.ll_event_parameter_content);
mBtnAddParameter = contentView.findViewById(R.id.btn_add_parameter);
mBtnAddParameter.setOnClickListener(this);
}
private EventItemView addParameterItemView(final String defaultKey, final String defaultValue,
boolean keyEditable, boolean deletable) {
EventItemView itemView = new EventItemView(getActivity());
itemView.setKeyEditable(keyEditable);
if(!StringUtil.isEmpty(defaultKey)) {
itemView.setKey(defaultKey);
itemView.setValueInputType(Util.getInputType(defaultKey));
}
if(!StringUtil.isEmpty(defaultValue)) {
itemView.setValue(defaultValue);
}
itemView.setOnDeleteListener(new EventItemView.OnDeleteListener() {
@Override
public void onDelete(EventItemView view) {
mLlParamsContent.removeView(view);
onParameterChanged(view.getKey(), false, view.getValue(), null);
}
});
itemView.setDeletable(deletable);
itemView.setOnDataChangedListener(new EventItemView.OnDataChangedListener() {
@Override
public void onDataChanged(int type, String key, boolean isKey, Object oldValue, Object newValue) {
// switch (type) {
// case TrackingSendActivity.TYPE_DEFAULT:
// onParameterChanged(key, isKey, oldValue, newValue);
// break;
// case TrackingSendActivity.TYPE_APPSFLYERS:
// case TrackingSendActivity.TYPE_FACEBOOK:
// default:
// break;
// }
onParameterChanged(key, isKey, oldValue, newValue);
}
});
mLlParamsContent.addView(itemView);
return itemView;
}
public void onEventNameChanged(String oldName, String newName) {
Object activity = getActivity();
if(activity instanceof TrackingSendActivity) {
((TrackingSendActivity) activity).onEventNameChanged(oldName, newName);
}
}
public void onEventValueChanged(float oldValue, float newValue) {
Object activity = getActivity();
if(activity instanceof TrackingSendActivity) {
((TrackingSendActivity) activity).onCountValueChanged(oldValue, newValue);
}
}
public void onParameterChanged(String key, boolean isKey, Object oldValue, Object newValue) {
Object activity = getActivity();
if(activity instanceof TrackingSendActivity) {
((TrackingSendActivity) activity).onParameterChanged(key, isKey, oldValue, newValue);
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.proxy.server;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.haproxy.HAProxyCommand;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.codec.haproxy.HAProxyProtocolVersion;
import io.netty.handler.codec.haproxy.HAProxyProxiedProtocol;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import javax.net.ssl.SSLSession;
import lombok.Getter;
import org.apache.pulsar.PulsarVersion;
import org.apache.pulsar.client.api.Authentication;
import org.apache.pulsar.client.api.AuthenticationDataProvider;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.common.allocator.PulsarByteBufAllocator;
import org.apache.pulsar.common.api.AuthData;
import org.apache.pulsar.common.api.proto.CommandAuthChallenge;
import org.apache.pulsar.common.api.proto.CommandConnected;
import org.apache.pulsar.common.protocol.Commands;
import org.apache.pulsar.common.protocol.PulsarDecoder;
import org.apache.pulsar.common.stats.Rate;
import org.apache.pulsar.common.tls.TlsHostnameVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DirectProxyHandler {
@Getter
private final Channel inboundChannel;
@Getter
Channel outboundChannel;
@Getter
private final Rate inboundChannelRequestsRate;
protected static Map<ChannelId, ChannelId> inboundOutboundChannelMap = new ConcurrentHashMap<>();
private final String originalPrincipal;
private final AuthData clientAuthData;
private final String clientAuthMethod;
public static final String TLS_HANDLER = "tls";
private final Authentication authentication;
private AuthenticationDataProvider authenticationDataProvider;
private final ProxyService service;
private final Runnable onHandshakeCompleteAction;
public DirectProxyHandler(ProxyService service, ProxyConnection proxyConnection, String targetBrokerUrl,
InetSocketAddress targetBrokerAddress, int protocolVersion,
Supplier<SslHandler> sslHandlerSupplier) {
this.service = service;
this.authentication = proxyConnection.getClientAuthentication();
this.inboundChannel = proxyConnection.ctx().channel();
this.inboundChannelRequestsRate = new Rate();
this.originalPrincipal = proxyConnection.clientAuthRole;
this.clientAuthData = proxyConnection.clientAuthData;
this.clientAuthMethod = proxyConnection.clientAuthMethod;
this.onHandshakeCompleteAction = proxyConnection::cancelKeepAliveTask;
ProxyConfiguration config = service.getConfiguration();
// Start the connection attempt.
Bootstrap b = new Bootstrap();
// Tie the backend connection on the same thread to avoid context
// switches when passing data between the 2
// connections
b.option(ChannelOption.ALLOCATOR, PulsarByteBufAllocator.DEFAULT);
int brokerProxyConnectTimeoutMs = service.getConfiguration().getBrokerProxyConnectTimeoutMs();
if (brokerProxyConnectTimeoutMs > 0) {
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, brokerProxyConnectTimeoutMs);
}
b.group(inboundChannel.eventLoop()).channel(inboundChannel.getClass()).option(ChannelOption.AUTO_READ, false);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
if (sslHandlerSupplier != null) {
ch.pipeline().addLast(TLS_HANDLER, sslHandlerSupplier.get());
}
int brokerProxyReadTimeoutMs = service.getConfiguration().getBrokerProxyReadTimeoutMs();
if (brokerProxyReadTimeoutMs > 0) {
ch.pipeline().addLast("readTimeoutHandler",
new ReadTimeoutHandler(brokerProxyReadTimeoutMs, TimeUnit.MILLISECONDS));
}
ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(
Commands.DEFAULT_MAX_MESSAGE_SIZE + Commands.MESSAGE_SIZE_FRAME_PADDING, 0, 4, 0, 4));
ch.pipeline().addLast("proxyOutboundHandler", new ProxyBackendHandler(config, protocolVersion));
}
});
URI targetBroker;
try {
// targetBrokerUrl is coming in the "hostname:6650" form, so we need
// to extract host and port
targetBroker = new URI("pulsar://" + targetBrokerUrl);
} catch (URISyntaxException e) {
log.warn("[{}] Failed to parse broker url '{}'", inboundChannel, targetBrokerUrl, e);
inboundChannel.close();
return;
}
ChannelFuture f = b.connect(targetBrokerAddress);
outboundChannel = f.channel();
f.addListener(future -> {
if (!future.isSuccess()) {
// Close the connection if the connection attempt has failed.
inboundChannel.close();
return;
}
final ProxyBackendHandler cnx = (ProxyBackendHandler) outboundChannel.pipeline()
.get("proxyOutboundHandler");
cnx.setRemoteHostName(targetBroker.getHost());
// if enable full parsing feature
if (service.getProxyLogLevel() == 2) {
//Set a map between inbound and outbound,
//so can find inbound by outbound or find outbound by inbound
inboundOutboundChannelMap.put(outboundChannel.id(), inboundChannel.id());
}
if (!config.isHaProxyProtocolEnabled()) {
return;
}
if (proxyConnection.hasHAProxyMessage()) {
outboundChannel.writeAndFlush(encodeProxyProtocolMessage(proxyConnection.getHAProxyMessage()));
} else {
if (!(inboundChannel.remoteAddress() instanceof InetSocketAddress)) {
return;
}
if (!(outboundChannel.localAddress() instanceof InetSocketAddress)) {
return;
}
InetSocketAddress clientAddress = (InetSocketAddress) inboundChannel.remoteAddress();
String sourceAddress = clientAddress.getAddress().getHostAddress();
int sourcePort = clientAddress.getPort();
InetSocketAddress proxyAddress = (InetSocketAddress) inboundChannel.remoteAddress();
String destinationAddress = proxyAddress.getAddress().getHostAddress();
int destinationPort = proxyAddress.getPort();
HAProxyMessage msg = new HAProxyMessage(HAProxyProtocolVersion.V1, HAProxyCommand.PROXY,
HAProxyProxiedProtocol.TCP4, sourceAddress, destinationAddress, sourcePort, destinationPort);
outboundChannel.writeAndFlush(encodeProxyProtocolMessage(msg));
msg.release();
}
});
}
private ByteBuf encodeProxyProtocolMessage(HAProxyMessage msg) {
// Max length of v1 version proxy protocol message is 108
ByteBuf out = Unpooled.buffer(108);
out.writeBytes(TEXT_PREFIX);
out.writeByte((byte) ' ');
out.writeCharSequence(msg.proxiedProtocol().name(), CharsetUtil.US_ASCII);
out.writeByte((byte) ' ');
out.writeCharSequence(msg.sourceAddress(), CharsetUtil.US_ASCII);
out.writeByte((byte) ' ');
out.writeCharSequence(msg.destinationAddress(), CharsetUtil.US_ASCII);
out.writeByte((byte) ' ');
out.writeCharSequence(String.valueOf(msg.sourcePort()), CharsetUtil.US_ASCII);
out.writeByte((byte) ' ');
out.writeCharSequence(String.valueOf(msg.destinationPort()), CharsetUtil.US_ASCII);
out.writeByte((byte) '\r');
out.writeByte((byte) '\n');
return out;
}
static final byte[] TEXT_PREFIX = {
(byte) 'P',
(byte) 'R',
(byte) 'O',
(byte) 'X',
(byte) 'Y',
};
enum BackendState {
Init, HandshakeCompleted
}
public class ProxyBackendHandler extends PulsarDecoder implements FutureListener<Void> {
private BackendState state = BackendState.Init;
private String remoteHostName;
protected ChannelHandlerContext ctx;
private final ProxyConfiguration config;
private final int protocolVersion;
public ProxyBackendHandler(ProxyConfiguration config, int protocolVersion) {
this.config = config;
this.protocolVersion = protocolVersion;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
// Send the Connect command to broker
authenticationDataProvider = authentication.getAuthData(remoteHostName);
AuthData authData = authenticationDataProvider.authenticate(AuthData.INIT_AUTH_DATA);
ByteBuf command;
command = Commands.newConnect(authentication.getAuthMethodName(), authData, protocolVersion, "Pulsar proxy",
null /* target broker */, originalPrincipal, clientAuthData, clientAuthMethod);
outboundChannel.writeAndFlush(command);
outboundChannel.read();
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
switch (state) {
case Init:
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Received msg on broker connection: {}", inboundChannel, outboundChannel,
msg.getClass());
}
// Do the regular decoding for the Connected message
super.channelRead(ctx, msg);
break;
case HandshakeCompleted:
ProxyService.OPS_COUNTER.inc();
if (msg instanceof ByteBuf) {
ProxyService.BYTES_COUNTER.inc(((ByteBuf) msg).readableBytes());
}
inboundChannel.writeAndFlush(msg).addListener(this);
break;
default:
break;
}
}
@Override
protected void handleAuthChallenge(CommandAuthChallenge authChallenge) {
checkArgument(authChallenge.hasChallenge());
checkArgument(authChallenge.getChallenge().hasAuthData() && authChallenge.getChallenge().hasAuthData());
if (Arrays.equals(AuthData.REFRESH_AUTH_DATA_BYTES, authChallenge.getChallenge().getAuthData())) {
try {
authenticationDataProvider = authentication.getAuthData(remoteHostName);
} catch (PulsarClientException e) {
log.error("{} Error when refreshing authentication data provider: {}", ctx.channel(), e);
return;
}
}
// mutual authn. If auth not complete, continue auth; if auth complete, complete connectionFuture.
try {
AuthData authData = authenticationDataProvider
.authenticate(AuthData.of(authChallenge.getChallenge().getAuthData()));
checkState(!authData.isComplete());
ByteBuf request = Commands.newAuthResponse(authentication.getAuthMethodName(),
authData,
this.protocolVersion,
PulsarVersion.getVersion());
if (log.isDebugEnabled()) {
log.debug("{} Mutual auth {}", ctx.channel(), authentication.getAuthMethodName());
}
outboundChannel.writeAndFlush(request);
outboundChannel.read();
} catch (Exception e) {
log.error("Error mutual verify", e);
}
}
@Override
public void operationComplete(Future<Void> future) {
// This is invoked when the write operation on the paired connection
// is completed
if (future.isSuccess()) {
outboundChannel.read();
} else {
log.warn("[{}] [{}] Failed to write on proxy connection. Closing both connections.", inboundChannel,
outboundChannel, future.cause());
inboundChannel.close();
}
}
@Override
protected void messageReceived() {
// no-op
}
@Override
protected void handleConnected(CommandConnected connected) {
checkArgument(state == BackendState.Init, "Unexpected state %s. BackendState.Init was expected.", state);
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Received Connected from broker", inboundChannel, outboundChannel);
}
if (config.isTlsHostnameVerificationEnabled() && remoteHostName != null
&& !verifyTlsHostName(remoteHostName, ctx)) {
// close the connection if host-verification failed with the
// broker
log.warn("[{}] Failed to verify hostname of {}", ctx.channel(), remoteHostName);
ctx.close();
return;
}
state = BackendState.HandshakeCompleted;
onHandshakeCompleteAction.run();
startDirectProxying(connected);
int maxMessageSize =
connected.hasMaxMessageSize() ? connected.getMaxMessageSize() : Commands.INVALID_MAX_MESSAGE_SIZE;
inboundChannel.writeAndFlush(Commands.newConnected(connected.getProtocolVersion(), maxMessageSize))
.addListener(future -> {
if (future.isSuccess()) {
// Start reading from both connections
inboundChannel.read();
outboundChannel.read();
} else {
log.warn("[{}] [{}] Failed to write to inbound connection. Closing both connections.",
inboundChannel,
outboundChannel, future.cause());
inboundChannel.close();
}
});
}
private void startDirectProxying(CommandConnected connected) {
if (service.getProxyLogLevel() == 0) {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Removing decoder from pipeline", inboundChannel, outboundChannel);
}
// direct tcp proxy
inboundChannel.pipeline().remove("frameDecoder");
outboundChannel.pipeline().remove("frameDecoder");
} else {
// Enable parsing feature, proxyLogLevel(1 or 2)
// Add parser handler
if (connected.hasMaxMessageSize()) {
inboundChannel.pipeline()
.replace("frameDecoder", "newFrameDecoder",
new LengthFieldBasedFrameDecoder(connected.getMaxMessageSize()
+ Commands.MESSAGE_SIZE_FRAME_PADDING,
0, 4, 0, 4));
outboundChannel.pipeline().replace("frameDecoder", "newFrameDecoder",
new LengthFieldBasedFrameDecoder(
connected.getMaxMessageSize()
+ Commands.MESSAGE_SIZE_FRAME_PADDING,
0, 4, 0, 4));
inboundChannel.pipeline().addBefore("handler", "inboundParser",
new ParserProxyHandler(service, inboundChannel,
ParserProxyHandler.FRONTEND_CONN,
connected.getMaxMessageSize()));
outboundChannel.pipeline().addBefore("proxyOutboundHandler", "outboundParser",
new ParserProxyHandler(service, outboundChannel,
ParserProxyHandler.BACKEND_CONN,
connected.getMaxMessageSize()));
} else {
inboundChannel.pipeline().addBefore("handler", "inboundParser",
new ParserProxyHandler(service, inboundChannel,
ParserProxyHandler.FRONTEND_CONN,
Commands.DEFAULT_MAX_MESSAGE_SIZE));
outboundChannel.pipeline().addBefore("proxyOutboundHandler", "outboundParser",
new ParserProxyHandler(service, outboundChannel,
ParserProxyHandler.BACKEND_CONN,
Commands.DEFAULT_MAX_MESSAGE_SIZE));
}
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
inboundChannel.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
log.warn("[{}] [{}] Caught exception: {}", inboundChannel, outboundChannel, cause.getMessage(), cause);
ctx.close();
}
public void setRemoteHostName(String remoteHostName) {
this.remoteHostName = remoteHostName;
}
private boolean verifyTlsHostName(String hostname, ChannelHandlerContext ctx) {
ChannelHandler sslHandler = ctx.channel().pipeline().get("tls");
SSLSession sslSession;
if (sslHandler != null) {
sslSession = ((SslHandler) sslHandler).engine().getSession();
return (new TlsHostnameVerifier()).verify(hostname, sslSession);
}
return false;
}
}
private static final Logger log = LoggerFactory.getLogger(DirectProxyHandler.class);
}
| |
/*******************************************************************************
* Copyright (c) 2008, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.bpel.ui.editparts;
import java.util.List;
import org.eclipse.bpel.common.ui.decorator.EditPartMarkerDecorator;
import org.eclipse.bpel.common.ui.tray.TrayCategoryEntryEditPart;
import org.eclipse.bpel.common.ui.tray.TrayMarkerDecorator;
import org.eclipse.bpel.model.Scope;
import org.eclipse.bpel.ui.BPELUIPlugin;
import org.eclipse.bpel.ui.IHoverHelper;
import org.eclipse.bpel.ui.IHoverHelperSupport;
import org.eclipse.bpel.ui.adapters.IMarkerHolder;
import org.eclipse.bpel.ui.editparts.policies.BPELComponentEditPolicy;
import org.eclipse.bpel.ui.editparts.policies.BPELDirectEditPolicy;
import org.eclipse.bpel.ui.extensions.BPELUIRegistry;
import org.eclipse.bpel.ui.util.BPELUtil;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.MouseEvent;
import org.eclipse.draw2d.MouseMotionListener;
import org.eclipse.draw2d.ToolbarLayout;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gef.AccessibleEditPart;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.RootEditPart;
/**
* Tray category edit part.
*
* @author IBM
* @author Michal Chmielewski (michal.chmielewski@oracle.com)
* @date May 23, 2007
*
*/
public abstract class BPELTrayCategoryEntryEditPart extends TrayCategoryEntryEditPart implements IHoverHelperSupport{
protected MouseMotionListener mouseMotionListener;
// added by Grid.Qian
// use the variable to hold the root of the editpart
// because when we delete a correlationSet from scope
// the editpart parent will be null
private RootEditPart holdRoot;
@Override
protected AccessibleEditPart createAccessible() {
return new BPELTrayAccessibleEditPart(this);
}
@Override
protected void createEditPolicies() {
super.createEditPolicies();
// handles deletions
installEditPolicy(EditPolicy.COMPONENT_ROLE, new BPELComponentEditPolicy());
installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE, new BPELDirectEditPolicy());
}
/** (non-Javadoc)
* @see org.eclipse.bpel.common.ui.tray.TrayCategoryEntryEditPart#createEditPartMarkerDecorator()
*/
@Override
protected EditPartMarkerDecorator createEditPartMarkerDecorator() {
return new TrayMarkerDecorator((EObject)getModel(), new ToolbarLayout()) {
@Override
protected IMarker[] getMarkers () {
IMarkerHolder holder = BPELUtil.adapt(modelObject, IMarkerHolder.class);
if (holder != null) {
return holder.getMarkers(modelObject);
}
return super.getMarkers();
}
};
}
/**
* @see org.eclipse.bpel.ui.IHoverHelperSupport#refreshHoverHelp()
*/
public void refreshHoverHelp() {
// Refresh the tool-tip if we can find a helper.
IHoverHelper helper = null;
try {
helper = BPELUIRegistry.getInstance().getHoverHelper();
if (helper == null) {
return;
}
} catch (CoreException e) {
getFigure().setToolTip(null);
BPELUIPlugin.log(e);
return ;
}
IFigure tooltip = helper.getHoverFigure((EObject)getModel());
getFigure().setToolTip(tooltip);
}
protected MouseMotionListener getMouseMotionListener() {
if (mouseMotionListener == null) {
this.mouseMotionListener = new MouseMotionListener() {
public void mouseDragged(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mouseHover(MouseEvent me) {
}
public void mouseMoved(MouseEvent me) {
refreshHoverHelp();
}
};
}
return mouseMotionListener;
}
@Override
protected IFigure createFigure() {
IFigure fig = super.createFigure();
fig.addMouseMotionListener(getMouseMotionListener());
return fig;
}
/**
* HACK
* See comments in org.eclipse.bpel.ui.editparts.BPELTrayCategoryEditPart.selectAnotherEntry()
*/
@Override
public void removeNotify() {
// we only do the following hack if we are dealing with scoped variables
// when we delete a variable from scope, the variables parent will
// be null, so we need to filter this
EObject eObj = ((EObject) getParent().getModel()).eContainer();
if (eObj != null && !(eObj instanceof Scope)) {
super.removeNotify();
return;
}
if (getSelected() != SELECTED_NONE) {
// getViewer().deselect(this);
// instead of deselecting this entry (which would cause the process to be selected)
// we should ask the parent edit part to select some other child
((BPELTrayCategoryEditPart)getParent()).selectAnotherEntry();
}
if (hasFocus())
getViewer().setFocus(null);
List<EditPart> children = getChildren();
for (int i = 0; i < children.size(); i++)
children.get(i).removeNotify();
unregister();
}
/**
* Overwrite the method by Grid.Qian to get the viewer
* when the editpart's parent == null
*/
public EditPartViewer getViewer() {
try {
return super.getViewer();
} catch (Exception e) {
return holdRoot.getViewer();
}
}
/**
* Overwrite the method by Grid.Qian
* Hold the editpart's root editpart
*/
public void setParent(EditPart parent) {
if (this.getParent() == parent)
return;
if (parent != null) {
holdRoot = parent.getRoot();
}
super.setParent(parent);
}
}
| |
/*
* Copyright (c) 2008-2022 The Aspectran Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aspectran.core.context.expr;
import com.aspectran.core.activity.Activity;
import com.aspectran.core.activity.request.FileParameter;
import com.aspectran.core.activity.request.ParameterMap;
import com.aspectran.core.context.expr.token.Token;
import com.aspectran.core.context.rule.BeanRule;
import com.aspectran.core.context.rule.ItemRule;
import com.aspectran.core.context.rule.ItemRuleMap;
import com.aspectran.core.context.rule.type.ItemType;
import com.aspectran.core.context.rule.type.ItemValueType;
import com.aspectran.core.util.LinkedMultiValueMap;
import com.aspectran.core.util.MultiValueMap;
import com.aspectran.core.util.apon.Parameters;
import com.aspectran.core.util.apon.VariableParameters;
import java.io.File;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* The Class ItemEvaluation.
*
* @since 2008. 06. 19
*/
public class ItemEvaluation extends TokenEvaluation implements ItemEvaluator {
/**
* Instantiates a new ItemEvaluation.
* @param activity the current Activity
*/
public ItemEvaluation(Activity activity) {
super(activity);
}
@Override
public Map<String, Object> evaluate(ItemRuleMap itemRuleMap) {
Map<String, Object> valueMap = new LinkedHashMap<>();
evaluate(itemRuleMap, valueMap);
return valueMap;
}
@Override
public void evaluate(ItemRuleMap itemRuleMap, Map<String, Object> valueMap) {
if (itemRuleMap != null) {
for (ItemRule itemRule : itemRuleMap.values()) {
valueMap.put(itemRule.getName(), evaluate(itemRule));
}
}
}
@Override
@SuppressWarnings("unchecked")
public <T> T evaluate(ItemRule itemRule) {
try {
ItemType itemType = itemRule.getType();
ItemValueType valueType = itemRule.getValueType();
Object value = null;
if (itemType == ItemType.SINGLE) {
if (valueType == ItemValueType.BEAN) {
value = evaluateBean(itemRule.getBeanRule());
} else {
value = evaluate(itemRule.getTokens(), valueType);
}
} else if (itemType == ItemType.ARRAY) {
if (valueType == ItemValueType.BEAN) {
value = evaluateBeanAsArray(itemRule.getBeanRuleList());
} else {
value = evaluateAsArray(itemRule.getTokensList(), valueType);
}
} else if (itemType == ItemType.LIST) {
if (valueType == ItemValueType.BEAN) {
value = evaluateBeanAsList(itemRule.getBeanRuleList());
} else {
value = evaluateAsList(itemRule.getTokensList(), valueType);
}
} else if (itemType == ItemType.SET) {
if (valueType == ItemValueType.BEAN) {
value = evaluateBeanAsSet(itemRule.getBeanRuleList());
} else {
value = evaluateAsSet(itemRule.getTokensList(), valueType);
}
} else if (itemType == ItemType.MAP) {
if (valueType == ItemValueType.BEAN) {
value = evaluateBeanAsMap(itemRule.getBeanRuleMap());
} else {
value = evaluateAsMap(itemRule.getTokensMap(), valueType);
}
} else if (itemType == ItemType.PROPERTIES) {
if (valueType == ItemValueType.BEAN) {
value = evaluateBeanAsProperties(itemRule.getBeanRuleMap());
} else {
value = evaluateAsProperties(itemRule.getTokensMap(), valueType);
}
}
return (T)value;
} catch (Exception e) {
throw new ItemEvaluationException(itemRule, e);
}
}
@Override
public MultiValueMap<String, String> evaluateAsMultiValueMap(ItemRuleMap itemRuleMap) {
return evaluateAsMultiValueMap(itemRuleMap.values());
}
@Override
public MultiValueMap<String, String> evaluateAsMultiValueMap(Collection<ItemRule> itemRules) {
MultiValueMap<String, String> valueMap = new LinkedMultiValueMap<>();
for (ItemRule itemRule : itemRules) {
String[] values = evaluateAsStringArray(itemRule);
valueMap.set(itemRule.getName(), values);
}
return valueMap;
}
@Override
public ParameterMap evaluateAsParameterMap(ItemRuleMap itemRuleMap) {
return evaluateAsParameterMap(itemRuleMap.values());
}
@Override
public ParameterMap evaluateAsParameterMap(Collection<ItemRule> itemRules) {
ParameterMap params = new ParameterMap();
for (ItemRule itemRule : itemRules) {
String[] values = evaluateAsStringArray(itemRule);
params.put(itemRule.getName(), values);
}
return params;
}
@Override
public String[] evaluateAsStringArray(ItemRule itemRule) {
try {
ItemType itemType = itemRule.getType();
ItemValueType valueType = itemRule.getValueType();
String[] values = null;
if (itemType == ItemType.SINGLE) {
Object value;
if (valueType == ItemValueType.BEAN) {
value = evaluateBean(itemRule.getBeanRule());
} else {
Token[] tokens = itemRule.getTokens();
value = evaluate(tokens, valueType);
}
if (value != null) {
if (value instanceof String[]) {
values = (String[])value;
} else {
values = new String[] { value.toString() };
}
}
} else if (itemType == ItemType.ARRAY) {
Object[] arr;
if (valueType == ItemValueType.BEAN) {
arr = evaluateBeanAsArray(itemRule.getBeanRuleList());
} else {
arr = evaluateAsArray(itemRule.getTokensList(), valueType);
}
if (arr != null) {
if (arr instanceof String[]) {
values = (String[])arr;
} else {
values = Arrays.stream(arr).map(Object::toString).toArray(String[]::new);
}
}
} else if (itemType == ItemType.LIST) {
List<Object> list;
if (valueType == ItemValueType.BEAN) {
list = evaluateBeanAsList(itemRule.getBeanRuleList());
} else {
list = evaluateAsList(itemRule.getTokensList(), valueType);
}
if (list != null) {
values = Arrays.stream(list.toArray()).map(Object::toString).toArray(String[]::new);
}
} else if (itemType == ItemType.SET) {
Set<Object> set;
if (valueType == ItemValueType.BEAN) {
set = evaluateBeanAsSet(itemRule.getBeanRuleList());
} else {
set = evaluateAsSet(itemRule.getTokensList(), valueType);
}
if (set != null) {
values = Arrays.stream(set.toArray()).map(Object::toString).toArray(String[]::new);
}
} else if (itemType == ItemType.MAP) {
Map<String, Object> map;
if (valueType == ItemValueType.BEAN) {
map = evaluateBeanAsMap(itemRule.getBeanRuleMap());
} else {
map = evaluateAsMap(itemRule.getTokensMap(), valueType);
}
if (map != null) {
values = new String[] { map.toString() };
}
} else if (itemType == ItemType.PROPERTIES) {
Properties prop;
if (valueType == ItemValueType.BEAN) {
prop = evaluateBeanAsProperties(itemRule.getBeanRuleMap());
} else {
prop = evaluateAsProperties(itemRule.getTokensMap(), valueType);
}
if (prop != null) {
values = new String[] { prop.toString() };
}
}
return values;
} catch (Exception e) {
throw new ItemEvaluationException(itemRule, e);
}
}
private Object evaluate(Token[] tokens, ItemValueType valueType) throws Exception {
Object value = evaluate(tokens);
return (value == null || valueType == null ? value : valuelize(value, valueType));
}
@SuppressWarnings("all")
private Object[] evaluateAsArray(List<Token[]> tokensList, ItemValueType valueType)
throws Exception {
List<Object> list = evaluateAsList(tokensList, valueType);
if (list == null) {
return null;
}
if (valueType == ItemValueType.STRING) {
return list.toArray(new String[0]);
} else if (valueType == ItemValueType.INT) {
return list.toArray(new Integer[0]);
} else if (valueType == ItemValueType.LONG) {
return list.toArray(new Long[0]);
} else if (valueType == ItemValueType.FLOAT) {
return list.toArray(new Float[0]);
} else if (valueType == ItemValueType.DOUBLE) {
return list.toArray(new Double[0]);
} else if (valueType == ItemValueType.BOOLEAN) {
return list.toArray(new Boolean[0]);
} else if (valueType == ItemValueType.PARAMETERS) {
return list.toArray(new Parameters[0]);
} else if (valueType == ItemValueType.FILE) {
return list.toArray(new File[0]);
} else if (valueType == ItemValueType.MULTIPART_FILE) {
return list.toArray(new FileParameter[0]);
} else {
return list.toArray(new Object[0]);
}
}
private List<Object> evaluateAsList(List<Token[]> tokensList, ItemValueType valueType)
throws Exception {
if (tokensList == null || tokensList.isEmpty()) {
return null;
}
List<Object> valueList = new ArrayList<>(tokensList.size());
for (Token[] tokens : tokensList) {
Object value = evaluate(tokens);
if (value != null && valueType != null) {
value = valuelize(value, valueType);
}
valueList.add(value);
}
return valueList;
}
private Set<Object> evaluateAsSet(List<Token[]> tokensList, ItemValueType valueType)
throws Exception {
if (tokensList == null || tokensList.isEmpty()) {
return null;
}
Set<Object> valueSet = new LinkedHashSet<>();
for (Token[] tokens : tokensList) {
Object value = evaluate(tokens);
if (value != null && valueType != null) {
value = valuelize(value, valueType);
}
valueSet.add(value);
}
return valueSet;
}
private Map<String, Object> evaluateAsMap(Map<String, Token[]> tokensMap, ItemValueType valueType)
throws Exception {
if (tokensMap == null || tokensMap.isEmpty()) {
return null;
}
Map<String, Object> valueMap = new LinkedHashMap<>();
for (Map.Entry<String, Token[]> entry : tokensMap.entrySet()) {
Object value = evaluate(entry.getValue());
if (value != null && valueType != null) {
value = valuelize(value, valueType);
}
valueMap.put(entry.getKey(), value);
}
return valueMap;
}
private Properties evaluateAsProperties(Map<String, Token[]> tokensMap, ItemValueType valueType)
throws Exception {
if (tokensMap == null || tokensMap.isEmpty()) {
return null;
}
Properties prop = new Properties();
for (Map.Entry<String, Token[]> entry : tokensMap.entrySet()) {
Object value = evaluate(entry.getValue());
if (value != null && valueType != null) {
value = valuelize(value, valueType);
}
if (value != null) {
prop.put(entry.getKey(), value);
}
}
return prop;
}
private Object valuelize(Object value, ItemValueType valueType) throws Exception {
if (valueType == ItemValueType.STRING) {
return value.toString();
} else if (valueType == ItemValueType.INT) {
return (value instanceof Integer ? value : Integer.valueOf(value.toString()));
} else if (valueType == ItemValueType.LONG) {
return (value instanceof Long ? value : Long.valueOf(value.toString()));
} else if (valueType == ItemValueType.FLOAT) {
return (value instanceof Float ? value : Float.valueOf(value.toString()));
} else if (valueType == ItemValueType.DOUBLE) {
return (value instanceof Double ? value : Double.valueOf(value.toString()));
} else if (valueType == ItemValueType.BOOLEAN) {
return (value instanceof Boolean ? value : Boolean.valueOf(value.toString()));
} else if (valueType == ItemValueType.PARAMETERS) {
return new VariableParameters(value.toString());
} else if (valueType == ItemValueType.FILE) {
return (value instanceof File ? value : new File(value.toString()));
} else if (valueType == ItemValueType.MULTIPART_FILE) {
return (value instanceof FileParameter ? value : new FileParameter(new File(value.toString())));
} else {
return value;
}
}
private Object evaluateBean(BeanRule beanRule) {
return activity.getPrototypeScopeBean(beanRule);
}
private Object[] evaluateBeanAsArray(List<BeanRule> beanRuleList) {
List<Object> valueList = evaluateBeanAsList(beanRuleList);
if (valueList == null) {
return null;
}
Class<?> componentType = null;
for (Object value : valueList) {
if (value != null) {
if (componentType == null) {
componentType = value.getClass();
} else if (componentType != value.getClass()) {
componentType = null;
break;
}
}
}
if (componentType != null) {
Object values = Array.newInstance(componentType, valueList.size());
for (int i = 0; i < valueList.size(); i++) {
Array.set(values, i, valueList.get(i));
}
return (Object[])values;
} else {
return valueList.toArray(new Object[0]);
}
}
private List<Object> evaluateBeanAsList(List<BeanRule> beanRuleList) {
if (beanRuleList == null || beanRuleList.isEmpty()) {
return null;
}
List<Object> valueList = new ArrayList<>(beanRuleList.size());
for (BeanRule beanRule : beanRuleList) {
valueList.add(evaluateBean(beanRule));
}
return valueList;
}
private Set<Object> evaluateBeanAsSet(List<BeanRule> beanRuleList) {
if (beanRuleList == null || beanRuleList.isEmpty()) {
return null;
}
Set<Object> valueSet = new LinkedHashSet<>();
for (BeanRule beanRule : beanRuleList) {
Object value = evaluateBean(beanRule);
valueSet.add(value);
}
return valueSet;
}
private Map<String, Object> evaluateBeanAsMap(Map<String, BeanRule> beanRuleMap) {
if (beanRuleMap == null || beanRuleMap.isEmpty()) {
return null;
}
Map<String, Object> valueMap = new LinkedHashMap<>();
for (Map.Entry<String, BeanRule> entry : beanRuleMap.entrySet()) {
Object value = evaluateBean(entry.getValue());
valueMap.put(entry.getKey(), value);
}
return valueMap;
}
private Properties evaluateBeanAsProperties(Map<String, BeanRule> beanRuleMap) {
if (beanRuleMap == null || beanRuleMap.isEmpty()) {
return null;
}
Properties prop = new Properties();
for (Map.Entry<String, BeanRule> entry : beanRuleMap.entrySet()) {
Object value = evaluateBean(entry.getValue());
if (value != null) {
prop.put(entry.getKey(), value);
}
}
return prop;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.phoenix.iterate;
import static org.apache.phoenix.monitoring.PhoenixMetrics.CountMetric.NUM_SPOOL_FILE;
import static org.apache.phoenix.monitoring.PhoenixMetrics.SizeMetric.SPOOL_FILE_SIZE;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.io.output.DeferredFileOutputStream;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.io.WritableUtils;
import org.apache.phoenix.compile.StatementContext;
import org.apache.phoenix.memory.MemoryManager;
import org.apache.phoenix.memory.MemoryManager.MemoryChunk;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.query.QueryServicesOptions;
import org.apache.phoenix.schema.tuple.ResultTuple;
import org.apache.phoenix.schema.tuple.Tuple;
import org.apache.phoenix.util.ByteUtil;
import org.apache.phoenix.util.ResultUtil;
import org.apache.phoenix.util.ServerUtil;
import org.apache.phoenix.util.TupleUtil;
/**
*
* Result iterator that spools the results of a scan to disk once an in-memory threshold has been reached.
* If the in-memory threshold is not reached, the results are held in memory with no disk writing perfomed.
*
*
* @since 0.1
*/
public class SpoolingResultIterator implements PeekingResultIterator {
private final PeekingResultIterator spoolFrom;
public static class SpoolingResultIteratorFactory implements ParallelIteratorFactory {
private final QueryServices services;
public SpoolingResultIteratorFactory(QueryServices services) {
this.services = services;
}
@Override
public PeekingResultIterator newIterator(StatementContext context, ResultIterator scanner, Scan scan) throws SQLException {
return new SpoolingResultIterator(scanner, services);
}
}
public SpoolingResultIterator(ResultIterator scanner, QueryServices services) throws SQLException {
this (scanner, services.getMemoryManager(),
services.getProps().getInt(QueryServices.SPOOL_THRESHOLD_BYTES_ATTRIB, QueryServicesOptions.DEFAULT_SPOOL_THRESHOLD_BYTES),
services.getProps().getLong(QueryServices.MAX_SPOOL_TO_DISK_BYTES_ATTRIB, QueryServicesOptions.DEFAULT_MAX_SPOOL_TO_DISK_BYTES),
services.getProps().get(QueryServices.SPOOL_DIRECTORY, QueryServicesOptions.DEFAULT_SPOOL_DIRECTORY));
}
/**
* Create a result iterator by iterating through the results of a scan, spooling them to disk once
* a threshold has been reached. The scanner passed in is closed prior to returning.
* @param scanner the results of a table scan
* @param mm memory manager tracking memory usage across threads.
* @param thresholdBytes the requested threshold. Will be dialed down if memory usage (as determined by
* the memory manager) is exceeded.
* @throws SQLException
*/
SpoolingResultIterator(ResultIterator scanner, MemoryManager mm, final int thresholdBytes, final long maxSpoolToDisk, final String spoolDirectory) throws SQLException {
boolean success = false;
final MemoryChunk chunk = mm.allocate(0, thresholdBytes);
DeferredFileOutputStream spoolTo = null;
try {
// Can't be bigger than int, since it's the max of the above allocation
int size = (int)chunk.getSize();
spoolTo = new DeferredFileOutputStream(size, "ResultSpooler",".bin", new File(spoolDirectory)) {
@Override
protected void thresholdReached() throws IOException {
super.thresholdReached();
chunk.close();
}
};
DataOutputStream out = new DataOutputStream(spoolTo);
final long maxBytesAllowed = maxSpoolToDisk == -1 ?
Long.MAX_VALUE : thresholdBytes + maxSpoolToDisk;
long bytesWritten = 0L;
for (Tuple result = scanner.next(); result != null; result = scanner.next()) {
int length = TupleUtil.write(result, out);
bytesWritten += length;
if(bytesWritten > maxBytesAllowed){
throw new SpoolTooBigToDiskException("result too big, max allowed(bytes): " + maxBytesAllowed);
}
}
if (spoolTo.isInMemory()) {
byte[] data = spoolTo.getData();
chunk.resize(data.length);
spoolFrom = new InMemoryResultIterator(data, chunk);
} else {
NUM_SPOOL_FILE.increment();
SPOOL_FILE_SIZE.update(spoolTo.getFile().length());
spoolFrom = new OnDiskResultIterator(spoolTo.getFile());
if (spoolTo.getFile() != null) {
spoolTo.getFile().deleteOnExit();
}
}
success = true;
} catch (IOException e) {
throw ServerUtil.parseServerException(e);
} finally {
try {
scanner.close();
} finally {
try {
if (spoolTo != null) {
if(!success && spoolTo.getFile() != null){
spoolTo.getFile().delete();
}
spoolTo.close();
}
} catch (IOException ignored) {
// ignore close error
} finally {
if (!success) {
chunk.close();
}
}
}
}
}
@Override
public Tuple peek() throws SQLException {
return spoolFrom.peek();
}
@Override
public Tuple next() throws SQLException {
return spoolFrom.next();
}
@Override
public void close() throws SQLException {
spoolFrom.close();
}
/**
*
* Backing result iterator if it was not necessary to spool results to disk.
*
*
* @since 0.1
*/
private static class InMemoryResultIterator implements PeekingResultIterator {
private final MemoryChunk memoryChunk;
private final byte[] bytes;
private Tuple next;
private int offset;
private InMemoryResultIterator(byte[] bytes, MemoryChunk memoryChunk) throws SQLException {
this.bytes = bytes;
this.memoryChunk = memoryChunk;
advance();
}
private Tuple advance() throws SQLException {
if (offset >= bytes.length) {
return next = null;
}
int resultSize = ByteUtil.vintFromBytes(bytes, offset);
offset += WritableUtils.getVIntSize(resultSize);
ImmutableBytesWritable value = new ImmutableBytesWritable(bytes,offset,resultSize);
offset += resultSize;
Tuple result = new ResultTuple(ResultUtil.toResult(value));
return next = result;
}
@Override
public Tuple peek() throws SQLException {
return next;
}
@Override
public Tuple next() throws SQLException {
Tuple current = next;
advance();
return current;
}
@Override
public void close() {
memoryChunk.close();
}
@Override
public void explain(List<String> planSteps) {
}
}
/**
*
* Backing result iterator if results were spooled to disk
*
*
* @since 0.1
*/
private static class OnDiskResultIterator implements PeekingResultIterator {
private final File file;
private DataInputStream spoolFrom;
private Tuple next;
private boolean isClosed;
private OnDiskResultIterator (File file) {
this.file = file;
}
private synchronized void init() throws IOException {
if (spoolFrom == null) {
spoolFrom = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
advance();
}
}
private synchronized void reachedEnd() throws IOException {
next = null;
isClosed = true;
try {
if (spoolFrom != null) {
spoolFrom.close();
}
} finally {
file.delete();
}
}
private synchronized Tuple advance() throws IOException {
if (isClosed) {
return next;
}
int length;
try {
length = WritableUtils.readVInt(spoolFrom);
} catch (EOFException e) {
reachedEnd();
return next;
}
int totalBytesRead = 0;
int offset = 0;
byte[] buffer = new byte[length];
while(totalBytesRead < length) {
int bytesRead = spoolFrom.read(buffer, offset, length);
if (bytesRead == -1) {
reachedEnd();
return next;
}
offset += bytesRead;
totalBytesRead += bytesRead;
}
next = new ResultTuple(ResultUtil.toResult(new ImmutableBytesWritable(buffer,0,length)));
return next;
}
@Override
public synchronized Tuple peek() throws SQLException {
try {
init();
return next;
} catch (IOException e) {
throw ServerUtil.parseServerException(e);
}
}
@Override
public synchronized Tuple next() throws SQLException {
try {
init();
Tuple current = next;
advance();
return current;
} catch (IOException e) {
throw ServerUtil.parseServerException(e);
}
}
@Override
public synchronized void close() throws SQLException {
try {
if (!isClosed) {
reachedEnd();
}
} catch (IOException e) {
throw ServerUtil.parseServerException(e);
}
}
@Override
public void explain(List<String> planSteps) {
}
}
@Override
public void explain(List<String> planSteps) {
}
}
| |
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.ocs.dynamo.ui.composite.grid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.ocs.dynamo.dao.FetchJoinInformation;
import com.ocs.dynamo.domain.AbstractEntity;
import com.ocs.dynamo.domain.model.AttributeModel;
import com.ocs.dynamo.domain.model.EntityModel;
import com.ocs.dynamo.service.BaseService;
import com.ocs.dynamo.ui.Searchable;
import com.ocs.dynamo.ui.composite.export.ExportDelegate;
import com.ocs.dynamo.ui.composite.layout.BaseCustomComponent;
import com.ocs.dynamo.ui.composite.layout.FormOptions;
import com.ocs.dynamo.ui.provider.QueryType;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridSortOrderBuilder;
import com.vaadin.flow.data.provider.DataProvider;
import com.vaadin.flow.data.provider.SortDirection;
import com.vaadin.flow.data.provider.SortOrder;
import com.vaadin.flow.function.SerializablePredicate;
public abstract class GridWrapper<ID extends Serializable, T extends AbstractEntity<ID>, U> extends BaseCustomComponent
implements Searchable<T> {
private static final long serialVersionUID = -7839990909007399928L;
/**
* The entity model used to create the container
*/
private EntityModel<T> entityModel;
/**
* The export service used for generating XLS and CSV exports
*/
private ExportDelegate exportDelegate = getService(ExportDelegate.class);
/**
* The entity model to use when exporting
*/
private EntityModel<T> exportEntityModel;
/**
* The joins to use when exporting (needed when using exportmode FULL)
*/
private FetchJoinInformation[] exportJoins;
/**
* The search filter that is applied to the grid
*/
private SerializablePredicate<T> filter;
/**
* The form options
*/
private FormOptions formOptions;
/**
* The fetch joins to use when querying
*/
private FetchJoinInformation[] joins;
/**
* The type of the query
*/
private final QueryType queryType;
/**
* The service used to query the database
*/
private final BaseService<ID, T> service;
/**
* The sort orders
*/
private List<SortOrder<?>> sortOrders = new ArrayList<>();
public GridWrapper(BaseService<ID, T> service, EntityModel<T> entityModel, QueryType queryType,
FormOptions formOptions, SerializablePredicate<T> filter, List<SortOrder<?>> sortOrders,
FetchJoinInformation... joins) {
setSpacing(false);
setPadding(false);
this.entityModel = entityModel;
this.filter = filter;
this.service = service;
this.queryType = queryType;
this.formOptions = formOptions;
this.sortOrders = sortOrders != null ? sortOrders : new ArrayList<>();
this.joins = joins;
}
/**
* Perform any actions that are necessary before carrying out a search
*
* @param filter the current search filter
*/
protected SerializablePredicate<T> beforeSearchPerformed(SerializablePredicate<T> filter) {
// overwrite in subclasses
return null;
}
public abstract DataProvider<U, SerializablePredicate<U>> getDataProvider();
public abstract int getDataProviderSize();
/**
* @return the entityModel
*/
public EntityModel<T> getEntityModel() {
return entityModel;
}
public ExportDelegate getExportDelegate() {
return exportDelegate;
}
public EntityModel<T> getExportEntityModel() {
return exportEntityModel;
}
public FetchJoinInformation[] getExportJoins() {
return exportJoins;
}
protected SerializablePredicate<T> getFilter() {
return filter;
}
public FormOptions getFormOptions() {
return formOptions;
}
public abstract Grid<U> getGrid();
public FetchJoinInformation[] getJoins() {
return joins;
}
public QueryType getQueryType() {
return queryType;
}
public BaseService<ID, T> getService() {
return service;
}
/**
*
* @return the sort orders
*/
public List<SortOrder<?>> getSortOrders() {
return Collections.unmodifiableList(sortOrders);
}
protected List<SortOrder<?>> initSortingAndFiltering() {
List<SortOrder<?>> fallBackOrders = new ArrayList<>();
if (getSortOrders() != null && !getSortOrders().isEmpty()) {
GridSortOrderBuilder<U> builder = new GridSortOrderBuilder<>();
for (SortOrder<?> o : getSortOrders()) {
if (getGrid().getColumnByKey((String) o.getSorted()) != null) {
// only include column in sort order if it is present in the grid
if (SortDirection.ASCENDING.equals(o.getDirection())) {
builder.thenAsc(getGrid().getColumnByKey(o.getSorted().toString()));
} else {
builder.thenDesc(getGrid().getColumnByKey(o.getSorted().toString()));
}
} else {
// not present in grid, add to backup
fallBackOrders.add(o);
}
}
getGrid().sort(builder.build());
} else if (getEntityModel().getSortOrder() != null && !getEntityModel().getSortOrder().keySet().isEmpty()) {
// sort based on the entity model
GridSortOrderBuilder<U> builder = new GridSortOrderBuilder<>();
for (AttributeModel am : entityModel.getSortOrder().keySet()) {
boolean asc = entityModel.getSortOrder().get(am);
if (getGrid().getColumnByKey(am.getPath()) != null) {
if (asc) {
builder.thenAsc(getGrid().getColumnByKey(am.getPath()));
} else {
builder.thenDesc(getGrid().getColumnByKey(am.getPath()));
}
} else {
fallBackOrders.add(new SortOrder<String>(am.getActualSortPath(),
asc ? SortDirection.ASCENDING : SortDirection.DESCENDING));
}
}
getGrid().sort(builder.build());
}
return fallBackOrders;
}
public abstract void reloadDataProvider();
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void search(SerializablePredicate<T> filter) {
SerializablePredicate<T> temp = beforeSearchPerformed(filter);
this.filter = temp != null ? temp : filter;
getGrid().getDataCommunicator().setDataProvider((DataProvider) getDataProvider(), temp != null ? temp : filter);
}
public void setExportEntityModel(EntityModel<T> exportEntityModel) {
this.exportEntityModel = exportEntityModel;
}
public void setExportJoins(FetchJoinInformation[] exportJoins) {
this.exportJoins = exportJoins;
}
/**
* Sets the provided filter as the component filter and then refreshes the
* container
*
* @param filter
*/
public void setFilter(SerializablePredicate<T> filter) {
this.filter = filter;
search(filter);
}
public void setJoins(FetchJoinInformation[] joins) {
this.joins = joins;
}
public void setSortOrders(List<SortOrder<?>> sortOrders) {
this.sortOrders = sortOrders;
}
}
| |
package org.eclipse.jetty.servlets;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.testing.ServletTester;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CrossOriginFilterTest
{
private ServletTester tester;
@Before
public void init() throws Exception
{
tester = new ServletTester();
tester.start();
}
@After
public void destroy() throws Exception
{
if (tester != null)
tester.stop();
}
@Test
public void testRequestWithNoOriginArrivesToApplication() throws Exception
{
tester.getContext().addFilter(CrossOriginFilter.class, "/*", FilterMapping.DEFAULT);
final CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testSimpleRequestWithNonMatchingOrigin() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
String origin = "http://localhost";
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, origin);
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String otherOrigin = origin.replace("localhost", "127.0.0.1");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: " + otherOrigin + "\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testSimpleRequestWithMatchingWildcardOrigin() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
String origin = "http://subdomain.example.com";
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "http://*.example.com");
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: " + origin + "\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testSimpleRequestWithMatchingWildcardOriginAndMultipleSubdomains() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
String origin = "http://subdomain.subdomain.example.com";
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "http://*.example.com");
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: " + origin + "\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testSimpleRequestWithMatchingOrigin() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
String origin = "http://localhost";
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, origin);
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: " + origin + "\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testSimpleRequestWithMatchingMultipleOrigins() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
String origin = "http://localhost";
String otherOrigin = origin.replace("localhost", "127.0.0.1");
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, origin + "," + otherOrigin);
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
// Use 2 spaces as separator to test that the implementation does not fail
"Origin: " + otherOrigin + " " + " " + origin + "\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testSimpleRequestWithoutCredentials() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
filterHolder.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "false");
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testNonSimpleRequestWithoutPreflight() throws Exception
{
// We cannot know if an actual request has performed the preflight before:
// we'll trust browsers to do it right, so responses to actual requests
// will contain the CORS response headers.
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"PUT / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testOptionsRequestButNotPreflight() throws Exception
{
// We cannot know if an actual request has performed the preflight before:
// we'll trust browsers to do it right, so responses to actual requests
// will contain the CORS response headers.
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"OPTIONS / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testPUTRequestWithPreflight() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "PUT");
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
// Preflight request
String request = "" +
"OPTIONS / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER + ": PUT\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_MAX_AGE_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_METHODS_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_HEADERS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
// Preflight request was ok, now make the actual request
request = "" +
"PUT / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
}
@Test
public void testDELETERequestWithPreflightAndAllowedCustomHeaders() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,HEAD,POST,PUT,DELETE");
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,X-Custom");
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
// Preflight request
String request = "" +
"OPTIONS / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER + ": DELETE\r\n" +
CrossOriginFilter.ACCESS_CONTROL_REQUEST_HEADERS_HEADER + ": origin,x-custom,x-requested-with\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_MAX_AGE_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_METHODS_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_HEADERS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
// Preflight request was ok, now make the actual request
request = "" +
"DELETE / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"X-Custom: value\r\n" +
"X-Requested-With: local\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
}
@Test
public void testDELETERequestWithPreflightAndNotAllowedCustomHeaders() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,HEAD,POST,PUT,DELETE");
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
// Preflight request
String request = "" +
"OPTIONS / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER + ": DELETE\r\n" +
CrossOriginFilter.ACCESS_CONTROL_REQUEST_HEADERS_HEADER + ": origin,x-custom,x-requested-with\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
// The preflight request failed because header X-Custom is not allowed, actual request not issued
}
@Test
public void testCrossOriginFilterDisabledForWebSocketUpgrade() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Connection: Upgrade\r\n" +
"Upgrade: WebSocket\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testSimpleRequestWithExposedHeaders() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
filterHolder.setInitParameter("exposedHeaders", "Content-Length");
tester.getContext().addFilter(filterHolder, "/*", FilterMapping.DEFAULT);
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_EXPOSE_HEADERS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
public static class ResourceServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private final CountDownLatch latch;
public ResourceServlet(CountDownLatch latch)
{
this.latch = latch;
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
latch.countDown();
}
}
}
| |
//pakage joney_000[let_me_start]
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
/******************** Main Class ***********************/
public class C
{
public static InputStream inputStream = System.in;
public static OutputStream outputStream = System.out;
public static FastReader in = new FastReader(inputStream);;
public static PrintWriter out = new PrintWriter(outputStream);;
/*
Overhead [Additional Temporary Strorage]
*/
public static int tempints[] = new int[100005];
public static long templongs[] = new long[100005];
public static double tempdoubles[] = new double[100005];
public static char tempchars[] = new char[100005];
public static long mod = 1000000000+7;
public static void main(String[] args) throws java.lang.Exception{
//let_me_start
int n = i(); int m = i();
//int arr[] = is((int)n);
//String ans = "NO";
long ans=0;
for(int i=1;i<=n;i++){
}
out.write(""+ans+"\n");
out.flush();
return;
}
out.write(""+ans+"\n");
out.flush();
return;
}
//****************************** Utilities ***********************//
public static boolean isPrime(long n)throws Exception{
if(n==1)return false;
if(n<=3)return true;
if(n%2==0)return false;
for(int i=2 ;i <= Math.sqrt(n); i++){
if(n%i==0)return false;
}
return true;
}
// sieve
public static int[] primes(int n)throws Exception{ // for(int i=1;i<=arr.length-1;i++)out.write(""+arr[i]+" ");
boolean arr[] = new boolean[n+1];
Arrays.fill(arr,true);
for(int i=1;i<=Math.sqrt(n);i++){
if(!arr[i])continue;
for(int j = 2*i ;j<=n;j+=i){
arr[i]=false;
}
}
LinkedList<Integer> ll = new LinkedList<Integer>();
for(int i=1;i<=n;i++){
if(arr[i])ll.add(i);
}
n = ll.size();
int primes[] = new int[n+1];
for(int i=1;i<=n;i++){
primes[i]=ll.removeFirst();
}
return primes;
}
public static long gcd (long a , long b)throws Exception{
if(b==0)return a;
return gcd(b , a%b);
}
public static long lcm (long a , long b)throws Exception{
if(a==0||b==0)return 0;
return (a*b)/gcd(a,b);
}
public static long mulmod(long a , long b ,long mod)throws Exception{
if(a==0||b==0)return 0;
if(b==1)return a;
long ans = mulmod(a,b/2,mod);
ans = (ans*2)% mod;
if(b%2==1)ans = (a + ans)% mod;
return ans;
}
public static long pow(long a , long b ,long mod)throws Exception{
if(b==0)return 1;
if(b==1)return a;
long ans = pow(a,b/2,mod);
ans = (ans * ans)% mod;
if(b%2==1)ans = (a * ans)% mod;
return ans;
}
// 20*20 nCr Pascal Table
public static long[][] ncrTable()throws Exception{
long ncr[][] = new long[21][21];
for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;}
for(int j=0;j<=20 ;j++){
for(int i=j+1;i<= 20 ;i++){
ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1];
}
}
return ncr;
}
//*******************************I/O******************************//
public static int i()throws Exception{
//return Integer.parseInt(br.readLine().trim());
return in.nextInt();
}
public static int[] is(int n)throws Exception{
//int arr[] = new int[n+1];
for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt();
return tempints;
}
public static long l()throws Exception{
return in.nextLong();
}
public static long[] ls(int n)throws Exception{
for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong();
return templongs;
}
public static double d()throws Exception{
return in.nextDouble();
}
public static double[] ds(int n)throws Exception{
for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble();
return tempdoubles;
}
public static char c()throws Exception{
return in.nextCharacter();
}
public static char[] cs(int n)throws Exception{
for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter();
return tempchars;
}
public static String s()throws Exception{
return in.nextLine();
}
public static BigInteger bi()throws Exception{
return in.nextBigInteger();
}
//***********************I/O ENDS ***********************//
//*********************** 0.3%f [precision]***********************//
/* roundoff upto 2 digits
double roundOff = Math.round(a * 100.0) / 100.0;
or
System.out.printf("%.2f", val);
*/
/*
print upto 2 digits after decimal
val = ((long)(val * 100.0))/100.0;
*/
}
class FastReader{
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastReader(InputStream stream){
this.stream = stream;
}
public int read(){
if (numChars == -1){
throw new InputMismatchException ();
}
if (curChar >= numChars){
curChar = 0;
try{
numChars = stream.read (buf);
} catch (IOException e){
throw new InputMismatchException ();
}
if (numChars <= 0){
return -1;
}
}
return buf[curChar++];
}
public int peek(){
if (numChars == -1){
return -1;
}
if (curChar >= numChars){
curChar = 0;
try{
numChars = stream.read (buf);
} catch (IOException e){
return -1;
}
if (numChars <= 0){
return -1;
}
}
return buf[curChar];
}
public int nextInt(){
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-'){
sgn = -1;
c = read ();
}
int res = 0;
do{
if(c==','){
c = read();
}
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
} while (!isSpaceChar (c));
return res * sgn;
}
public long nextLong(){
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-'){
sgn = -1;
c = read ();
}
long res = 0;
do{
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
} while (!isSpaceChar (c));
return res * sgn;
}
public String nextString(){
int c = read ();
while (isSpaceChar (c))
c = read ();
StringBuilder res = new StringBuilder ();
do{
res.appendCodePoint (c);
c = read ();
} while (!isSpaceChar (c));
return res.toString ();
}
public boolean isSpaceChar(int c){
if (filter != null){
return filter.isSpaceChar (c);
}
return isWhitespace (c);
}
public static boolean isWhitespace(int c){
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0(){
StringBuilder buf = new StringBuilder ();
int c = read ();
while (c != '\n' && c != -1){
if (c != '\r'){
buf.appendCodePoint (c);
}
c = read ();
}
return buf.toString ();
}
public String nextLine(){
String s = readLine0 ();
while (s.trim ().length () == 0)
s = readLine0 ();
return s;
}
public String nextLine(boolean ignoreEmptyLines){
if (ignoreEmptyLines){
return nextLine ();
}else{
return readLine0 ();
}
}
public BigInteger nextBigInteger(){
try{
return new BigInteger (nextString ());
} catch (NumberFormatException e){
throw new InputMismatchException ();
}
}
public char nextCharacter(){
int c = read ();
while (isSpaceChar (c))
c = read ();
return (char) c;
}
public double nextDouble(){
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-'){
sgn = -1;
c = read ();
}
double res = 0;
while (!isSpaceChar (c) && c != '.'){
if (c == 'e' || c == 'E'){
return res * Math.pow (10, nextInt ());
}
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
}
if (c == '.'){
c = read ();
double m = 1;
while (!isSpaceChar (c)){
if (c == 'e' || c == 'E'){
return res * Math.pow (10, nextInt ());
}
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
m /= 10;
res += (c - '0') * m;
c = read ();
}
}
return res * sgn;
}
public boolean isExhausted(){
int value;
while (isSpaceChar (value = peek ()) && value != -1)
read ();
return value == -1;
}
public String next(){
return nextString ();
}
public SpaceCharFilter getFilter(){
return filter;
}
public void setFilter(SpaceCharFilter filter){
this.filter = filter;
}
public interface SpaceCharFilter{
public boolean isSpaceChar(int ch);
}
}
/******************** Pair class ***********************/
class Pair implements Comparable<Pair>{
public int a;
public int b;
public Pair(){
this.a = 0;
this.b = 0;
}
public Pair(int a,int b){
this.a = a;
this.b = b;
}
public int compareTo(Pair p){
if(this.a==p.a){
return this.b-p.b;
}
return this.a-p.a;
}
public String toString(){
return "a="+this.a+" b="+this.b;
}
}
| |
/*
* Copyright 2004-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.store.jdbc;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.jdbc.datasource.DataSourceUtils;
import org.apache.lucene.store.jdbc.handler.ActualDeleteFileEntryHandler;
import org.apache.lucene.store.jdbc.support.JdbcTable;
import org.apache.lucene.store.jdbc.support.JdbcTemplate;
/**
* @author kimchy
*/
public class GeneralOperationsJdbcDirectoryTests extends AbstractJdbcDirectoryTests {
private JdbcDirectory jdbcDirectory;
protected void setUp() throws Exception {
super.setUp();
JdbcDirectorySettings settings = new JdbcDirectorySettings();
settings.getDefaultFileEntrySettings().setClassSetting(
JdbcFileEntrySettings.FILE_ENTRY_HANDLER_TYPE, ActualDeleteFileEntryHandler.class);
jdbcDirectory = new JdbcDirectory(dataSource, new JdbcTable(settings, createDialect(), "TEST"));
}
protected void tearDown() throws Exception {
jdbcDirectory.close();
super.tearDown();
}
public void testCreateDelteExists() throws IOException {
Connection con = DataSourceUtils.getConnection(dataSource);
jdbcDirectory.create();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
if (jdbcDirectory.getDialect().supportsTableExists()) {
con = DataSourceUtils.getConnection(dataSource);
assertTrue(jdbcDirectory.tableExists());
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
}
con = DataSourceUtils.getConnection(dataSource);
jdbcDirectory.delete();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
if (jdbcDirectory.getDialect().supportsTableExists()) {
con = DataSourceUtils.getConnection(dataSource);
assertFalse(jdbcDirectory.tableExists());
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
}
}
public void testCreateDelteExistsWitinTransaction() throws IOException {
Connection con = DataSourceUtils.getConnection(dataSource);
jdbcDirectory.create();
if (jdbcDirectory.getDialect().supportsTableExists()) {
assertTrue(jdbcDirectory.tableExists());
}
jdbcTemplate.executeSelect("select * from test", new JdbcTemplate.ExecuteSelectCallback() {
public void fillPrepareStatement(PreparedStatement ps) throws Exception {
}
public Object execute(ResultSet rs) throws Exception {
assertFalse(rs.next());
return null;
}
});
jdbcDirectory.delete();
if (jdbcDirectory.getDialect().supportsTableExists()) {
assertFalse(jdbcDirectory.tableExists());
}
try {
jdbcTemplate.executeSelect("select * from test", new JdbcTemplate.ExecuteSelectCallback() {
public void fillPrepareStatement(PreparedStatement ps) throws Exception {
}
public Object execute(ResultSet rs) throws Exception {
assertFalse(rs.next());
return null;
}
});
fail();
} catch (Exception e) {
}
DataSourceUtils.rollbackConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
}
public void testList() throws IOException {
Connection con = DataSourceUtils.getConnection(dataSource);
jdbcDirectory.create();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
con = DataSourceUtils.getConnection(dataSource);
String[] list = jdbcDirectory.list();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
assertEquals(0, list.length);
con = DataSourceUtils.getConnection(dataSource);
IndexOutput indexOutput = jdbcDirectory.createOutput("test1");
indexOutput.writeString("TEST STRING");
indexOutput.close();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
jdbcTemplate.executeSelect("select * from test", new JdbcTemplate.ExecuteSelectCallback() {
public void fillPrepareStatement(PreparedStatement ps) throws Exception {
}
public Object execute(ResultSet rs) throws Exception {
assertTrue(rs.next());
return null;
}
});
con = DataSourceUtils.getConnection(dataSource);
list = jdbcDirectory.list();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
assertEquals(1, list.length);
con = DataSourceUtils.getConnection(dataSource);
jdbcDirectory.deleteFile("test1");
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
con = DataSourceUtils.getConnection(dataSource);
list = jdbcDirectory.list();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
assertEquals(0, list.length);
}
public void testListWithinTransaction() throws IOException {
Connection con = DataSourceUtils.getConnection(dataSource);
jdbcDirectory.create();
String[] list = jdbcDirectory.list();
assertEquals(0, list.length);
IndexOutput indexOutput = jdbcDirectory.createOutput("test1");
indexOutput.writeString("TEST STRING");
indexOutput.close();
jdbcTemplate.executeSelect("select * from test", new JdbcTemplate.ExecuteSelectCallback() {
public void fillPrepareStatement(PreparedStatement ps) throws Exception {
}
public Object execute(ResultSet rs) throws Exception {
assertTrue(rs.next());
return null;
}
});
list = jdbcDirectory.list();
assertEquals(1, list.length);
jdbcDirectory.deleteFile("test1");
list = jdbcDirectory.list();
assertEquals(0, list.length);
DataSourceUtils.rollbackConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
}
public void testDeleteContent() throws IOException {
Connection con = DataSourceUtils.getConnection(dataSource);
jdbcDirectory.create();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
con = DataSourceUtils.getConnection(dataSource);
String[] list = jdbcDirectory.list();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
assertEquals(0, list.length);
con = DataSourceUtils.getConnection(dataSource);
IndexOutput indexOutput = jdbcDirectory.createOutput("test1");
indexOutput.writeString("TEST STRING");
indexOutput.close();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
con = DataSourceUtils.getConnection(dataSource);
list = jdbcDirectory.list();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
assertEquals(1, list.length);
con = DataSourceUtils.getConnection(dataSource);
jdbcDirectory.deleteContent();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
con = DataSourceUtils.getConnection(dataSource);
list = jdbcDirectory.list();
DataSourceUtils.commitConnectionIfPossible(con);
DataSourceUtils.releaseConnection(con);
assertEquals(0, list.length);
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.logs.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeLogGroups" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeLogGroupsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The prefix to match.
* </p>
*/
private String logGroupNamePrefix;
/**
* <p>
* The token for the next set of items to return. (You received this token from a previous call.)
* </p>
*/
private String nextToken;
/**
* <p>
* The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
* </p>
*/
private Integer limit;
/**
* <p>
* The prefix to match.
* </p>
*
* @param logGroupNamePrefix
* The prefix to match.
*/
public void setLogGroupNamePrefix(String logGroupNamePrefix) {
this.logGroupNamePrefix = logGroupNamePrefix;
}
/**
* <p>
* The prefix to match.
* </p>
*
* @return The prefix to match.
*/
public String getLogGroupNamePrefix() {
return this.logGroupNamePrefix;
}
/**
* <p>
* The prefix to match.
* </p>
*
* @param logGroupNamePrefix
* The prefix to match.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeLogGroupsRequest withLogGroupNamePrefix(String logGroupNamePrefix) {
setLogGroupNamePrefix(logGroupNamePrefix);
return this;
}
/**
* <p>
* The token for the next set of items to return. (You received this token from a previous call.)
* </p>
*
* @param nextToken
* The token for the next set of items to return. (You received this token from a previous call.)
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* The token for the next set of items to return. (You received this token from a previous call.)
* </p>
*
* @return The token for the next set of items to return. (You received this token from a previous call.)
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* The token for the next set of items to return. (You received this token from a previous call.)
* </p>
*
* @param nextToken
* The token for the next set of items to return. (You received this token from a previous call.)
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeLogGroupsRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* <p>
* The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
* </p>
*
* @param limit
* The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
*/
public void setLimit(Integer limit) {
this.limit = limit;
}
/**
* <p>
* The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
* </p>
*
* @return The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
*/
public Integer getLimit() {
return this.limit;
}
/**
* <p>
* The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
* </p>
*
* @param limit
* The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeLogGroupsRequest withLimit(Integer limit) {
setLimit(limit);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getLogGroupNamePrefix() != null)
sb.append("LogGroupNamePrefix: ").append(getLogGroupNamePrefix()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken()).append(",");
if (getLimit() != null)
sb.append("Limit: ").append(getLimit());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeLogGroupsRequest == false)
return false;
DescribeLogGroupsRequest other = (DescribeLogGroupsRequest) obj;
if (other.getLogGroupNamePrefix() == null ^ this.getLogGroupNamePrefix() == null)
return false;
if (other.getLogGroupNamePrefix() != null && other.getLogGroupNamePrefix().equals(this.getLogGroupNamePrefix()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
if (other.getLimit() == null ^ this.getLimit() == null)
return false;
if (other.getLimit() != null && other.getLimit().equals(this.getLimit()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getLogGroupNamePrefix() == null) ? 0 : getLogGroupNamePrefix().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
hashCode = prime * hashCode + ((getLimit() == null) ? 0 : getLimit().hashCode());
return hashCode;
}
@Override
public DescribeLogGroupsRequest clone() {
return (DescribeLogGroupsRequest) super.clone();
}
}
| |
package io.dropwizard.configuration;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.fasterxml.jackson.databind.node.TreeTraversingParser;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.snakeyaml.error.MarkedYAMLException;
import com.fasterxml.jackson.dataformat.yaml.snakeyaml.error.YAMLException;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A factory class for loading YAML configuration files, binding them to configuration objects, and
* and validating their constraints. Allows for overriding configuration parameters from system
* properties.
*
* @param <T> the type of the configuration objects to produce
*/
public class ConfigurationFactory<T> {
private final Class<T> klass;
private final String propertyPrefix;
private final ObjectMapper mapper;
private final Validator validator;
private final YAMLFactory yamlFactory;
/**
* Creates a new configuration factory for the given class.
*
* @param klass the configuration class
* @param validator the validator to use
* @param objectMapper the Jackson {@link ObjectMapper} to use
* @param propertyPrefix the system property name prefix used by overrides
*/
public ConfigurationFactory(Class<T> klass,
Validator validator,
ObjectMapper objectMapper,
String propertyPrefix) {
this.klass = klass;
this.propertyPrefix = propertyPrefix.endsWith(".") ? propertyPrefix : propertyPrefix + '.';
this.mapper = objectMapper.copy();
mapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
this.validator = validator;
this.yamlFactory = new YAMLFactory();
}
/**
* Loads, parses, binds, and validates a configuration object.
*
* @param provider the provider to to use for reading configuration files
* @param path the path of the configuration file
* @return a validated configuration object
* @throws IOException if there is an error reading the file
* @throws ConfigurationException if there is an error parsing or validating the file
*/
public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException {
try (InputStream input = provider.open(checkNotNull(path))) {
final JsonNode node = mapper.readTree(yamlFactory.createParser(input));
return build(node, path);
} catch (YAMLException e) {
ConfigurationParsingException.Builder builder = ConfigurationParsingException
.builder("Malformed YAML")
.setCause(e)
.setDetail(e.getMessage());
if (e instanceof MarkedYAMLException) {
builder.setLocation(((MarkedYAMLException) e).getProblemMark());
}
throw builder.build(path);
}
}
/**
* Loads, parses, binds, and validates a configuration object from a file.
*
* @param file the path of the configuration file
* @return a validated configuration object
* @throws IOException if there is an error reading the file
* @throws ConfigurationException if there is an error parsing or validating the file
*/
public T build(File file) throws IOException, ConfigurationException {
return build(new FileConfigurationSourceProvider(), file.toString());
}
/**
* Loads, parses, binds, and validates a configuration object from an empty document.
*
* @return a validated configuration object
* @throws IOException if there is an error reading the file
* @throws ConfigurationException if there is an error parsing or validating the file
*/
public T build() throws IOException, ConfigurationException {
return build(JsonNodeFactory.instance.objectNode(), "default configuration");
}
private T build(JsonNode node, String path) throws IOException, ConfigurationException {
for (Map.Entry<Object, Object> pref : System.getProperties().entrySet()) {
final String prefName = (String) pref.getKey();
if (prefName.startsWith(propertyPrefix)) {
final String configName = prefName.substring(propertyPrefix.length());
addOverride(node, configName, System.getProperty(prefName));
}
}
try {
final T config = mapper.readValue(new TreeTraversingParser(node), klass);
validate(path, config);
return config;
} catch (UnrecognizedPropertyException e) {
Collection<Object> knownProperties = e.getKnownPropertyIds();
List<String> properties = new ArrayList<>(knownProperties.size());
for (Object property : knownProperties) {
properties.add(property.toString());
}
throw ConfigurationParsingException.builder("Unrecognized field")
.setFieldPath(e.getPath())
.setLocation(e.getLocation())
.addSuggestions(properties)
.setSuggestionBase(e.getPropertyName())
.setCause(e)
.build(path);
} catch (InvalidFormatException e) {
String sourceType = e.getValue().getClass().getSimpleName();
String targetType = e.getTargetType().getSimpleName();
throw ConfigurationParsingException.builder("Incorrect type of value")
.setDetail("is of type: " + sourceType + ", expected: " + targetType)
.setLocation(e.getLocation())
.setFieldPath(e.getPath())
.setCause(e)
.build(path);
} catch (JsonMappingException e) {
throw ConfigurationParsingException.builder("Failed to parse configuration")
.setDetail(e.getMessage())
.setFieldPath(e.getPath())
.setLocation(e.getLocation())
.setCause(e)
.build(path);
}
}
private void addOverride(JsonNode root, String name, String value) {
JsonNode node = root;
final Iterable<String> split = Splitter.on('.').trimResults().split(name);
final String[] parts = Iterables.toArray(split, String.class);
for(int i = 0; i < parts.length; i++) {
String key = parts[i];
if (!(node instanceof ObjectNode)) {
throw new IllegalArgumentException("Unable to override " + name + "; it's not a valid path.");
}
final ObjectNode obj = (ObjectNode) node;
final String remainingPath = Joiner.on('.').join(Arrays.copyOfRange(parts, i, parts.length));
if (obj.has(remainingPath) && !remainingPath.equals(key)) {
if (obj.get(remainingPath).isValueNode()) {
obj.put(remainingPath, value);
return;
}
}
JsonNode child;
final boolean moreParts = i < parts.length - 1;
if (key.matches(".+\\[\\d+\\]$")) {
final int s = key.indexOf('[');
final int index = Integer.parseInt(key.substring(s + 1, key.length() - 1));
key = key.substring(0, s);
child = obj.get(key);
if (child == null) {
throw new IllegalArgumentException("Unable to override " + name + "; node with index not found.");
}
if (!child.isArray()) {
throw new IllegalArgumentException("Unable to override " + name + "; node with index is not an array.");
}
else if (index >= child.size()) {
throw new ArrayIndexOutOfBoundsException("Unable to override " + name + "; index is greater than size of array.");
}
if (moreParts) {
child = child.get(index);
node = child;
}
else {
ArrayNode array = (ArrayNode)child;
array.set(index, TextNode.valueOf(value));
return;
}
}
else if (moreParts) {
child = obj.get(key);
if (child == null) {
child = obj.objectNode();
obj.set(key, child);
}
if (child.isArray()) {
throw new IllegalArgumentException("Unable to override " + name + "; target is an array but no index specified");
}
node = child;
}
if (!moreParts) {
if (node.get(key) != null && node.get(key).isArray()) {
ArrayNode arrayNode = (ArrayNode) obj.get(key);
arrayNode.removeAll();
Pattern escapedComma = Pattern.compile("\\\\,");
for (String val : Splitter.on(Pattern.compile("(?<!\\\\),")).trimResults().split(value)) {
arrayNode.add(escapedComma.matcher(val).replaceAll(","));
}
}
else {
obj.put(key, value);
}
}
}
}
private void validate(String path, T config) throws ConfigurationValidationException {
final Set<ConstraintViolation<T>> violations = validator.validate(config);
if (!violations.isEmpty()) {
throw new ConfigurationValidationException(path, violations);
}
}
}
| |
/* Copyright 2014 Jim Voris
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qumasoft.guitools.qwin.filefilter;
import com.qumasoft.qvcslib.MergedInfoInterface;
import com.qumasoft.qvcslib.QVCSConstants;
import com.qumasoft.qvcslib.WorkFile;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.junit.Test;
/**
* Use JMockit mocking library to test file size greater than filter.
* @author JimVoris
*/
public class FileFilterFilesizeGreaterThanFilterTest {
@Mocked
MergedInfoInterface mergedInfo;
@Mocked
WorkFile workFile;
public FileFilterFilesizeGreaterThanFilterTest() {
}
/**
* Test of passesFilter method, of class FileFilterFilesizeGreaterThanFilter.
*/
@Test
public void testPassesFilter() {
System.out.println("passesFilter");
// New expectations...
new NonStrictExpectations() {{
mergedInfo.getWorkfile();
result = workFile;
mergedInfo.getWorkfileSize();
result = 100;
}};
FileFilterFilesizeGreaterThanFilter instance = new FileFilterFilesizeGreaterThanFilter("99", true);
boolean expResult = true;
boolean result = instance.passesFilter(mergedInfo, null);
assertEquals(expResult, result);
}
/**
* Test of passesFilter method, of class FileFilterFilesizeGreaterThanFilter.
*/
@Test
public void testNotPassesFilter() {
System.out.println("not passesFilter");
// New expectations...
new NonStrictExpectations() {{
mergedInfo.getWorkfile();
result = workFile;
mergedInfo.getWorkfileSize();
result = 100;
}};
FileFilterFilesizeGreaterThanFilter instance = new FileFilterFilesizeGreaterThanFilter("100", true);
boolean expResult = false;
boolean result = instance.passesFilter(mergedInfo, null);
assertEquals(expResult, result);
}
/**
* Test of getFilterType method, of class FileFilterFilesizeGreaterThanFilter.
*/
@Test
public void testGetFilterType() {
System.out.println("getFilterType");
FileFilterFilesizeGreaterThanFilter instance = new FileFilterFilesizeGreaterThanFilter("100", true);
String expResult = QVCSConstants.FILESIZE_GREATER_THAN_FILTER;
String result = instance.getFilterType();
assertEquals(expResult, result);
}
/**
* Test of toString method, of class FileFilterFilesizeGreaterThanFilter.
*/
@Test
public void testToString() {
System.out.println("toString");
FileFilterFilesizeGreaterThanFilter instance = new FileFilterFilesizeGreaterThanFilter("100", true);
String expResult = QVCSConstants.FILESIZE_GREATER_THAN_FILTER;
String result = instance.toString();
assertEquals(expResult, result);
}
/**
* Test of getFilterData method, of class FileFilterFilesizeGreaterThanFilter.
*/
@Test
public void testGetFilterData() {
System.out.println("getFilterData");
FileFilterFilesizeGreaterThanFilter instance = new FileFilterFilesizeGreaterThanFilter("100", true);
String expResult = "100";
String result = instance.getFilterData();
assertEquals(expResult, result);
}
/**
* Test of equals method, of class FileFilterFilesizeGreaterThanFilter.
*/
@Test
public void testEquals() {
System.out.println("equals");
Object o = new FileFilterFilesizeGreaterThanFilter("100", true);
FileFilterFilesizeGreaterThanFilter instance = new FileFilterFilesizeGreaterThanFilter("100", true);
boolean expResult = true;
boolean result = instance.equals(o);
assertEquals(expResult, result);
}
/**
* Test of equals method, of class FileFilterLastEditByFilter.
*/
@Test
public void testEqualsToNull() {
System.out.println("equals to null");
Object o = null;
FileFilterFilesizeGreaterThanFilter instance = new FileFilterFilesizeGreaterThanFilter("100", true);
boolean expResult = false;
boolean result = instance.equals(o);
assertEquals(expResult, result);
}
/**
* Test of equals method, of class FileFilterLastEditByFilter.
*/
@Test
public void testNotEquals() {
System.out.println("no equals");
Object o = new FileFilterFilesizeGreaterThanFilter("100", true);
FileFilterFilesizeGreaterThanFilter instance = new FileFilterFilesizeGreaterThanFilter("101", true);
boolean expResult = false;
boolean result = instance.equals(o);
assertEquals(expResult, result);
}
/**
* Test of equals method, of class FileFilterLastEditByFilter.
*/
@Test
public void testNotEquals2() {
System.out.println("no equals AND different");
Object o = new FileFilterFilesizeGreaterThanFilter("100", true);
FileFilterFilesizeGreaterThanFilter instance = new FileFilterFilesizeGreaterThanFilter("100", false);
boolean expResult = false;
boolean result = instance.equals(o);
assertEquals(expResult, result);
}
/**
* Test of hashCode method, of class FileFilterFilesizeGreaterThanFilter.
*/
@Test
public void testHashCode() {
System.out.println("hashCode");
FileFilterFilesizeGreaterThanFilter instance = new FileFilterFilesizeGreaterThanFilter("100", true);
int expResult = 666;
int result = instance.hashCode();
assertEquals(expResult, result);
}
/**
* Test of hashCode method, of class FileFilterLastEditByFilter.
*/
@Test
public void testDiffHashCode() {
System.out.println("diff hashCode");
FileFilterFilesizeGreaterThanFilter instanceA = new FileFilterFilesizeGreaterThanFilter("100", true);
FileFilterFilesizeGreaterThanFilter instanceB = new FileFilterFilesizeGreaterThanFilter("100", false);
assertNotEquals(instanceA.hashCode(), instanceB.hashCode());
}
/**
* Test of getRawFilterData method, of class FileFilterFilesizeGreaterThanFilter.
*/
@Test
public void testGetRawFilterData() {
System.out.println("getRawFilterData");
FileFilterFilesizeGreaterThanFilter instance = new FileFilterFilesizeGreaterThanFilter("100", true);
String expResult = "100";
String result = instance.getRawFilterData();
assertEquals(expResult, result);
}
}
| |
package zendesk.belvedere;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Pair;
import android.widget.ImageView;
import androidx.annotation.RestrictTo;
import androidx.appcompat.widget.AppCompatImageView;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.util.concurrent.atomic.AtomicBoolean;
import zendesk.belvedere.ui.R;
/**
* For internal use only.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class FixedWidthImageView extends AppCompatImageView implements Target {
private static final String LOG_TAG = "FixedWidthImageView";
private int viewWidth = -1;
private int viewHeight = -1;
private int rawImageWidth;
private int rawImageHeight;
private Uri uri = null;
private Picasso picasso;
private final AtomicBoolean imageWaiting = new AtomicBoolean(false);
private DimensionsCallback dimensionsCallback;
public FixedWidthImageView(Context context) {
super(context);
init();
}
public FixedWidthImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FixedWidthImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
void init() {
viewHeight = getResources().getDimensionPixelOffset(R.dimen.belvedere_image_stream_image_height);
}
public void showImage(final Picasso picasso, final Uri uri, CalculatedDimensions dimensions) {
if(uri == null || uri.equals(this.uri)) {
L.d(LOG_TAG, "Image already loaded. " + uri);
return;
}
// cancel running picasso operations
if(this.picasso != null) {
this.picasso.cancelRequest((Target) this);
this.picasso.cancelRequest((ImageView) this);
}
this.uri = uri;
this.picasso = picasso;
this.rawImageWidth = dimensions.rawImageWidth;
this.rawImageHeight = dimensions.rawImageHeight;
this.viewHeight = dimensions.viewHeight;
this.viewWidth = dimensions.viewWidth;
startImageLoading(picasso, uri, viewWidth, rawImageWidth, rawImageHeight);
}
public void showImage(final Picasso picasso, final Uri uri, long rawImageWidth, long rawImageHeight,
DimensionsCallback dimensionsCallback) {
if(uri == null || uri.equals(this.uri)) {
L.d(LOG_TAG, "Image already loaded. " + uri);
return;
}
// cancel running picasso operations
if(this.picasso != null) {
this.picasso.cancelRequest((Target) this);
this.picasso.cancelRequest((ImageView) this);
}
this.uri = uri;
this.picasso = picasso;
this.rawImageWidth = (int) rawImageWidth;
this.rawImageHeight = (int) rawImageHeight;
this.dimensionsCallback = dimensionsCallback;
if(viewWidth > 0) {
startImageLoading(picasso, uri, viewWidth, this.rawImageWidth, this.rawImageHeight);
} else {
imageWaiting.set(true);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
final int finalHeight = MeasureSpec.makeMeasureSpec(viewHeight, MeasureSpec.EXACTLY);
final int finalWidth;
if(viewWidth == -1) {
// the width is known; save it
viewWidth = measuredWidth;
}
if(viewWidth > 0) {
// the width is known, use it
finalWidth = MeasureSpec.makeMeasureSpec(viewWidth, MeasureSpec.EXACTLY);
// showImage() was called before we knew the view size
// now it's the time to load the image
if(imageWaiting.compareAndSet(true, false)) {
startImageLoading(picasso, uri, viewWidth, rawImageWidth, rawImageHeight);
}
} else {
finalWidth = widthMeasureSpec;
}
super.onMeasure(finalWidth, finalHeight);
}
private Pair<Integer, Integer> scale(int width, int imageWidth, int imageHeight) {
final float scaleFactor = (float)width / imageWidth;
return Pair.create(width, (int)(imageHeight * scaleFactor));
}
private void startImageLoading(Picasso picasso, Uri uri, int viewWidth, int rawImageWidth, int rawImageHeight) {
L.d(LOG_TAG, "Start loading image: " + viewWidth + " " + rawImageWidth + " " + rawImageHeight);
if(rawImageWidth > 0 && rawImageHeight > 0) {
final Pair<Integer, Integer> scaledDimensions =
scale(viewWidth, rawImageWidth, rawImageHeight);
loadImage(picasso, scaledDimensions.first, scaledDimensions.second, uri);
} else {
picasso.load(uri).into((Target) this);
}
}
private void loadImage(Picasso picasso, int scaledImageWidth, int scaledImageHeight, Uri uri) {
// the image height is known. update the view
this.viewHeight = scaledImageHeight;
// posting requestlayout makes it work better ... no idea why
post(new Runnable() {
@Override
public void run() {
requestLayout();
}
});
if(dimensionsCallback != null) {
dimensionsCallback.onImageDimensionsFound(
new CalculatedDimensions(rawImageHeight, rawImageWidth, viewHeight, viewWidth));
dimensionsCallback = null;
}
picasso.load(uri)
.resize(scaledImageWidth, scaledImageHeight)
.transform(Utils.roundTransformation(getContext(), R.dimen.belvedere_image_stream_item_radius))
.into((ImageView) this);
}
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
this.rawImageHeight = bitmap.getHeight();
this.rawImageWidth = bitmap.getWidth();
Pair<Integer, Integer> scaledDimensions = scale(viewWidth, rawImageWidth, rawImageHeight);
loadImage(picasso, scaledDimensions.first, scaledDimensions.second, uri);
}
@Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
// intentionally empty
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
// intentionally empty
}
interface DimensionsCallback {
void onImageDimensionsFound(CalculatedDimensions dimensions);
}
static class CalculatedDimensions {
private final int rawImageHeight;
private final int rawImageWidth;
private final int viewHeight;
private final int viewWidth;
CalculatedDimensions(int rawImageHeight, int rawImageWidth, int viewHeight, int viewWidth) {
this.rawImageHeight = rawImageHeight;
this.rawImageWidth = rawImageWidth;
this.viewHeight = viewHeight;
this.viewWidth = viewWidth;
}
}
}
| |
package it.angelic.soulissclient.helpers;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import it.angelic.soulissclient.Constants;
import it.angelic.soulissclient.R;
import it.angelic.soulissclient.adapters.TagRecyclerAdapter;
import it.angelic.soulissclient.model.ISoulissObject;
import it.angelic.soulissclient.model.SoulissNode;
import it.angelic.soulissclient.model.SoulissScene;
import it.angelic.soulissclient.model.SoulissTag;
import it.angelic.soulissclient.model.SoulissTypical;
import it.angelic.soulissclient.model.db.SoulissDBHelper;
import it.angelic.soulissclient.model.db.SoulissDBOpenHelper;
import it.angelic.soulissclient.model.db.SoulissDBTagHelper;
import static junit.framework.Assert.assertTrue;
/**
* Classe helper per i dialoghi riciclabili CHE USANO GRIDVIEW
*/
public class AlertDialogGridHelper {
/**
* Rename a node
*
* @param tagRecyclerAdapter used to invalidate views
* @param datasource to store new value
* @param toRename
* @return
*/
public static AlertDialog.Builder renameSoulissObjectDialog(final Context cont, final TextView tgt,
final TagRecyclerAdapter tagRecyclerAdapter, final SoulissDBHelper datasource, final ISoulissObject toRename) {
final AlertDialog.Builder alert = new AlertDialog.Builder(cont);
final SoulissPreferenceHelper opzioni = new SoulissPreferenceHelper(cont);
assertTrue("chooseIconDialog: NOT instanceof", toRename instanceof SoulissNode
|| toRename instanceof SoulissScene || toRename instanceof SoulissTypical || toRename instanceof SoulissTag);
alert.setIcon(android.R.drawable.ic_dialog_dialer);
alert.setTitle(cont.getString(R.string.rename) + " " + toRename.getNiceName());
// Set an EditText view to get user input
final EditText input = new EditText(cont);
alert.setView(input);
input.setText(toRename.getNiceName());
alert.setPositiveButton(cont.getResources().getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
toRename.setName(value);
SoulissDBHelper.open();
if (toRename instanceof SoulissNode) {
datasource.createOrUpdateNode((SoulissNode) toRename);
if (tagRecyclerAdapter != null) {
throw new RuntimeException("NOT IMPLEMENTED");
}
} else if (toRename instanceof SoulissScene) {
datasource.createOrUpdateScene((SoulissScene) toRename);
if (tagRecyclerAdapter != null) {
throw new RuntimeException("NOT IMPLEMENTED");
}
} else if (toRename instanceof SoulissTag) {
if (((SoulissTag) toRename).getTagId() <= SoulissDBOpenHelper.FAVOURITES_TAG_ID) {
Toast.makeText(cont, cont.getString(R.string.nodeleteFav), Toast.LENGTH_SHORT).show();
return;
}
SoulissDBTagHelper dbt = new SoulissDBTagHelper(cont);
dbt.createOrUpdateTag((SoulissTag) toRename);
if (tagRecyclerAdapter != null) {
int tgtPos = -1;
List<SoulissTag> goer = dbt.getRootTags();
tagRecyclerAdapter.setTagArray(goer);
try {
for (int i = 0; i < goer.size(); i++) {
if (goer.get(i).getTagId().equals(((SoulissTag) toRename).getTagId())) {
tgtPos = i;
tagRecyclerAdapter.notifyItemChanged(tgtPos);
Log.w(Constants.TAG, "notifiedAdapter of change on index " + tgtPos);
}
}
} catch (Exception e) {
Log.w(Constants.TAG, "rename didn't find proper view to refresh");
}
}
} else {
if (tagRecyclerAdapter != null) {
throw new RuntimeException("NOT IMPLEMENTED");
}
}
if (cont instanceof Activity && !(toRename instanceof SoulissTypical))
((Activity) cont).setTitle(toRename.getNiceName());
if (tgt != null) {
tgt.setText(value);
tgt.setText(toRename.getNiceName());
}
}
});
alert.setNegativeButton(cont.getResources().getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
return alert;
}
/* public static AlertDialog.Builder chooseIconDialog(final Context context, final TagRecyclerAdapter list,
final SoulissDBHelper datasource, final ISoulissObject toRename) {
final int savepoint = toRename.getIconResourceId();
final SoulissPreferenceHelper opzioni = new SoulissPreferenceHelper(context);
assertTrue("chooseIconDialog: NOT instanceof", toRename instanceof SoulissNode
|| toRename instanceof SoulissScene || toRename instanceof SoulissTypical || toRename instanceof SoulissTag);
final AlertDialog.Builder alert2 = new AlertDialog.Builder(context);
// alert2.setTitle("Choose " + toRename.toString() + " icon");
alert2.setTitle(context.getString(R.string.dialog_choose_icon) + " " + toRename.getNiceName());
alert2.setIcon(android.R.drawable.ic_dialog_dialer);
// loads gallery and requires icon selection
final EcoGallery gallery = new EcoGallery(context);
// final Gallery gallery = new Gallery(context);
// Gallery gallery = (Gallery) findViewById(R.id.gallery);
// gallery.setMinimumHeight(300);
// gallery.setLayoutParams(new Layo);
gallery.setAdapter(new SoulissIconAdapter(context));
alert2.setView(gallery);
alert2.setPositiveButton(context.getResources().getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
int pos = gallery.getSelectedItemPosition();
SoulissFontAwesomeAdapter ad = (SoulissFontAwesomeAdapter) gallery.getAdapter();
toRename.setIconResourceId(FontAwesomeUtil.getCodeIndexByFontName(context, FontAwesomeEnum.values()[pos].getFontName()));
if (toRename instanceof SoulissNode) {
datasource.createOrUpdateNode((SoulissNode) toRename);
} else if (toRename instanceof SoulissScene) {
datasource.createOrUpdateScene((SoulissScene) toRename);
} else if (toRename instanceof SoulissTag) {
SoulissDBTagHelper dbt = new SoulissDBTagHelper(SoulissApp.getAppContext());
dbt.createOrUpdateTag((SoulissTag) toRename);
if (list != null) {
// List<SoulissTag> goer = dbt.getRootTags(SoulissClient.getAppContext());
List<SoulissTag> tagArray = list.getTagArray();
// tagArray = goer.toArray(tagArray);
//list.setTagArray(tagArray);
try {
for (int i = 0; i < tagArray.size(); i++) {
if (tagArray.get(i).getTagId().equals(((SoulissTag) toRename).getTagId())) {
list.getTag(i).setIconResourceId(toRename.getIconResourceId());
list.notifyItemChanged(i);
Log.w(Constants.TAG, "notifiedAdapter of change on index " + i);
}
}
} catch (Exception e) {
Log.w(Constants.TAG, "rename didn't find proper view to refresh");
}
}
} else {
((SoulissTypical) toRename).getTypicalDTO().persist();
if (list != null) {
}
}
}
});
alert2.setNegativeButton(context.getResources().getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
toRename.setIconResourceId(savepoint);
}
});
return alert2;
}
*/
/**
* Remove a Scene
*
* @param ctx used to invalidate views
* @param datasource to store new value
* @param toRename
* @return
*/
public static void removeTagDialog(final Context cont, final TagRecyclerAdapter ctx, final SoulissDBTagHelper datasource,
final SoulissTag toRename) {
Log.w(Constants.TAG, "Removing TAG:" + toRename.getNiceName() + " ID:" + toRename.getTagId());
if (toRename.getTagId() <= SoulissDBOpenHelper.FAVOURITES_TAG_ID) {
Toast.makeText(cont, R.string.cantRemoveDefault, Toast.LENGTH_SHORT).show();
return;
}
AlertDialog.Builder alert = new AlertDialog.Builder(cont);
alert.setTitle(R.string.removeTag);
alert.setIcon(android.R.drawable.ic_dialog_alert);
alert.setMessage(R.string.sureToRemoveTag);
alert.setPositiveButton(cont.getResources().getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
int tgtPos = -1;
datasource.deleteTag(toRename);
if (ctx != null) {
List<SoulissTag> tagArrBck = ctx.getTagArray();
for (int i = 0; i < tagArrBck.size(); i++) {
if (tagArrBck.get(i).getTagId().equals(toRename.getTagId()))
tgtPos = i;
}
// prendo dal DB
List<SoulissTag> goer = datasource.getRootTags();
ctx.setTagArray(goer);
//shift visivo
ctx.notifyItemRemoved(tgtPos);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
//brutta pezza per riallineare position
public void run() {
ctx.notifyDataSetChanged();
}
}, 500); // 1500 seconds
}
}
});
alert.setNegativeButton(cont.getResources().getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
int tgtPos = -1;
if (ctx != null) {
List<SoulissTag> tagArrBck = ctx.getTagArray();
for (int i = 0; i < tagArrBck.size(); i++) {
if (tagArrBck.get(i).getTagId().equals(toRename.getTagId()))
tgtPos = i;
}
}
if (tgtPos != -1) {
ctx.notifyItemChanged(tgtPos);
}
}
});
alert.show();
}
}
| |
package com.charlesbodman.cordova.plugin.ironsource;
import android.util.Log;
import android.text.TextUtils;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ironsource.adapters.supersonicads.SupersonicConfig;
import com.ironsource.mediationsdk.IronSource;
import com.ironsource.mediationsdk.IronSourceBannerLayout;
import com.ironsource.mediationsdk.ISBannerSize;
import com.ironsource.mediationsdk.integration.IntegrationHelper;
import com.ironsource.mediationsdk.logger.IronSourceError;
import com.ironsource.mediationsdk.model.Placement;
import com.ironsource.mediationsdk.sdk.InterstitialListener;
import com.ironsource.mediationsdk.sdk.OfferwallListener;
import com.ironsource.mediationsdk.sdk.RewardedVideoListener;
import com.ironsource.mediationsdk.sdk.BannerListener;
public class IronSourceAdsPlugin extends CordovaPlugin
implements RewardedVideoListener, OfferwallListener, InterstitialListener {
private final String FALLBACK_USER_ID = "userId";
private static final String TAG = "[IronSourceAdsPlugin]";
private static final String EVENT_INTERSTITIAL_LOADED = "interstitialLoaded";
private static final String EVENT_INTERSTITIAL_SHOWN = "interstitialShown";
private static final String EVENT_INTERSTITIAL_SHOW_FAILED = "interstitialShowFailed";
private static final String EVENT_INTERSTITIAL_CLICKED = "interstitialClicked";
private static final String EVENT_INTERSTITIAL_CLOSED = "interstitialClosed";
private static final String EVENT_INTERSTITIAL_WILL_OPEN = "interstitialWillOpen";
private static final String EVENT_INTERSTITIAL_FAILED_TO_LOAD = "interstitialFailedToLoad";
private static final String EVENT_OFFERWALL_CLOSED = "offerwallClosed";
private static final String EVENT_OFFERWALL_CREDIT_FAILED = "offerwallCreditFailed";
private static final String EVENT_OFFERWALL_CREDITED = "offerwallCreditReceived";
private static final String EVENT_OFFERWALL_SHOW_FAILED = "offerwallShowFailed";
private static final String EVENT_OFFERWALL_SHOWN = "offerwallShown";
private static final String EVENT_OFFERWALL_AVAILABILITY_CHANGED = "offerwallAvailabilityChanged";
private static final String EVENT_REWARDED_VIDEO_FAILED = "rewardedVideoFailed";
private static final String EVENT_REWARDED_VIDEO_REWARDED = "rewardedVideoRewardReceived";
private static final String EVENT_REWARDED_VIDEO_ENDED = "rewardedVideoEnded";
private static final String EVENT_REWARDED_VIDEO_STARTED = "rewardedVideoStarted";
private static final String EVENT_REWARDED_VIDEO_AVAILABILITY_CHANGED = "rewardedVideoAvailabilityChanged";
private static final String EVENT_REWARDED_VIDEO_CLOSED = "rewardedVideoClosed";
private static final String EVENT_REWARDED_VIDEO_OPENED = "rewardedVideoOpened";
private static final String EVENT_REWARDED_VIDEO_CLICKED = "rewardedVideoClicked";
private static final String EVENT_BANNER_DID_LOAD = "bannerDidLoad";
private static final String EVENT_BANNER_FAILED_TO_LOAD = "bannerFailedToLoad";
private static final String EVENT_BANNER_DID_CLICK = "bannerDidClick";
private static final String EVENT_BANNER_WILL_PRESENT_SCREEN = "bannerWillPresentScreen";
private static final String EVENT_BANNER_DID_DISMISS_SCREEN = "bannerDidDismissScreen";
private static final String EVENT_BANNER_WILL_LEAVE_APPLICATION = "bannerWillLeaveApplication";
private IronSourceBannerLayout mIronSourceBannerLayout;
private RelativeLayout bannerContainerLayout;
private boolean bannerLoaded;
private boolean bannerShowing;
private CordovaWebView cordovaWebView;
private ViewGroup parentLayout;
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("init")) {
this.initAction(args, callbackContext);
return true;
}
else if (action.equals("setDynamicUserId")) {
this.setDynamicUserIdAction(args, callbackContext);
return true;
}
else if (action.equals("setConsent")) {
this.setConsentAction(args, callbackContext);
return true;
}
else if (action.equals("validateIntegration")) {
this.validateIntegrationAction(args, callbackContext);
return true;
}
else if (action.equals("showRewardedVideo")) {
this.showRewardedVideoAction(args, callbackContext);
return true;
}
else if (action.equals("hasRewardedVideo")) {
this.hasRewardedVideoAction(args, callbackContext);
return true;
}
else if (action.equals("isRewardedVideoCappedForPlacement")) {
this.isRewardedVideoCappedForPlacementAction(args, callbackContext);
return true;
}
else if (action.equals("loadBanner")) {
this.loadBannerAction(args, callbackContext);
return true;
}
else if (action.equals("showBanner")) {
this.showBannerAction(args, callbackContext);
return true;
}
else if (action.equals("hideBanner")) {
this.hideBannerAction(args, callbackContext);
return true;
}
else if (action.equals("hasOfferwall")) {
this.hasOfferwallAction(args, callbackContext);
return true;
}
else if (action.equals("showOfferwall")) {
this.showOfferwallAction(args, callbackContext);
return true;
}
else if (action.equals("loadInterstitial")) {
this.loadInterstitialAction(args, callbackContext);
return true;
}
else if (action.equals("hasInterstitial")) {
this.hasInterstitialAction(args, callbackContext);
return true;
}
else if (action.equals("showInterstitial")) {
this.showInterstitialAction(args, callbackContext);
return true;
}
return false;
}
/** --------------------------------------------------------------- */
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
cordovaWebView = webView;
bannerLoaded = false;
bannerShowing = false;
super.initialize(cordova, webView);
}
@Override
public void onPause(boolean multitasking) {
super.onPause(multitasking);
IronSource.onPause(this.cordova.getActivity());
}
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
IronSource.onResume(this.cordova.getActivity());
}
/** ----------------------- UTILS --------------------------- */
private JSONObject createErrorJSON(IronSourceError ironSourceError) {
JSONObject data = new JSONObject();
JSONObject errorData = new JSONObject();
try {
errorData.put("code", ironSourceError.getErrorCode());
errorData.put("message", ironSourceError.getErrorMessage());
data.put("error", errorData);
} catch (JSONException e) {
e.printStackTrace();
}
return data;
}
private void emitWindowEvent(final String event) {
final CordovaWebView view = this.webView;
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
view.loadUrl(String.format("javascript:cordova.fireWindowEvent('%s');", event));
}
});
}
private void emitWindowEvent(final String event, final JSONObject data) {
final CordovaWebView view = this.webView;
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
view.loadUrl(String.format("javascript:cordova.fireWindowEvent('%s', %s);", event, data.toString()));
}
});
}
/** ----------------------- INITIALIZATION --------------------------- */
/**
* Intilization action Initializes IronSource
*/
private void initAction(JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String appKey = args.getString(0);
final String providedUserId = args.getString(1);
final IronSourceAdsPlugin self = this;
// getting advertiser id should be done on a background thread
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
return IronSource.getAdvertiserId(self.cordova.getActivity());
}
@Override
protected void onPostExecute(String advertisingId) {
String userId = providedUserId;
if (TextUtils.isEmpty(userId)) {
userId = advertisingId;
}
if (TextUtils.isEmpty(userId)) {
userId = FALLBACK_USER_ID;
}
// we're using an advertisingId as the 'userId'
init(appKey, userId);
callbackContext.success();
}
};
task.execute();
}
/**
* Initializes IronSource
*
* @todo Provide
*/
private void init(String appKey, String userId) {
// Be sure to set a listener to each product that is being initiated
// set the IronSource rewarded video listener
IronSource.setRewardedVideoListener(this);
// set the IronSource offerwall listener
IronSource.setOfferwallListener(this);
// set the IronSource interstitial listener;
IronSource.setInterstitialListener(this);
// set client side callbacks for the offerwall
SupersonicConfig.getConfigObj().setClientSideCallbacks(true);
// Set user id
IronSource.setUserId(userId);
// init the IronSource SDK
IronSource.init(this.cordova.getActivity(), appKey);
}
/** ----------------------- SET DYNAMIC USER ID --------------------------- */
private void setDynamicUserIdAction(JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String userId = args.getString(0);
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
IronSource.setDynamicUserId(userId);
callbackContext.success();
}
});
}
/** ----------------------- SET CONSENT --------------------------- */
private void setConsentAction(JSONArray args, final CallbackContext callbackContext) throws JSONException {
final boolean consent = args.getBoolean(0);
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
IronSource.setConsent(consent);
callbackContext.success();
}
});
}
/**
* ----------------------- VALIDATION INTEGRATION ---------------------------
*/
/**
* Validates integration action
*/
private void validateIntegrationAction(JSONArray args, final CallbackContext callbackContext) {
final IronSourceAdsPlugin self = this;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
IntegrationHelper.validateIntegration(self.cordova.getActivity());
callbackContext.success();
}
});
}
/** ----------------------- REWARDED VIDEO --------------------------- */
private void showRewardedVideoAction(JSONArray args, final CallbackContext callbackContext) throws JSONException {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
IronSource.showRewardedVideo();
callbackContext.success();
}
});
}
private void hasRewardedVideoAction(JSONArray args, final CallbackContext callbackContext) throws JSONException {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
boolean available = IronSource.isRewardedVideoAvailable();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, available));
}
});
}
private void isRewardedVideoCappedForPlacementAction(JSONArray args, final CallbackContext callbackContext)
throws JSONException {
final String placementName = args.getString(0);
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
boolean capped = IronSource.isRewardedVideoPlacementCapped(placementName);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, capped));
}
});
}
@Override
public void onRewardedVideoAdOpened() {
this.emitWindowEvent(EVENT_REWARDED_VIDEO_OPENED);
}
@Override
public void onRewardedVideoAdClosed() {
this.emitWindowEvent(EVENT_REWARDED_VIDEO_CLOSED);
}
@Override
public void onRewardedVideoAvailabilityChanged(boolean available) {
JSONObject data = new JSONObject();
try {
data.put("available", available);
} catch (JSONException e) {
e.printStackTrace();
}
this.emitWindowEvent(EVENT_REWARDED_VIDEO_AVAILABILITY_CHANGED, data);
}
@Override
public void onRewardedVideoAdStarted() {
this.emitWindowEvent(EVENT_REWARDED_VIDEO_STARTED);
}
@Override
public void onRewardedVideoAdEnded() {
this.emitWindowEvent(EVENT_REWARDED_VIDEO_ENDED);
}
@Override
public void onRewardedVideoAdRewarded(Placement placement) {
String rewardName = placement.getRewardName();
int rewardAmount = placement.getRewardAmount();
JSONObject placementData = new JSONObject();
try {
placementData.put("name", placement.getPlacementName());
placementData.put("reward", placement.getRewardName());
placementData.put("amount", placement.getRewardAmount());
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject data = new JSONObject();
try {
data.put("placement", placementData);
} catch (JSONException e) {
e.printStackTrace();
}
this.emitWindowEvent(EVENT_REWARDED_VIDEO_REWARDED, data);
}
@Override
public void onRewardedVideoAdShowFailed(IronSourceError ironSourceError) {
this.emitWindowEvent(EVENT_REWARDED_VIDEO_FAILED, createErrorJSON(ironSourceError));
}
@Override
public void onRewardedVideoAdClicked(Placement placement) {
this.emitWindowEvent(EVENT_REWARDED_VIDEO_CLICKED);
}
/** ----------------------- INTERSTITIAL --------------------------- */
private void hasInterstitialAction(JSONArray args, final CallbackContext callbackContext) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
boolean ready = IronSource.isInterstitialReady();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, ready));
}
});
}
private void loadInterstitialAction(JSONArray args, final CallbackContext callbackContext) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
IronSource.loadInterstitial();
callbackContext.success();
}
});
}
private void showInterstitialAction(JSONArray args, final CallbackContext callbackContext) throws JSONException {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
IronSource.showInterstitial();
callbackContext.success();
}
});
}
@Override
public void onInterstitialAdReady() {
this.emitWindowEvent(EVENT_INTERSTITIAL_LOADED);
}
@Override
public void onInterstitialAdLoadFailed(IronSourceError ironSourceError) {
this.emitWindowEvent(EVENT_INTERSTITIAL_FAILED_TO_LOAD, createErrorJSON(ironSourceError));
}
@Override
public void onInterstitialAdOpened() {
this.emitWindowEvent(EVENT_INTERSTITIAL_WILL_OPEN, new JSONObject());
}
@Override
public void onInterstitialAdClosed() {
this.emitWindowEvent(EVENT_INTERSTITIAL_CLOSED, new JSONObject());
}
@Override
public void onInterstitialAdShowSucceeded() {
this.emitWindowEvent(EVENT_INTERSTITIAL_SHOWN, new JSONObject());
}
@Override
public void onInterstitialAdShowFailed(IronSourceError ironSourceError) {
this.emitWindowEvent(EVENT_INTERSTITIAL_SHOW_FAILED, createErrorJSON(ironSourceError));
}
@Override
public void onInterstitialAdClicked() {
this.emitWindowEvent(EVENT_INTERSTITIAL_CLICKED, new JSONObject());
}
/** ----------------------- OFFERWALL --------------------------- */
private void showOfferwallAction(JSONArray args, final CallbackContext callbackContext) throws JSONException {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
IronSource.showOfferwall();
callbackContext.success();
}
});
}
private void hasOfferwallAction(JSONArray args, final CallbackContext callbackContext) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
boolean available = IronSource.isOfferwallAvailable();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, available));
}
});
}
@Override
public void onOfferwallAvailable(boolean available) {
JSONObject data = new JSONObject();
try {
data.put("available", available);
} catch (JSONException e) {
e.printStackTrace();
}
this.emitWindowEvent(EVENT_OFFERWALL_AVAILABILITY_CHANGED, data);
}
@Override
public void onOfferwallOpened() {
this.emitWindowEvent(EVENT_OFFERWALL_SHOWN, new JSONObject());
}
@Override
public void onOfferwallShowFailed(IronSourceError ironSourceError) {
this.emitWindowEvent(EVENT_OFFERWALL_SHOW_FAILED, createErrorJSON(ironSourceError));
}
@Override
public boolean onOfferwallAdCredited(int credits, int totalCredits, boolean totalCreditsFlag) {
JSONObject data = new JSONObject();
try {
data.put("credits", credits);
data.put("totalCredits", totalCredits);
data.put("totalCreditsFlag", totalCreditsFlag);
} catch (JSONException e) {
e.printStackTrace();
}
this.emitWindowEvent(EVENT_OFFERWALL_CREDITED, data);
return true;
}
@Override
public void onGetOfferwallCreditsFailed(IronSourceError ironSourceError) {
this.emitWindowEvent(EVENT_OFFERWALL_CREDIT_FAILED, createErrorJSON(ironSourceError));
}
@Override
public void onOfferwallClosed() {
this.emitWindowEvent(EVENT_OFFERWALL_CLOSED);
}
/** ----------------------- BANNER --------------------------- */
private void showBannerAction(JSONArray args, final CallbackContext callbackContext) {
final IronSourceAdsPlugin self = this;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (mIronSourceBannerLayout != null && bannerLoaded && !bannerShowing) {
parentLayout = (ViewGroup) cordovaWebView.getView().getParent();
View view = cordovaWebView.getView();
ViewGroup wvParentView = (ViewGroup) view.getParent();
LinearLayout parentView = new LinearLayout(cordovaWebView.getContext());
if (wvParentView != null && wvParentView != parentView) {
ViewGroup rootView = (ViewGroup) (view.getParent());
wvParentView.removeView(view);
((LinearLayout) parentView).setOrientation(LinearLayout.VERTICAL);
parentView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, 0.0F));
view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, 1.0F));
parentView.addView(view);
rootView.addView(parentView);
}
bannerContainerLayout = new RelativeLayout(self.cordova.getActivity());
RelativeLayout.LayoutParams bannerContainerLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
bannerContainerLayout.setGravity(Gravity.BOTTOM);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
bannerContainerLayout.addView(mIronSourceBannerLayout, layoutParams);
mIronSourceBannerLayout.setLayoutParams(layoutParams);
parentView.addView(bannerContainerLayout);
bannerShowing = true;
}
callbackContext.success();
}
});
}
private void loadBannerAction(JSONArray args, final CallbackContext callbackContext) {
final IronSourceAdsPlugin self = this;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
hideBannerView();
destroyBanner();
// choose banner size
ISBannerSize size = ISBannerSize.BANNER;
// instantiate IronSourceBanner object, using the IronSource.createBanner API
mIronSourceBannerLayout = IronSource.createBanner(self.cordova.getActivity(), size);
if (mIronSourceBannerLayout != null) {
mIronSourceBannerLayout.setBannerListener(new BannerListener() {
@Override
public void onBannerAdLoaded() {
Log.d(TAG, "onBannerAdLoaded");
self.emitWindowEvent(EVENT_BANNER_DID_LOAD);
bannerLoaded = true;
}
@Override
public void onBannerAdLoadFailed(IronSourceError ironSourceError) {
self.emitWindowEvent(EVENT_BANNER_FAILED_TO_LOAD, createErrorJSON(ironSourceError));
}
@Override
public void onBannerAdClicked() {
self.emitWindowEvent(EVENT_BANNER_DID_CLICK);
}
@Override
public void onBannerAdScreenPresented() {
self.emitWindowEvent(EVENT_BANNER_WILL_PRESENT_SCREEN);
}
@Override
public void onBannerAdScreenDismissed() {
self.emitWindowEvent(EVENT_BANNER_DID_DISMISS_SCREEN);
}
@Override
public void onBannerAdLeftApplication() {
self.emitWindowEvent(EVENT_BANNER_WILL_LEAVE_APPLICATION);
}
});
}
IronSource.loadBanner(mIronSourceBannerLayout);
callbackContext.success();
}
});
}
private void hideBannerView() {
final IronSourceAdsPlugin self = this;
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
bannerShowing = false;
if (mIronSourceBannerLayout != null) {
if (parentLayout != null && bannerContainerLayout != null) {
if (mIronSourceBannerLayout.getParent() != null) {
bannerContainerLayout.removeView(mIronSourceBannerLayout);
}
if (bannerContainerLayout.getParent() != null) {
parentLayout.removeView(bannerContainerLayout);
}
}
}
}
});
}
/**
* Destory Banner
*/
private void destroyBanner() {
if (mIronSourceBannerLayout != null) {
IronSource.destroyBanner(mIronSourceBannerLayout);
mIronSourceBannerLayout = null;
}
}
/**
* Destroys IronSource Banner and removes it from the container
*/
private void hideBannerAction(JSONArray args, final CallbackContext callbackContext) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
hideBannerView();
callbackContext.success();
}
});
};
}
| |
/*
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.multi;
import java.util.Vector;
import javax.swing.plaf.DesktopIconUI;
import javax.swing.plaf.ComponentUI;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.accessibility.Accessible;
/**
* A multiplexing UI used to combine <code>DesktopIconUI</code>s.
*
* <p>This file was automatically generated by AutoMulti.
*
* @author Otto Multey
*/
public class MultiDesktopIconUI extends DesktopIconUI {
/**
* The vector containing the real UIs. This is populated
* in the call to <code>createUI</code>, and can be obtained by calling
* the <code>getUIs</code> method. The first element is guaranteed to be the real UI
* obtained from the default look and feel.
*/
protected Vector<ComponentUI> uis = new Vector<>();
/**
* Constructs a {@code MultiDesktopIconUI}.
*/
public MultiDesktopIconUI() {}
////////////////////
// Common UI methods
////////////////////
/**
* Returns the list of UIs associated with this multiplexing UI. This
* allows processing of the UIs by an application aware of multiplexing
* UIs on components.
*
* @return an array of the UI delegates
*/
public ComponentUI[] getUIs() {
return MultiLookAndFeel.uisToArray(uis);
}
////////////////////
// DesktopIconUI methods
////////////////////
////////////////////
// ComponentUI methods
////////////////////
/**
* Invokes the <code>contains</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public boolean contains(JComponent a, int b, int c) {
boolean returnValue =
uis.elementAt(0).contains(a,b,c);
for (int i = 1; i < uis.size(); i++) {
uis.elementAt(i).contains(a,b,c);
}
return returnValue;
}
/**
* Invokes the <code>update</code> method on each UI handled by this object.
*/
public void update(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
uis.elementAt(i).update(a,b);
}
}
/**
* Returns a multiplexing UI instance if any of the auxiliary
* <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the
* UI object obtained from the default <code>LookAndFeel</code>.
*
* @param a the component to create the UI for
* @return the UI delegate created
*/
public static ComponentUI createUI(JComponent a) {
MultiDesktopIconUI mui = new MultiDesktopIconUI();
return MultiLookAndFeel.createUIs(mui, mui.uis, a);
}
/**
* Invokes the <code>installUI</code> method on each UI handled by this object.
*/
public void installUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
uis.elementAt(i).installUI(a);
}
}
/**
* Invokes the <code>uninstallUI</code> method on each UI handled by this object.
*/
public void uninstallUI(JComponent a) {
for (int i = 0; i < uis.size(); i++) {
uis.elementAt(i).uninstallUI(a);
}
}
/**
* Invokes the <code>paint</code> method on each UI handled by this object.
*/
public void paint(Graphics a, JComponent b) {
for (int i = 0; i < uis.size(); i++) {
uis.elementAt(i).paint(a,b);
}
}
/**
* Invokes the <code>getPreferredSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getPreferredSize(JComponent a) {
Dimension returnValue =
uis.elementAt(0).getPreferredSize(a);
for (int i = 1; i < uis.size(); i++) {
uis.elementAt(i).getPreferredSize(a);
}
return returnValue;
}
/**
* Invokes the <code>getMinimumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMinimumSize(JComponent a) {
Dimension returnValue =
uis.elementAt(0).getMinimumSize(a);
for (int i = 1; i < uis.size(); i++) {
uis.elementAt(i).getMinimumSize(a);
}
return returnValue;
}
/**
* Invokes the <code>getMaximumSize</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Dimension getMaximumSize(JComponent a) {
Dimension returnValue =
uis.elementAt(0).getMaximumSize(a);
for (int i = 1; i < uis.size(); i++) {
uis.elementAt(i).getMaximumSize(a);
}
return returnValue;
}
/**
* Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public int getAccessibleChildrenCount(JComponent a) {
int returnValue =
uis.elementAt(0).getAccessibleChildrenCount(a);
for (int i = 1; i < uis.size(); i++) {
uis.elementAt(i).getAccessibleChildrenCount(a);
}
return returnValue;
}
/**
* Invokes the <code>getAccessibleChild</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public Accessible getAccessibleChild(JComponent a, int b) {
Accessible returnValue =
uis.elementAt(0).getAccessibleChild(a,b);
for (int i = 1; i < uis.size(); i++) {
uis.elementAt(i).getAccessibleChild(a,b);
}
return returnValue;
}
}
| |
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.opengles.spritetext;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.os.SystemClock;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.opengles.GL10;
public class SpriteTextRenderer implements GLView.Renderer{
public SpriteTextRenderer(Context context) {
mContext = context;
mTriangle = new Triangle();
mProjector = new Projector();
mLabelPaint = new Paint();
mLabelPaint.setTextSize(32);
mLabelPaint.setAntiAlias(true);
mLabelPaint.setARGB(0xff, 0x00, 0x00, 0x00);
}
public int[] getConfigSpec() {
// We don't need a depth buffer, and don't care about our
// color depth.
int[] configSpec = {
EGL10.EGL_DEPTH_SIZE, 0,
EGL10.EGL_NONE
};
return configSpec;
}
public void surfaceCreated(GL10 gl) {
/*
* By default, OpenGL enables features that improve quality
* but reduce performance. One might want to tweak that
* especially on software renderer.
*/
gl.glDisable(GL10.GL_DITHER);
/*
* Some one-time OpenGL initialization can be made here
* probably based on features of this particular context
*/
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,
GL10.GL_FASTEST);
gl.glClearColor(.5f, .5f, .5f, 1);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
/*
* Create our texture. This has to be done each time the
* surface is created.
*/
int[] textures = new int[1];
gl.glGenTextures(1, textures, 0);
mTextureID = textures[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MAG_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_REPLACE);
InputStream is = mContext.getResources()
.openRawResource(R.drawable.tex);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is);
} finally {
try {
is.close();
} catch(IOException e) {
// Ignore.
}
}
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
if (mLabels != null) {
mLabels.shutdown(gl);
} else {
mLabels = new LabelMaker(true, 256, 64);
}
mLabels.initialize(gl);
mLabels.beginAdding(gl);
mLabelA = mLabels.add(gl, "A", mLabelPaint);
mLabelB = mLabels.add(gl, "B", mLabelPaint);
mLabelC = mLabels.add(gl, "C", mLabelPaint);
mLabelMsPF = mLabels.add(gl, "ms/f", mLabelPaint);
mLabels.endAdding(gl);
if (mNumericSprite != null) {
mNumericSprite.shutdown(gl);
} else {
mNumericSprite = new NumericSprite();
}
mNumericSprite.initialize(gl, mLabelPaint);
}
public void drawFrame(GL10 gl) {
/*
* By default, OpenGL enables features that improve quality
* but reduce performance. One might want to tweak that
* especially on software renderer.
*/
gl.glDisable(GL10.GL_DITHER);
gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_MODULATE);
/*
* Usually, the first thing one might want to do is to clear
* the screen. The most efficient way of doing this is to use
* glClear().
*/
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
/*
* Now we're ready to draw some 3D objects
*/
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
GLU.gluLookAt(gl, 0.0f, 0.0f, -2.5f,
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glActiveTexture(GL10.GL_TEXTURE0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_REPEAT);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_REPEAT);
long time = SystemClock.uptimeMillis() % 4000L;
float angle = 0.090f * ((int) time);
gl.glRotatef(angle, 0, 0, 1.0f);
gl.glScalef(2.0f, 2.0f, 2.0f);
mTriangle.draw(gl);
mProjector.getCurrentModelView(gl);
mLabels.beginDrawing(gl, mWidth, mHeight);
drawLabel(gl, 0, mLabelA);
drawLabel(gl, 1, mLabelB);
drawLabel(gl, 2, mLabelC);
float msPFX = mWidth - mLabels.getWidth(mLabelMsPF) - 1;
mLabels.draw(gl, msPFX, 0, mLabelMsPF);
mLabels.endDrawing(gl);
drawMsPF(gl, msPFX);
}
private void drawMsPF(GL10 gl, float rightMargin) {
long time = SystemClock.uptimeMillis();
if (mStartTime == 0) {
mStartTime = time;
}
if (mFrames++ == SAMPLE_PERIOD_FRAMES) {
mFrames = 0;
long delta = time - mStartTime;
mStartTime = time;
mMsPerFrame = (int) (delta * SAMPLE_FACTOR);
}
if (mMsPerFrame > 0) {
mNumericSprite.setValue(mMsPerFrame);
float numWidth = mNumericSprite.width();
float x = rightMargin - numWidth;
mNumericSprite.draw(gl, x, 0, mWidth, mHeight);
}
}
private void drawLabel(GL10 gl, int triangleVertex, int labelId) {
float x = mTriangle.getX(triangleVertex);
float y = mTriangle.getY(triangleVertex);
mScratch[0] = x;
mScratch[1] = y;
mScratch[2] = 0.0f;
mScratch[3] = 1.0f;
mProjector.project(mScratch, 0, mScratch, 4);
float sx = mScratch[4];
float sy = mScratch[5];
float height = mLabels.getHeight(labelId);
float width = mLabels.getWidth(labelId);
float tx = sx - width * 0.5f;
float ty = sy - height * 0.5f;
mLabels.draw(gl, tx, ty, labelId);
}
public void sizeChanged(GL10 gl, int w, int h) {
mWidth = w;
mHeight = h;
gl.glViewport(0, 0, w, h);
mProjector.setCurrentView(0, 0, w, h);
/*
* Set our projection matrix. This doesn't have to be done
* each time we draw, but usually a new projection needs to
* be set when the viewport is resized.
*/
float ratio = (float) w / h;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
mProjector.getCurrentProjection(gl);
}
private int mWidth;
private int mHeight;
private Context mContext;
private Triangle mTriangle;
private int mTextureID;
private int mFrames;
private int mMsPerFrame;
private final static int SAMPLE_PERIOD_FRAMES = 12;
private final static float SAMPLE_FACTOR = 1.0f / SAMPLE_PERIOD_FRAMES;
private long mStartTime;
private LabelMaker mLabels;
private Paint mLabelPaint;
private int mLabelA;
private int mLabelB;
private int mLabelC;
private int mLabelMsPF;
private Projector mProjector;
private NumericSprite mNumericSprite;
private float[] mScratch = new float[8];
}
class Triangle {
public Triangle() {
// Buffers to be passed to gl*Pointer() functions
// must be direct, i.e., they must be placed on the
// native heap where the garbage collector cannot
// move them.
//
// Buffers with multi-byte datatypes (e.g., short, int, float)
// must have their byte order set to native order
ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4);
vbb.order(ByteOrder.nativeOrder());
mFVertexBuffer = vbb.asFloatBuffer();
ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4);
tbb.order(ByteOrder.nativeOrder());
mTexBuffer = tbb.asFloatBuffer();
ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2);
ibb.order(ByteOrder.nativeOrder());
mIndexBuffer = ibb.asShortBuffer();
for (int i = 0; i < VERTS; i++) {
for(int j = 0; j < 3; j++) {
mFVertexBuffer.put(sCoords[i*3+j]);
}
}
for (int i = 0; i < VERTS; i++) {
for(int j = 0; j < 2; j++) {
mTexBuffer.put(sCoords[i*3+j] * 2.0f + 0.5f);
}
}
for(int i = 0; i < VERTS; i++) {
mIndexBuffer.put((short) i);
}
mFVertexBuffer.position(0);
mTexBuffer.position(0);
mIndexBuffer.position(0);
}
public void draw(GL10 gl) {
gl.glFrontFace(GL10.GL_CCW);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer);
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer);
gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
}
public float getX(int vertex) {
return sCoords[3*vertex];
}
public float getY(int vertex) {
return sCoords[3*vertex+1];
}
private final static int VERTS = 3;
private FloatBuffer mFVertexBuffer;
private FloatBuffer mTexBuffer;
private ShortBuffer mIndexBuffer;
// A unit-sided equalateral triangle centered on the origin.
private final static float[] sCoords = {
// X, Y, Z
-0.5f, -0.25f, 0,
0.5f, -0.25f, 0,
0.0f, 0.559016994f, 0
};
}
| |
/**
* This software is released as part of the Pumpernickel project.
*
* All com.pump resources in the Pumpernickel project are distributed under the
* MIT License:
* https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt
*
* More information about the Pumpernickel project is available here:
* https://mickleness.github.io/pumpernickel/
*/
package com.pump.swing;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.prefs.Preferences;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.pump.math.Length;
/**
* A <code>JSpinner</code> that adjusts <code>Length</code> values.
* <P>
* You can monitor the unit this spinner is currently using two ways:
* <P>
* 1. Add a <code>PropertyChangeListener</code> to this object, and listen for
* <code>PROPERTY_UNIT</code> changes. Likewise you can call
* <code>putClientProperty(PROPERTY_UNIT, ...)</code> to change the unit
* currently displayed.
* <P>
* 2. Get the <code>SpinnerModel</code> for this spinner, which will be a
* <code>LengthSpinnerModel</code>. This class contains methods to get and set
* the <code>Length.Unit</code> that is in use.
*
* @see <a
* href="https://javagraphics.blogspot.com/2008/11/internationalization-measuring-lengths.html">Internationalization:
* Measuring Lengths</a>
*/
public class LengthSpinner extends JSpinner {
private static final long serialVersionUID = 1L;
public static BufferedImage createBlurbGraphic(Dimension preferredSize)
throws Exception {
final LengthSpinner spinner = new LengthSpinner(5, 1, 1, Length.INCH,
"");
JFrame frame = new JFrame();
frame.getContentPane().add(spinner);
frame.pack();
final BufferedImage image = new BufferedImage(spinner.getWidth(),
spinner.getHeight(), BufferedImage.TYPE_INT_ARGB);
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
Graphics2D g = image.createGraphics();
spinner.paint(g);
g.dispose();
}
});
return image;
}
/**
* A simple demo program to test <code>LengthSpinners</code>.
*
* @param args
* the application's arguments. (This is unused.)
*/
public static void main(String[] args) {
try {
String lf = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(lf);
} catch (Throwable e) {
e.printStackTrace();
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
f.getContentPane().add(panel);
panel.setPreferredSize(new Dimension(200, 70));
final LengthSpinner lengthSpinner1 = new LengthSpinner(5, 36, 100,
Length.INCH, "prefs");
final LengthSpinner lengthSpinner2 = new LengthSpinner(5, 36, 100,
Length.INCH, "prefs");
final JLabel label1 = new JLabel(" ");
final JLabel label2 = new JLabel(" ");
GridBagConstraints c = new GridBagConstraints();
c.weightx = 0;
c.weighty = 1;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(4, 4, 4, 4);
c.gridx = 0;
c.gridy = 0;
panel.add(lengthSpinner1, c);
c.gridy++;
panel.add(lengthSpinner2, c);
c.gridy++;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx++;
c.gridy = 0;
panel.add(label1, c);
c.gridy++;
panel.add(label2, c);
c.gridx++;
c.gridy = 0;
c.gridheight = 2;
c.weightx = 1;
panel.add(new JPanel(), c);
final DecimalFormat format = new DecimalFormat("#.###");
ChangeListener changeListener1 = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
LengthSpinnerModel model = (LengthSpinnerModel) lengthSpinner1
.getModel();
Length l = (Length) model.getValue();
label1.setText(format.format(l.getValue(Length.METER)) + " m");
}
};
ChangeListener changeListener2 = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
LengthSpinnerModel model = (LengthSpinnerModel) lengthSpinner2
.getModel();
Length l = (Length) model.getValue();
label2.setText(format.format(l.getValue(Length.FOOT)) + " ft");
}
};
lengthSpinner1.addChangeListener(changeListener1);
lengthSpinner2.addChangeListener(changeListener2);
// force the labels to update once
changeListener1.stateChanged(null);
changeListener2.stateChanged(null);
LengthSpinnerGroup group = new LengthSpinnerGroup();
group.add(lengthSpinner1);
group.add(lengthSpinner2);
f.pack();
f.setVisible(true);
}
public static final String PROPERTY_UNIT = "unit";
/**
* This is where the last-used unit is stored for
* <code>LengthSpinners</code> with a shared <code>preferenceKey</code>. By
* default this value is: <BR>
* <code>Preferences.userNodeForPackage(LengthSpinner.class)</code>
*/
public static Preferences prefs = Preferences
.userNodeForPackage(LengthSpinner.class);
private String preferenceKey = null;
private ChangeListener unitChangeListener = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
LengthSpinnerModel model = (LengthSpinnerModel) getModel();
Length.Unit currentUnit = model.getCurrentUnit();
putClientProperty(PROPERTY_UNIT, currentUnit);
}
};
private PropertyChangeListener unitPropertyListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
Length.Unit newUnit = (Length.Unit) e.getNewValue();
LengthSpinnerModel model = (LengthSpinnerModel) getModel();
model.setUnit(newUnit);
if (preferenceKey != null) {
prefs.put(preferenceKey, newUnit.getAbbreviation());
}
}
};
private static Map<Length.Unit, Length> defaultStepTable = new HashMap<>();
static {
defaultStepTable.put(Length.INCH, new Length(1, Length.INCH));
defaultStepTable.put(Length.FOOT, new Length(1, Length.FOOT));
defaultStepTable.put(Length.MILLIMETER,
new Length(1, Length.MILLIMETER));
defaultStepTable.put(Length.CENTIMETER,
new Length(1, Length.CENTIMETER));
defaultStepTable.put(Length.DECIMETER, new Length(1, Length.DECIMETER));
defaultStepTable.put(Length.METER, new Length(.5, Length.METER));
defaultStepTable.put(Length.YARD, new Length(.5, Length.YARD));
}
private static Map<Length.Unit, Length> createTable(double inch, double cm) {
Map<Length.Unit, Length> table = new HashMap<>();
table.put(Length.INCH, new Length(inch, Length.INCH));
table.put(Length.FOOT, new Length(inch / 12, Length.FOOT));
table.put(Length.YARD, new Length(inch / 36, Length.YARD));
table.put(Length.MILLIMETER, new Length(cm * 10, Length.MILLIMETER));
table.put(Length.CENTIMETER, new Length(cm, Length.CENTIMETER));
table.put(Length.DECIMETER, new Length(cm / 10, Length.DECIMETER));
table.put(Length.METER, new Length(cm / 100, Length.METER));
return table;
}
private static Map<Length.Unit, Length> wrap(double v, Length.Unit u) {
Map<Length.Unit, Length> table = new HashMap<Length.Unit, Length>();
table.put(u, new Length(v, u));
return table;
}
/**
* Creates a new <code>LengthSpinner</code> using numbers meant for only 1
* type of unit.
* <P>
* This is not really recommended, unless your users have to comply with
* certain length restrictions. For example, if the default unit is inch and
* the step size is 1, then when the user increases or decreases this
* spinner it will always use a step size of 1 inch. So if this spinner is
* set to work in centimeters: then the user will see a step size of 2.54
* cm.
*
* @param value
* the initial value
* @param min
* the minimal value
* @param max
* the maximum value
* @param stepSize
* the step size
* @param unit
* the default unit
* @param numberFormat
* an optional format to specify how to round/display values.
* @param preferenceKey
* an optional key to save the unit the user views this data in
* across sessions. If this is null, then the preferred unit is
* not saved between sessions. If this is non-null, then this key
* is used to store/retrieve the unit the user prefers for this
* spinner (and all other spinners that share the same key).
*/
public LengthSpinner(double value, double min, double max, double stepSize,
Length.Unit unit, DecimalFormat numberFormat, String preferenceKey) {
this(value, wrap(min, unit), wrap(max, unit), wrap(stepSize, unit),
unit, numberFormat, preferenceKey);
}
/**
* Creates a <code>LengthSpinner</code> with a "standard" set of step sizes
* and minimums of zero.
*
* @param value
* the initial value, in the default unit
* @param inchMax
* the maximum value in inches. (The maximum value for feet/yards
* will be computed from this value.)
* @param cmMax
* the maximum value in centimeters. (The maximum value for other
* metric lengths will be computed from this value.)
* @param defaultUnit
* the default unit to use when the preferenceKey is null or
* uninitialized.
* @param preferenceKey
* an optional key to save the unit the user views this data in
* across sessions. If this is null, then the preferred unit is
* not saved between sessions. If this is non-null, then this key
* is used to store/retrieve the unit the user prefers for this
* spinner (and all other spinners that share the same key).
*/
public LengthSpinner(double value, double inchMax, double cmMax,
Length.Unit defaultUnit, String preferenceKey) {
this(value, 0, 0, inchMax, cmMax, defaultUnit, preferenceKey);
}
/**
* Creates a <code>LengthSpinner</code> with a "standard" set of step sizes
* (each step size is 1 or .5).
*
* @param value
* the initial value, in the default unit
* @param inchMin
* the minimum value in inches. (The minimum value for feet/yards
* will be computed from this value.)
* @param cmMin
* the minimum value in centimeters. (The minimum value for other
* metric lengths will be computed from this value.)
* @param inchMax
* the maximum value in inches. (The maximum value for feet/yards
* will be computed from this value.)
* @param cmMax
* the maximum value in centimeters. (The maximum value for other
* metric lengths will be computed from this value.)
* @param defaultUnit
* the default unit to use when the preferenceKey is null or
* uninitialized.
* @param preferenceKey
* an optional key to save the unit the user views this data in
* across sessions. If this is null, then the preferred unit is
* not saved between sessions. If this is non-null, then this key
* is used to store/retrieve the unit the user prefers for this
* spinner (and all other spinners that share the same key).
*/
public LengthSpinner(double value, double inchMin, double cmMin,
double inchMax, double cmMax, Length.Unit defaultUnit,
String preferenceKey) {
this(value, createTable(inchMin, cmMin), createTable(inchMax, cmMax),
defaultStepTable, defaultUnit, null, preferenceKey);
// by default we're going to allow for millimeters; so let's
// shorten a little bit:
setColumns(getColumns() - 1);
}
/**
* Creates a new <code>LengthSpinner</code>.
* <P>
* This is the constructor all other constructors delegate to.
*
* @param value
* the initial value, in the default unit.
* @param mins
* a table of minimum values. Each entry in this table has a
* key/value pair of Length.Unit/Length. Depending on the unit
* the user is currently using, different minimums may be used.
* If a minimum is not defined for the current unit, then the
* minimum for the default unit is used. (At the very least this
* table <i>must</i> contain an entry for the default unit; an
* exception is thrown otherwise.)
* @param maxs
* a table of maximum values. Each entry in this table has a
* key/value pair of Length.Unit/Length. Depending on the unit
* the user is currently using, different maximums may be used.
* If a maximum is not defined for the current unit, then the
* maximum for the default unit is used. (At the very least this
* table <i>must</i> contain an entry for the default unit; an
* exception is thrown otherwise.)
* @param stepSizes
* a table of step size values. Each entry in this table has a
* key/value pair of Length.Unit/Length. Depending on the unit
* the user is currently using, different step sizes may be used.
* If a step size is not defined for the current unit, then the
* step size for the default unit is used. (At the very least
* this table <i>must</i> contain an entry for the default unit;
* an exception is thrown otherwise.)
* @param unit
* the default unit to use when the preferenceKey is null or
* uninitialized.
* @param numberFormat
* an optional format for the numeric part of the length.
* @param preferenceKey
* an optional key to save the unit the user views this data in
* across sessions. If this is null, then the preferred unit is
* not saved between sessions. If this is non-null, then this key
* is used to store/retrieve the unit the user prefers for this
* spinner (and all other spinners that share the same key).
*/
public LengthSpinner(double value, Map<Length.Unit, Length> mins,
Map<Length.Unit, Length> maxs, Map<Length.Unit, Length> stepSizes,
Length.Unit unit, DecimalFormat numberFormat, String preferenceKey) {
super(new LengthSpinnerModel(value, mins, maxs, stepSizes, unit));
this.preferenceKey = preferenceKey;
LengthSpinnerModel model = (LengthSpinnerModel) getModel();
String preferredUnitName = preferenceKey == null ? null : prefs.get(
preferenceKey, null);
if (preferredUnitName != null) {
Length.Unit preferredUnit = Length.getUnitByName(preferredUnitName);
model.setUnit(preferredUnit);
}
putClientProperty(PROPERTY_UNIT, model.getCurrentUnit());
setEditor(new LengthSpinnerEditor(this, numberFormat));
model.addChangeListener(unitChangeListener);
addPropertyChangeListener(PROPERTY_UNIT, unitPropertyListener);
}
/**
* This directly sets the number of columns in the text field in the spinner
* editor.
* <P>
* The field picks a reasonable number of default columns, but you may find
* it necessary to increase this in certain cases.
*/
public void setColumns(int c) {
LengthSpinnerEditor editor = (LengthSpinnerEditor) getEditor();
editor.setColumns(c);
}
/**
* This returns the number of columns the text field in the spinner editor
* is designed for.
*/
public int getColumns() {
LengthSpinnerEditor editor = (LengthSpinnerEditor) getEditor();
return editor.getColumns();
}
/**
* Sets the spinner editor. If the argument is not a
* <code>LengthSpinnerEditor</code> then an
* <code>IllegalArgumentException</code> is thrown.
*/
@Override
public void setEditor(JComponent c) {
if (getEditor() instanceof LengthSpinnerEditor
&& (c instanceof LengthSpinnerEditor) == false)
throw new IllegalArgumentException(
"LengthSpinner.setEditor() can only be called for LengthSpinnerEditors ("
+ c.getClass().getName() + ")");
super.setEditor(c);
}
/**
* Sets the spinner model. If the argument is not a
* <code>LengthSpinnerModel</code> then an
* <code>IllegalArgumentException</code> is thrown.
*/
@Override
public void setModel(SpinnerModel c) {
if (getModel() instanceof LengthSpinnerModel
&& (c instanceof LengthSpinnerModel) == false)
throw new IllegalArgumentException(
"LengthSpinner.setModel() can only be called for LengthSpinnerModels ("
+ c.getClass().getName() + ")");
super.setModel(c);
}
/**
* Returns the current value as a <code>Length</code>.
*/
@Override
public Object getValue() {
return super.getValue();
}
/**
* Sets the current value.
*
* @param value
* the new value.
*/
@Override
public void setValue(Object value) {
setValue(value, true);
}
/**
* Sets the current value.
*
* @param value
* the new value.
* @param changeUnitsToMatchArgument
* if this is false, then the units currently being used in this
* <code>LengthSpinner</code> are retained. Otherwise this
* spinner takes on the units of the argument.
*/
public void setValue(Object value, boolean changeUnitsToMatchArgument) {
if (changeUnitsToMatchArgument == false) {
Length newV = (Length) value;
Length oldV = (Length) getValue();
Length.Unit oldUnit = oldV.getUnit();
if (oldUnit.equals(newV.getUnit()) == false) {
double d = newV.getValue(oldUnit);
newV = new Length(d, oldUnit);
}
value = newV;
}
super.setValue(value);
}
}
| |
/**
* ISC License (ISC)
*
* Copyright (c) 2014, Sam Lanning <sam@samlanning.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
package com.samlanning.tools.cdst;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.concurrent.Semaphore;
/**
* Tool which allows you to test arbitrary duplex "streams" that run over
* multiple threads.
*
* You specify a way for the tester to send input to the stream, and to handle
* failures, and then you can specify a synchronous list of "communications"
* to test the stream.
*
* @author Sam Lanning <sam@samlanning.com>
*
*/
public class CDSTester<InputType, OutputType> {
// Log Levels
// Logs are written to stdout
public static final int L_NONE = 0x0;
public static final int L_INFO = 0x1;
public static final int L_INPUT = 0x2;
public static final int L_OUTPUT = 0x4;
public static final int L_INTERNALS = 0x8;
public static final int L_INTERACTION = L_INPUT | L_OUTPUT;
public static final int L_ALL = L_INFO | L_INPUT | L_OUTPUT | L_INTERNALS;
private int logLevel = L_NONE;
/**
* How long should the tester wait before writing to the input to try and
* catch out invalid outputs from the stream?
*
* In milliseconds
*/
private long writeDelay = 20;
private Semaphore lock = new Semaphore(1);
private Semaphore readWait = new Semaphore(1);
/**
* Current state of the test
*/
private TesterState state = TesterState.PREPARING;
/**
* Handler to forward requests on to
*/
private CDSTHandler<InputType> handler = null;
/**
* List of Communications which should take place
*/
private LinkedList<Communication> comms = new LinkedList<Communication>();
/**
* Iterator used during testing
*/
private Iterator<Communication> iter;
private Communication nextExpectedComm;
/**
* Start a tester with a specific delay before writing to stream input
* (see CDSTester.writeDelay)
*
* @param writeDelay
*/
public CDSTester(long writeDelay){
this();
this.writeDelay = writeDelay;
}
public CDSTester(){
try {
this.lock.acquire();
this.readWait.acquire();
// Have Baton
// this.lock: 0
// this.readWait: 0
} catch (InterruptedException e) {
}
}
/**
* Setup the correct handler for this tester
* @param handler
*/
public void setHandler(CDSTHandler<InputType> handler) throws CDSTException {
this.assertPreparing();
if(this.handler != null)
throw new CDSTException("Already set Handler");
this.handler = handler;
}
public void setLogLevel(int logLevel){
this.logLevel = logLevel;
}
// ***************
// Methods used to build up list of communications
/**
* Tell the tester to expect some output from the stream at this point.
* @param object
* @throws CDSTException
*/
public void addOutputRead(OutputType object) throws CDSTException {
this.assertPreparing();
comms.add(new Communication(CommunicationType.OUTPUT, object,
new Exception()));
}
/**
* Tell the tester to write to the stream at this point.
* @param object
* @throws CDSTException
*/
public void addInputWrite(InputType object) throws CDSTException {
this.assertPreparing();
comms.add(new Communication(CommunicationType.INPUT, object,
new Exception()));
}
/**
* Tell the tester to expect some output from the stream at this point, and
* pass the object to the handler.
* @param handler
* @throws CDSTException
*/
public void addOutputRead(CDSTReadHandler<OutputType> handler)
throws CDSTException {
this.assertPreparing();
comms.add(new Communication(handler, new Exception()));
}
/**
* Tell the tester to write to the stream at this point, using a handler.
* @param handler
* @throws CDSTException
*/
public void addInputWrite(CDSTWriteHandler<InputType> handler)
throws CDSTException {
this.assertPreparing();
comms.add(new Communication(handler, new Exception()));
}
// End
// ***************
// ***************
// Methods used to communicate with the tester during testing
/**
* Tell the tester that there has been output received from the stream.
* @param object
* @throws InterruptedException
*/
public void readFromStream(OutputType object) throws CDSTException {
this.doRead(object);
}
// End
// ***************
/**
* Run the test
* @throws CDSTException
*/
public void run() throws CDSTException {
this.assertPreparing();
this.log("Running", CDSTester.L_INFO);
// Have Baton
// this.lock: 0
// this.readWait: 0
if(this.handler == null)
throw new CDSTException("Didn't set Handler");
this.doRun();
}
// ***************
// Internal methods used to actually run the test
private void doRun() throws CDSTException {
// Have Baton
// this.lock: 0
// this.readWait: 0
this.state = TesterState.RUNNING;
this.iter = this.comms.iterator();
this.doLoop();
}
private void doRead(OutputType object) throws CDSTException {
this.log("Read: " + object.toString(), CDSTester.L_OUTPUT);
// this.lock: 1 -> 0
// this.readWait: 0 -> 0
this.acquire(this.lock);
if(this.state == TesterState.STOPPED){
// Don't need to return transfer back to main thread, only to self
// this.lock: 0 -> 1
// this.readWait: 0 -> 0
this.release(this.lock);
throw new CDSTException("Already Stopped Testing");
}
// Have lock
if(!this.nextExpectedComm.isOutput()){
// Have received output when not supposed to
this.handler.fail(String.format(
"Received unexpected output from stream, was going to input: " +
"'%s' after delay, but instead received output: '%s'",
this.nextExpectedComm.getInput(),
object),
this.nextExpectedComm.trace);
// Stop testing
this.state = TesterState.STOPPED;
// Main Thread for testing is expecting this.lock to be released
// and not waiting on this.readWait
// this.lock: 0 -> 1
// this.readWait: 0 -> 0
this.release(this.lock);
} else {
// An output is expected, lets check it is the correct output
if(!this.nextExpectedComm.checkOutput(object)){
// Stop testing
this.state = TesterState.STOPPED;
}
// Pass the Baton
// this.lock: 0 -> 0
// this.readWait: 0 -> 1
this.release(this.readWait);
}
}
private void doLoop() throws CDSTException {
// Have Baton
// this.lock: 0
// this.readWait: 0
while(true){
this.log("Next Communication...", CDSTester.L_INTERNALS);
try {
this.nextExpectedComm = this.iter.next();
} catch (NoSuchElementException e) {
this.state = TesterState.STOPPED;
this.log("Finished (success)", CDSTester.L_INFO);
// Release Baton
this.release(this.lock);
return;
}
this.log("... is: " + this.nextExpectedComm.toString(),
CDSTester.L_INTERNALS);
// Inspect what the next communication is
if(this.nextExpectedComm.isInput()){
// Need to send input to stream, first wait to see if an invalid
// output will be sent first.
// this.lock: 0 -> 1
// this.readWait: 0 -> 0
this.release(this.lock);
this.sleep(this.writeDelay);
// this.lock: 1 -> 0
// this.readWait: 0 -> 0
this.acquire(this.lock);
// Check that we are still running
if(this.state == TesterState.STOPPED){
// this.lock: 0 -> 1
// this.readWait: 0 -> 0
this.release(this.lock);
return;
}
// Now send input
this.log("Writing: " + this.nextExpectedComm.getInput(),
CDSTester.L_INPUT);
this.handler.writeToStream(this.nextExpectedComm.getInput());
// And now loop back for next communication
} else {
// Next communication is an output, so we expect to have
// readFromStream called next
// transfer control to that thread and wait for transfer back
// Pass the Baton
// this.lock: 0 -> 1
// this.readWait: 0 -> 0
this.release(this.lock);
// Wait for transfer back
// this.lock: 0 -> 0
// this.readWait: 1 -> 0
this.acquire(this.readWait);
// Check that we are still running
if(this.state == TesterState.STOPPED){
// this.lock: 0 -> 1
// this.readWait: 0 -> 0
this.release(this.lock);
return;
}
// Now loop round again
}
}
}
// End
// ***************
// ***************
// Helper Methods
/**
* Acquire the lock on the mutex
* @throws CDSTException
*/
private void acquire(Semaphore s) throws CDSTException {
try {
s.acquire();
} catch (InterruptedException e) {
throw new CDSTException(e);
}
}
private void release(Semaphore s) {
s.release();
}
private void assertPreparing() throws CDSTException {
if(this.state != TesterState.PREPARING)
throw new CDSTException("Already run, can't perform action.");
}
private void sleep(long milliseconds) throws CDSTException{
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
throw new CDSTException(e);
}
}
/**
* Log something at a specific log level
* @param msg
* @param logLevel
*/
private void log(String msg, int logLevel){
if((logLevel & this.logLevel) > 0)
System.out.println("[CDST] " + msg);
}
// End
// ***************
private enum TesterState {
PREPARING,
RUNNING,
STOPPED
}
private class Communication {
private InputType input;
private OutputType output;
private CDSTWriteHandler<InputType> inputHandler;
private InputType inputHandlerCache;
private CDSTReadHandler<OutputType> outputHandler;
public final Exception trace;
@SuppressWarnings("unchecked")
public Communication(CommunicationType type, Object object
, Exception trace){
this.trace = trace;
switch(type){
case INPUT:
this.input = (InputType) object;
break;
case OUTPUT:
this.output = (OutputType) object;
break;
}
}
public Communication(CDSTWriteHandler<InputType> handler
, Exception trace){
this.trace = trace;
this.inputHandler = handler;
}
public Communication(CDSTReadHandler<OutputType> handler
, Exception trace){
this.trace = trace;
this.outputHandler = handler;
}
public boolean isInput(){
return this.input != null || this.inputHandler != null;
}
public InputType getInput(){
if(this.input != null)
return this.input;
else
if(this.inputHandlerCache != null)
return this.inputHandlerCache;
else
return this.inputHandlerCache = this.inputHandler.write();
}
public boolean isOutput(){
return this.output != null || this.outputHandler != null;
}
public boolean checkOutput(OutputType object) {
if(this.output != null)
if(this.output.equals(object))
return true;
else {
// Have received invalid output.
CDSTester.this.handler.fail(String.format(
"Received incorrect output from stream, was " +
"expecting: '%s' but instead received: '%s'",
this.output,
object),
this.trace);
return false;
}
else
try {
this.outputHandler.read(object);
return true;
} catch (Exception e) {
CDSTester.this.handler.fail(String.format(
"Received incorrect output from stream, " +
"CDSTReadHandler gave exception: '%s' after " +
"receiving: '%s'",
e,
object),
this.trace);
return false;
}
}
public String toString(){
if(this.input != null)
return "INPUT (" + this.input.toString() + ")";
else if(this.inputHandler != null)
return "INPUT (" + this.inputHandler.toString() + ")";
else if(this.output != null)
return "OUTPUT (" + this.output.toString() + ")";
else
return "INPUT (" + this.outputHandler.toString() + ")";
}
}
private enum CommunicationType {
INPUT, OUTPUT
}
}
| |
/*
* Copyright 2015-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.intentperf;
import com.google.common.collect.ImmutableList;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.ControllerNode;
import org.onosproject.cluster.NodeId;
import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
import org.onosproject.store.cluster.messaging.ClusterMessage;
import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
import org.onosproject.store.cluster.messaging.MessageSubject;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static org.onlab.util.SharedExecutors.getPoolThreadExecutor;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Collects and distributes performance samples.
*/
@Component(immediate = true)
@Service(value = IntentPerfCollector.class)
public class IntentPerfCollector {
private static final long SAMPLE_TIME_WINDOW_MS = 5_000;
private final Logger log = getLogger(getClass());
private static final int MAX_SAMPLES = 1_000;
private final List<Sample> samples = new LinkedList<>();
private static final MessageSubject SAMPLE = new MessageSubject("intent-perf-sample");
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected ClusterCommunicationService communicationService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected ClusterService clusterService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected IntentPerfUi ui;
// Auxiliary structures used to accrue data for normalized time interval
// across all nodes.
private long newestTime;
private Sample overall;
private Sample current;
private ControllerNode[] nodes;
private Map<NodeId, Integer> nodeToIndex;
private NodeId nodeId;
@Activate
public void activate() {
nodeId = clusterService.getLocalNode().id();
communicationService.addSubscriber(SAMPLE, new InternalSampleCollector(),
getPoolThreadExecutor());
nodes = clusterService.getNodes().toArray(new ControllerNode[]{});
Arrays.sort(nodes, (a, b) -> a.id().toString().compareTo(b.id().toString()));
nodeToIndex = new HashMap<>();
for (int i = 0; i < nodes.length; i++) {
nodeToIndex.put(nodes[i].id(), i);
}
clearSamples();
ui.setCollector(this);
log.info("Started");
}
@Deactivate
public void deactivate() {
communicationService.removeSubscriber(SAMPLE);
log.info("Stopped");
}
/**
* Clears all previously accumulated data.
*/
public synchronized void clearSamples() {
newestTime = 0;
overall = new Sample(0, nodes.length);
current = new Sample(0, nodes.length);
samples.clear();
}
/**
* Records a sample point of data about intent operation rate.
*
* @param overallRate overall rate
* @param currentRate current rate
*/
public void recordSample(double overallRate, double currentRate) {
long now = System.currentTimeMillis();
addSample(now, nodeId, overallRate, currentRate);
broadcastSample(now, nodeId, overallRate, currentRate);
}
/**
* Returns set of node ids as headers.
*
* @return node id headers
*/
public List<String> getSampleHeaders() {
List<String> headers = new ArrayList<>();
for (ControllerNode node : nodes) {
headers.add(node.id().toString());
}
return headers;
}
/**
* Returns set of all accumulated samples normalized to the local set of
* samples.
*
* @return accumulated samples
*/
public synchronized List<Sample> getSamples() {
return ImmutableList.copyOf(samples);
}
/**
* Returns overall throughput performance for each of the cluster nodes.
*
* @return overall intent throughput
*/
public synchronized Sample getOverall() {
return overall;
}
// Records a new sample to our collection of samples
private synchronized void addSample(long time, NodeId nodeId,
double overallRate, double currentRate) {
Sample fullSample = createCurrentSampleIfNeeded(time);
setSampleData(current, nodeId, currentRate);
setSampleData(overall, nodeId, overallRate);
pruneSamplesIfNeeded();
if (fullSample != null && ui != null) {
ui.reportSample(fullSample);
}
}
private Sample createCurrentSampleIfNeeded(long time) {
Sample oldSample = time - newestTime > SAMPLE_TIME_WINDOW_MS || current.isComplete() ? current : null;
if (oldSample != null) {
newestTime = time;
current = new Sample(time, nodes.length);
if (oldSample.time > 0) {
samples.add(oldSample);
}
}
return oldSample;
}
private void setSampleData(Sample sample, NodeId nodeId, double data) {
Integer index = nodeToIndex.get(nodeId);
if (index != null) {
sample.data[index] = data;
}
}
private void pruneSamplesIfNeeded() {
if (samples.size() > MAX_SAMPLES) {
samples.remove(0);
}
}
// Performance data sample.
static class Sample {
final long time;
final double[] data;
public Sample(long time, int nodeCount) {
this.time = time;
this.data = new double[nodeCount];
Arrays.fill(data, -1);
}
public boolean isComplete() {
for (int i = 0; i < data.length; i++) {
if (data[i] < 0) {
return false;
}
}
return true;
}
}
private void broadcastSample(long time, NodeId nodeId, double overallRate, double currentRate) {
String data = String.format("%d|%f|%f", time, overallRate, currentRate);
communicationService.broadcast(data, SAMPLE, str -> str.getBytes());
}
private class InternalSampleCollector implements ClusterMessageHandler {
@Override
public void handle(ClusterMessage message) {
String[] fields = new String(message.payload()).split("\\|");
log.debug("Received sample from {}: {}", message.sender(), fields);
addSample(Long.parseLong(fields[0]), message.sender(),
Double.parseDouble(fields[1]), Double.parseDouble(fields[2]));
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package backtype.storm.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
abstract public class ShellUtils {
public static final Logger LOG = LoggerFactory.getLogger(ShellUtils.class);
// OSType detection
public enum OSType {
OS_TYPE_LINUX,
OS_TYPE_WIN,
OS_TYPE_SOLARIS,
OS_TYPE_MAC,
OS_TYPE_FREEBSD,
OS_TYPE_OTHER
}
public static final OSType osType = getOSType();
static private OSType getOSType() {
String osName = System.getProperty("os.name");
if (osName.startsWith("Windows")) {
return OSType.OS_TYPE_WIN;
} else if (osName.contains("SunOS") || osName.contains("Solaris")) {
return OSType.OS_TYPE_SOLARIS;
} else if (osName.contains("Mac")) {
return OSType.OS_TYPE_MAC;
} else if (osName.contains("FreeBSD")) {
return OSType.OS_TYPE_FREEBSD;
} else if (osName.startsWith("Linux")) {
return OSType.OS_TYPE_LINUX;
} else {
// Some other form of Unix
return OSType.OS_TYPE_OTHER;
}
}
// Helper static vars for each platform
public static final boolean WINDOWS = (osType == OSType.OS_TYPE_WIN);
public static final boolean SOLARIS = (osType == OSType.OS_TYPE_SOLARIS);
public static final boolean MAC = (osType == OSType.OS_TYPE_MAC);
public static final boolean FREEBSD = (osType == OSType.OS_TYPE_FREEBSD);
public static final boolean LINUX = (osType == OSType.OS_TYPE_LINUX);
public static final boolean OTHER = (osType == OSType.OS_TYPE_OTHER);
/** Token separator regex used to parse Shell tool outputs */
public static final String TOKEN_SEPARATOR_REGEX
= WINDOWS ? "[|\n\r]" : "[ \t\n\r\f]";
private long interval; // refresh interval in msec
private long lastTime; // last time the command was performed
final private boolean redirectErrorStream; // merge stdout and stderr
private Map<String, String> environment; // env for the command execution
private File dir;
private Process process; // sub process used to execute the command
private int exitCode;
/** Time after which the executing script would be timedout */
protected long timeOutInterval = 0L;
/** If or not script timed out */
private AtomicBoolean timedOut;
/** If or not script finished executing */
private volatile AtomicBoolean completed;
public ShellUtils() {
this(0L);
}
public ShellUtils(long interval) {
this(interval, false);
}
public int getExitCode() {
return exitCode;
}
/**
* @param interval the minimum duration to wait before re-executing the command.
*/
public ShellUtils(long interval, boolean redirectErrorStream) {
this.interval = interval;
this.lastTime = (interval < 0) ? 0 : -interval;
this.redirectErrorStream = redirectErrorStream;
}
/**
* set the environment for the command
*
* @param env Mapping of environment variables
*/
protected void setEnvironment(Map<String, String> env) {
this.environment = env;
}
/**
* set the working directory
*
* @param dir The directory where the command would be executed
*/
protected void setWorkingDirectory(File dir) {
this.dir = dir;
}
/** a Unix command to get the current user's groups list */
public static String[] getGroupsCommand() {
return (WINDOWS)? new String[]{"cmd", "/c", "groups"}
: new String[]{"bash", "-c", "groups"};
}
/**
* a Unix command to get a given user's groups list. If the OS is not WINDOWS, the command will get the user's primary group first and finally get the
* groups list which includes the primary group. i.e. the user's primary group will be included twice.
*/
public static String[] getGroupsForUserCommand(final String user) {
// 'groups username' command return is non-consistent across different unixes
return new String [] {"bash", "-c", "id -gn " + user
+ "&& id -Gn " + user};
}
/** check to see if a command needs to be executed and execute if needed */
protected void run() throws IOException {
if (lastTime + interval > System.currentTimeMillis())
return;
exitCode = 0; // reset for next run
runCommand();
}
/** Run a command */
private void runCommand() throws IOException {
ProcessBuilder builder = new ProcessBuilder(getExecString());
Timer timeOutTimer = null;
ShellTimeoutTimerTask timeoutTimerTask = null;
timedOut = new AtomicBoolean(false);
completed = new AtomicBoolean(false);
if (environment != null) {
builder.environment().putAll(this.environment);
}
if (dir != null) {
builder.directory(this.dir);
}
builder.redirectErrorStream(redirectErrorStream);
process = builder.start();
if (timeOutInterval > 0) {
timeOutTimer = new Timer("Shell command timeout");
timeoutTimerTask = new ShellTimeoutTimerTask(this);
// One time scheduling.
timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
}
final BufferedReader errReader =
new BufferedReader(new InputStreamReader(process
.getErrorStream()));
BufferedReader inReader =
new BufferedReader(new InputStreamReader(process
.getInputStream()));
final StringBuffer errMsg = new StringBuffer();
// read error and input streams as this would free up the buffers
// free the error stream buffer
Thread errThread = new Thread() {
@Override
public void run() {
try {
String line = errReader.readLine();
while ((line != null) && !isInterrupted()) {
errMsg.append(line);
errMsg.append(System.getProperty("line.separator"));
line = errReader.readLine();
}
} catch (IOException ioe) {
LOG.warn("Error reading the error stream", ioe);
}
}
};
try {
errThread.start();
} catch (IllegalStateException ise) { }
try {
parseExecResult(inReader); // parse the output
// clear the input stream buffer
String line = inReader.readLine();
while (line != null) {
line = inReader.readLine();
}
// wait for the process to finish and check the exit code
exitCode = process.waitFor();
// make sure that the error thread exits
joinThread(errThread);
completed.set(true);
// the timeout thread handling
// taken care in finally block
if (exitCode != 0) {
throw new ExitCodeException(exitCode, errMsg.toString());
}
} catch (InterruptedException ie) {
throw new IOException(ie.toString());
} finally {
if (timeOutTimer != null) {
timeOutTimer.cancel();
}
// close the input stream
try {
// JDK 7 tries to automatically drain the input streams for us
// when the process exits, but since close is not synchronized,
// it creates a race if we close the stream first and the same
// fd is recycled. the stream draining thread will attempt to
// drain that fd!! it may block, OOM, or cause bizarre behavior
// see: https://bugs.openjdk.java.net/browse/JDK-8024521
// issue is fixed in build 7u60
InputStream stdout = process.getInputStream();
synchronized (stdout) {
inReader.close();
}
} catch (IOException ioe) {
LOG.warn("Error while closing the input stream", ioe);
}
if (!completed.get()) {
errThread.interrupt();
joinThread(errThread);
}
try {
InputStream stderr = process.getErrorStream();
synchronized (stderr) {
errReader.close();
}
} catch (IOException ioe) {
LOG.warn("Error while closing the error stream", ioe);
}
process.destroy();
lastTime = System.currentTimeMillis();
}
}
private static void joinThread(Thread t) {
while (t.isAlive()) {
try {
t.join();
} catch (InterruptedException ie) {
if (LOG.isWarnEnabled()) {
LOG.warn("Interrupted while joining on: " + t, ie);
}
t.interrupt(); // propagate interrupt
}
}
}
/** return an array containing the command name & its parameters */
protected abstract String[] getExecString();
/** Parse the execution result */
protected abstract void parseExecResult(BufferedReader lines)
throws IOException;
/**
* get the current sub-process executing the given command
*
* @return process executing the command
*/
public Process getProcess() {
return process;
}
/**
* This is an IOException with exit code added.
*/
public static class ExitCodeException extends IOException {
int exitCode;
public ExitCodeException(int exitCode, String message) {
super(message);
this.exitCode = exitCode;
}
public int getExitCode() {
return exitCode;
}
}
/**
* A simple shell command executor.
*
* <code>ShellCommandExecutor</code>should be used in cases where the output of the command needs no explicit parsing and where the command, working
* directory and the environment remains unchanged. The output of the command is stored as-is and is expected to be small.
*/
public static class ShellCommandExecutor extends ShellUtils {
private String[] command;
private StringBuffer output;
public ShellCommandExecutor(String[] execString) {
this(execString, null);
}
public ShellCommandExecutor(String[] execString, File dir) {
this(execString, dir, null);
}
public ShellCommandExecutor(String[] execString, File dir,
Map<String, String> env) {
this(execString, dir, env, 0L);
}
/**
* Create a new instance of the ShellCommandExecutor to execute a command.
*
* @param execString The command to execute with arguments
* @param dir If not-null, specifies the directory which should be set as the current working directory for the command. If null, the current working
* directory is not modified.
* @param env If not-null, environment of the command will include the key-value pairs specified in the map. If null, the current environment is not
* modified.
* @param timeout Specifies the time in milliseconds, after which the command will be killed and the status marked as timedout. If 0, the command will
* not be timed out.
*/
public ShellCommandExecutor(String[] execString, File dir,
Map<String, String> env, long timeout) {
command = execString.clone();
if (dir != null) {
setWorkingDirectory(dir);
}
if (env != null) {
setEnvironment(env);
}
timeOutInterval = timeout;
}
/** Execute the shell command. */
public void execute() throws IOException {
this.run();
}
@Override
public String[] getExecString() {
return command;
}
@Override
protected void parseExecResult(BufferedReader lines) throws IOException {
output = new StringBuffer();
char[] buf = new char[512];
int nRead;
while ((nRead = lines.read(buf, 0, buf.length)) > 0) {
output.append(buf, 0, nRead);
}
}
/** Get the output of the shell command. */
public String getOutput() {
return (output == null) ? "" : output.toString();
}
/**
* Returns the commands of this instance. Arguments with spaces in are presented with quotes round; other arguments are presented raw
*
* @return a string representation of the object.
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
String[] args = getExecString();
for (String s : args) {
if (s.indexOf(' ') >= 0) {
builder.append('"').append(s).append('"');
} else {
builder.append(s);
}
builder.append(' ');
}
return builder.toString();
}
}
/**
* To check if the passed script to shell command executor timed out or not.
*
* @return if the script timed out.
*/
public boolean isTimedOut() {
return timedOut.get();
}
/**
* Set if the command has timed out.
*
*/
private void setTimedOut() {
this.timedOut.set(true);
}
/**
* Static method to execute a shell command. Covers most of the simple cases without requiring the user to implement the <code>Shell</code> interface.
*
* @param cmd shell command to execute.
* @return the output of the executed command.
*/
public static String execCommand(String... cmd) throws IOException {
return execCommand(null, cmd, 0L);
}
/**
* Static method to execute a shell command. Covers most of the simple cases without requiring the user to implement the <code>Shell</code> interface.
*
* @param env the map of environment key=value
* @param cmd shell command to execute.
* @param timeout time in milliseconds after which script should be marked timeout
* @return the output of the executed command.o
*/
public static String execCommand(Map<String, String> env, String[] cmd,
long timeout) throws IOException {
ShellCommandExecutor exec = new ShellCommandExecutor(cmd, null, env,
timeout);
exec.execute();
return exec.getOutput();
}
/**
* Static method to execute a shell command. Covers most of the simple cases without requiring the user to implement the <code>Shell</code> interface.
*
* @param env the map of environment key=value
* @param cmd shell command to execute.
* @return the output of the executed command.
*/
public static String execCommand(Map<String,String> env, String ... cmd)
throws IOException {
return execCommand(env, cmd, 0L);
}
/**
* Timer which is used to timeout scripts spawned off by shell.
*/
private static class ShellTimeoutTimerTask extends TimerTask {
private ShellUtils shell;
public ShellTimeoutTimerTask(ShellUtils shell) {
this.shell = shell;
}
@Override
public void run() {
Process p = shell.getProcess();
try {
p.exitValue();
} catch (Exception e) {
// Process has not terminated.
// So check if it has completed
// if not just destroy it.
if (p != null && !shell.completed.get()) {
shell.setTimedOut();
p.destroy();
}
}
}
}
}
| |
/*
* Further modifications by TOGoS for use in TMCRS:
* - Removed use of templates, auto[un]boxing, and foreach loops
* to make source compatible with Java 1.4
* - Added ability to write chunks in both formats (gzip and deflate)
* - Implement AutoCloseable
*/
/*
** 2011 January 5
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**/
/*
* 2011 February 16
*
* This source code is based on the work of Scaevolus (see notice above).
* It has been slightly modified by Mojang AB (constants instead of magic
* numbers, a chunk timestamp header, and auto-formatted according to our
* formatter template).
*/
// Interfaces with region files on the disk
/*
Region File Format
Concept: The minimum unit of storage on hard drives is 4KB. 90% of Minecraft
chunks are smaller than 4KB. 99% are smaller than 8KB. Write a simple
container to store chunks in single files in runs of 4KB sectors.
Each region file represents a 32x32 group of chunks. The conversion from
chunk number to region number is floor(coord / 32): a chunk at (30, -3)
would be in region (0, -1), and one at (70, -30) would be at (3, -1).
Region files are named "r.x.z.data", where x and z are the region coordinates.
A region file begins with a 4KB header that describes where chunks are stored
in the file. A 4-byte big-endian integer represents sector offsets and sector
counts. The chunk offset for a chunk (x, z) begins at byte 4*(x+z*32) in the
file. The bottom byte of the chunk offset indicates the number of sectors the
chunk takes up, and the top 3 bytes represent the sector number of the chunk.
Given a chunk offset o, the chunk data begins at byte 4096*(o/256) and takes up
at most 4096*(o%256) bytes. A chunk cannot exceed 1MB in size. If a chunk
offset is 0, the corresponding chunk is not stored in the region file.
Chunk data begins with a 4-byte big-endian integer representing the chunk data
length in bytes, not counting the length field. The length must be smaller than
4096 times the number of sectors. The next byte is a version field, to allow
backwards-compatible updates to how chunks are encoded.
A version of 1 represents a gzipped NBT file. The gzipped data is the chunk
length - 1.
A version of 2 represents a deflated (zlib compressed) NBT file. The deflated
data is the chunk length - 1.
*/
package togos.minecraft.regionshifter;
import java.io.*;
import java.util.ArrayList;
import java.util.zip.*;
public class RegionFile implements AutoCloseable
{
public static final int VERSION_GZIP = 1;
public static final int VERSION_DEFLATE = 2;
private static final int SECTOR_BYTES = 4096;
private static final int SECTOR_INTS = SECTOR_BYTES / 4;
static final int CHUNK_HEADER_SIZE = 5;
private static final byte emptySector[] = new byte[4096];
private final File fileName;
private RandomAccessFile file;
private final int offsets[];
private final int chunkTimestamps[];
private ArrayList<Boolean> sectorFree;
private int sizeDelta;
private long lastModified = 0;
public RegionFile(File path) {
offsets = new int[SECTOR_INTS];
chunkTimestamps = new int[SECTOR_INTS];
fileName = path;
debugln("REGION LOAD " + fileName);
sizeDelta = 0;
try {
if (path.exists()) {
lastModified = path.lastModified();
}
file = new RandomAccessFile(path, "rw");
if (file.length() < SECTOR_BYTES) {
/* we need to write the chunk offset table */
for (int i = 0; i < SECTOR_INTS; ++i) {
file.writeInt(0);
}
// write another sector for the timestamp info
for (int i = 0; i < SECTOR_INTS; ++i) {
file.writeInt(0);
}
sizeDelta += SECTOR_BYTES * 2;
}
if ((file.length() & 0xfff) != 0) {
file.seek(file.length());
/* the file size is not a multiple of 4KB, grow it */
for (int i = 0; i < (file.length() & 0xfff); ++i) {
file.write((byte) 0);
}
}
/* set up the available sector map */
int nSectors = (int) file.length() / SECTOR_BYTES;
sectorFree = new ArrayList<Boolean>(nSectors);
for (int i = 0; i < nSectors; ++i) {
sectorFree.add(Boolean.TRUE);
}
sectorFree.set(0, Boolean.FALSE); // chunk offset table
sectorFree.set(1, Boolean.FALSE); // for the last modified info
file.seek(0);
for (int i = 0; i < SECTOR_INTS; ++i) {
int offset = file.readInt();
offsets[i] = offset;
if (offset != 0 && (offset >> 8) + (offset & 0xFF) <= sectorFree.size()) {
for (int sectorNum = 0; sectorNum < (offset & 0xFF); ++sectorNum) {
sectorFree.set((offset >> 8) + sectorNum, Boolean.FALSE);
}
}
}
for (int i = 0; i < SECTOR_INTS; ++i) {
int lastModValue = file.readInt();
chunkTimestamps[i] = lastModValue;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public File getFile() {
return fileName;
}
/* the modification date of the region file when it was first opened */
public long lastModified() {
return lastModified;
}
/* gets how much the region file has grown since it was last checked */
public synchronized int getSizeDelta() {
int ret = sizeDelta;
sizeDelta = 0;
return ret;
}
// various small debug printing helpers
private void debug(String in) {
// System.out.print(in);
}
private void debugln(String in) {
debug(in + "\n");
}
private void debug(String mode, int x, int z, String in) {
debug("REGION " + mode + " " + fileName.getName() + "[" + x + "," + z + "] = " + in);
}
private void debug(String mode, int x, int z, int count, String in) {
debug("REGION " + mode + " " + fileName.getName() + "[" + x + "," + z + "] " + count + "B = " + in);
}
private void debugln(String mode, int x, int z, String in) {
debug(mode, x, z, in + "\n");
}
/*
* gets an (uncompressed) stream representing the chunk data returns null if
* the chunk is not found or an error occurs
*/
public synchronized DataInputStream getChunkDataInputStream(int x, int z) {
if (outOfBounds(x, z)) {
debugln("READ", x, z, "out of bounds");
return null;
}
try {
int offset = getOffset(x, z);
if (offset == 0) {
// debugln("READ", x, z, "miss");
return null;
}
int sectorNumber = offset >> 8;
int numSectors = offset & 0xFF;
if (sectorNumber + numSectors > sectorFree.size()) {
debugln("READ", x, z, "invalid sector");
return null;
}
file.seek(sectorNumber * SECTOR_BYTES);
int length = file.readInt();
if (length > SECTOR_BYTES * numSectors) {
debugln("READ", x, z, "invalid length: " + length + " > 4096 * " + numSectors);
return null;
}
byte version = file.readByte();
if (version == VERSION_GZIP) {
byte[] data = new byte[length - 1];
file.read(data);
DataInputStream ret = new DataInputStream(new GZIPInputStream(new ByteArrayInputStream(data)));
// debug("READ", x, z, " = found");
return ret;
} else if (version == VERSION_DEFLATE) {
byte[] data = new byte[length - 1];
file.read(data);
DataInputStream ret = new DataInputStream(new InflaterInputStream(new ByteArrayInputStream(data)));
// debug("READ", x, z, " = found");
return ret;
}
debugln("READ", x, z, "unknown version " + version);
return null;
} catch (IOException e) {
debugln("READ", x, z, "exception");
return null;
}
}
public DataOutputStream getChunkDataOutputStream(int x, int z) {
if (outOfBounds(x, z)) return null;
return new DataOutputStream(new DeflaterOutputStream(getChunkOutputStream(x, z, VERSION_DEFLATE)));
}
/**
* Returns a low-level OutputStream object that is not wrapped in
* compressing and DataOutputStream objects. May be useful if
* data to be written is already compressed.
* @author TOGoS
*/
public OutputStream getChunkOutputStream( int x, int z, int format ) {
if (outOfBounds(x, z)) return null;
return new ChunkBuffer(x, z, format);
}
/*
* lets chunk writing be multithreaded by not locking the whole file as a
* chunk is serializing -- only writes when serialization is over
*/
class ChunkBuffer extends ByteArrayOutputStream {
public final int x, z, format;
public ChunkBuffer(int x, int z, int format) {
super(8096); // initialize to 8KB
this.x = x;
this.z = z;
this.format = format;
}
public void close() {
RegionFile.this.write(x, z, buf, count, format);
}
}
/* write a chunk at (x,z) with length bytes of data to disk */
protected synchronized void write(int x, int z, byte[] data, int length, int format) {
try {
int offset = getOffset(x, z);
int sectorNumber = offset >> 8;
int sectorsAllocated = offset & 0xFF;
int sectorsNeeded = (length + CHUNK_HEADER_SIZE) / SECTOR_BYTES + 1;
// maximum chunk size is 1MB
if (sectorsNeeded >= 256) {
return;
}
if (sectorNumber != 0 && sectorsAllocated == sectorsNeeded) {
/* we can simply overwrite the old sectors */
debug("SAVE", x, z, length, "rewrite");
write(sectorNumber, data, length, format);
} else {
/* we need to allocate new sectors */
/* mark the sectors previously used for this chunk as free */
for (int i = 0; i < sectorsAllocated; ++i) {
sectorFree.set(sectorNumber + i, Boolean.TRUE);
}
/* scan for a free space large enough to store this chunk */
int runStart = sectorFree.indexOf(Boolean.TRUE);
int runLength = 0;
if (runStart != -1) {
for (int i = runStart; i < sectorFree.size(); ++i) {
if (runLength != 0) {
if( sectorFree.get(i) ) runLength++;
else runLength = 0;
} else if( sectorFree.get(i) ) {
runStart = i;
runLength = 1;
}
if (runLength >= sectorsNeeded) {
break;
}
}
}
if (runLength >= sectorsNeeded) {
/* we found a free space large enough */
debug("SAVE", x, z, length, "reuse");
sectorNumber = runStart;
setOffset(x, z, (sectorNumber << 8) | sectorsNeeded);
for (int i = 0; i < sectorsNeeded; ++i) {
sectorFree.set(sectorNumber + i, Boolean.FALSE);
}
write(sectorNumber, data, length, format);
} else {
/*
* no free space large enough found -- we need to grow the
* file
*/
debug("SAVE", x, z, length, "grow");
file.seek(file.length());
sectorNumber = sectorFree.size();
for (int i = 0; i < sectorsNeeded; ++i) {
file.write(emptySector);
sectorFree.add(Boolean.FALSE);
}
sizeDelta += SECTOR_BYTES * sectorsNeeded;
write(sectorNumber, data, length, format);
setOffset(x, z, (sectorNumber << 8) | sectorsNeeded);
}
}
setTimestamp(x, z, (int) (System.currentTimeMillis() / 1000L));
} catch (IOException e) {
e.printStackTrace();
}
}
/* write a chunk data to the region file at specified sector number */
private void write(int sectorNumber, byte[] data, int length, int format) throws IOException {
debugln(" " + sectorNumber);
file.seek(sectorNumber * SECTOR_BYTES);
file.writeInt(length + 1); // chunk length
file.writeByte(format); // chunk version number
file.write(data, 0, length); // chunk data
}
/* is this an invalid chunk coordinate? */
private boolean outOfBounds(int x, int z) {
return x < 0 || x >= 32 || z < 0 || z >= 32;
}
private int getOffset(int x, int z) {
return offsets[x + z * 32];
}
public boolean hasChunk(int x, int z) {
return getOffset(x, z) != 0;
}
private void setOffset(int x, int z, int offset) throws IOException {
offsets[x + z * 32] = offset;
file.seek((x + z * 32) * 4);
file.writeInt(offset);
}
private void setTimestamp(int x, int z, int value) throws IOException {
chunkTimestamps[x + z * 32] = value;
file.seek(SECTOR_BYTES + (x + z * 32) * 4);
file.writeInt(value);
}
public void close() throws IOException {
if( file != null ) {
file.close();
file = null;
}
}
}
| |
package com.thebluealliance.androidclient.activities;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.thebluealliance.androidclient.Constants;
import com.thebluealliance.androidclient.NfcUris;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.Utilities;
import com.thebluealliance.androidclient.adapters.ViewEventFragmentPagerAdapter;
import com.thebluealliance.androidclient.datafeed.ConnectionDetector;
import com.thebluealliance.androidclient.helpers.ModelHelper;
import com.thebluealliance.androidclient.helpers.MyTBAHelper;
import com.thebluealliance.androidclient.views.SlidingTabs;
/**
* File created by phil on 4/20/14.
*/
public class ViewEventActivity extends FABNotificationSettingsActivity implements ViewPager.OnPageChangeListener {
public static final String EVENTKEY = "eventKey";
public static final String TAB = "tab";
private String mEventKey;
private int currentTab;
private TextView infoMessage;
private TextView warningMessage;
private ViewPager pager;
private ViewEventFragmentPagerAdapter adapter;
private boolean isDistrict;
/**
* Create new intent for ViewEventActivity
*
* @param c context
* @param eventKey Key of the event to show
* @param tab The tab number from ViewEventFragmentPagerAdapter.
* @return Intent you can launch
*/
public static Intent newInstance(Context c, String eventKey, int tab) {
Intent intent = new Intent(c, ViewEventActivity.class);
intent.putExtra(EVENTKEY, eventKey);
intent.putExtra(TAB, tab);
return intent;
}
public static Intent newInstance(Context c, String eventKey) {
return newInstance(c, eventKey, ViewEventFragmentPagerAdapter.TAB_INFO);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyTBAHelper.serializeIntent(getIntent());
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(EVENTKEY)) {
mEventKey = getIntent().getExtras().getString(EVENTKEY, "");
} else {
throw new IllegalArgumentException("ViewEventActivity must be constructed with a key");
}
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(TAB)) {
currentTab = getIntent().getExtras().getInt(TAB, ViewEventFragmentPagerAdapter.TAB_INFO);
} else {
Log.i(Constants.LOG_TAG, "ViewEvent intent doesn't contain TAB. Defaulting to TAB_INFO");
currentTab = ViewEventFragmentPagerAdapter.TAB_INFO;
}
setModelKey(mEventKey, ModelHelper.MODELS.EVENT);
setContentView(R.layout.activity_view_event);
infoMessage = (TextView) findViewById(R.id.info_container);
warningMessage = (TextView) findViewById(R.id.warning_container);
hideInfoMessage();
hideWarningMessage();
pager = (ViewPager) findViewById(R.id.view_pager);
adapter = new ViewEventFragmentPagerAdapter(getSupportFragmentManager(), mEventKey);
pager.setAdapter(adapter);
// To support refreshing, all pages must be held in memory at once
// This should be increased if we ever add more pages
pager.setOffscreenPageLimit(10);
pager.setPageMargin(Utilities.getPixelsFromDp(this, 16));
SlidingTabs tabs = (SlidingTabs) findViewById(R.id.tabs);
tabs.setOnPageChangeListener(this);
tabs.setViewPager(pager);
ViewCompat.setElevation(tabs, getResources().getDimension(R.dimen.toolbar_elevation));
pager.setCurrentItem(currentTab); // Do this after we set onPageChangeListener, so that FAB gets hidden, if needed
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
setupActionBar();
if (!ConnectionDetector.isConnectedToInternet(this)) {
showWarningMessage(getString(R.string.warning_unable_to_load));
}
isDistrict = true;
setSettingsToolbarTitle("Event Settings");
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
if (intent.getExtras() != null && intent.getExtras().containsKey(EVENTKEY)) {
mEventKey = intent.getExtras().getString(EVENTKEY, "");
} else {
throw new IllegalArgumentException("ViewEventActivity must be constructed with a key");
}
setModelKey(mEventKey, ModelHelper.MODELS.EVENT);
adapter = new ViewEventFragmentPagerAdapter(getSupportFragmentManager(), mEventKey);
pager.setAdapter(adapter);
adapter.notifyDataSetChanged();
Log.d(Constants.LOG_TAG, "Got new ViewEvent intent with key: " + mEventKey);
}
@Override
protected void onResume() {
super.onResume();
setBeamUri(String.format(NfcUris.URI_EVENT, mEventKey));
startRefresh();
}
public void updateDistrict(boolean isDistrict) {
this.isDistrict = isDistrict;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
mOptionsMenu = menu;
return true;
}
@Override
public void onCreateNavigationDrawer() {
useActionBarToggle(false);
encourageLearning(false);
}
private void setupActionBar() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// The title is empty now; the EventInfoFragment will set the appropriate title
// once it is loaded.
setActionBarTitle("");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case android.R.id.home:
if (isDrawerOpen()) {
closeDrawer();
return true;
}
// If this tasks exists in the back stack, it will be brought to the front and all other activities
// will be destroyed. HomeActivity will be delivered this intent via onNewIntent().
startActivity(HomeActivity.newInstance(this, R.id.nav_item_events).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
return true;
case R.id.stats_help:
Utilities.showHelpDialog(this, R.raw.stats_help, getString(R.string.stats_help_title));
return true;
case R.id.points_help:
Utilities.showHelpDialog(this, R.raw.district_points_help, getString(R.string.district_points_help));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public ViewPager getPager() {
return pager;
}
public void scrollToTab(int tab) {
if (pager != null) {
pager.setCurrentItem(tab);
}
}
public void showInfoMessage(String message) {
infoMessage.setText(message);
infoMessage.setVisibility(View.VISIBLE);
}
public void hideInfoMessage() {
infoMessage.setVisibility(View.GONE);
}
@Override
public void showWarningMessage(String message) {
warningMessage.setText(message);
warningMessage.setVisibility(View.VISIBLE);
}
@Override
public void hideWarningMessage() {
warningMessage.setVisibility(View.GONE);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
currentTab = position;
if (mOptionsMenu != null) {
if (position == ViewEventFragmentPagerAdapter.TAB_STATS && !isDistrict) {
showInfoMessage(getString(R.string.warning_not_real_district));
} else {
hideInfoMessage();
}
}
// hide the FAB if we aren't on the first page
if (position != ViewEventFragmentPagerAdapter.TAB_INFO) {
hideFab(true);
} else {
showFab(true);
}
/* Track the call */
/*Tracker t = Analytics.getTracker(Analytics.GAnalyticsTracker.ANDROID_TRACKER, ViewEventActivity.this);
t.send(new HitBuilders.EventBuilder()
.setCategory("view_event-tabs")
.setAction("tab_change")
.setLabel(mEventKey+ " "+adapter.getPageTitle(position))
.build());*/
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
| |
/*
* Copyright (c) 2017 Ni YueMing<niyueming@163.com>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*
*/
package net.nym.utilslibrary.utils;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.MimeTypeMap;
import net.nym.utilslibrary.BuildConfig;
import java.io.File;
import java.io.FileFilter;
import java.text.DecimalFormat;
import java.util.Comparator;
/**
* @author Peli
* @author paulburke (ipaulpro)
* @version 2013-12-11
*/
public class FileUtils {
public static final String MIME_TYPE_AUDIO = "audio/*";
public static final String MIME_TYPE_TEXT = "text/*";
public static final String MIME_TYPE_IMAGE = "image/*";
public static final String MIME_TYPE_VIDEO = "video/*";
public static final String MIME_TYPE_APP = "application/*";
public static final String HIDDEN_PREFIX = ".";
/**
* TAG for log messages.
*/
static final String TAG = "FileUtils";
private static final boolean DEBUG = BuildConfig.DEBUG; // Set to true to enable logging
/**
* File and folder comparator. TODO Expose sorting option method
*
* @author paulburke
*/
public static Comparator<File> sComparator = new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
// Sort alphabetically by lower case, which is much cleaner
return f1.getName().toLowerCase().compareTo(
f2.getName().toLowerCase());
}
};
/**
* File (not directories) filter.
*
* @author paulburke
*/
public static FileFilter sFileFilter = new FileFilter() {
@Override
public boolean accept(File file) {
final String fileName = file.getName();
// Return files only (not directories) and skip hidden files
return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX);
}
};
/**
* Folder (directories) filter.
*
* @author paulburke
*/
public static FileFilter sDirFilter = new FileFilter() {
@Override
public boolean accept(File file) {
final String fileName = file.getName();
// Return directories only and skip hidden directories
return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX);
}
};
private FileUtils() {
} //private constructor to enforce Singleton pattern
/**
* Gets the extension of a file name, like ".png" or ".jpg".
*
* @param uri
* @return Extension including the dot("."); "" if there is no extension;
* null if uri was null.
*/
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
}
/**
* @return Whether the URI is a local one.
*/
public static boolean isLocal(String url) {
if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) {
return true;
}
return false;
}
/**
* @return True if Uri is a MediaStore Uri.
* @author paulburke
*/
public static boolean isMediaUri(Uri uri) {
return "media".equalsIgnoreCase(uri.getAuthority());
}
/**
* Convert File into Uri.
*
* @param file
* @return uri
*/
public static Uri getUri(File file) {
if (file != null) {
return Uri.fromFile(file);
}
return null;
}
/**
* Returns the path only (without file name).
*
* @param file
* @return
*/
public static File getPathWithoutFilename(File file) {
if (file != null) {
if (file.isDirectory()) {
// no file to be split off. Return everything
return file;
} else {
String filename = file.getName();
String filepath = file.getAbsolutePath();
// Construct path without file name.
String pathwithoutname = filepath.substring(0,
filepath.length() - filename.length());
if (pathwithoutname.endsWith("/")) {
pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);
}
return new File(pathwithoutname);
}
}
return null;
}
/**
* @return The MIME type for the given file.
*/
public static String getMimeType(File file) {
String extension = getExtension(file.getName());
if (extension.length() > 0)
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
return "application/octet-stream";
}
/**
* @return The MIME type for the give Uri.
*/
public static String getMimeType(Context context, Uri uri) {
File file = new File(getPath(context, uri));
return getMimeType(file);
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is {@link LocalStorageProvider}.
* @author paulburke
*/
public static boolean isLocalStorageDocument(Uri uri) {
return LocalStorageProvider.AUTHORITY.equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
* @author paulburke
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
* @author paulburke
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
* @author paulburke
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
* @author paulburke
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.<br>
* <br>
* Callers should check whether the path is local before assuming it
* represents a local file.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
* @see #isLocal(String)
* @see #getFile(Context, Uri)
*/
public static String getPath(final Context context, final Uri uri) {
if (DEBUG)
Log.d(TAG + " File -",
"Authority: " + uri.getAuthority() +
", Fragment: " + uri.getFragment() +
", Port: " + uri.getPort() +
", Query: " + uri.getQuery() +
", Scheme: " + uri.getScheme() +
", Host: " + uri.getHost() +
", Segments: " + uri.getPathSegments().toString()
);
// DocumentProvider
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
&& DocumentsContract.isDocumentUri(context, uri)
) {
// LocalStorageProvider
if (isLocalStorageDocument(uri)) {
// The path is the id
return DocumentsContract.getDocumentId(uri);
}
// ExternalStorageProvider
else if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Convert Uri into File, if possible.
*
* @return file A local file that the Uri was pointing to, or null if the
* Uri is unsupported or pointed to a remote resource.
* @author paulburke
* @see #getPath(Context, Uri)
*/
public static File getFile(Context context, Uri uri) {
if (uri != null) {
String path = getPath(context, uri);
if (path != null && isLocal(path)) {
return new File(path);
}
}
return null;
}
/**
* Get the file size in a human-readable string.
*
* @param size
* @return
* @author paulburke
*/
public static String getReadableFileSize(int size) {
final int BYTES_IN_KILOBYTES = 1024;
final DecimalFormat dec = new DecimalFormat("###.#");
final String KILOBYTES = " KB";
final String MEGABYTES = " MB";
final String GIGABYTES = " GB";
float fileSize = 0;
String suffix = KILOBYTES;
if (size > BYTES_IN_KILOBYTES) {
fileSize = size / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
suffix = GIGABYTES;
} else {
suffix = MEGABYTES;
}
}
}
return String.valueOf(dec.format(fileSize) + suffix);
}
/**
* Attempt to retrieve the thumbnail of given File from the MediaStore. This
* should not be called on the UI thread.
*
* @param context
* @param file
* @return
* @author paulburke
*/
public static Bitmap getThumbnail(Context context, File file) {
return getThumbnail(context, getUri(file), getMimeType(file));
}
/**
* Attempt to retrieve the thumbnail of given Uri from the MediaStore. This
* should not be called on the UI thread.
*
* @param context
* @param uri
* @return
* @author paulburke
*/
public static Bitmap getThumbnail(Context context, Uri uri) {
return getThumbnail(context, uri, getMimeType(context, uri));
}
/**
* Attempt to retrieve the thumbnail of given Uri from the MediaStore. This
* should not be called on the UI thread.
*
* @param context
* @param uri
* @param mimeType
* @return
* @author paulburke
*/
public static Bitmap getThumbnail(Context context, Uri uri, String mimeType) {
if (DEBUG)
Log.d(TAG, "Attempting to get thumbnail");
if (!isMediaUri(uri)) {
Log.e(TAG, "You can only retrieve thumbnails for images and videos.");
return null;
}
Bitmap bm = null;
if (uri != null) {
final ContentResolver resolver = context.getContentResolver();
Cursor cursor = null;
try {
cursor = resolver.query(uri, null, null, null, null);
if (cursor.moveToFirst()) {
final int id = cursor.getInt(0);
if (DEBUG)
Log.d(TAG, "Got thumb ID: " + id);
if (mimeType.contains("video")) {
bm = MediaStore.Video.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Video.Thumbnails.MINI_KIND,
null);
} else if (mimeType.contains(FileUtils.MIME_TYPE_IMAGE)) {
bm = MediaStore.Images.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Images.Thumbnails.MINI_KIND,
null);
}
}
} catch (Exception e) {
if (DEBUG)
Log.e(TAG, "getThumbnail", e);
} finally {
if (cursor != null)
cursor.close();
}
}
return bm;
}
/**
* Get the Intent for selecting content to be used in an Intent Chooser.
*
* @return The intent for opening a file with Intent.createChooser()
* @author paulburke
*/
public static Intent createGetContentIntent() {
// Implicitly allow the user to select a particular kind of data
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// The MIME data type filter
intent.setType("*/*");
// Only return URIs that can be opened with ContentResolver
intent.addCategory(Intent.CATEGORY_OPENABLE);
return intent;
}
}
| |
/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.python;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.Pair;
import com.facebook.buck.rules.AbstractBuildRule;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BinaryBuildRule;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.ExternalTestRunnerRule;
import com.facebook.buck.rules.ExternalTestRunnerTestSpec;
import com.facebook.buck.rules.ForwardingBuildTargetSourcePath;
import com.facebook.buck.rules.HasRuntimeDeps;
import com.facebook.buck.rules.Label;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TestRule;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.test.TestCaseSummary;
import com.facebook.buck.test.TestResultSummary;
import com.facebook.buck.test.TestResults;
import com.facebook.buck.test.TestRunningOptions;
import com.facebook.buck.util.MoreCollectors;
import com.facebook.buck.util.RichStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.stream.Stream;
@SuppressWarnings("PMD.TestClassWithoutTestCases")
public class PythonTest
extends AbstractBuildRule
implements TestRule, HasRuntimeDeps, ExternalTestRunnerRule, BinaryBuildRule {
private final SourcePathRuleFinder ruleFinder;
private final Supplier<ImmutableSortedSet<BuildRule>> originalDeclaredDeps;
@AddToRuleKey
private final Supplier<ImmutableMap<String, String>> env;
@AddToRuleKey
private final PythonBinary binary;
private final ImmutableSet<Label> labels;
private final Optional<Long> testRuleTimeoutMs;
private final ImmutableSet<String> contacts;
private final ImmutableList<Pair<Float, ImmutableSet<Path>>> neededCoverage;
private PythonTest(
BuildRuleParams params,
SourcePathRuleFinder ruleFinder,
Supplier<ImmutableSortedSet<BuildRule>> originalDeclaredDeps,
Supplier<ImmutableMap<String, String>> env,
PythonBinary binary,
ImmutableSet<Label> labels,
ImmutableList<Pair<Float, ImmutableSet<Path>>> neededCoverage,
Optional<Long> testRuleTimeoutMs,
ImmutableSet<String> contacts) {
super(params);
this.ruleFinder = ruleFinder;
this.originalDeclaredDeps = originalDeclaredDeps;
this.env = env;
this.binary = binary;
this.labels = labels;
this.neededCoverage = neededCoverage;
this.testRuleTimeoutMs = testRuleTimeoutMs;
this.contacts = contacts;
}
public static PythonTest from(
BuildRuleParams params,
SourcePathRuleFinder ruleFinder,
Supplier<ImmutableMap<String, String>> env,
PythonBinary binary,
ImmutableSet<Label> labels,
ImmutableList<Pair<Float, ImmutableSet<Path>>> neededCoverage,
Optional<Long> testRuleTimeoutMs,
ImmutableSet<String> contacts) {
return new PythonTest(
params.copyReplacingDeclaredAndExtraDeps(
Suppliers.ofInstance(ImmutableSortedSet.of(binary)),
Suppliers.ofInstance(ImmutableSortedSet.of())),
ruleFinder,
params.getDeclaredDeps(),
env,
binary,
labels,
neededCoverage,
testRuleTimeoutMs,
contacts);
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
return ImmutableList.of();
}
@Override
public SourcePath getSourcePathToOutput() {
return new ForwardingBuildTargetSourcePath(getBuildTarget(), binary.getSourcePathToOutput());
}
@Override
public ImmutableList<Step> runTests(
ExecutionContext executionContext,
TestRunningOptions options,
SourcePathResolver pathResolver,
TestReportingCallback testReportingCallback) {
return ImmutableList.of(
new MakeCleanDirectoryStep(getProjectFilesystem(), getPathToTestOutputDirectory()),
new PythonRunTestsStep(
getProjectFilesystem().getRootPath(),
getBuildTarget().getFullyQualifiedName(),
binary.getExecutableCommand().getCommandPrefix(pathResolver),
getMergedEnv(pathResolver),
options.getTestSelectorList(),
testRuleTimeoutMs,
getProjectFilesystem().resolve(getPathToTestOutputResult())));
}
private ImmutableMap<String, String> getMergedEnv(SourcePathResolver pathResolver) {
return new ImmutableMap.Builder<String, String>()
.putAll(binary.getExecutableCommand().getEnvironment(pathResolver))
.putAll(env.get())
.build();
}
@Override
public ImmutableSet<String> getContacts() {
return contacts;
}
@Override
public Path getPathToTestOutputDirectory() {
return BuildTargets.getGenPath(
getProjectFilesystem(),
getBuildTarget(),
"__test_%s_output__");
}
public Path getPathToTestOutputResult() {
return getPathToTestOutputDirectory().resolve("results.json");
}
@Override
public boolean hasTestResultFiles() {
return getProjectFilesystem().isFile(getPathToTestOutputResult());
}
@Override
public ImmutableSet<Label> getLabels() {
return labels;
}
@Override
public Callable<TestResults> interpretTestResults(
final ExecutionContext executionContext,
boolean isUsingTestSelectors) {
return () -> {
Optional<String> resultsFileContents =
getProjectFilesystem().readFileIfItExists(
getPathToTestOutputResult());
ObjectMapper mapper = executionContext.getObjectMapper();
TestResultSummary[] testResultSummaries = mapper.readValue(
resultsFileContents.get(),
TestResultSummary[].class);
return TestResults.of(
getBuildTarget(),
ImmutableList.of(
new TestCaseSummary(
getBuildTarget().getFullyQualifiedName(),
ImmutableList.copyOf(testResultSummaries))),
contacts,
labels.stream()
.map(Object::toString)
.collect(MoreCollectors.toImmutableSet()));
};
}
@Override
public boolean runTestSeparately() {
return false;
}
// A python test rule is actually just a {@link NoopBuildRule} which contains a references to
// a {@link PythonBinary} rule, which is the actual test binary. Therefore, we *need* this
// rule around to run this test, so model this via the {@link HasRuntimeDeps} interface.
@Override
public Stream<BuildTarget> getRuntimeDeps() {
return RichStream.<BuildTarget>empty()
.concat(originalDeclaredDeps.get().stream().map(BuildRule::getBuildTarget))
.concat(binary.getRuntimeDeps())
.concat(
binary.getExecutableCommand().getDeps(ruleFinder).stream()
.map(BuildRule::getBuildTarget));
}
@Override
public boolean supportsStreamingTests() {
return false;
}
@VisibleForTesting
protected PythonBinary getBinary() {
return binary;
}
@Override
public Tool getExecutableCommand() {
return binary.getExecutableCommand();
}
@Override
public ExternalTestRunnerTestSpec getExternalTestRunnerSpec(
ExecutionContext executionContext,
TestRunningOptions testRunningOptions,
SourcePathResolver pathResolver) {
return ExternalTestRunnerTestSpec.builder()
.setTarget(getBuildTarget())
.setType("pyunit")
.setNeededCoverage(neededCoverage)
.addAllCommand(binary.getExecutableCommand().getCommandPrefix(pathResolver))
.putAllEnv(getMergedEnv(pathResolver))
.addAllLabels(getLabels())
.addAllContacts(getContacts())
.build();
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexFormatTooNewException;
import org.apache.lucene.index.IndexFormatTooOldException;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.LockObtainFailedException;
import org.elasticsearch.action.FailedNodeException;
import org.elasticsearch.action.RoutingMissingException;
import org.elasticsearch.action.TimestampParsingException;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.action.support.replication.ReplicationOperation;
import org.elasticsearch.client.AbstractClientHeadersTestCase;
import org.elasticsearch.cluster.action.shard.ShardStateAction;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.IllegalShardRoutingStateException;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardRoutingState;
import org.elasticsearch.cluster.routing.TestShardRouting;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.breaker.CircuitBreakingException;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.io.PathUtils;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.NotSerializableExceptionWrapper;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.CancellableThreadsTests;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.common.xcontent.UnknownNamedObjectException;
import org.elasticsearch.common.xcontent.XContentLocation;
import org.elasticsearch.discovery.DiscoverySettings;
import org.elasticsearch.env.ShardLockObtainFailedException;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.engine.RecoveryEngineException;
import org.elasticsearch.index.query.QueryShardException;
import org.elasticsearch.index.shard.IllegalIndexShardStateException;
import org.elasticsearch.index.shard.IndexShardState;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.IndexTemplateMissingException;
import org.elasticsearch.indices.InvalidIndexTemplateException;
import org.elasticsearch.indices.recovery.RecoverFilesRecoveryException;
import org.elasticsearch.repositories.RepositoryException;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.action.admin.indices.AliasesNotFoundException;
import org.elasticsearch.search.SearchContextMissingException;
import org.elasticsearch.search.SearchException;
import org.elasticsearch.search.SearchParseException;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.aggregations.MultiBucketConsumerService;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.snapshots.Snapshot;
import org.elasticsearch.snapshots.SnapshotException;
import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.TestSearchContext;
import org.elasticsearch.test.VersionUtils;
import org.elasticsearch.test.hamcrest.ElasticsearchAssertions;
import org.elasticsearch.transport.ActionNotFoundTransportException;
import org.elasticsearch.transport.ActionTransportException;
import org.elasticsearch.transport.ConnectTransportException;
import org.elasticsearch.transport.TcpTransport;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.AccessDeniedException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystemException;
import java.nio.file.FileSystemLoopException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.NotDirectoryException;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static java.lang.reflect.Modifier.isAbstract;
import static java.lang.reflect.Modifier.isInterface;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertVersionSerializable;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.instanceOf;
public class ExceptionSerializationTests extends ESTestCase {
public void testExceptionRegistration()
throws ClassNotFoundException, IOException, URISyntaxException {
final Set<Class<?>> notRegistered = new HashSet<>();
final Set<Class<?>> hasDedicatedWrite = new HashSet<>();
final Set<Class<?>> registered = new HashSet<>();
final String path = "/org/elasticsearch";
final Path startPath = PathUtils.get(ElasticsearchException.class.getProtectionDomain().getCodeSource().getLocation().toURI())
.resolve("org").resolve("elasticsearch");
final Set<? extends Class<?>> ignore = Sets.newHashSet(
CancellableThreadsTests.CustomException.class,
org.elasticsearch.rest.BytesRestResponseTests.WithHeadersException.class,
AbstractClientHeadersTestCase.InternalException.class);
FileVisitor<Path> visitor = new FileVisitor<Path>() {
private Path pkgPrefix = PathUtils.get(path).getParent();
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path next = pkgPrefix.resolve(dir.getFileName());
if (ignore.contains(next)) {
return FileVisitResult.SKIP_SUBTREE;
}
pkgPrefix = next;
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
checkFile(file.getFileName().toString());
return FileVisitResult.CONTINUE;
}
private void checkFile(String filename) {
if (filename.endsWith(".class") == false) {
return;
}
try {
checkClass(loadClass(filename));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private void checkClass(Class<?> clazz) {
if (ignore.contains(clazz) || isAbstract(clazz.getModifiers()) || isInterface(clazz.getModifiers())) {
return;
}
if (isEsException(clazz) == false) {
return;
}
if (ElasticsearchException.isRegistered(clazz.asSubclass(Throwable.class), Version.CURRENT) == false
&& ElasticsearchException.class.equals(clazz.getEnclosingClass()) == false) {
notRegistered.add(clazz);
} else if (ElasticsearchException.isRegistered(clazz.asSubclass(Throwable.class), Version.CURRENT)) {
registered.add(clazz);
try {
if (clazz.getMethod("writeTo", StreamOutput.class) != null) {
hasDedicatedWrite.add(clazz);
}
} catch (Exception e) {
// fair enough
}
}
}
private boolean isEsException(Class<?> clazz) {
return ElasticsearchException.class.isAssignableFrom(clazz);
}
private Class<?> loadClass(String filename) throws ClassNotFoundException {
StringBuilder pkg = new StringBuilder();
for (Path p : pkgPrefix) {
pkg.append(p.getFileName().toString()).append(".");
}
pkg.append(filename.substring(0, filename.length() - 6));
return getClass().getClassLoader().loadClass(pkg.toString());
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
throw exc;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
pkgPrefix = pkgPrefix.getParent();
return FileVisitResult.CONTINUE;
}
};
Files.walkFileTree(startPath, visitor);
final Path testStartPath = PathUtils.get(ExceptionSerializationTests.class.getResource(path).toURI());
Files.walkFileTree(testStartPath, visitor);
assertTrue(notRegistered.remove(TestException.class));
assertTrue(notRegistered.remove(UnknownHeaderException.class));
assertTrue("Classes subclassing ElasticsearchException must be registered \n" + notRegistered.toString(),
notRegistered.isEmpty());
assertTrue(registered.removeAll(ElasticsearchException.getRegisteredKeys())); // check
assertEquals(registered.toString(), 0, registered.size());
}
public static final class TestException extends ElasticsearchException {
public TestException(StreamInput in) throws IOException {
super(in);
}
}
private <T extends Exception> T serialize(T exception) throws IOException {
return serialize(exception, VersionUtils.randomVersion(random()));
}
private <T extends Exception> T serialize(T exception, Version version) throws IOException {
ElasticsearchAssertions.assertVersionSerializable(version, exception);
BytesStreamOutput out = new BytesStreamOutput();
out.setVersion(version);
out.writeException(exception);
StreamInput in = out.bytes().streamInput();
in.setVersion(version);
return in.readException();
}
public void testIllegalShardRoutingStateException() throws IOException {
final ShardRouting routing = TestShardRouting.newShardRouting("test", 0, "xyz", "def", false, ShardRoutingState.STARTED);
final String routingAsString = routing.toString();
IllegalShardRoutingStateException serialize = serialize(
new IllegalShardRoutingStateException(routing, "foo", new NullPointerException()));
assertNotNull(serialize.shard());
assertEquals(routing, serialize.shard());
assertEquals(routingAsString + ": foo", serialize.getMessage());
assertTrue(serialize.getCause() instanceof NullPointerException);
serialize = serialize(new IllegalShardRoutingStateException(routing, "bar", null));
assertNotNull(serialize.shard());
assertEquals(routing, serialize.shard());
assertEquals(routingAsString + ": bar", serialize.getMessage());
assertNull(serialize.getCause());
}
public void testParsingException() throws IOException {
ParsingException ex = serialize(new ParsingException(1, 2, "fobar", null));
assertNull(ex.getIndex());
assertEquals(ex.getMessage(), "fobar");
assertEquals(ex.getLineNumber(), 1);
assertEquals(ex.getColumnNumber(), 2);
ex = serialize(new ParsingException(1, 2, null, null));
assertNull(ex.getIndex());
assertNull(ex.getMessage());
assertEquals(ex.getLineNumber(), 1);
assertEquals(ex.getColumnNumber(), 2);
}
public void testQueryShardException() throws IOException {
QueryShardException ex = serialize(new QueryShardException(new Index("foo", "_na_"), "fobar", null));
assertEquals(ex.getIndex().getName(), "foo");
assertEquals(ex.getMessage(), "fobar");
ex = serialize(new QueryShardException((Index) null, null, null));
assertNull(ex.getIndex());
assertNull(ex.getMessage());
}
public void testSearchException() throws IOException {
SearchShardTarget target = new SearchShardTarget("foo", new Index("bar", "_na_"), 1, null);
SearchException ex = serialize(new SearchException(target, "hello world"));
assertEquals(target, ex.shard());
assertEquals(ex.getMessage(), "hello world");
ex = serialize(new SearchException(null, "hello world", new NullPointerException()));
assertNull(ex.shard());
assertEquals(ex.getMessage(), "hello world");
assertTrue(ex.getCause() instanceof NullPointerException);
}
public void testActionNotFoundTransportException() throws IOException {
ActionNotFoundTransportException ex = serialize(new ActionNotFoundTransportException("AACCCTION"));
assertEquals("AACCCTION", ex.action());
assertEquals("No handler for action [AACCCTION]", ex.getMessage());
}
public void testSnapshotException() throws IOException {
final Snapshot snapshot = new Snapshot("repo", new SnapshotId("snap", UUIDs.randomBase64UUID()));
SnapshotException ex = serialize(new SnapshotException(snapshot, "no such snapshot", new NullPointerException()));
assertEquals(ex.getRepositoryName(), snapshot.getRepository());
assertEquals(ex.getSnapshotName(), snapshot.getSnapshotId().getName());
assertEquals(ex.getMessage(), "[" + snapshot + "] no such snapshot");
assertTrue(ex.getCause() instanceof NullPointerException);
ex = serialize(new SnapshotException(null, "no such snapshot", new NullPointerException()));
assertNull(ex.getRepositoryName());
assertNull(ex.getSnapshotName());
assertEquals(ex.getMessage(), "[_na] no such snapshot");
assertTrue(ex.getCause() instanceof NullPointerException);
}
public void testRecoverFilesRecoveryException() throws IOException {
ShardId id = new ShardId("foo", "_na_", 1);
ByteSizeValue bytes = new ByteSizeValue(randomIntBetween(0, 10000));
RecoverFilesRecoveryException ex = serialize(new RecoverFilesRecoveryException(id, 10, bytes, null));
assertEquals(ex.getShardId(), id);
assertEquals(ex.numberOfFiles(), 10);
assertEquals(ex.totalFilesSize(), bytes);
assertEquals(ex.getMessage(), "Failed to transfer [10] files with total size of [" + bytes + "]");
assertNull(ex.getCause());
ex = serialize(new RecoverFilesRecoveryException(null, 10, bytes, new NullPointerException()));
assertNull(ex.getShardId());
assertEquals(ex.numberOfFiles(), 10);
assertEquals(ex.totalFilesSize(), bytes);
assertEquals(ex.getMessage(), "Failed to transfer [10] files with total size of [" + bytes + "]");
assertTrue(ex.getCause() instanceof NullPointerException);
}
public void testInvalidIndexTemplateException() throws IOException {
InvalidIndexTemplateException ex = serialize(new InvalidIndexTemplateException("foo", "bar"));
assertEquals(ex.getMessage(), "index_template [foo] invalid, cause [bar]");
assertEquals(ex.name(), "foo");
ex = serialize(new InvalidIndexTemplateException(null, "bar"));
assertEquals(ex.getMessage(), "index_template [null] invalid, cause [bar]");
assertEquals(ex.name(), null);
}
public void testActionTransportException() throws IOException {
TransportAddress transportAddress = buildNewFakeTransportAddress();
ActionTransportException ex = serialize(
new ActionTransportException("name?", transportAddress, "ACTION BABY!", "message?", null));
assertEquals("ACTION BABY!", ex.action());
assertEquals(transportAddress, ex.address());
assertEquals("[name?][" + transportAddress.toString() +"][ACTION BABY!] message?", ex.getMessage());
}
public void testSearchContextMissingException() throws IOException {
long id = randomLong();
SearchContextMissingException ex = serialize(new SearchContextMissingException(id));
assertEquals(id, ex.id());
}
public void testCircuitBreakingException() throws IOException {
CircuitBreakingException ex = serialize(new CircuitBreakingException("I hate to say I told you so...", 0, 100));
assertEquals("I hate to say I told you so...", ex.getMessage());
assertEquals(100, ex.getByteLimit());
assertEquals(0, ex.getBytesWanted());
}
public void testTooManyBucketsException() throws IOException {
MultiBucketConsumerService.TooManyBucketsException ex =
serialize(new MultiBucketConsumerService.TooManyBucketsException("Too many buckets", 100),
randomFrom(Version.V_7_0_0_alpha1));
assertEquals("Too many buckets", ex.getMessage());
assertEquals(100, ex.getMaxBuckets());
}
public void testTimestampParsingException() throws IOException {
TimestampParsingException ex = serialize(new TimestampParsingException("TIMESTAMP", null));
assertEquals("failed to parse timestamp [TIMESTAMP]", ex.getMessage());
assertEquals("TIMESTAMP", ex.timestamp());
}
public void testAliasesMissingException() throws IOException {
AliasesNotFoundException ex = serialize(new AliasesNotFoundException("one", "two", "three"));
assertEquals("aliases [one, two, three] missing", ex.getMessage());
assertEquals("aliases", ex.getResourceType());
assertArrayEquals(new String[]{"one", "two", "three"}, ex.getResourceId().toArray(new String[0]));
}
public void testSearchParseException() throws IOException {
SearchContext ctx = new TestSearchContext(null);
SearchParseException ex = serialize(new SearchParseException(ctx, "foo", new XContentLocation(66, 666)));
assertEquals("foo", ex.getMessage());
assertEquals(66, ex.getLineNumber());
assertEquals(666, ex.getColumnNumber());
assertEquals(ctx.shardTarget(), ex.shard());
}
public void testIllegalIndexShardStateException() throws IOException {
ShardId id = new ShardId("foo", "_na_", 1);
IndexShardState state = randomFrom(IndexShardState.values());
IllegalIndexShardStateException ex = serialize(new IllegalIndexShardStateException(id, state, "come back later buddy"));
assertEquals(id, ex.getShardId());
assertEquals("CurrentState[" + state.name() + "] come back later buddy", ex.getMessage());
assertEquals(state, ex.currentState());
}
public void testConnectTransportException() throws IOException {
TransportAddress transportAddress = buildNewFakeTransportAddress();
DiscoveryNode node = new DiscoveryNode("thenode", transportAddress,
emptyMap(), emptySet(), Version.CURRENT);
ConnectTransportException ex = serialize(new ConnectTransportException(node, "msg", "action", null));
assertEquals("[][" + transportAddress.toString() + "][action] msg", ex.getMessage());
assertEquals(node, ex.node());
assertEquals("action", ex.action());
assertNull(ex.getCause());
ex = serialize(new ConnectTransportException(node, "msg", "action", new NullPointerException()));
assertEquals("[]["+ transportAddress+ "][action] msg", ex.getMessage());
assertEquals(node, ex.node());
assertEquals("action", ex.action());
assertTrue(ex.getCause() instanceof NullPointerException);
}
public void testSearchPhaseExecutionException() throws IOException {
ShardSearchFailure[] empty = new ShardSearchFailure[0];
SearchPhaseExecutionException ex = serialize(new SearchPhaseExecutionException("boom", "baam", new NullPointerException(), empty));
assertEquals("boom", ex.getPhaseName());
assertEquals("baam", ex.getMessage());
assertTrue(ex.getCause() instanceof NullPointerException);
assertEquals(empty.length, ex.shardFailures().length);
ShardSearchFailure[] one = new ShardSearchFailure[]{
new ShardSearchFailure(new IllegalArgumentException("nono!"))
};
ex = serialize(new SearchPhaseExecutionException("boom", "baam", new NullPointerException(), one));
assertEquals("boom", ex.getPhaseName());
assertEquals("baam", ex.getMessage());
assertTrue(ex.getCause() instanceof NullPointerException);
assertEquals(one.length, ex.shardFailures().length);
assertTrue(ex.shardFailures()[0].getCause() instanceof IllegalArgumentException);
}
public void testRoutingMissingException() throws IOException {
RoutingMissingException ex = serialize(new RoutingMissingException("idx", "type", "id"));
assertEquals("idx", ex.getIndex().getName());
assertEquals("type", ex.getType());
assertEquals("id", ex.getId());
assertEquals("routing is required for [idx]/[type]/[id]", ex.getMessage());
}
public void testRepositoryException() throws IOException {
RepositoryException ex = serialize(new RepositoryException("repo", "msg"));
assertEquals("repo", ex.repository());
assertEquals("[repo] msg", ex.getMessage());
ex = serialize(new RepositoryException(null, "msg"));
assertNull(ex.repository());
assertEquals("[_na] msg", ex.getMessage());
}
public void testIndexTemplateMissingException() throws IOException {
IndexTemplateMissingException ex = serialize(new IndexTemplateMissingException("name"));
assertEquals("index_template [name] missing", ex.getMessage());
assertEquals("name", ex.name());
ex = serialize(new IndexTemplateMissingException((String) null));
assertEquals("index_template [null] missing", ex.getMessage());
assertNull(ex.name());
}
public void testRecoveryEngineException() throws IOException {
ShardId id = new ShardId("foo", "_na_", 1);
RecoveryEngineException ex = serialize(new RecoveryEngineException(id, 10, "total failure", new NullPointerException()));
assertEquals(id, ex.getShardId());
assertEquals("Phase[10] total failure", ex.getMessage());
assertEquals(10, ex.phase());
ex = serialize(new RecoveryEngineException(null, -1, "total failure", new NullPointerException()));
assertNull(ex.getShardId());
assertEquals(-1, ex.phase());
assertTrue(ex.getCause() instanceof NullPointerException);
}
public void testFailedNodeException() throws IOException {
FailedNodeException ex = serialize(new FailedNodeException("the node", "the message", null));
assertEquals("the node", ex.nodeId());
assertEquals("the message", ex.getMessage());
}
public void testClusterBlockException() throws IOException {
ClusterBlockException ex = serialize(new ClusterBlockException(singleton(DiscoverySettings.NO_MASTER_BLOCK_WRITES)));
assertEquals("blocked by: [SERVICE_UNAVAILABLE/2/no master];", ex.getMessage());
assertTrue(ex.blocks().contains(DiscoverySettings.NO_MASTER_BLOCK_WRITES));
assertEquals(1, ex.blocks().size());
}
public void testNotSerializableExceptionWrapper() throws IOException {
NotSerializableExceptionWrapper ex = serialize(new NotSerializableExceptionWrapper(new NullPointerException()));
assertEquals("{\"type\":\"null_pointer_exception\",\"reason\":\"null_pointer_exception: null\"}", Strings.toString(ex));
ex = serialize(new NotSerializableExceptionWrapper(new IllegalArgumentException("nono!")));
assertEquals("{\"type\":\"illegal_argument_exception\",\"reason\":\"illegal_argument_exception: nono!\"}", Strings.toString(ex));
class UnknownException extends Exception {
UnknownException(final String message) {
super(message);
}
}
Exception[] unknowns = new Exception[]{
new Exception("foobar"),
new ClassCastException("boom boom boom"),
new UnknownException("boom")
};
for (Exception t : unknowns) {
if (randomBoolean()) {
t.addSuppressed(new UnsatisfiedLinkError("suppressed"));
t.addSuppressed(new NullPointerException());
}
Throwable deserialized = serialize(t);
assertTrue(deserialized.getClass().toString(), deserialized instanceof NotSerializableExceptionWrapper);
assertArrayEquals(t.getStackTrace(), deserialized.getStackTrace());
assertEquals(t.getSuppressed().length, deserialized.getSuppressed().length);
if (t.getSuppressed().length > 0) {
assertTrue(deserialized.getSuppressed()[0] instanceof NotSerializableExceptionWrapper);
assertArrayEquals(t.getSuppressed()[0].getStackTrace(), deserialized.getSuppressed()[0].getStackTrace());
assertTrue(deserialized.getSuppressed()[1] instanceof NullPointerException);
}
}
}
public void testUnknownException() throws IOException {
ParsingException parsingException = new ParsingException(1, 2, "foobar", null);
final Exception ex = new UnknownException("eggplant", parsingException);
Exception exception = serialize(ex);
assertEquals("unknown_exception: eggplant", exception.getMessage());
assertTrue(exception instanceof ElasticsearchException);
ParsingException e = (ParsingException)exception.getCause();
assertEquals(parsingException.getIndex(), e.getIndex());
assertEquals(parsingException.getMessage(), e.getMessage());
assertEquals(parsingException.getLineNumber(), e.getLineNumber());
assertEquals(parsingException.getColumnNumber(), e.getColumnNumber());
}
public void testWriteThrowable() throws IOException {
final QueryShardException queryShardException = new QueryShardException(new Index("foo", "_na_"), "foobar", null);
final UnknownException unknownException = new UnknownException("this exception is unknown", queryShardException);
final Exception[] causes = new Exception[]{
new IllegalStateException("foobar"),
new IllegalArgumentException("alalaal"),
new NullPointerException("boom"),
new EOFException("dadada"),
new ElasticsearchSecurityException("nono!"),
new NumberFormatException("not a number"),
new CorruptIndexException("baaaam booom", "this is my resource"),
new IndexFormatTooNewException("tooo new", 1, 2, 3),
new IndexFormatTooOldException("tooo new", 1, 2, 3),
new IndexFormatTooOldException("tooo new", "very old version"),
new ArrayIndexOutOfBoundsException("booom"),
new StringIndexOutOfBoundsException("booom"),
new FileNotFoundException("booom"),
new NoSuchFileException("booom"),
new AlreadyClosedException("closed!!", new NullPointerException()),
new LockObtainFailedException("can't lock directory", new NullPointerException()),
unknownException};
for (final Exception cause : causes) {
ElasticsearchException ex = new ElasticsearchException("topLevel", cause);
ElasticsearchException deserialized = serialize(ex);
assertEquals(deserialized.getMessage(), ex.getMessage());
assertTrue("Expected: " + deserialized.getCause().getMessage() + " to contain: " +
ex.getCause().getClass().getName() + " but it didn't",
deserialized.getCause().getMessage().contains(ex.getCause().getMessage()));
if (ex.getCause().getClass() != UnknownException.class) { // unknown exception is not directly mapped
assertEquals(deserialized.getCause().getClass(), ex.getCause().getClass());
} else {
assertEquals(deserialized.getCause().getClass(), NotSerializableExceptionWrapper.class);
}
assertArrayEquals(deserialized.getStackTrace(), ex.getStackTrace());
assertTrue(deserialized.getStackTrace().length > 1);
assertVersionSerializable(VersionUtils.randomVersion(random()), cause);
assertVersionSerializable(VersionUtils.randomVersion(random()), ex);
assertVersionSerializable(VersionUtils.randomVersion(random()), deserialized);
}
}
public void testWithRestHeadersException() throws IOException {
{
ElasticsearchException ex = new ElasticsearchException("msg");
ex.addHeader("foo", "foo", "bar");
ex.addMetadata("es.foo_metadata", "value1", "value2");
ex = serialize(ex);
assertEquals("msg", ex.getMessage());
assertEquals(2, ex.getHeader("foo").size());
assertEquals("foo", ex.getHeader("foo").get(0));
assertEquals("bar", ex.getHeader("foo").get(1));
assertEquals(2, ex.getMetadata("es.foo_metadata").size());
assertEquals("value1", ex.getMetadata("es.foo_metadata").get(0));
assertEquals("value2", ex.getMetadata("es.foo_metadata").get(1));
}
{
RestStatus status = randomFrom(RestStatus.values());
// ensure we are carrying over the headers and metadata even if not serialized
UnknownHeaderException uhe = new UnknownHeaderException("msg", status);
uhe.addHeader("foo", "foo", "bar");
uhe.addMetadata("es.foo_metadata", "value1", "value2");
ElasticsearchException serialize = serialize((ElasticsearchException) uhe);
assertTrue(serialize instanceof NotSerializableExceptionWrapper);
NotSerializableExceptionWrapper e = (NotSerializableExceptionWrapper) serialize;
assertEquals("unknown_header_exception: msg", e.getMessage());
assertEquals(2, e.getHeader("foo").size());
assertEquals("foo", e.getHeader("foo").get(0));
assertEquals("bar", e.getHeader("foo").get(1));
assertEquals(2, e.getMetadata("es.foo_metadata").size());
assertEquals("value1", e.getMetadata("es.foo_metadata").get(0));
assertEquals("value2", e.getMetadata("es.foo_metadata").get(1));
assertSame(status, e.status());
}
}
public void testNoLongerPrimaryShardException() throws IOException {
ShardId shardId = new ShardId(new Index(randomAlphaOfLength(4), randomAlphaOfLength(4)), randomIntBetween(0, Integer.MAX_VALUE));
String msg = randomAlphaOfLength(4);
ShardStateAction.NoLongerPrimaryShardException ex = serialize(new ShardStateAction.NoLongerPrimaryShardException(shardId, msg));
assertEquals(shardId, ex.getShardId());
assertEquals(msg, ex.getMessage());
}
public static class UnknownHeaderException extends ElasticsearchException {
private final RestStatus status;
UnknownHeaderException(String msg, RestStatus status) {
super(msg);
this.status = status;
}
@Override
public RestStatus status() {
return status;
}
}
public void testElasticsearchSecurityException() throws IOException {
ElasticsearchSecurityException ex = new ElasticsearchSecurityException("user [{}] is not allowed", RestStatus.UNAUTHORIZED, "foo");
ElasticsearchSecurityException e = serialize(ex);
assertEquals(ex.status(), e.status());
assertEquals(RestStatus.UNAUTHORIZED, e.status());
}
public void testInterruptedException() throws IOException {
InterruptedException orig = randomBoolean() ? new InterruptedException("boom") : new InterruptedException();
InterruptedException ex = serialize(orig);
assertEquals(orig.getMessage(), ex.getMessage());
}
public void testThatIdsArePositive() {
for (final int id : ElasticsearchException.ids()) {
assertThat("negative id", id, greaterThanOrEqualTo(0));
}
}
public void testThatIdsAreUnique() {
final Set<Integer> ids = new HashSet<>();
for (final int id: ElasticsearchException.ids()) {
assertTrue("duplicate id", ids.add(id));
}
}
public void testIds() {
Map<Integer, Class<? extends ElasticsearchException>> ids = new HashMap<>();
ids.put(0, org.elasticsearch.index.snapshots.IndexShardSnapshotFailedException.class);
ids.put(1, org.elasticsearch.search.dfs.DfsPhaseExecutionException.class);
ids.put(2, org.elasticsearch.common.util.CancellableThreads.ExecutionCancelledException.class);
ids.put(3, org.elasticsearch.discovery.MasterNotDiscoveredException.class);
ids.put(4, org.elasticsearch.ElasticsearchSecurityException.class);
ids.put(5, org.elasticsearch.index.snapshots.IndexShardRestoreException.class);
ids.put(6, org.elasticsearch.indices.IndexClosedException.class);
ids.put(7, org.elasticsearch.http.BindHttpException.class);
ids.put(8, org.elasticsearch.action.search.ReduceSearchPhaseException.class);
ids.put(9, org.elasticsearch.node.NodeClosedException.class);
ids.put(10, org.elasticsearch.index.engine.SnapshotFailedEngineException.class);
ids.put(11, org.elasticsearch.index.shard.ShardNotFoundException.class);
ids.put(12, org.elasticsearch.transport.ConnectTransportException.class);
ids.put(13, org.elasticsearch.transport.NotSerializableTransportException.class);
ids.put(14, org.elasticsearch.transport.ResponseHandlerFailureTransportException.class);
ids.put(15, org.elasticsearch.indices.IndexCreationException.class);
ids.put(16, org.elasticsearch.index.IndexNotFoundException.class);
ids.put(17, org.elasticsearch.cluster.routing.IllegalShardRoutingStateException.class);
ids.put(18, org.elasticsearch.action.support.broadcast.BroadcastShardOperationFailedException.class);
ids.put(19, org.elasticsearch.ResourceNotFoundException.class);
ids.put(20, org.elasticsearch.transport.ActionTransportException.class);
ids.put(21, org.elasticsearch.ElasticsearchGenerationException.class);
ids.put(22, null); // was CreateFailedEngineException
ids.put(23, org.elasticsearch.index.shard.IndexShardStartedException.class);
ids.put(24, org.elasticsearch.search.SearchContextMissingException.class);
ids.put(25, org.elasticsearch.script.GeneralScriptException.class);
ids.put(26, null);
ids.put(27, org.elasticsearch.snapshots.SnapshotCreationException.class);
ids.put(28, null); // was DeleteFailedEngineException, deprecated in 6.0 and removed in 7.0
ids.put(29, org.elasticsearch.index.engine.DocumentMissingException.class);
ids.put(30, org.elasticsearch.snapshots.SnapshotException.class);
ids.put(31, org.elasticsearch.indices.InvalidAliasNameException.class);
ids.put(32, org.elasticsearch.indices.InvalidIndexNameException.class);
ids.put(33, org.elasticsearch.indices.IndexPrimaryShardNotAllocatedException.class);
ids.put(34, org.elasticsearch.transport.TransportException.class);
ids.put(35, org.elasticsearch.ElasticsearchParseException.class);
ids.put(36, org.elasticsearch.search.SearchException.class);
ids.put(37, org.elasticsearch.index.mapper.MapperException.class);
ids.put(38, org.elasticsearch.indices.InvalidTypeNameException.class);
ids.put(39, org.elasticsearch.snapshots.SnapshotRestoreException.class);
ids.put(40, org.elasticsearch.common.ParsingException.class);
ids.put(41, org.elasticsearch.index.shard.IndexShardClosedException.class);
ids.put(42, org.elasticsearch.indices.recovery.RecoverFilesRecoveryException.class);
ids.put(43, org.elasticsearch.index.translog.TruncatedTranslogException.class);
ids.put(44, org.elasticsearch.indices.recovery.RecoveryFailedException.class);
ids.put(45, org.elasticsearch.index.shard.IndexShardRelocatedException.class);
ids.put(46, org.elasticsearch.transport.NodeShouldNotConnectException.class);
ids.put(47, null);
ids.put(48, org.elasticsearch.index.translog.TranslogCorruptedException.class);
ids.put(49, org.elasticsearch.cluster.block.ClusterBlockException.class);
ids.put(50, org.elasticsearch.search.fetch.FetchPhaseExecutionException.class);
ids.put(51, null);
ids.put(52, org.elasticsearch.index.engine.VersionConflictEngineException.class);
ids.put(53, org.elasticsearch.index.engine.EngineException.class);
ids.put(54, null); // was DocumentAlreadyExistsException, which is superseded with VersionConflictEngineException
ids.put(55, org.elasticsearch.action.NoSuchNodeException.class);
ids.put(56, org.elasticsearch.common.settings.SettingsException.class);
ids.put(57, org.elasticsearch.indices.IndexTemplateMissingException.class);
ids.put(58, org.elasticsearch.transport.SendRequestTransportException.class);
ids.put(59, null); // was EsRejectedExecutionException, which is no longer an instance of ElasticsearchException
ids.put(60, null); // EarlyTerminationException was removed in 6.0
ids.put(61, null); // RoutingValidationException was removed in 5.0
ids.put(62, org.elasticsearch.common.io.stream.NotSerializableExceptionWrapper.class);
ids.put(63, org.elasticsearch.indices.AliasFilterParsingException.class);
ids.put(64, null); // DeleteByQueryFailedEngineException was removed in 3.0
ids.put(65, org.elasticsearch.gateway.GatewayException.class);
ids.put(66, org.elasticsearch.index.shard.IndexShardNotRecoveringException.class);
ids.put(67, org.elasticsearch.http.HttpException.class);
ids.put(68, org.elasticsearch.ElasticsearchException.class);
ids.put(69, org.elasticsearch.snapshots.SnapshotMissingException.class);
ids.put(70, org.elasticsearch.action.PrimaryMissingActionException.class);
ids.put(71, org.elasticsearch.action.FailedNodeException.class);
ids.put(72, org.elasticsearch.search.SearchParseException.class);
ids.put(73, org.elasticsearch.snapshots.ConcurrentSnapshotExecutionException.class);
ids.put(74, org.elasticsearch.common.blobstore.BlobStoreException.class);
ids.put(75, org.elasticsearch.cluster.IncompatibleClusterStateVersionException.class);
ids.put(76, org.elasticsearch.index.engine.RecoveryEngineException.class);
ids.put(77, org.elasticsearch.common.util.concurrent.UncategorizedExecutionException.class);
ids.put(78, org.elasticsearch.action.TimestampParsingException.class);
ids.put(79, org.elasticsearch.action.RoutingMissingException.class);
ids.put(80, null); // was IndexFailedEngineException, deprecated in 6.0 and removed in 7.0
ids.put(81, org.elasticsearch.index.snapshots.IndexShardRestoreFailedException.class);
ids.put(82, org.elasticsearch.repositories.RepositoryException.class);
ids.put(83, org.elasticsearch.transport.ReceiveTimeoutTransportException.class);
ids.put(84, org.elasticsearch.transport.NodeDisconnectedException.class);
ids.put(85, null);
ids.put(86, org.elasticsearch.search.aggregations.AggregationExecutionException.class);
ids.put(88, org.elasticsearch.indices.InvalidIndexTemplateException.class);
ids.put(90, org.elasticsearch.index.engine.RefreshFailedEngineException.class);
ids.put(91, org.elasticsearch.search.aggregations.AggregationInitializationException.class);
ids.put(92, org.elasticsearch.indices.recovery.DelayRecoveryException.class);
ids.put(94, org.elasticsearch.client.transport.NoNodeAvailableException.class);
ids.put(95, null);
ids.put(96, org.elasticsearch.snapshots.InvalidSnapshotNameException.class);
ids.put(97, org.elasticsearch.index.shard.IllegalIndexShardStateException.class);
ids.put(98, org.elasticsearch.index.snapshots.IndexShardSnapshotException.class);
ids.put(99, org.elasticsearch.index.shard.IndexShardNotStartedException.class);
ids.put(100, org.elasticsearch.action.search.SearchPhaseExecutionException.class);
ids.put(101, org.elasticsearch.transport.ActionNotFoundTransportException.class);
ids.put(102, org.elasticsearch.transport.TransportSerializationException.class);
ids.put(103, org.elasticsearch.transport.RemoteTransportException.class);
ids.put(104, org.elasticsearch.index.engine.EngineCreationFailureException.class);
ids.put(105, org.elasticsearch.cluster.routing.RoutingException.class);
ids.put(106, org.elasticsearch.index.shard.IndexShardRecoveryException.class);
ids.put(107, org.elasticsearch.repositories.RepositoryMissingException.class);
ids.put(108, null);
ids.put(109, org.elasticsearch.index.engine.DocumentSourceMissingException.class);
ids.put(110, null); // FlushNotAllowedEngineException was removed in 5.0
ids.put(111, org.elasticsearch.common.settings.NoClassSettingsException.class);
ids.put(112, org.elasticsearch.transport.BindTransportException.class);
ids.put(113, org.elasticsearch.rest.action.admin.indices.AliasesNotFoundException.class);
ids.put(114, org.elasticsearch.index.shard.IndexShardRecoveringException.class);
ids.put(115, org.elasticsearch.index.translog.TranslogException.class);
ids.put(116, org.elasticsearch.cluster.metadata.ProcessClusterEventTimeoutException.class);
ids.put(117, ReplicationOperation.RetryOnPrimaryException.class);
ids.put(118, org.elasticsearch.ElasticsearchTimeoutException.class);
ids.put(119, org.elasticsearch.search.query.QueryPhaseExecutionException.class);
ids.put(120, org.elasticsearch.repositories.RepositoryVerificationException.class);
ids.put(121, org.elasticsearch.search.aggregations.InvalidAggregationPathException.class);
ids.put(122, null);
ids.put(123, org.elasticsearch.ResourceAlreadyExistsException.class);
ids.put(124, null);
ids.put(125, TcpTransport.HttpOnTransportException.class);
ids.put(126, org.elasticsearch.index.mapper.MapperParsingException.class);
ids.put(127, org.elasticsearch.search.SearchContextException.class);
ids.put(128, org.elasticsearch.search.builder.SearchSourceBuilderException.class);
ids.put(129, null); // was org.elasticsearch.index.engine.EngineClosedException.class
ids.put(130, org.elasticsearch.action.NoShardAvailableActionException.class);
ids.put(131, org.elasticsearch.action.UnavailableShardsException.class);
ids.put(132, org.elasticsearch.index.engine.FlushFailedEngineException.class);
ids.put(133, org.elasticsearch.common.breaker.CircuitBreakingException.class);
ids.put(134, org.elasticsearch.transport.NodeNotConnectedException.class);
ids.put(135, org.elasticsearch.index.mapper.StrictDynamicMappingException.class);
ids.put(136, org.elasticsearch.action.support.replication.TransportReplicationAction.RetryOnReplicaException.class);
ids.put(137, org.elasticsearch.indices.TypeMissingException.class);
ids.put(138, null);
ids.put(139, null);
ids.put(140, org.elasticsearch.discovery.Discovery.FailedToCommitClusterStateException.class);
ids.put(141, org.elasticsearch.index.query.QueryShardException.class);
ids.put(142, ShardStateAction.NoLongerPrimaryShardException.class);
ids.put(143, org.elasticsearch.script.ScriptException.class);
ids.put(144, org.elasticsearch.cluster.NotMasterException.class);
ids.put(145, org.elasticsearch.ElasticsearchStatusException.class);
ids.put(146, org.elasticsearch.tasks.TaskCancelledException.class);
ids.put(147, org.elasticsearch.env.ShardLockObtainFailedException.class);
ids.put(148, UnknownNamedObjectException.class);
ids.put(149, MultiBucketConsumerService.TooManyBucketsException.class);
Map<Class<? extends ElasticsearchException>, Integer> reverse = new HashMap<>();
for (Map.Entry<Integer, Class<? extends ElasticsearchException>> entry : ids.entrySet()) {
if (entry.getValue() != null) {
reverse.put(entry.getValue(), entry.getKey());
}
}
for (final Tuple<Integer, Class<? extends ElasticsearchException>> tuple : ElasticsearchException.classes()) {
assertNotNull(tuple.v1());
assertEquals((int) reverse.get(tuple.v2()), (int)tuple.v1());
}
for (Map.Entry<Integer, Class<? extends ElasticsearchException>> entry : ids.entrySet()) {
if (entry.getValue() != null) {
assertEquals((int) entry.getKey(), ElasticsearchException.getId(entry.getValue()));
}
}
}
public void testIOException() throws IOException {
IOException serialize = serialize(new IOException("boom", new NullPointerException()));
assertEquals("boom", serialize.getMessage());
assertTrue(serialize.getCause() instanceof NullPointerException);
}
public void testFileSystemExceptions() throws IOException {
for (FileSystemException ex : Arrays.asList(new FileSystemException("a", "b", "c"),
new NoSuchFileException("a", "b", "c"),
new NotDirectoryException("a"),
new DirectoryNotEmptyException("a"),
new AtomicMoveNotSupportedException("a", "b", "c"),
new FileAlreadyExistsException("a", "b", "c"),
new AccessDeniedException("a", "b", "c"),
new FileSystemLoopException("a"))) {
FileSystemException serialize = serialize(ex);
assertEquals(serialize.getClass(), ex.getClass());
assertEquals("a", serialize.getFile());
if (serialize.getClass() == NotDirectoryException.class ||
serialize.getClass() == FileSystemLoopException.class ||
serialize.getClass() == DirectoryNotEmptyException.class) {
assertNull(serialize.getOtherFile());
assertNull(serialize.getReason());
} else {
assertEquals(serialize.getClass().toString(), "b", serialize.getOtherFile());
assertEquals(serialize.getClass().toString(), "c", serialize.getReason());
}
}
}
public void testElasticsearchRemoteException() throws IOException {
ElasticsearchStatusException ex = new ElasticsearchStatusException("something", RestStatus.TOO_MANY_REQUESTS);
ElasticsearchStatusException e = serialize(ex);
assertEquals(ex.status(), e.status());
assertEquals(RestStatus.TOO_MANY_REQUESTS, e.status());
}
public void testShardLockObtainFailedException() throws IOException {
ShardId shardId = new ShardId("foo", "_na_", 1);
ShardLockObtainFailedException orig = new ShardLockObtainFailedException(shardId, "boom");
Version version = VersionUtils.randomVersionBetween(random(), Version.V_5_0_0, Version.CURRENT);
if (version.before(Version.V_5_0_2)) {
version = Version.V_5_0_2;
}
ShardLockObtainFailedException ex = serialize(orig, version);
assertEquals(orig.getMessage(), ex.getMessage());
assertEquals(orig.getShardId(), ex.getShardId());
}
public void testBWCShardLockObtainFailedException() throws IOException {
ShardId shardId = new ShardId("foo", "_na_", 1);
ShardLockObtainFailedException orig = new ShardLockObtainFailedException(shardId, "boom");
Exception ex = serialize((Exception)orig, randomFrom(Version.V_5_0_0, Version.V_5_0_1));
assertThat(ex, instanceOf(NotSerializableExceptionWrapper.class));
assertEquals("shard_lock_obtain_failed_exception: [foo][1]: boom", ex.getMessage());
}
public void testBWCHeadersAndMetadata() throws IOException {
//this is a request serialized with headers only, no metadata as they were added in 5.3.0
BytesReference decoded = new BytesArray(Base64.getDecoder().decode
("AQ10ZXN0ICBtZXNzYWdlACYtb3JnLmVsYXN0aWNzZWFyY2guRXhjZXB0aW9uU2VyaWFsaXphdGlvblRlc3RzASBFeGNlcHRpb25TZXJpYWxpemF0aW9uVG" +
"VzdHMuamF2YQR0ZXN03wYkc3VuLnJlZmxlY3QuTmF0aXZlTWV0aG9kQWNjZXNzb3JJbXBsAR1OYXRpdmVNZXRob2RBY2Nlc3NvckltcGwuamF2Y" +
"QdpbnZva2Uw/v///w8kc3VuLnJlZmxlY3QuTmF0aXZlTWV0aG9kQWNjZXNzb3JJbXBsAR1OYXRpdmVNZXRob2RBY2Nlc3NvckltcGwuamF2YQZp" +
"bnZva2U+KHN1bi5yZWZsZWN0LkRlbGVnYXRpbmdNZXRob2RBY2Nlc3NvckltcGwBIURlbGVnYXRpbmdNZXRob2RBY2Nlc3NvckltcGwuamF2YQZ" +
"pbnZva2UrGGphdmEubGFuZy5yZWZsZWN0Lk1ldGhvZAELTWV0aG9kLmphdmEGaW52b2tl8QMzY29tLmNhcnJvdHNlYXJjaC5yYW5kb21pemVkdG" +
"VzdGluZy5SYW5kb21pemVkUnVubmVyARVSYW5kb21pemVkUnVubmVyLmphdmEGaW52b2tlsQ01Y29tLmNhcnJvdHNlYXJjaC5yYW5kb21pemVkd" +
"GVzdGluZy5SYW5kb21pemVkUnVubmVyJDgBFVJhbmRvbWl6ZWRSdW5uZXIuamF2YQhldmFsdWF0ZYsHNWNvbS5jYXJyb3RzZWFyY2gucmFuZG9t" +
"aXplZHRlc3RpbmcuUmFuZG9taXplZFJ1bm5lciQ5ARVSYW5kb21pemVkUnVubmVyLmphdmEIZXZhbHVhdGWvBzZjb20uY2Fycm90c2VhcmNoLnJ" +
"hbmRvbWl6ZWR0ZXN0aW5nLlJhbmRvbWl6ZWRSdW5uZXIkMTABFVJhbmRvbWl6ZWRSdW5uZXIuamF2YQhldmFsdWF0Zb0HOWNvbS5jYXJyb3RzZW" +
"FyY2gucmFuZG9taXplZHRlc3RpbmcucnVsZXMuU3RhdGVtZW50QWRhcHRlcgEVU3RhdGVtZW50QWRhcHRlci5qYXZhCGV2YWx1YXRlJDVvcmcuY" +
"XBhY2hlLmx1Y2VuZS51dGlsLlRlc3RSdWxlU2V0dXBUZWFyZG93bkNoYWluZWQkMQEhVGVzdFJ1bGVTZXR1cFRlYXJkb3duQ2hhaW5lZC5qYXZh" +
"CGV2YWx1YXRlMTBvcmcuYXBhY2hlLmx1Y2VuZS51dGlsLkFic3RyYWN0QmVmb3JlQWZ0ZXJSdWxlJDEBHEFic3RyYWN0QmVmb3JlQWZ0ZXJSdWx" +
"lLmphdmEIZXZhbHVhdGUtMm9yZy5hcGFjaGUubHVjZW5lLnV0aWwuVGVzdFJ1bGVUaHJlYWRBbmRUZXN0TmFtZSQxAR5UZXN0UnVsZVRocmVhZE" +
"FuZFRlc3ROYW1lLmphdmEIZXZhbHVhdGUwN29yZy5hcGFjaGUubHVjZW5lLnV0aWwuVGVzdFJ1bGVJZ25vcmVBZnRlck1heEZhaWx1cmVzJDEBI" +
"1Rlc3RSdWxlSWdub3JlQWZ0ZXJNYXhGYWlsdXJlcy5qYXZhCGV2YWx1YXRlQCxvcmcuYXBhY2hlLmx1Y2VuZS51dGlsLlRlc3RSdWxlTWFya0Zh" +
"aWx1cmUkMQEYVGVzdFJ1bGVNYXJrRmFpbHVyZS5qYXZhCGV2YWx1YXRlLzljb20uY2Fycm90c2VhcmNoLnJhbmRvbWl6ZWR0ZXN0aW5nLnJ1bGV" +
"zLlN0YXRlbWVudEFkYXB0ZXIBFVN0YXRlbWVudEFkYXB0ZXIuamF2YQhldmFsdWF0ZSREY29tLmNhcnJvdHNlYXJjaC5yYW5kb21pemVkdGVzdG" +
"luZy5UaHJlYWRMZWFrQ29udHJvbCRTdGF0ZW1lbnRSdW5uZXIBFlRocmVhZExlYWtDb250cm9sLmphdmEDcnVu7wI0Y29tLmNhcnJvdHNlYXJja" +
"C5yYW5kb21pemVkdGVzdGluZy5UaHJlYWRMZWFrQ29udHJvbAEWVGhyZWFkTGVha0NvbnRyb2wuamF2YRJmb3JrVGltZW91dGluZ1Rhc2urBjZj" +
"b20uY2Fycm90c2VhcmNoLnJhbmRvbWl6ZWR0ZXN0aW5nLlRocmVhZExlYWtDb250cm9sJDMBFlRocmVhZExlYWtDb250cm9sLmphdmEIZXZhbHV" +
"hdGXOAzNjb20uY2Fycm90c2VhcmNoLnJhbmRvbWl6ZWR0ZXN0aW5nLlJhbmRvbWl6ZWRSdW5uZXIBFVJhbmRvbWl6ZWRSdW5uZXIuamF2YQ1ydW" +
"5TaW5nbGVUZXN0lAc1Y29tLmNhcnJvdHNlYXJjaC5yYW5kb21pemVkdGVzdGluZy5SYW5kb21pemVkUnVubmVyJDUBFVJhbmRvbWl6ZWRSdW5uZ" +
"XIuamF2YQhldmFsdWF0ZaIGNWNvbS5jYXJyb3RzZWFyY2gucmFuZG9taXplZHRlc3RpbmcuUmFuZG9taXplZFJ1bm5lciQ2ARVSYW5kb21pemVk" +
"UnVubmVyLmphdmEIZXZhbHVhdGXUBjVjb20uY2Fycm90c2VhcmNoLnJhbmRvbWl6ZWR0ZXN0aW5nLlJhbmRvbWl6ZWRSdW5uZXIkNwEVUmFuZG9" +
"taXplZFJ1bm5lci5qYXZhCGV2YWx1YXRl3wYwb3JnLmFwYWNoZS5sdWNlbmUudXRpbC5BYnN0cmFjdEJlZm9yZUFmdGVyUnVsZSQxARxBYnN0cm" +
"FjdEJlZm9yZUFmdGVyUnVsZS5qYXZhCGV2YWx1YXRlLTljb20uY2Fycm90c2VhcmNoLnJhbmRvbWl6ZWR0ZXN0aW5nLnJ1bGVzLlN0YXRlbWVud" +
"EFkYXB0ZXIBFVN0YXRlbWVudEFkYXB0ZXIuamF2YQhldmFsdWF0ZSQvb3JnLmFwYWNoZS5sdWNlbmUudXRpbC5UZXN0UnVsZVN0b3JlQ2xhc3NO" +
"YW1lJDEBG1Rlc3RSdWxlU3RvcmVDbGFzc05hbWUuamF2YQhldmFsdWF0ZSlOY29tLmNhcnJvdHNlYXJjaC5yYW5kb21pemVkdGVzdGluZy5ydWx" +
"lcy5Ob1NoYWRvd2luZ09yT3ZlcnJpZGVzT25NZXRob2RzUnVsZSQxAShOb1NoYWRvd2luZ09yT3ZlcnJpZGVzT25NZXRob2RzUnVsZS5qYXZhCG" +
"V2YWx1YXRlKE5jb20uY2Fycm90c2VhcmNoLnJhbmRvbWl6ZWR0ZXN0aW5nLnJ1bGVzLk5vU2hhZG93aW5nT3JPdmVycmlkZXNPbk1ldGhvZHNSd" +
"WxlJDEBKE5vU2hhZG93aW5nT3JPdmVycmlkZXNPbk1ldGhvZHNSdWxlLmphdmEIZXZhbHVhdGUoOWNvbS5jYXJyb3RzZWFyY2gucmFuZG9taXpl" +
"ZHRlc3RpbmcucnVsZXMuU3RhdGVtZW50QWRhcHRlcgEVU3RhdGVtZW50QWRhcHRlci5qYXZhCGV2YWx1YXRlJDljb20uY2Fycm90c2VhcmNoLnJ" +
"hbmRvbWl6ZWR0ZXN0aW5nLnJ1bGVzLlN0YXRlbWVudEFkYXB0ZXIBFVN0YXRlbWVudEFkYXB0ZXIuamF2YQhldmFsdWF0ZSQ5Y29tLmNhcnJvdH" +
"NlYXJjaC5yYW5kb21pemVkdGVzdGluZy5ydWxlcy5TdGF0ZW1lbnRBZGFwdGVyARVTdGF0ZW1lbnRBZGFwdGVyLmphdmEIZXZhbHVhdGUkM29yZ" +
"y5hcGFjaGUubHVjZW5lLnV0aWwuVGVzdFJ1bGVBc3NlcnRpb25zUmVxdWlyZWQkMQEfVGVzdFJ1bGVBc3NlcnRpb25zUmVxdWlyZWQuamF2YQhl" +
"dmFsdWF0ZTUsb3JnLmFwYWNoZS5sdWNlbmUudXRpbC5UZXN0UnVsZU1hcmtGYWlsdXJlJDEBGFRlc3RSdWxlTWFya0ZhaWx1cmUuamF2YQhldmF" +
"sdWF0ZS83b3JnLmFwYWNoZS5sdWNlbmUudXRpbC5UZXN0UnVsZUlnbm9yZUFmdGVyTWF4RmFpbHVyZXMkMQEjVGVzdFJ1bGVJZ25vcmVBZnRlck" +
"1heEZhaWx1cmVzLmphdmEIZXZhbHVhdGVAMW9yZy5hcGFjaGUubHVjZW5lLnV0aWwuVGVzdFJ1bGVJZ25vcmVUZXN0U3VpdGVzJDEBHVRlc3RSd" +
"WxlSWdub3JlVGVzdFN1aXRlcy5qYXZhCGV2YWx1YXRlNjljb20uY2Fycm90c2VhcmNoLnJhbmRvbWl6ZWR0ZXN0aW5nLnJ1bGVzLlN0YXRlbWVu" +
"dEFkYXB0ZXIBFVN0YXRlbWVudEFkYXB0ZXIuamF2YQhldmFsdWF0ZSREY29tLmNhcnJvdHNlYXJjaC5yYW5kb21pemVkdGVzdGluZy5UaHJlYWR" +
"MZWFrQ29udHJvbCRTdGF0ZW1lbnRSdW5uZXIBFlRocmVhZExlYWtDb250cm9sLmphdmEDcnVu7wIQamF2YS5sYW5nLlRocmVhZAELVGhyZWFkLm" +
"phdmEDcnVu6QUABAdoZWFkZXIyAQZ2YWx1ZTIKZXMuaGVhZGVyMwEGdmFsdWUzB2hlYWRlcjEBBnZhbHVlMQplcy5oZWFkZXI0AQZ2YWx1ZTQAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAA"));
try (StreamInput in = decoded.streamInput()) {
//randomize the version across released and unreleased ones
Version version = randomFrom(Version.V_5_0_0, Version.V_5_0_1, Version.V_5_0_2,
Version.V_5_1_1, Version.V_5_1_2, Version.V_5_2_0);
in.setVersion(version);
ElasticsearchException exception = new ElasticsearchException(in);
assertEquals("test message", exception.getMessage());
//the headers received as part of a single set get split based on their prefix
assertEquals(2, exception.getHeaderKeys().size());
assertEquals("value1", exception.getHeader("header1").get(0));
assertEquals("value2", exception.getHeader("header2").get(0));
assertEquals(2, exception.getMetadataKeys().size());
assertEquals("value3", exception.getMetadata("es.header3").get(0));
assertEquals("value4", exception.getMetadata("es.header4").get(0));
}
}
private static class UnknownException extends Exception {
UnknownException(final String message, final Exception cause) {
super(message, cause);
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.mapper.core;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.ParseContext;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeBooleanValue;
import static org.elasticsearch.index.mapper.MapperBuilders.booleanField;
import static org.elasticsearch.index.mapper.core.TypeParsers.parseField;
import static org.elasticsearch.index.mapper.core.TypeParsers.parseMultiField;
/**
* A field mapper for boolean fields.
*/
public class BooleanFieldMapper extends FieldMapper {
public static final String CONTENT_TYPE = "boolean";
public static class Defaults {
public static final MappedFieldType FIELD_TYPE = new BooleanFieldType();
static {
FIELD_TYPE.setOmitNorms(true);
FIELD_TYPE.setIndexOptions(IndexOptions.DOCS);
FIELD_TYPE.setTokenized(false);
FIELD_TYPE.setIndexAnalyzer(Lucene.KEYWORD_ANALYZER);
FIELD_TYPE.setSearchAnalyzer(Lucene.KEYWORD_ANALYZER);
FIELD_TYPE.freeze();
}
}
public static class Values {
public final static BytesRef TRUE = new BytesRef("T");
public final static BytesRef FALSE = new BytesRef("F");
}
public static class Builder extends FieldMapper.Builder<Builder, BooleanFieldMapper> {
public Builder(String name) {
super(name, Defaults.FIELD_TYPE, Defaults.FIELD_TYPE);
this.builder = this;
}
@Override
public Builder tokenized(boolean tokenized) {
if (tokenized) {
throw new IllegalArgumentException("bool field can't be tokenized");
}
return super.tokenized(tokenized);
}
@Override
public BooleanFieldMapper build(BuilderContext context) {
setupFieldType(context);
return new BooleanFieldMapper(name, fieldType, defaultFieldType,
context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo);
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
BooleanFieldMapper.Builder builder = booleanField(name);
parseField(builder, name, node, parserContext);
for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, Object> entry = iterator.next();
String propName = Strings.toUnderscoreCase(entry.getKey());
Object propNode = entry.getValue();
if (propName.equals("null_value")) {
if (propNode == null) {
throw new MapperParsingException("Property [null_value] cannot be null.");
}
builder.nullValue(nodeBooleanValue(propNode));
iterator.remove();
} else if (parseMultiField(builder, name, parserContext, propName, propNode)) {
iterator.remove();
}
}
return builder;
}
}
public static final class BooleanFieldType extends MappedFieldType {
public BooleanFieldType() {}
protected BooleanFieldType(BooleanFieldType ref) {
super(ref);
}
@Override
public MappedFieldType clone() {
return new BooleanFieldType(this);
}
@Override
public String typeName() {
return CONTENT_TYPE;
}
@Override
public Boolean nullValue() {
return (Boolean)super.nullValue();
}
@Override
public BytesRef indexedValueForSearch(Object value) {
if (value == null) {
return Values.FALSE;
}
if (value instanceof Boolean) {
return ((Boolean) value) ? Values.TRUE : Values.FALSE;
}
String sValue;
if (value instanceof BytesRef) {
sValue = ((BytesRef) value).utf8ToString();
} else {
sValue = value.toString();
}
if (sValue.length() == 0) {
return Values.FALSE;
}
if (sValue.length() == 1 && sValue.charAt(0) == 'F') {
return Values.FALSE;
}
if (Booleans.parseBoolean(sValue, false)) {
return Values.TRUE;
}
return Values.FALSE;
}
@Override
public Boolean value(Object value) {
if (value == null) {
return Boolean.FALSE;
}
String sValue = value.toString();
if (sValue.length() == 0) {
return Boolean.FALSE;
}
if (sValue.length() == 1 && sValue.charAt(0) == 'F') {
return Boolean.FALSE;
}
if (Booleans.parseBoolean(sValue, false)) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
@Override
public Object valueForSearch(Object value) {
return value(value);
}
@Override
public boolean useTermQueryWithQueryString() {
return true;
}
}
protected BooleanFieldMapper(String simpleName, MappedFieldType fieldType, MappedFieldType defaultFieldType,
Settings indexSettings, MultiFields multiFields, CopyTo copyTo) {
super(simpleName, fieldType, defaultFieldType, indexSettings, multiFields, copyTo);
}
@Override
public BooleanFieldType fieldType() {
return (BooleanFieldType) super.fieldType();
}
@Override
protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException {
if (fieldType().indexOptions() == IndexOptions.NONE && !fieldType().stored() && !fieldType().hasDocValues()) {
return;
}
Boolean value = context.parseExternalValue(Boolean.class);
if (value == null) {
XContentParser.Token token = context.parser().currentToken();
if (token == XContentParser.Token.VALUE_NULL) {
if (fieldType().nullValue() != null) {
value = fieldType().nullValue();
}
} else {
value = context.parser().booleanValue();
}
}
if (value == null) {
return;
}
fields.add(new Field(fieldType().names().indexName(), value ? "T" : "F", fieldType()));
if (fieldType().hasDocValues()) {
fields.add(new SortedNumericDocValuesField(fieldType().names().indexName(), value ? 1 : 0));
}
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
super.doXContentBody(builder, includeDefaults, params);
if (includeDefaults || fieldType().nullValue() != null) {
builder.field("null_value", fieldType().nullValue());
}
}
}
| |
package com.LilG;
import ch.qos.logback.classic.Logger;
import com.LilG.DataClasses.Meme;
import com.LilG.DataClasses.Note;
import com.LilG.DataClasses.SaveDataStore;
import com.LilG.Serialization.GuildKeyDeserializer;
import com.LilG.Serialization.ISnowflakeSerializer;
import com.LilG.Serialization.MixInModule;
import com.LilG.Serialization.TextChannelKeyDeserializer;
import com.LilG.utils.CryptoUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.rmtheis.yandtran.ApiKeys;
import com.rmtheis.yandtran.YandexTranslatorAPI;
import com.rmtheis.yandtran.detect.Detect;
import com.rmtheis.yandtran.translate.Translate;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers;
import com.sedmelluq.discord.lavaplayer.source.local.LocalAudioSourceManager;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.ISnowflake;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.exceptions.RateLimitedException;
import org.jetbrains.annotations.NotNull;
import org.pircbotx.Configuration;
import org.pircbotx.MultiBotManager;
import org.pircbotx.UtilSSLSocketFactory;
import org.pircbotx.cap.EnableCapHandler;
import org.slf4j.LoggerFactory;
import javax.security.auth.login.LoginException;
import java.io.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;
//import com.google.gson.Gson;
//import com.google.gson.GsonBuilder;
/**
* Created by ggonz on 10/12/2015.
* The Main file with all of the configs
*/
public class FozConfig {
public final static boolean debug = false;
public final static String badnik = "irc.badnik.zone";
public final static String twitch = "irc.twitch.tv";
public final static String caffie = "irc.caffie.net";
public final static String esper = "irc.esper.net";
public final static String nova = "comit.electrocode.net";
public final static String rizon = "irc.rizon.io";
public final static String Lil_G_Net;
//Configure what we want our bot to do
public final static String nick = "FozruciX";
public final static String login = "SmugLeaf";
public final static String kvircFlags = "\u00034\u000F";
public final static String realName = kvircFlags + "* Why do i always get the freaks...";
public final static MultiBotManager manager = new MultiBotManager();
public final static LocationRelativeToServer location;
public final static edu.cmu.sphinx.api.Configuration configuration = new edu.cmu.sphinx.api.Configuration();
private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(FozConfig.class);
transient final static String PASSWORD = setPassword(Password.normal);
private final static File bak = new File("Data/DataBak.json");
private final static File saveFile = new File("Data/Data.json");
private final static int attempts = 10;
private final static int connectDelay = 15 * 1000;
//private final static Gson gson = new GsonBuilder().setPrettyPrinting().create();
private final static ObjectMapper objectMapper = new ObjectMapper();
public final static AudioPlayerManager playerManager = new DefaultAudioPlayerManager();
public static JDA jda;
static Thread game;
static Thread avatar;
static {
String token = CryptoUtil.decrypt(FozConfig.setPassword(FozConfig.Password.discord));
LOGGER.trace("Calling data loader JDA Builder with token: " + token);
try {
jda = new JDABuilder(AccountType.BOT)
.setToken(token)
.setAutoReconnect(true)
.setAudioEnabled(true)
.setEnableShutdownHook(true)
.buildAsync();
} catch (LoginException | RateLimitedException e) {
e.printStackTrace();
System.exit(-1);
}
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
SimpleModule module = new SimpleModule();
module.addKeyDeserializer(Guild.class, new GuildKeyDeserializer());
module.addKeyDeserializer(TextChannel.class, new TextChannelKeyDeserializer());
module.addSerializer(ISnowflake.class, new ISnowflakeSerializer());
//module.addSerializer(Guild.class, new ISnowflakeSerializer());
//module.addSerializer(TextChannel.class, new ISnowflakeSerializer());
objectMapper.registerModule(module);
objectMapper.registerModule(new MixInModule());
loadData();
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.bin");
AudioSourceManagers.registerRemoteSources(playerManager);
playerManager.registerSourceManager(new LocalAudioSourceManager());
LocationRelativeToServer locationTemp = LocationRelativeToServer.local;
try {
System.setProperty("jna.library.path", "M68k");
System.setProperty("jna.debug_load", "true");
System.setProperty("jna.debug_load.jna", "true");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
getAddress:
for (; n.hasMoreElements(); ) {
Enumeration<InetAddress> inetAddresses = n.nextElement().getInetAddresses();
for (; inetAddresses.hasMoreElements(); ) {
InetAddress inetAddress = inetAddresses.nextElement();
if (inetAddress.isLoopbackAddress() || inetAddress.isLinkLocalAddress() || inetAddress.isMulticastAddress())
continue;
String address = inetAddress.getHostAddress();
LOGGER.debug("Address is " + address);
if (address.startsWith("192.168.1.")) {
if (address.equalsIgnoreCase("192.168.1.178")) {
locationTemp = LocationRelativeToServer.self;
break getAddress;
} else {
locationTemp = LocationRelativeToServer.local;
break getAddress;
}
} else {
locationTemp = LocationRelativeToServer.global;
}
}
}
} catch (ClassNotFoundException e) {
LOGGER.error("SQL Driver not found", e);
} catch (Exception e2) {
LOGGER.error("Error", e2);
}
location = locationTemp;
if (location == LocationRelativeToServer.global) {
Lil_G_Net = "irc." + location.address;
} else {
Lil_G_Net = location.address;
}
}
public final static Configuration.Builder debugLil_G_NetConfig = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setNickservPassword(CryptoUtil.decrypt(PASSWORD))
.setName(nick) //Set the nick of the bot.
.setLogin(login)
.setRealName(realName)
//.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates())
.addAutoJoinChannel("#FozruciX")
.addListener(new FozruciX(manager)); //Add our listener that will be called on Events
public final static Configuration.Builder normalLil_G_NetConfig = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setNickservPassword(CryptoUtil.decrypt(PASSWORD))
.setName(nick) //Set the nick of the bot.
.setLogin(login)
.setRealName(realName)
//.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates())
.addAutoJoinChannel("#FozruciX")
.addAutoJoinChannel("#chat")
.addListener(new FozruciX(manager)); //Add our listener that will be called on Events
public final static Configuration.Builder debugConfig = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setNickservPassword(CryptoUtil.decrypt(PASSWORD))
.setName(nick) //Set the nick of the bot.
.setLogin(login)
.setRealName(realName)
.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates())
.addAutoJoinChannel("#Lil-G|bot") //Join the official #Lil-G|Bot channel
.addAutoJoinChannel("#SSB")
.addListener(new FozruciX(manager)); //Add our listener that will be called on Events
public final static Configuration.Builder debugConfigSmwc = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setNickservPassword(CryptoUtil.decrypt(PASSWORD))
.setName(nick) //Set the nick of the bot.
.setLogin(login)
.setRealName(realName)
.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates())
.addAutoJoinChannel("#sm64")
.addAutoJoinChannel("#botTest")
.addListener(new FozruciX(manager)); //Add our listener that will be called on Events
public final static Configuration.Builder twitchDebug = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setEncoding(Charset.forName("UTF-8"))
.setName(nick.toLowerCase()) //Set the nick of the bot.
.setLogin(nick.toLowerCase())
.addAutoJoinChannel("#lilggamegenuis") //Join lilggamegenuis's twitch chat
.addListener(new FozruciX(FozruciX.Network.twitch, manager)); //Add our listener that will be called on Events
public final static Configuration.Builder debugConfigEsper = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setNickservPassword(CryptoUtil.decrypt(PASSWORD))
.setName(nick) //Set the nick of the bot.
.setLogin(login)
.setRealName(realName)
.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates())
.addAutoJoinChannel("#savespam")
//.setIdentServerEnabled(true)
.addListener(new FozruciX(manager)); //Add our listener that will be called on Events
public final static Configuration.Builder debugConfigNova = new Configuration.Builder() //same as normal for now
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setNickservPassword(CryptoUtil.decrypt(PASSWORD))
.setName(nick) //Set the nick of the bot.
.setLogin(login)
.setRealName(realName)
.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates())
.addAutoJoinChannel("#bots")
//.setIdentServerEnabled(true)
.addListener(new FozruciX(manager)); //Add our listener that will be called on Events
public final static Configuration.Builder normal = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setNickservPassword(CryptoUtil.decrypt(PASSWORD))
.setName(nick) //Set the nick of the bot.
.setLogin(login)
.setRealName(realName)
.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates())
.addAutoJoinChannel("#Lil-G|bot") //Join the official #Lil-G|Bot channel
.addAutoJoinChannel("#dnd")
.addAutoJoinChannel("#retro")
.addAutoJoinChannel("#pokemon")
.addAutoJoinChannel("#retrotech")
.addAutoJoinChannel("#SSB")
.addAutoJoinChannel("#idkwtf")
.addAutoJoinChannel("#ducks")
.addAutoJoinChannel("#SSRG")
.addAutoJoinChannel("#GensGS")
.addListener(new FozruciX(manager)); //Add our listener that will be called on Events
public final static Configuration.Builder normalSmwc = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setNickservPassword(CryptoUtil.decrypt(PASSWORD))
.setName(nick) //Set the nick of the bot.
.setLogin(login)
.setRealName(realName)
.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates())
.addAutoJoinChannel("#sm64")
.addAutoJoinChannel("#pmd")
.addAutoJoinChannel("#botTest")
.addAutoJoinChannel("#unix")
.addAutoJoinChannel("#smashbros")
.addAutoJoinChannel("#undertale")
.addAutoJoinChannel("#homebrew")
.addAutoJoinChannel("#radbusiness")
.addListener(new FozruciX(manager)); //Add our listener that will be called on Events
public final static Configuration.Builder twitchNormal = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setAutoNickChange(false) //Twitch doesn't support multiple users
.setOnJoinWhoEnabled(false) //Twitch doesn't support WHO command
.setCapEnabled(true)
.addCapHandler(new EnableCapHandler("twitch.tv/membership")) //Twitch by default doesn't send JOIN, PART, and NAMES unless you request it, see https://github.com/justintv/Twitch-API/blob/master/IRC.md#membership
.addCapHandler(new EnableCapHandler("twitch.tv/commands"))
.addCapHandler(new EnableCapHandler("twitch.tv/tags"))
.setName(nick.toLowerCase()) //Set the nick of the bot.
.setLogin(nick.toLowerCase())
.addAutoJoinChannel("#lilggamegenuis") //Join lilggamegenuis's twitch chat
.addAutoJoinChannel("#deltasmash")
.addListener(new FozruciX(FozruciX.Network.twitch, manager)); //Add our listener that will be called on Events
public final static Configuration.Builder normalEsper = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setNickservPassword(CryptoUtil.decrypt(PASSWORD))
.setName(nick) //Set the nick of the bot.
.setLogin(login)
.setRealName(realName)
.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates())
.addAutoJoinChannel("#savespam")
.addAutoJoinChannel("#ducks")
//.setIdentServerEnabled(true)
.addListener(new FozruciX(manager)); //Add our listener that will be called on Events
public final static Configuration.Builder normalNova = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setNickservPassword(CryptoUtil.decrypt(PASSWORD))
.setName(nick) //Set the nick of the bot.
.setLogin(login)
.setRealName(realName)
.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates())
.addAutoJoinChannel("#bots")
//.setIdentServerEnabled(true)
.addListener(new FozruciX(manager)); //Add our listener that will be called on Events
public final static Configuration.Builder normalRizon = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setNickservPassword(CryptoUtil.decrypt(PASSWORD))
.setName(nick) //Set the nick of the bot.
.setLogin(login)
.setRealName(realName)
.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates())
.addAutoJoinChannel("#origami64")
.addAutoJoinChannel("#FozruciX")
//.setIdentServerEnabled(true)
.addListener(new FozruciX(manager)); //Add our listener that will be called on Events
public final static Configuration.Builder debugConfigRizon = new Configuration.Builder()
.setAutoReconnectDelay(connectDelay)
.setEncoding(Charset.forName("UTF-8"))
.setAutoReconnect(true)
.setAutoReconnectAttempts(attempts)
.setNickservPassword(CryptoUtil.decrypt(PASSWORD))
.setName(nick) //Set the nick of the bot.
.setLogin(login)
.setRealName(realName)
.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates())
.addAutoJoinChannel("#FozruciX")
//.setIdentServerEnabled(true)
.addListener(new FozruciX(manager)); //Add our listener that will be called on Events
//Create our bot with the configuration
public static void main(String[] args) throws Exception {
//Before anything else
//IdentServer.startServer();
LOGGER.debug("Setting key");
YandexTranslatorAPI.setKey(ApiKeys.YANDEX_API_KEY);
Translate.setKey(ApiKeys.YANDEX_API_KEY);
Detect.setKey(ApiKeys.YANDEX_API_KEY);
if (debug) {
manager.addBot(debugConfig.buildForServer(badnik, 6697));
manager.addBot(debugConfigSmwc.buildForServer(caffie, 6697));
manager.addBot(debugConfigEsper.buildForServer(esper, 6697));
manager.addBot(twitchDebug.buildForServer(twitch, 6667, CryptoUtil.decrypt(setPassword(Password.twitch))));
manager.addBot(debugConfigNova.buildForServer(nova, 6697));
manager.addBot(debugConfigRizon.buildForServer(rizon, 9999));
manager.addBot(debugLil_G_NetConfig.buildForServer(Lil_G_Net, 6667));
} else {
manager.addBot(normal.buildForServer(badnik, 6697));
manager.addBot(normalSmwc.buildForServer(caffie, 6697));
manager.addBot(normalEsper.buildForServer(esper, 6697));
manager.addBot(twitchNormal.buildForServer(twitch, 6667, CryptoUtil.decrypt(setPassword(Password.twitch))));
manager.addBot(normalNova.buildForServer(nova, 6697));
manager.addBot(normalRizon.buildForServer(rizon, 9999));
manager.addBot(normalLil_G_NetConfig.buildForServer(Lil_G_Net, 6667));
}
//Connect to the server
manager.start();
}
@NotNull
public static String setPassword(Password password) {
@NotNull File file;
if (password == Password.normal) {
file = new File("pass.bin");
} else if (password == Password.twitch) {
file = new File("twitch.bin");
} else if (password == Password.discord) {
file = new File("discord.bin");
} else if (password == Password.key) {
file = new File("key.bin");
} else if (password == Password.salt) {
file = new File("salt.bin");
} else if (password == Password.ssh) {
file = new File("ssh.bin");
} else {
throw new RuntimeException("Can't find file specified");
}
String ret = " ";
try (FileInputStream fin = new FileInputStream(file)) {
byte fileContent[] = new byte[(int) file.length()];
// Reads up to certain bytes of data from this input stream into an array of bytes.
//noinspection ResultOfMethodCallIgnored
fin.read(fileContent);
//create string from byte array
ret = new String(fileContent);
} catch (FileNotFoundException e) {
LOGGER.error("File not found", e);
} catch (IOException ioe) {
LOGGER.error("Exception while reading file", ioe);
}
return ret;
}
public static synchronized void loadData() {
LOGGER.info("Starting to loadData");
if (!saveFile.exists()) {
LOGGER.info("Save file doesn't exist. Attempting to load backup");
try {
//noinspection StatementWithEmptyBody
//while(!bak.canWrite() || !saveFile.canWrite()){}
Files.move(bak.toPath(), saveFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
LOGGER.info("Backup file moved");
} catch (java.nio.file.FileSystemException e) {
LOGGER.error("file in use", e);
return;
} catch (Exception e) {
LOGGER.error("failed renaming backup file", e);
}
}
try (BufferedReader br = new BufferedReader(new FileReader(saveFile))) {
LOGGER.info("Attempting to load data");
//SaveDataStore.setINSTANCE(gson.fromJson(br, SaveDataStore.class));
SaveDataStore.setINSTANCE(objectMapper.readValue(br, SaveDataStore.class));
if (SaveDataStore.getINSTANCE() != null) {
LOGGER.info("Loaded data");
}
} catch (Exception e) {
LOGGER.error("failed loading data, Attempting to save empty copy", e);
try (FileWriter writer = new FileWriter(new File("Data/DataEmpty.json"))) {
SaveDataStore temp = new SaveDataStore();
temp.getNoteList().add(new Note("sender", "receiver", "message", "channel"));
temp.getAuthedUser().put("name", 0);
temp.getMemes().put("meme", new Meme("creator", "meme"));
temp.getFCList().put("name", "fc");
Map<String, List<String>> tempMap = new HashMap<>();
List<String> tempArray = new ArrayList<>();
tempArray.add("command");
tempMap.put("channel", tempArray);
temp.getAllowedCommands().put("server", tempMap);
temp.getCheckJoinsAndQuits().put("server", "channel");
temp.getMutedServerList().add("server");
tempArray.clear();
tempArray.add("filter");
temp.getWordFilter().put(jda.getTextChannels().get(0).getId(), tempArray);
//temp.getGuildGuildEXMap().put(jda.getGuilds().get(0), GuildEX.getGuildEX(jda.getGuilds().get(0)));
tempArray.clear();
tempArray.add("word");
temp.getMarkovChain().put("key", tempArray);
//writer.write(gson.toJson(temp));
objectMapper.writeValue(writer, temp);
} catch (Exception e1) {
LOGGER.error("Couldn't save empty data", e1);
}
System.exit(1);
}
}
public static synchronized void saveData() throws IOException {
try (FileWriter writer = new FileWriter(bak)) {
//writer.write(gson.toJson(SaveDataStore.getINSTANCE()));
objectMapper.writeValue(writer, SaveDataStore.getINSTANCE());
Files.move(bak.toPath(), saveFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
LOGGER.info("Data saved");
} catch (Exception e) {
LOGGER.error("Couldn't save data", e);
}
}
public static MultiBotManager getManager() {
return manager;
}
public enum Password {
normal, twitch, discord, key, salt, ssh
}
public enum LocationRelativeToServer {
self("localhost"),
local("192.168.1.178"),
global("lilggamegenius.ml");
public final String address;
LocationRelativeToServer(String address) {
this.address = address;
}
}
}
| |
/*******************************************************************************
"FreePastry" Peer-to-Peer Application Development Substrate
Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute
for Software Systems. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Rice University (RICE), Max Planck Institute for Software
Systems (MPI-SWS) nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
This software is provided by RICE, MPI-SWS and the contributors on an "as is"
basis, without any representations or warranties of any kind, express or implied
including, but not limited to, representations or warranties of
non-infringement, merchantability or fitness for a particular purpose. In no
event shall RICE, MPI-SWS or contributors be liable for any direct, indirect,
incidental, special, exemplary, or consequential damages (including, but not
limited to, procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even if
advised of the possibility of such damage.
*******************************************************************************/
package rice.p2p.scribe.testing;
import java.io.IOException;
import java.io.PrintStream;
import java.util.*;
import rice.environment.Environment;
import rice.environment.logging.Logger;
import rice.environment.params.simple.SimpleParameters;
import rice.environment.time.simulated.DirectTimeSource;
import rice.p2p.commonapi.*;
import rice.p2p.commonapi.rawserialization.*;
import rice.p2p.commonapi.testing.CommonAPITest;
import rice.p2p.scribe.*;
import rice.p2p.scribe.messaging.SubscribeMessage;
import rice.p2p.util.tuples.Tuple;
import rice.pastry.PastryNode;
/**
* @(#) DistScribeRegrTest.java Provides regression testing for the Scribe service using distributed
* nodes.
*
* @version $Id: ScribeRegrTest.java 4221 2008-05-19 16:41:19Z jeffh $
* @author Alan Mislove
*/
public class ScribeRegrTest extends CommonAPITest {
// the instance name to use
/**
* DESCRIBE THE FIELD
*/
public static String INSTANCE = "ScribeRegrTest";
// the scribe impls in the ring
/**
* DESCRIBE THE FIELD
*/
protected ScribeImpl[] scribes;
/**
* The scribe policies
*/
protected TestScribePolicy policies[];
/**
* Constructor which sets up all local variables
*/
public ScribeRegrTest(Environment env) throws IOException {
super(env);
scribes = new ScribeImpl[NUM_NODES+1];
policies = new TestScribePolicy[NUM_NODES+1];
}
public TestScribeContent buildTestScribeContent(Topic topic, int numMessages) {
return new TestScribeContent(topic, numMessages);
}
public void setupParams(Environment env) {
super.setupParams(env);
// we want to see if messages are dropped because not ready
// if (!env.getParameters().contains("rice.p2p.scribe.ScribeImpl@ScribeRegrTest_loglevel"))
// env.getParameters().setInt("rice.p2p.scribe.ScribeImpl@ScribeRegrTest_loglevel",Logger.INFO);
// want to retry fast because of problems with isReady()
env.getParameters().setInt("p2p_scribe_message_timeout",3000);
}
/**
* Usage: DistScribeRegrTest [-port p] [-bootstrap host[:port]] [-nodes n] [-protocol (rmi|wire)]
* [-help]
*
* @param args DESCRIBE THE PARAMETER
*/
public static void main(String args[]) throws IOException {
// System.setOut(new PrintStream("srt.log"));
// System.setErr(System.out);
Environment env = parseArgs(args);
ScribeRegrTest scribeTest = new ScribeRegrTest(env);
scribeTest.start();
env.destroy();
}
/**
* Method which should process the given newly-created node
*
* @param node The newly created node
* @param num The number of this node
*/
protected void processNode(int num, Node node) {
scribes[num] = new ScribeImpl(node, INSTANCE);
policies[num] = new TestScribePolicy(scribes[num]);
scribes[num].setPolicy(policies[num]);
}
/**
* Method which should run the test - this is called once all of the nodes have been created and
* are ready.
*/
protected void runTest() {
if (NUM_NODES < 2) {
System.out.println("The DistScribeRegrTest must be run with at least 2 nodes for proper testing. Use the '-nodes n' to specify the number of nodes.");
return;
}
// Run each test
testBasic(1, "Basic");
testBasic(2, "Partial (1)");
testBasic(4, "Partial (2)");
testMultiSubscribe(1, "Basic");
testSingleRoot("Single rooted Trees");
testAPI();
testFailureNotification();
testAddNode();
testMaintenance();
}
/*
* ---------- Test methods and classes ----------
*/
protected void testAddNode() {
String name = "TestAddNode";
Topic topic = new Topic(generateId());
Id id = topic.getId();
TestScribeClient[] clients = new TestScribeClient[NUM_NODES];
sectionStart("Test Add Node");
stepStart("Tree Construction id "+id);
for (int i = 0; i < NUM_NODES; i++) {
clients[i] = new TestScribeClient(scribes[i], topic, i);
scribes[i].subscribe(topic, clients[i]);
simulate();
}
stepDone(SUCCESS);
stepStart("Add New Root");
PastryNode pn = factory.newNode(getBootstrap(),(rice.pastry.Id)id);
nodes[NUM_NODES] = pn;
processNode(NUM_NODES, pn);
if (logger.level <= Logger.INFO) logger.log("Adding new root: "+ pn);
synchronized(nodes[NUM_NODES]) {
while(!pn.isReady()) {
try { pn.wait(1000); } catch (InterruptedException ie) {return;}
}
}
Collection<NodeHandle> children = scribes[NUM_NODES].getChildrenOfTopic(topic);
if (children.size() >= 1) {
stepDone(SUCCESS);
} else {
stepDone(FAILURE, "Node should be the root, has "+children.size()+" children for topic "+topic+".");
}
sectionDone();
}
/**
* Tests basic functionality
*/
protected void testBasic(int skip, String name) {
sectionStart(name + " Scribe Networks");
int NUM_MESSAGES = 5;
int SKIP = skip;
Topic topic = new Topic(generateId());
TestScribeClient[] clients = new TestScribeClient[NUM_NODES/SKIP];
stepStart(name + " Tree Construction");
for (int i = 0; i < NUM_NODES/SKIP; i++) {
clients[i] = new TestScribeClient(scribes[i], topic, i);
scribes[i].subscribe(topic, clients[i]);
simulate();
}
simulate(NUM_NODES/SKIP);
int numWithParent = 0;
for (int i=0; i < NUM_NODES/SKIP; i++) {
if (scribes[i].getParent(topic) != null)
numWithParent++;
}
if (numWithParent < (NUM_NODES/SKIP) - 1)
stepDone(FAILURE, "Expected at least " + (NUM_NODES/SKIP - 1) + " nodes with parents, found " + numWithParent);
else
stepDone(SUCCESS);
stepStart(name + " Publish");
ScribeImpl local = scribes[environment.getRandomSource().nextInt(NUM_NODES/SKIP)];
for (int i = 0; i < NUM_MESSAGES; i++) {
local.publish(topic, buildTestScribeContent(topic, i));
simulate();
}
boolean failed = false;
for (int i=0; i < NUM_NODES/SKIP; i++) {
if (clients[i].getPublishMessages().size() != NUM_MESSAGES) {
stepDone(FAILURE, "Expected client " + clients[i] + " to receive all "+NUM_MESSAGES+" messages, received " + clients[i].getPublishMessages().size());
failed = true;
}
}
if (! failed)
stepDone(SUCCESS);
stepStart(name + " Anycast - No Accept");
local = scribes[environment.getRandomSource().nextInt(NUM_NODES)];
local.anycast(topic, buildTestScribeContent(topic, 59));
simulate(NUM_NODES);
failed = false;
for (int i=0; i < NUM_NODES/SKIP; i++) {
if (clients[i].getAnycastMessages().size() != 0) {
stepDone(FAILURE, "Expected no accepters for anycast, found one at " + scribes[i]);
failed = true;
}
}
if (! failed)
stepDone(SUCCESS);
/**
* This test sends an anycast ... (write more)
*/
stepStart(name + " Anycast - 1 Accept");
TestScribeClient client = clients[environment.getRandomSource().nextInt(NUM_NODES/SKIP)];
client.acceptAnycast(true);
local = scribes[environment.getRandomSource().nextInt(NUM_NODES)];
local.anycast(topic, buildTestScribeContent(topic, 60));
simulate(NUM_NODES);
failed = false;
for (int i=0; i < NUM_NODES/SKIP; i++) {
if (clients[i].equals(client)) {
if (clients[i].getAnycastMessages().size() != 1) {
String s = "";
for (ScribeContent item : clients[i].getAnycastMessages()) {
s+=" "+item;
}
stepDone(FAILURE, "Expected node "+client.scribe+" to accept anycast at " + client+" accepted "+clients[i].getAnycastMessages().size()+" local "+local+" "+s);
failed = true;
}
} else {
if (clients[i].getAnycastMessages().size() != 0) {
stepDone(FAILURE, "Expected no accepters for anycast, found one at " + scribes[i]);
failed = true;
}
}
}
if (! failed)
stepDone(SUCCESS);
stepStart(name + " Anycast - All Accept");
for (int i=0; i < NUM_NODES/SKIP; i++) {
clients[i].acceptAnycast(true);
}
local = scribes[environment.getRandomSource().nextInt(NUM_NODES/SKIP)];
local.anycast(topic, buildTestScribeContent(topic, 61));
simulate(NUM_NODES);
int total = 0;
for (int i=0; i < NUM_NODES/SKIP; i++) {
total += clients[i].getAnycastMessages().size();
}
if (total != 2) {
String str = "";
for (int i=0; i < NUM_NODES/SKIP; i++) {
if (clients[i].getAnycastMessages().size() != 0) {
for (ScribeContent sc : clients[i].getAnycastMessages()) {
str+="\n"+clients[i]+" "+sc;
}
}
}
stepDone(FAILURE, "Expected 2 anycast messages to be found, found "+total+" l:"+str);
} else {
stepDone(SUCCESS);
}
stepStart(name + " Unsubscribe");
for (int i=0; i < NUM_NODES/SKIP; i++) {
scribes[i].unsubscribe(topic, clients[i]);
simulate();
}
local = scribes[environment.getRandomSource().nextInt(NUM_NODES)];
local.publish(topic, buildTestScribeContent(topic, 100));
simulate(NUM_NODES);
failed = false;
for (int i=0; i < NUM_NODES/SKIP; i++) {
if (clients[i].getPublishMessages().size() != NUM_MESSAGES) {
stepDone(FAILURE, "Expected client " + clients[i] + " to receive no additional messages, received " + clients[i].getPublishMessages().size());
failed = true;
}
}
if (! failed)
stepDone(SUCCESS);
stepStart(name + " Tree Completely Demolished");
failed = false;
for (int i=0; i < NUM_NODES; i++) {
if (scribes[i].getClients(topic).size() > 0) {
stepDone(FAILURE, "Expected scribe " + scribes[i] + " to have no clients, had " + scribes[i].getClients(topic).size());
failed = true;
}
if (scribes[i].getChildren(topic).length > 0) {
stepDone(FAILURE, "Expected scribe " + scribes[i] + " to have no children, had " + scribes[i].getChildren(topic).length);
failed = true;
}
if (scribes[i].getParent(topic) != null) {
stepDone(FAILURE, "Expected scribe " + scribes[i] + " to have no parent, had " + scribes[i].getParent(topic));
failed = true;
}
}
if (! failed)
stepDone(SUCCESS);
sectionDone();
}
/**
* Makes sure that if you subscribe to multiple topics at once that they end up on different nodes.
*
*/
protected void testMultiSubscribe(int skip, String name) {
sectionStart(name + " MultiSubscription Scribe Network");
int NUM_MESSAGES = 5;
int SKIP = skip;
int NUM_TOPICS = 2;
// build antipodal topics so they are guaranteed to have different parents
// TODO: Randomize this
TestScribeClient[] clients = new TestScribeClient[NUM_NODES];
List<Topic> topics = new ArrayList<Topic>(NUM_TOPICS);
int[] id1 = {0, 0, 0, 0, 0x80000000};
int[] id2 = {0, 0, 0, 0, 0};
topics.add(new Topic(FACTORY.buildId(id1)));
topics.add(new Topic(FACTORY.buildId(id2)));
// System.out.println(topics.get(0).toString()+" "+topics.get(1).toString());
stepStart(name + " Tree Construction (Parent Independence)");
for (int i = 0; i < NUM_NODES; i++) {
clients[i] = new TestScribeClient(scribes[i], topics, i);
scribes[i].subscribe(topics, clients[i],null, null);
simulate();
}
int numWithParent = 0;
for (int i=0; i < NUM_NODES; i++) {
if (scribes[i].getParent(topics.get(0)) == scribes[i].getParent(topics.get(1))) {
stepDone(FAILURE, "Topics "+topics.get(0)+" and "+topics.get(1)+" had same parent "+scribes[i].getParent(topics.get(0))+" on node "+scribes[i].getEndpoint().getLocalNodeHandle());
}
}
stepDone(SUCCESS);
stepStart(name + " Publish");
ScribeImpl local = scribes[environment.getRandomSource().nextInt(NUM_NODES/SKIP)];
for (int i = 0; i < NUM_MESSAGES; i++) {
for (Topic topic : topics) {
local.publish(topic, buildTestScribeContent(topic, i));
}
simulate();
}
boolean failed = false;
for (int i=0; i < NUM_NODES/SKIP; i++) {
if (clients[i].getPublishMessages().size() != NUM_MESSAGES*NUM_TOPICS) {
stepDone(FAILURE, "Expected client " + clients[i] + " to receive all "+NUM_MESSAGES*NUM_TOPICS+" messages, received " + clients[i].getPublishMessages().size());
failed = true;
}
}
if (! failed)
stepDone(SUCCESS);
stepStart(name + " Anycast - No Accept");
local = scribes[environment.getRandomSource().nextInt(NUM_NODES)];
for (Topic topic : topics)
local.anycast(topic, buildTestScribeContent(topic, 62));
simulate(NUM_NODES*NUM_TOPICS);
failed = false;
for (int i=0; i < NUM_NODES/SKIP; i++) {
if (clients[i].getAnycastMessages().size() != 0) {
stepDone(FAILURE, "Expected no accepters for anycast, found one at " + scribes[i]);
failed = true;
}
}
if (! failed)
stepDone(SUCCESS);
/**
* This test sends an anycast on each topic, but only 1 client is allowed to accept the message
*/
stepStart(name + " Anycast - 1 Accept");
TestScribeClient client = clients[environment.getRandomSource().nextInt(NUM_NODES/SKIP)];
client.acceptAnycast(true);
local = scribes[environment.getRandomSource().nextInt(NUM_NODES)];
for (Topic topic : topics)
local.anycast(topic, buildTestScribeContent(topic, 63));
simulate(NUM_NODES*NUM_TOPICS);
failed = false;
for (int i=0; i < NUM_NODES/SKIP; i++) {
if (clients[i].equals(client)) {
if (clients[i].getAnycastMessages().size() != NUM_TOPICS) {
String s = "";
for (ScribeContent item : clients[i].getAnycastMessages()) {
s+=" "+item;
}
stepDone(FAILURE, "Expected node to accept "+NUM_TOPICS+" anycasts at " + client+" accepted "+clients[i].getAnycastMessages().size()+" local "+local+" "+s);
failed = true;
}
} else {
if (clients[i].getAnycastMessages().size() != 0) {
stepDone(FAILURE, "Expected no accepters for anycast, found one at " + scribes[i]);
failed = true;
}
}
}
if (! failed)
stepDone(SUCCESS);
stepStart(name + " Anycast - All Accept");
for (int i=0; i < NUM_NODES/SKIP; i++) {
clients[i].acceptAnycast(true);
}
local = scribes[environment.getRandomSource().nextInt(NUM_NODES/SKIP)];
for (Topic topic : topics)
local.anycast(topic, buildTestScribeContent(topic, 64));
simulate(NUM_TOPICS);
int total = 0;
for (int i=0; i < NUM_NODES/SKIP; i++) {
total += clients[i].getAnycastMessages().size();
}
if (total != NUM_TOPICS*2) {
String str = "";
for (int i=0; i < NUM_NODES/SKIP; i++) {
if (clients[i].getAnycastMessages().size() != 0) {
for (ScribeContent sc : clients[i].getAnycastMessages()) {
str+="\n"+clients[i]+" "+sc;
}
}
}
stepDone(FAILURE, "Expected "+(NUM_TOPICS*2)+" anycast messages to be found, found "+total+" l:"+str);
} else {
stepDone(SUCCESS);
}
stepStart(name + " Unsubscribe");
for (int i=0; i < NUM_NODES/SKIP; i++) {
for (Topic topic : topics) {
scribes[i].unsubscribe(topic, clients[i]);
}
simulate();
}
local = scribes[environment.getRandomSource().nextInt(NUM_NODES)];
for (Topic topic : topics)
local.publish(topic, buildTestScribeContent(topic, 100));
simulate();
failed = false;
for (int i=0; i < NUM_NODES/SKIP; i++) {
if (clients[i].getPublishMessages().size() != NUM_MESSAGES*NUM_TOPICS) {
stepDone(FAILURE, "Expected client " + clients[i] + " to receive no additional messages, received " + clients[i].getPublishMessages().size());
failed = true;
}
}
if (! failed)
stepDone(SUCCESS);
stepStart(name + " Tree Completely Demolished");
failed = false;
for (int i=0; i < NUM_NODES; i++) {
for (Topic topic : topics) {
if (scribes[i].getClients(topic).size() > 0) {
stepDone(FAILURE, "Expected scribe " + scribes[i] + " to have no clients, had " + scribes[i].getClients(topic).size());
failed = true;
}
if (scribes[i].getChildren(topic).length > 0) {
stepDone(FAILURE, "Expected scribe " + scribes[i] + " to have no children, had " + scribes[i].getChildren(topic).length);
failed = true;
}
if (scribes[i].getParent(topic) != null) {
stepDone(FAILURE, "Expected scribe " + scribes[i] + " to have no parent, had " + scribes[i].getParent(topic));
failed = true;
}
}
}
if (! failed)
stepDone(SUCCESS);
sectionDone();
}
/**
* Tests basic publish functionality
*/
protected void testAPI() {
sectionStart("Scribe API Functionality");
int NUM_MESSAGES = 5;
Topic topic = new Topic(generateId());
TestScribeClient[] clients = new TestScribeClient[NUM_NODES];
stepStart("Tree Construction");
for(int i = 0; i < NUM_NODES; i++)
policies[i].allowSubscribe(false);
for (int i = 0; i < NUM_NODES/2; i++) {
clients[i] = new TestScribeClient(scribes[i], topic, i);
scribes[i].subscribe(topic, clients[i]);
simulate();
}
simulate(NUM_NODES);
int numWithParent = 0;
for (int i=0; i < NUM_NODES; i++) {
if (scribes[i].getParent(topic) != null)
numWithParent++;
}
if (numWithParent < (NUM_NODES/2) - 1) {
String s = "";
for (int i=0; i < NUM_NODES; i++) {
if (scribes[i].getParent(topic) == null) {
s+=" "+scribes[i];
}
}
stepDone(FAILURE, "Expected at least " + (NUM_NODES/2 - 1) + " nodes with parents, found " + numWithParent+" "+s);
} else
if (numWithParent > (NUM_NODES/2))
stepDone(FAILURE, "Expected no more than " + (NUM_NODES/2) + " nodes with parents, due to policy, found " + numWithParent);
else
stepDone(SUCCESS);
stepStart("Drop Child");
// now, find a scribe with a child
ScribeImpl scribe = null;
TestScribeClient client = null;
TestScribePolicy policy = null;
for (int i=0; (i<NUM_NODES) && (scribe == null); i++) {
if (scribes[i].getChildren(topic).length > 0) {
scribe = scribes[i];
client = clients[i];
policy = policies[i];
}
}
if (scribe == null) {
stepDone(FAILURE, "Could not find any scribes with children");
} else {
NodeHandle child = scribe.getChildren(topic)[0];
// set this client to never allow subscribes
policy.neverAllowSubscribe(true);
// drop the handle now
scribe.removeChild(topic, child);
simulate();
ScribeImpl local = scribes[environment.getRandomSource().nextInt(NUM_NODES)];
for (int i = 0; i < NUM_MESSAGES; i++) {
local.publish(topic, buildTestScribeContent(topic, i));
simulate();
}
boolean failed = false;
for (int i=0; i < NUM_NODES/2; i++) {
if (clients[i].getPublishMessages().size() != NUM_MESSAGES) {
stepDone(FAILURE, "Expected client " + clients[i] + " to receive all "+NUM_MESSAGES+" messages, received " + clients[i].getPublishMessages().size());
failed = true;
}
}
NodeHandle[] children = scribe.getChildren(topic);
if (Arrays.asList(children).contains(child)) {
stepDone(FAILURE, "Child resubscribed to previous node, policy should prevent this.");
failed = true;
}
if (! failed)
stepDone(SUCCESS);
}
stepStart("Reset Policies");
for (int i=0; i<NUM_NODES; i++) {
policies[i].allowSubscribe(true);
policies[i].neverAllowSubscribe(false);
}
stepDone(SUCCESS);
sectionDone();
}
/**
* Tests failure notification
*/
protected void testFailureNotification() {
sectionStart("Subscribe Failure Notification");
Topic topic = new Topic(generateId());
TestScribeClient client;
stepStart("Policy Change");
for (int i=0; i < NUM_NODES; i++) {
policies[i].neverAllowSubscribe(true);
}
stepDone(SUCCESS);
// stepStart("Force Root To Accept");
// client = new TestScribeClient(scribes[NUM_NODES-1], topic, NUM_NODES-1);
// // join 1 node first to force the Topic to be created
// scribes[NUM_NODES-1].subscribe(topic, client);
// simulate();
// if (client.getSubscribeFailed())
// stepDone(FAILURE, "Expected subscribe to succeed because we force the root to accept 1 child.");
// else
// stepDone(SUCCESS);
stepStart("Subscribe Attempt");
int i = environment.getRandomSource().nextInt(NUM_NODES-1);
while (scribes[i].isRoot(topic))
i = environment.getRandomSource().nextInt(NUM_NODES-1);
client = new TestScribeClient(scribes[i], topic, i);
scribes[i].subscribe(topic, client);
simulate();
stepDone(SUCCESS);
stepStart("Failure Notification Delivered");
if (! client.getSubscribeFailed())
stepDone(FAILURE, "Expected subscribe to fail, but did not.");
else
stepDone(SUCCESS);
stepStart("Policy Reset");
for (int j=0; j < NUM_NODES; j++) {
policies[j].neverAllowSubscribe(false);
}
stepDone(SUCCESS);
sectionDone();
}
protected void testSingleRoot(String name) {
sectionStart(name + "");
int numTrees = 10;
boolean failed = false;
for(int num=0; num<numTrees; num ++) {
Topic topic = new Topic(generateId());
TestScribeClient[] clients = new TestScribeClient[NUM_NODES];
stepStart(name + " TopicId=" + topic.getId());
for (int i = 0; i < NUM_NODES; i++) {
clients[i] = new TestScribeClient(scribes[i], topic, i);
scribes[i].subscribe(topic, clients[i]);
simulate();
}
int numRoot = 0;
for (int i=0; i < NUM_NODES; i++) {
if (scribes[i].isRoot(topic)) {
numRoot++;
//System.out.println("myId= " + scribes[i].getId());
}
}
if (numRoot != 1) {
stepDone(FAILURE, "Number of roots= " + numRoot);
failed = true;
}
else
stepDone(SUCCESS);
}
sectionDone();
}
/**
* Tests basic publish functionality
*/
protected void testMaintenance() {
sectionStart("Tree Maintenance Under Node Death");
int NUM_MESSAGES = 5;
Topic topic = new Topic(generateId());
TestScribeClient[] clients = new TestScribeClient[NUM_NODES];
stepStart("Tree Construction");
for (int i = 0; i < NUM_NODES; i++) {
clients[i] = new TestScribeClient(scribes[i], topic, i);
scribes[i].subscribe(topic, clients[i]);
simulate();
}
simulate(NUM_NODES);
int numWithParent = 0;
for (int i=0; i < NUM_NODES; i++) {
if (scribes[i].getParent(topic) != null)
numWithParent++;
}
if (numWithParent < NUM_NODES-1)
stepDone(FAILURE, "Expected at least " + (NUM_NODES - 1) + " nodes with parents, found " + numWithParent);
else
stepDone(SUCCESS);
// environment.getParameters().setInt("org.mpisws.p2p.transport.wire.UDPLayer_loglevel", Logger.ALL);
stepStart("Killing Nodes");
for (int i=0; i<NUM_NODES/2; i++) {
// System.out.println("Killing " + scribes[i].getId());
// logger.log("Killing " + nodes[i]);
if (logger.level <= Logger.INFO) logger.log("Killing " + nodes[i]);
scribes[i].destroy();
kill(i);
simulate(5);
}
waitToRecoverFromKilling(scribes[0].MESSAGE_TIMEOUT);
stepDone(SUCCESS);
stepStart("Tree Recovery");
int localIndex = environment.getRandomSource().nextInt(NUM_NODES/2) + NUM_NODES/2;
ScribeImpl local = scribes[localIndex];
// System.out.println("Local:"+nodes[localIndex]);
for (int i = 0; i < NUM_MESSAGES; i++) {
local.publish(topic, buildTestScribeContent(topic, i));
simulate(5);
}
boolean failed = false;
for (int i=NUM_NODES/2; i < NUM_NODES; i++) {
if (clients[i].getPublishMessages().size() != NUM_MESSAGES) {
stepDone(FAILURE, "Expected client " + nodes[i] +":"+clients[i]+ " to receive all "+NUM_MESSAGES+" messages, received " + clients[i].getPublishMessages().size());
failed = true;
}
}
if (! failed)
stepDone(SUCCESS);
sectionDone();
}
/**
* Private method which generates a random Id
*
* @return A new random Id
*/
private Id generateId() {
byte[] data = new byte[20];
environment.getRandomSource().nextBytes(data);
return FACTORY.buildId(data);
}
public static List<Topic> buildListOf1(Topic topic) {
List<Topic> ret = new ArrayList<Topic>(1);
ret.add(topic);
return ret;
}
/**
* Utility class for past content objects
*
* @version $Id: ScribeRegrTest.java 4221 2008-05-19 16:41:19Z jeffh $
* @author amislove
*/
protected static class TestScribeContent implements ScribeContent {
/**
* DESCRIBE THE FIELD
*/
protected Topic topic;
/**
* DESCRIBE THE FIELD
*/
protected int num;
/**
* Constructor for TestScribeContent.
*
* @param topic DESCRIBE THE PARAMETER
* @param num DESCRIBE THE PARAMETER
*/
public TestScribeContent(Topic topic, int num) {
this.topic = topic;
this.num = num;
}
/**
* DESCRIBE THE METHOD
*
* @param o DESCRIBE THE PARAMETER
* @return DESCRIBE THE RETURN VALUE
*/
public boolean equals(Object o) {
if (!(o instanceof TestScribeContent)) {
return false;
}
return (((TestScribeContent) o).topic.equals(topic) &&
((TestScribeContent) o).num == num);
}
/**
* DESCRIBE THE METHOD
*
* @return DESCRIBE THE RETURN VALUE
*/
public String toString() {
return "TestScribeContent(" + topic + ", " + num + ")";
}
}
/**
* Utility class which simulates a route message
*
* @version $Id: ScribeRegrTest.java 4221 2008-05-19 16:41:19Z jeffh $
* @author amislove
*/
protected static class TestRouteMessage implements RouteMessage {
private Id id;
private NodeHandle nextHop;
private Message message;
/**
* Constructor for TestRouteMessage.
*
* @param id DESCRIBE THE PARAMETER
* @param nextHop DESCRIBE THE PARAMETER
* @param message DESCRIBE THE PARAMETER
*/
public TestRouteMessage(Id id, NodeHandle nextHop, Message message) {
this.id = id;
this.nextHop = nextHop;
this.message = message;
}
/**
* Gets the DestinationId attribute of the TestRouteMessage object
*
* @return The DestinationId value
*/
public Id getDestinationId() {
return id;
}
/**
* Gets the NextHopHandle attribute of the TestRouteMessage object
*
* @return The NextHopHandle value
*/
public NodeHandle getNextHopHandle() {
return nextHop;
}
/**
* Gets the Message attribute of the TestRouteMessage object
*
* @deprecated
* @return The Message value
*/
public Message getMessage() {
return message;
}
public Message getMessage(MessageDeserializer md) {
return message;
}
/**
* Sets the DestinationId attribute of the TestRouteMessage object
*
* @param id The new DestinationId value
*/
public void setDestinationId(Id id) {
this.id = id;
}
/**
* Sets the NextHopHandle attribute of the TestRouteMessage object
*
* @param nextHop The new NextHopHandle value
*/
public void setNextHopHandle(NodeHandle nextHop) {
this.nextHop = nextHop;
}
/**
* Sets the Message attribute of the TestRouteMessage object
*
* @param message The new Message value
*/
public void setMessage(Message message) {
this.message = message;
}
public void setMessage(RawMessage message) {
this.message = message;
}
}
/**
* DESCRIBE THE CLASS
*
* @version $Id: ScribeRegrTest.java 4221 2008-05-19 16:41:19Z jeffh $
* @author amislove
*/
protected class TestScribeClient implements ScribeClient {
/**
* DESCRIBE THE FIELD
*/
protected Scribe scribe;
/**
* DESCRIBE THE FIELD
*/
protected int i;
/**
* The publish messages received so far
*/
protected Vector publishMessages;
/**
* The publish messages received so far
*/
protected Vector anycastMessages;
/**
* The topic this client is listening for
*/
protected List<Topic> topics;
/**
* Whether or not this client should accept anycasts
*/
protected boolean acceptAnycast;
/**
* Whether this client has had a subscribe fail
*/
protected boolean subscribeFailed;
/**
* Constructor for TestScribeClient.
*
* @param scribe DESCRIBE THE PARAMETER
* @param i DESCRIBE THE PARAMETER
*/
public TestScribeClient(Scribe scribe, Topic topic, int i) {
this(scribe, buildListOf1(topic), i);
}
public TestScribeClient(Scribe scribe, List<Topic> topics, int i) {
this.scribe = scribe;
this.i = i;
this.topics = topics;
this.publishMessages = new Vector();
this.anycastMessages = new Vector();
this.acceptAnycast = false;
this.subscribeFailed = false;
}
public List<ScribeContent> getPublishMessages() {
return publishMessages;
}
public List<ScribeContent> getAnycastMessages() {
return anycastMessages;
}
public void acceptAnycast(boolean value) {
this.acceptAnycast = value;
}
/**
* DESCRIBE THE METHOD
*
* @param topic DESCRIBE THE PARAMETER
* @param content DESCRIBE THE PARAMETER
* @return DESCRIBE THE RETURN VALUE
*/
public boolean anycast(Topic topic, ScribeContent content) {
// System.out.println(scribe+" "+this+".anycast():"+acceptAnycast);
if (acceptAnycast)
anycastMessages.add(content);
return acceptAnycast;
}
/**
* DESCRIBE THE METHOD
*
* @param topic DESCRIBE THE PARAMETER
* @param content DESCRIBE THE PARAMETER
*/
public void deliver(Topic topic, ScribeContent content) {
// scribe.getEnvironment().getLogManager().getLogger(TestScribeClient.class,null).log(this+"deliver("+topic+","+content+")");
publishMessages.add(content);
}
/**
* DESCRIBE THE METHOD
*
* @param topic DESCRIBE THE PARAMETER
* @param child DESCRIBE THE PARAMETER
*/
public void childAdded(Topic topic, NodeHandle child) {
// System.out.println("CHILD ADDED AT " + scribe.getId());
}
/**
* DESCRIBE THE METHOD
*
* @param topic DESCRIBE THE PARAMETER
* @param child DESCRIBE THE PARAMETER
*/
public void childRemoved(Topic topic, NodeHandle child) {
// System.out.println("CHILD REMOVED AT " + scribe.getId());
}
public void subscribeFailed(Topic topic) {
subscribeFailed = true;
scribe.subscribe(topic, this);
}
public boolean getSubscribeFailed() {
return subscribeFailed;
}
public String toString() {
if (topics.size() == 1) {
return topics.get(0).toString();
}
String s = "";
for (Topic topic : topics) {
s+=topics.toString()+" ";
}
return s+scribe;
}
}
public class TestScribePolicy extends ScribePolicy.DefaultScribePolicy {
protected Scribe scribe;
protected boolean allowSubscribe;
protected boolean neverAllowSubscribe;
public TestScribePolicy(Scribe scribe) {
super(scribe.getEnvironment());
this.scribe = scribe;
allowSubscribe = true;
neverAllowSubscribe = false;
}
public void allowSubscribe(boolean allowSubscribe) {
this.allowSubscribe = allowSubscribe;
}
public void neverAllowSubscribe(boolean neverAllowSubscribe) {
this.neverAllowSubscribe = neverAllowSubscribe;
}
public boolean allowSubscribe(SubscribeMessage message, ScribeClient[] clients, NodeHandle[] children) {
//System.out.println("Allow subscribe , client.size "+clients.length+", children "+children.length+" for subscriber "+message.getSubscriber());
return (! neverAllowSubscribe) && (allowSubscribe || (clients.length > 0) || this.scribe.isRoot(message.getTopic()));
}
}
}
| |
/*
* Copyright 2017 LinkedIn Corp. Licensed under the BSD 2-Clause License (the "License"). See License in the project root for license information.
*/
package com.linkedin.kafka.cruisecontrol.model;
import com.linkedin.kafka.cruisecontrol.config.KafkaCruiseControlConfig;
import com.linkedin.kafka.cruisecontrol.common.Resource;
import com.linkedin.kafka.cruisecontrol.exception.ModelInputException;
import com.google.gson.Gson;
import com.linkedin.kafka.cruisecontrol.monitor.sampling.Snapshot;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A class for representing load information for each resource. Each Load in a cluster must have the same number of
* snapshots.
*/
public class Load implements Serializable {
private static final Comparator<Snapshot> TIME_COMPARATOR = (t1, t2) -> Long.compare(t2.time(), t1.time());
// Number of snapshots in this load.
private static int _maxNumSnapshots = -1;
// Snapshots by their time.
private final List<Snapshot> _snapshotsByTime;
private final double[] _accumulatedUtilization;
private final int _maxNumSnapshotForObject;
/**
* Initialize the Load class. The initialization should be done once and only once.
*
* @param config The configurations for Kafka Cruise Control
*/
public static void init(KafkaCruiseControlConfig config) {
if (_maxNumSnapshots > 0) {
throw new IllegalStateException("The Load has already been initialized.");
}
int numSnapshots = config.getInt(KafkaCruiseControlConfig.NUM_LOAD_SNAPSHOTS_CONFIG);
if (numSnapshots <= 0) {
throw new IllegalArgumentException("The number of snapshots is " + numSnapshots + ". It must be greater than 0.");
}
_maxNumSnapshots = numSnapshots;
}
/**
* Get snapshots in this load by their snapshot time.
*/
public List<Snapshot> snapshotsByTime() {
return _snapshotsByTime;
}
/**
* Get the number of snapshots in the load.
*/
public int numSnapshots() {
return _snapshotsByTime.size();
}
/**
* Generate a new Load with the number of snapshots specified in {@link #init}.
*/
public static Load newLoad() {
if (_maxNumSnapshots <= 0) {
throw new IllegalStateException("The LoadFactory hasn't been initialized.");
}
return new Load(_maxNumSnapshots);
}
/**
* Check if the load is initialized.
*/
public static boolean initialized() {
return _maxNumSnapshots > 0;
}
/**
* Get the number of snapshots setting.
*/
public static int maxNumSnapshots() {
return _maxNumSnapshots;
}
/**
* Get a single snapshot value that is representative for the given resource. The current algorithm uses
* (1) the mean of the recent resource load for inbound network load, outbound network load, and cpu load
* (2) the latest utilization for disk space usage.
*
* @param resource Resource for which the expected utilization will be provided.
* @return A single representative utilization value on a resource.
*/
public double expectedUtilizationFor(Resource resource) {
if (_snapshotsByTime.isEmpty()) {
return 0.0;
}
return resource == Resource.DISK ? Math.max(0, _snapshotsByTime.get(0).utilizationFor(resource)) :
Math.max(0, _accumulatedUtilization[resource.id()] / _snapshotsByTime.size());
}
/**
* Package constructor for load with given load properties.
*/
Load(int maxNumSnapshots) {
_snapshotsByTime = new ArrayList<>(maxNumSnapshots);
_maxNumSnapshotForObject = maxNumSnapshots;
_accumulatedUtilization = new double[Resource.values().length];
for (Resource resource : Resource.cachedValues()) {
_accumulatedUtilization[resource.id()] = 0.0;
}
}
/**
* Overwrite the load for given resource with the given load.
*
* @param resource Resource for which the load will be overwritten.
* @param loadBySnapshotTime Load for the given resource to overwrite the original load by snapshot time.
*/
void setLoadFor(Resource resource, Map<Long, Double> loadBySnapshotTime) throws ModelInputException {
if (loadBySnapshotTime.size() != _snapshotsByTime.size()) {
throw new ModelInputException("Load to set and load for the resources must have exactly " +
_snapshotsByTime.size() + " entries.");
}
double delta = 0.0;
for (Snapshot snapshot : _snapshotsByTime) {
long time = snapshot.time();
if (!loadBySnapshotTime.containsKey(time)) {
throw new IllegalStateException("The new snapshot time does not match the current snapshot time.");
}
double oldUtilization = snapshot.utilizationFor(resource);
double newUtilization = loadBySnapshotTime.get(time);
snapshot.setUtilizationFor(resource, newUtilization);
delta += newUtilization - oldUtilization;
}
_accumulatedUtilization[resource.id()] = _accumulatedUtilization[resource.id()] + delta;
}
/**
* Clear the utilization for given resource.
*
* @param resource Resource for which the utilization will be cleared.
*/
void clearLoadFor(Resource resource) {
for (Snapshot snapshot : _snapshotsByTime) {
snapshot.clearUtilizationFor(resource);
}
_accumulatedUtilization[resource.id()] = 0.0;
}
/**
* Push the latest snapshot.
*
* @param snapshot Snapshot containing latest time and state for each resource.
* @throws ModelInputException
*/
void pushLatestSnapshot(Snapshot snapshot) throws ModelInputException {
if (_snapshotsByTime.size() >= _maxNumSnapshotForObject) {
throw new ModelInputException("Already have " + _snapshotsByTime.size() + " snapshots but see a different " +
"snapshot time" + snapshot.time() + ". Existing snapshot times: " +
Arrays.toString(allSnapshotTimes()));
}
if (!_snapshotsByTime.isEmpty() && snapshot.time() >= _snapshotsByTime.get(_snapshotsByTime.size() - 1).time()) {
throw new ModelInputException("Attempt to push an out of order snapshot with timestamp " + snapshot.time() +
" to a replica. Existing snapshot times: " +
Arrays.toString(allSnapshotTimes()));
}
_snapshotsByTime.add(snapshot);
for (Resource r : Resource.cachedValues()) {
double utilization = _accumulatedUtilization[r.id()];
_accumulatedUtilization[r.id()] = utilization + snapshot.utilizationFor(r);
}
}
/**
* Add the given snapshot to the existing load.
* Used by cluster/rack/broker when the load in the structure is updated with the push of a new snapshot.
*
* @param snapshotToAdd Snapshot to add to the original load.
*/
void addSnapshot(Snapshot snapshotToAdd) {
getAndMaybeCreateSnapshot(snapshotToAdd.time()).addSnapshot(snapshotToAdd);
for (Resource r : Resource.cachedValues()) {
_accumulatedUtilization[r.id()] = _accumulatedUtilization[r.id()] + snapshotToAdd.utilizationFor(r);
}
}
/**
* Subtract the given snapshot from the existing load.
*
* @param snapshotToSubtract Snapshot to subtract from the original load.
*/
void subtractSnapshot(Snapshot snapshotToSubtract) {
snapshotForTime(snapshotToSubtract.time()).subtractSnapshot(snapshotToSubtract);
for (Resource r : Resource.cachedValues()) {
_accumulatedUtilization[r.id()] = _accumulatedUtilization[r.id()] - snapshotToSubtract.utilizationFor(r);
}
}
/**
* Add the given load to this load.
*
* @param loadToAdd Load to add to this load.
*/
void addLoad(Load loadToAdd) {
for (Snapshot snapshot : loadToAdd.snapshotsByTime()) {
getAndMaybeCreateSnapshot(snapshot.time()).addSnapshot(snapshot);
}
for (Resource r : Resource.cachedValues()) {
_accumulatedUtilization[r.id()] = this._accumulatedUtilization[r.id()] + loadToAdd.accumulatedUtilization()[r.id()];
}
}
/**
* Subtract the given load from this load.
*
* @param loadToSubtract Load to subtract from this load.
*/
void subtractLoad(Load loadToSubtract) {
for (Snapshot snapshot : loadToSubtract.snapshotsByTime()) {
snapshotForTime(snapshot.time()).subtractSnapshot(snapshot);
}
for (Resource r : Resource.cachedValues()) {
_accumulatedUtilization[r.id()] = this._accumulatedUtilization[r.id()] - loadToSubtract.accumulatedUtilization()[r.id()];
}
}
/**
* Add the given load for the given resource to this load.
*
* @param resource Resource for which the given load will be added.
* @param loadToAddBySnapshotTime Load to add to this load for the given resource.
*/
void addLoadFor(Resource resource, Map<Long, Double> loadToAddBySnapshotTime) {
double delta = 0.0;
for (Snapshot snapshot : _snapshotsByTime) {
double loadToAdd = loadToAddBySnapshotTime.get(snapshot.time());
snapshot.addUtilizationFor(resource, loadToAdd);
delta += loadToAdd;
}
_accumulatedUtilization[resource.id()] = _accumulatedUtilization[resource.id()] + delta;
}
/**
* Subtract the given load for the given resource from this load.
*
* @param resource Resource for which the given load will be subtracted.
* @param loadToSubtractBySnapshotTime Load to subtract from this load for the given resource.
*/
void subtractLoadFor(Resource resource, Map<Long, Double> loadToSubtractBySnapshotTime) {
double delta = 0.0;
for (Snapshot snapshot : _snapshotsByTime) {
double loadToSubtract = loadToSubtractBySnapshotTime.get(snapshot.time());
snapshot.subtractUtilizationFor(resource, loadToSubtract);
delta += loadToSubtract;
}
_accumulatedUtilization[resource.id()] = _accumulatedUtilization[resource.id()] - delta;
}
/**
* Clear the content of the circular list for each resource.
*/
void clearLoad() {
_snapshotsByTime.clear();
for (Resource r : Resource.cachedValues()) {
_accumulatedUtilization[r.id()] = 0.0;
}
}
/**
* Get the load for the requested resource as a mapping from snapshot time to utilization for the given resource.
*
* @param resource Resource for which the load will be provided.
* @return Load of the requested resource as a mapping from snapshot time to utilization for the given resource.
*/
Map<Long, Double> loadFor(Resource resource) {
Map<Long, Double> loadForResource = new HashMap<>();
for (Snapshot snapshot : _snapshotsByTime) {
loadForResource.put(snapshot.time(), snapshot.utilizationFor(resource));
}
return loadForResource;
}
private double[] accumulatedUtilization() {
return _accumulatedUtilization;
}
// A binary search by time. package private for testing.
Snapshot snapshotForTime(long time) {
int index = Collections.binarySearch(_snapshotsByTime, new Snapshot(time), TIME_COMPARATOR);
if (index < 0) {
return null;
}
return _snapshotsByTime.get(index);
}
// package private for testing.
Snapshot getAndMaybeCreateSnapshot(long time) {
// First do a binary search.
int index = Collections.binarySearch(_snapshotsByTime, new Snapshot(time), TIME_COMPARATOR);
if (index >= 0) {
return _snapshotsByTime.get(index);
}
Snapshot snapshot = new Snapshot(time);
_snapshotsByTime.add(-(index + 1), snapshot);
return snapshot;
}
private long[] allSnapshotTimes() {
long[] times = new long[_snapshotsByTime.size()];
for (int i = 0; i < _snapshotsByTime.size(); i++) {
times[i] = _snapshotsByTime.get(i).time();
}
return times;
}
/*
* Return a valid JSON encoded string
*/
public String getJSONString() {
Gson gson = new Gson();
return gson.toJson(getJsonStructure());
}
/*
* Return an object that can be further used
* to encode into JSON
*/
public Map<String, Object> getJsonStructure() {
Map<String, Object> loadMap = new HashMap<>();
List<Object> snapList = new ArrayList<>();
for (Snapshot snapshot : _snapshotsByTime) {
snapList.add(snapshot.getJsonStructureForLoad());
}
loadMap.put("snapshots", snapList);
return loadMap;
}
/**
* Output writing string representation of this class to the stream.
* @param out the output stream.
*/
public void writeTo(OutputStream out) throws IOException {
out.write("<Load>".getBytes(StandardCharsets.UTF_8));
for (Snapshot snapshot : _snapshotsByTime) {
snapshot.writeTo(out);
}
out.write("</Load>%n".getBytes(StandardCharsets.UTF_8));
}
/**
* Get string representation of Load in XML format.
*/
@Override
public String toString() {
StringBuilder load = new StringBuilder().append("<Load>");
for (Snapshot snapshot : _snapshotsByTime) {
load.append(snapshot.toString());
}
return load.append("</Load>%n").toString();
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.jdbc;
import com.google.common.base.Joiner;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.RowIdLifetime;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
public class PrestoDatabaseMetaData
implements DatabaseMetaData
{
private final PrestoConnection connection;
PrestoDatabaseMetaData(PrestoConnection connection)
{
this.connection = checkNotNull(connection, "connection is null");
}
@Override
public boolean allProceduresAreCallable()
throws SQLException
{
return true;
}
@Override
public boolean allTablesAreSelectable()
throws SQLException
{
return true;
}
@Override
public String getURL()
throws SQLException
{
return connection.getURI().toString();
}
@Override
public String getUserName()
throws SQLException
{
return connection.getUser();
}
@Override
public boolean isReadOnly()
throws SQLException
{
return connection.isReadOnly();
}
@Override
public boolean nullsAreSortedHigh()
throws SQLException
{
// TODO: determine null sort order
throw new NotImplementedException("DatabaseMetaData", "nullsAreSortedHigh");
}
@Override
public boolean nullsAreSortedLow()
throws SQLException
{
// TODO: determine null sort order
throw new NotImplementedException("DatabaseMetaData", "nullsAreSortedLow");
}
@Override
public boolean nullsAreSortedAtStart()
throws SQLException
{
// TODO: determine null sort order
throw new NotImplementedException("DatabaseMetaData", "nullsAreSortedAtStart");
}
@Override
public boolean nullsAreSortedAtEnd()
throws SQLException
{
// TODO: determine null sort order
throw new NotImplementedException("DatabaseMetaData", "nullsAreSortedAtEnd");
}
@Override
public String getDatabaseProductName()
throws SQLException
{
return "Presto";
}
@Override
public String getDatabaseProductVersion()
throws SQLException
{
// TODO: get version from server
return "UNKNOWN";
}
@Override
public String getDriverName()
throws SQLException
{
return PrestoDriver.DRIVER_NAME;
}
@Override
public String getDriverVersion()
throws SQLException
{
return PrestoDriver.DRIVER_VERSION;
}
@Override
public int getDriverMajorVersion()
{
return PrestoDriver.VERSION_MAJOR;
}
@Override
public int getDriverMinorVersion()
{
return PrestoDriver.VERSION_MINOR;
}
@Override
public boolean usesLocalFiles()
throws SQLException
{
return false;
}
@Override
public boolean usesLocalFilePerTable()
throws SQLException
{
return false;
}
@Override
public boolean supportsMixedCaseIdentifiers()
throws SQLException
{
return false;
}
@Override
public boolean storesUpperCaseIdentifiers()
throws SQLException
{
return false;
}
@Override
public boolean storesLowerCaseIdentifiers()
throws SQLException
{
return true;
}
@Override
public boolean storesMixedCaseIdentifiers()
throws SQLException
{
return false;
}
@Override
public boolean supportsMixedCaseQuotedIdentifiers()
throws SQLException
{
return true;
}
@Override
public boolean storesUpperCaseQuotedIdentifiers()
throws SQLException
{
return false;
}
@Override
public boolean storesLowerCaseQuotedIdentifiers()
throws SQLException
{
return false;
}
@Override
public boolean storesMixedCaseQuotedIdentifiers()
throws SQLException
{
return true;
}
@Override
public String getIdentifierQuoteString()
throws SQLException
{
return "\"";
}
@Override
public String getSQLKeywords()
throws SQLException
{
return "LIMIT";
}
@Override
public String getNumericFunctions()
throws SQLException
{
return "";
}
@Override
public String getStringFunctions()
throws SQLException
{
return "";
}
@Override
public String getSystemFunctions()
throws SQLException
{
return "";
}
@Override
public String getTimeDateFunctions()
throws SQLException
{
return "";
}
@Override
public String getSearchStringEscape()
throws SQLException
{
return "\\";
}
@Override
public String getExtraNameCharacters()
throws SQLException
{
return "";
}
@Override
public boolean supportsAlterTableWithAddColumn()
throws SQLException
{
return false;
}
@Override
public boolean supportsAlterTableWithDropColumn()
throws SQLException
{
return false;
}
@Override
public boolean supportsColumnAliasing()
throws SQLException
{
return true;
}
@Override
public boolean nullPlusNonNullIsNull()
throws SQLException
{
return true;
}
@Override
public boolean supportsConvert()
throws SQLException
{
// TODO: support convert
return false;
}
@Override
public boolean supportsConvert(int fromType, int toType)
throws SQLException
{
// TODO: support convert
return false;
}
@Override
public boolean supportsTableCorrelationNames()
throws SQLException
{
return true;
}
@Override
public boolean supportsDifferentTableCorrelationNames()
throws SQLException
{
// TODO: verify this
return false;
}
@Override
public boolean supportsExpressionsInOrderBy()
throws SQLException
{
return true;
}
@Override
public boolean supportsOrderByUnrelated()
throws SQLException
{
// TODO: verify this
return true;
}
@Override
public boolean supportsGroupBy()
throws SQLException
{
return true;
}
@Override
public boolean supportsGroupByUnrelated()
throws SQLException
{
return true;
}
@Override
public boolean supportsGroupByBeyondSelect()
throws SQLException
{
return true;
}
@Override
public boolean supportsLikeEscapeClause()
throws SQLException
{
return true;
}
@Override
public boolean supportsMultipleResultSets()
throws SQLException
{
return false;
}
@Override
public boolean supportsMultipleTransactions()
throws SQLException
{
return true;
}
@Override
public boolean supportsNonNullableColumns()
throws SQLException
{
return true;
}
@Override
public boolean supportsMinimumSQLGrammar()
throws SQLException
{
return true;
}
@Override
public boolean supportsCoreSQLGrammar()
throws SQLException
{
// TODO: support this
return false;
}
@Override
public boolean supportsExtendedSQLGrammar()
throws SQLException
{
// TODO: support this
return false;
}
@Override
public boolean supportsANSI92EntryLevelSQL()
throws SQLException
{
// TODO: verify this
return true;
}
@Override
public boolean supportsANSI92IntermediateSQL()
throws SQLException
{
// TODO: support this
return false;
}
@Override
public boolean supportsANSI92FullSQL()
throws SQLException
{
// TODO: support this
return false;
}
@Override
public boolean supportsIntegrityEnhancementFacility()
throws SQLException
{
return false;
}
@Override
public boolean supportsOuterJoins()
throws SQLException
{
return true;
}
@Override
public boolean supportsFullOuterJoins()
throws SQLException
{
// TODO: support full outer joins
return false;
}
@Override
public boolean supportsLimitedOuterJoins()
throws SQLException
{
return true;
}
@Override
public String getSchemaTerm()
throws SQLException
{
return "schema";
}
@Override
public String getProcedureTerm()
throws SQLException
{
return "procedure";
}
@Override
public String getCatalogTerm()
throws SQLException
{
return "catalog";
}
@Override
public boolean isCatalogAtStart()
throws SQLException
{
return true;
}
@Override
public String getCatalogSeparator()
throws SQLException
{
return ".";
}
@Override
public boolean supportsSchemasInDataManipulation()
throws SQLException
{
return true;
}
@Override
public boolean supportsSchemasInProcedureCalls()
throws SQLException
{
return true;
}
@Override
public boolean supportsSchemasInTableDefinitions()
throws SQLException
{
return true;
}
@Override
public boolean supportsSchemasInIndexDefinitions()
throws SQLException
{
return true;
}
@Override
public boolean supportsSchemasInPrivilegeDefinitions()
throws SQLException
{
return true;
}
@Override
public boolean supportsCatalogsInDataManipulation()
throws SQLException
{
return true;
}
@Override
public boolean supportsCatalogsInProcedureCalls()
throws SQLException
{
return true;
}
@Override
public boolean supportsCatalogsInTableDefinitions()
throws SQLException
{
return true;
}
@Override
public boolean supportsCatalogsInIndexDefinitions()
throws SQLException
{
return true;
}
@Override
public boolean supportsCatalogsInPrivilegeDefinitions()
throws SQLException
{
return true;
}
@Override
public boolean supportsPositionedDelete()
throws SQLException
{
return false;
}
@Override
public boolean supportsPositionedUpdate()
throws SQLException
{
return false;
}
@Override
public boolean supportsSelectForUpdate()
throws SQLException
{
return false;
}
@Override
public boolean supportsStoredProcedures()
throws SQLException
{
// TODO: support stored procedures
return false;
}
@Override
public boolean supportsSubqueriesInComparisons()
throws SQLException
{
// TODO: support subqueries in comparisons
return false;
}
@Override
public boolean supportsSubqueriesInExists()
throws SQLException
{
// TODO: support EXISTS
return false;
}
@Override
public boolean supportsSubqueriesInIns()
throws SQLException
{
// TODO: support subqueries in IN clauses
return false;
}
@Override
public boolean supportsSubqueriesInQuantifieds()
throws SQLException
{
// TODO: support subqueries in ANY/SOME/ALL predicates
return false;
}
@Override
public boolean supportsCorrelatedSubqueries()
throws SQLException
{
// TODO: support correlated subqueries
return false;
}
@Override
public boolean supportsUnion()
throws SQLException
{
// TODO: support UNION
return false;
}
@Override
public boolean supportsUnionAll()
throws SQLException
{
// TODO: support UNION ALL
return false;
}
@Override
public boolean supportsOpenCursorsAcrossCommit()
throws SQLException
{
return true;
}
@Override
public boolean supportsOpenCursorsAcrossRollback()
throws SQLException
{
return false;
}
@Override
public boolean supportsOpenStatementsAcrossCommit()
throws SQLException
{
return true;
}
@Override
public boolean supportsOpenStatementsAcrossRollback()
throws SQLException
{
return true;
}
@Override
public int getMaxBinaryLiteralLength()
throws SQLException
{
return 0;
}
@Override
public int getMaxCharLiteralLength()
throws SQLException
{
return 0;
}
@Override
public int getMaxColumnNameLength()
throws SQLException
{
// TODO: define max identifier length
return 0;
}
@Override
public int getMaxColumnsInGroupBy()
throws SQLException
{
return 0;
}
@Override
public int getMaxColumnsInIndex()
throws SQLException
{
return 0;
}
@Override
public int getMaxColumnsInOrderBy()
throws SQLException
{
return 0;
}
@Override
public int getMaxColumnsInSelect()
throws SQLException
{
return 0;
}
@Override
public int getMaxColumnsInTable()
throws SQLException
{
return 0;
}
@Override
public int getMaxConnections()
throws SQLException
{
return 0;
}
@Override
public int getMaxCursorNameLength()
throws SQLException
{
return 0;
}
@Override
public int getMaxIndexLength()
throws SQLException
{
return 0;
}
@Override
public int getMaxSchemaNameLength()
throws SQLException
{
// TODO: define max identifier length
return 0;
}
@Override
public int getMaxProcedureNameLength()
throws SQLException
{
// TODO: define max identifier length
return 0;
}
@Override
public int getMaxCatalogNameLength()
throws SQLException
{
// TODO: define max identifier length
return 0;
}
@Override
public int getMaxRowSize()
throws SQLException
{
return 0;
}
@Override
public boolean doesMaxRowSizeIncludeBlobs()
throws SQLException
{
return true;
}
@Override
public int getMaxStatementLength()
throws SQLException
{
return 0;
}
@Override
public int getMaxStatements()
throws SQLException
{
return 0;
}
@Override
public int getMaxTableNameLength()
throws SQLException
{
// TODO: define max identifier length
return 0;
}
@Override
public int getMaxTablesInSelect()
throws SQLException
{
return 0;
}
@Override
public int getMaxUserNameLength()
throws SQLException
{
// TODO: define max identifier length
return 0;
}
@Override
public int getDefaultTransactionIsolation()
throws SQLException
{
// TODO: support transactions
return Connection.TRANSACTION_NONE;
}
@Override
public boolean supportsTransactions()
throws SQLException
{
// TODO: support transactions
return false;
}
@Override
public boolean supportsTransactionIsolationLevel(int level)
throws SQLException
{
return level == Connection.TRANSACTION_NONE;
}
@Override
public boolean supportsDataDefinitionAndDataManipulationTransactions()
throws SQLException
{
return true;
}
@Override
public boolean supportsDataManipulationTransactionsOnly()
throws SQLException
{
return false;
}
@Override
public boolean dataDefinitionCausesTransactionCommit()
throws SQLException
{
return false;
}
@Override
public boolean dataDefinitionIgnoredInTransactions()
throws SQLException
{
return false;
}
@Override
public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern)
throws SQLException
{
// TODO: support stored procedures
throw new SQLFeatureNotSupportedException("stored procedures not supported");
}
@Override
public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern)
throws SQLException
{
// TODO: support stored procedures
throw new SQLFeatureNotSupportedException("stored procedures not supported");
}
@Override
public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)
throws SQLException
{
StringBuilder query = new StringBuilder(1024);
query.append("SELECT");
query.append(" table_catalog AS TABLE_CAT");
query.append(", table_schema AS TABLE_SCHEM");
query.append(", table_name AS TABLE_NAME");
query.append(", table_type AS TABLE_TYPE");
query.append(", '' AS REMARKS");
query.append(", '' AS TYPE_CAT");
query.append(", '' AS TYPE_SCHEM");
query.append(", '' AS TYPE_NAME");
query.append(", '' AS SELF_REFERENCING_COL_NAME");
query.append(", '' AS REF_GENERATION");
query.append(" FROM information_schema.tables ");
List<String> filters = new ArrayList<>(4);
if (catalog != null) {
if (catalog.isEmpty()) {
filters.add("table_catalog IS NULL");
}
else {
filters.add(stringColumnEquals("table_catalog", catalog));
}
}
if (schemaPattern != null) {
if (schemaPattern.isEmpty()) {
filters.add("table_schema IS NULL");
}
else {
filters.add(stringColumnLike("table_schema", schemaPattern));
}
}
if (tableNamePattern != null) {
filters.add(stringColumnLike("table_name", tableNamePattern));
}
if (types != null && types.length > 0) {
StringBuilder filter = new StringBuilder();
filter.append("table_type in (");
for (int i = 0; i < types.length; i++) {
String type = types[i];
if (i > 0) {
filter.append(" ,");
}
quoteStringLiteral(filter, type);
}
filter.append(")");
filters.add(filter.toString());
}
if (!filters.isEmpty()) {
query.append(" WHERE ");
Joiner.on(" AND ").appendTo(query, filters);
}
query.append(" ORDER BY TABLE_TYPE, TABLE_CAT, TABLE_SCHEM, TABLE_NAME");
return select(query.toString());
}
@Override
public ResultSet getSchemas()
throws SQLException
{
return select("" +
"SELECT schema_name AS TABLE_SCHEM, catalog_name TABLE_CATALOG " +
"FROM information_schema.schemata " +
"ORDER BY TABLE_CATALOG, TABLE_SCHEM");
}
@Override
public ResultSet getCatalogs()
throws SQLException
{
return select("" +
"SELECT DISTINCT catalog_name AS TABLE_CAT " +
"FROM information_schema.schemata " +
"ORDER BY TABLE_CAT");
}
@Override
public ResultSet getTableTypes()
throws SQLException
{
return select("" +
"SELECT DISTINCT table_type AS TABLE_TYPE " +
"FROM information_schema.tables " +
"ORDER BY TABLE_TYPE");
}
@Override
public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern)
throws SQLException
{
StringBuilder query = new StringBuilder("" +
"SELECT " +
" table_catalog TABLE_CAT " +
", table_schema TABLE_SCHEM " +
", table_name TABLE_NAME " +
", column_name COLUMN_NAME " +
", CASE data_type " +
" WHEN 'bigint' THEN " + Types.BIGINT + " " +
" WHEN 'double' THEN " + Types.DOUBLE + " " +
" WHEN 'varchar' THEN " + Types.LONGNVARCHAR + " " +
" WHEN 'boolean' THEN " + Types.BOOLEAN + " " +
" ELSE " + Types.OTHER + " " +
" END DATA_TYPE " +
", data_type TYPE_NAME " +
", 0 COLUMN_SIZE " +
", 0 BUFFER_LENGTH " +
", CASE data_type " +
" WHEN 'bigint' THEN 0 " +
" END DECIMAL_DIGITS " +
", CASE data_type " +
" WHEN 'bigint' THEN 10 " +
" WHEN 'double' THEN 10 " +
" ELSE 0 " +
" END AS NUM_PREC_RADIX " +
", CASE is_nullable " +
" WHEN 'NO' THEN " + columnNoNulls + " " +
" WHEN 'YES' THEN 1" + columnNullable + " " +
" ELSE 2" + columnNullableUnknown + " " +
" END NULLABLE " +
", CAST(NULL AS varchar) REMARKS " +
", column_default AS COLUMN_DEF " +
", CAST(NULL AS bigint) AS SQL_DATA_TYPE " +
", CAST(NULL AS bigint) AS SQL_DATETIME_SUB " +
", 0 AS CHAR_OCTET_LENGTH " +
", ordinal_position ORDINAL_POSITION " +
", is_nullable IS_NULLABLE " +
", CAST(NULL AS varchar) SCOPE_CATALOG " +
", CAST(NULL AS varchar) SCOPE_SCHEMA " +
", CAST(NULL AS varchar) SCOPE_TABLE " +
", CAST(NULL AS bigint) SOURCE_DATA_TYPE " +
", '' IS_AUTOINCREMENT " +
", '' IS_GENERATEDCOLUMN " +
"FROM information_schema.columns ");
List<String> filters = new ArrayList<>(4);
if (catalog != null) {
if (catalog.isEmpty()) {
filters.add("table_catalog IS NULL");
}
else {
filters.add(stringColumnEquals("table_catalog", catalog));
}
}
if (schemaPattern != null) {
if (schemaPattern.isEmpty()) {
filters.add("table_schema IS NULL");
}
else {
filters.add(stringColumnLike("table_schema", schemaPattern));
}
}
if (tableNamePattern != null) {
filters.add(stringColumnLike("table_name", tableNamePattern));
}
if (columnNamePattern != null) {
filters.add(stringColumnLike("column_name", columnNamePattern));
}
if (!filters.isEmpty()) {
query.append(" WHERE ");
Joiner.on(" AND ").appendTo(query, filters);
}
query.append(" ORDER BY table_cat, table_schem, table_name, ordinal_position");
return select(query.toString());
}
@Override
public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern)
throws SQLException
{
throw new SQLFeatureNotSupportedException("privileges not supported");
}
@Override
public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern)
throws SQLException
{
throw new SQLFeatureNotSupportedException("privileges not supported");
}
@Override
public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable)
throws SQLException
{
throw new SQLFeatureNotSupportedException("row identifiers not supported");
}
@Override
public ResultSet getVersionColumns(String catalog, String schema, String table)
throws SQLException
{
throw new SQLFeatureNotSupportedException("version columns not supported");
}
@Override
public ResultSet getPrimaryKeys(String catalog, String schema, String table)
throws SQLException
{
throw new SQLFeatureNotSupportedException("primary keys not supported");
}
@Override
public ResultSet getImportedKeys(String catalog, String schema, String table)
throws SQLException
{
throw new SQLFeatureNotSupportedException("imported keys not supported");
}
@Override
public ResultSet getExportedKeys(String catalog, String schema, String table)
throws SQLException
{
throw new SQLFeatureNotSupportedException("exported keys not supported");
}
@Override
public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable)
throws SQLException
{
throw new SQLFeatureNotSupportedException("cross reference not supported");
}
@Override
public ResultSet getTypeInfo()
throws SQLException
{
// TODO: implement this
throw new NotImplementedException("DatabaseMetaData", "getTypeInfo");
}
@Override
public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate)
throws SQLException
{
throw new SQLFeatureNotSupportedException("indexes not supported");
}
@Override
public boolean supportsResultSetType(int type)
throws SQLException
{
return type == ResultSet.TYPE_FORWARD_ONLY;
}
@Override
public boolean supportsResultSetConcurrency(int type, int concurrency)
throws SQLException
{
return (type == ResultSet.TYPE_FORWARD_ONLY) &&
(concurrency == ResultSet.CONCUR_READ_ONLY);
}
@Override
public boolean ownUpdatesAreVisible(int type)
throws SQLException
{
return false;
}
@Override
public boolean ownDeletesAreVisible(int type)
throws SQLException
{
return false;
}
@Override
public boolean ownInsertsAreVisible(int type)
throws SQLException
{
return false;
}
@Override
public boolean othersUpdatesAreVisible(int type)
throws SQLException
{
return false;
}
@Override
public boolean othersDeletesAreVisible(int type)
throws SQLException
{
return false;
}
@Override
public boolean othersInsertsAreVisible(int type)
throws SQLException
{
return false;
}
@Override
public boolean updatesAreDetected(int type)
throws SQLException
{
return false;
}
@Override
public boolean deletesAreDetected(int type)
throws SQLException
{
return false;
}
@Override
public boolean insertsAreDetected(int type)
throws SQLException
{
return false;
}
@Override
public boolean supportsBatchUpdates()
throws SQLException
{
// TODO: support batch updates
return false;
}
@Override
public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types)
throws SQLException
{
throw new SQLFeatureNotSupportedException("user-defined types not supported");
}
@Override
public Connection getConnection()
throws SQLException
{
return connection;
}
@Override
public boolean supportsSavepoints()
throws SQLException
{
return false;
}
@Override
public boolean supportsNamedParameters()
throws SQLException
{
return true;
}
@Override
public boolean supportsMultipleOpenResults()
throws SQLException
{
return false;
}
@Override
public boolean supportsGetGeneratedKeys()
throws SQLException
{
return false;
}
@Override
public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern)
throws SQLException
{
throw new SQLFeatureNotSupportedException("type hierarchies not supported");
}
@Override
public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern)
throws SQLException
{
throw new SQLFeatureNotSupportedException("type hierarchies not supported");
}
@Override
public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern)
throws SQLException
{
throw new SQLFeatureNotSupportedException("user-defined types not supported");
}
@Override
public boolean supportsResultSetHoldability(int holdability)
throws SQLException
{
return holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT;
}
@Override
public int getResultSetHoldability()
throws SQLException
{
return ResultSet.HOLD_CURSORS_OVER_COMMIT;
}
@Override
public int getDatabaseMajorVersion()
throws SQLException
{
// TODO: get version from server
return PrestoDriver.VERSION_MAJOR;
}
@Override
public int getDatabaseMinorVersion()
throws SQLException
{
return PrestoDriver.VERSION_MINOR;
}
@Override
public int getJDBCMajorVersion()
throws SQLException
{
return PrestoDriver.JDBC_VERSION_MAJOR;
}
@Override
public int getJDBCMinorVersion()
throws SQLException
{
return PrestoDriver.JDBC_VERSION_MINOR;
}
@Override
public int getSQLStateType()
throws SQLException
{
return DatabaseMetaData.sqlStateSQL;
}
@Override
public boolean locatorsUpdateCopy()
throws SQLException
{
return true;
}
@Override
public boolean supportsStatementPooling()
throws SQLException
{
return false;
}
@Override
public RowIdLifetime getRowIdLifetime()
throws SQLException
{
return RowIdLifetime.ROWID_UNSUPPORTED;
}
@Override
public ResultSet getSchemas(String catalog, String schemaPattern)
throws SQLException
{
// The schema columns are:
// TABLE_SCHEM String => schema name
// TABLE_CATALOG String => catalog name (may be null)
StringBuilder query = new StringBuilder(512);
query.append("SELECT DISTINCT schema_name TABLE_SCHEM, catalog_name TABLE_CATALOG ");
query.append(" FROM information_schema.schemata");
List<String> filters = new ArrayList<>(4);
if (catalog != null) {
if (catalog.isEmpty()) {
filters.add("catalog_name IS NULL");
}
else {
filters.add(stringColumnEquals("catalog_name", catalog));
}
}
if (schemaPattern != null) {
filters.add(stringColumnLike("schema_name", schemaPattern));
}
if (!filters.isEmpty()) {
query.append(" WHERE ");
Joiner.on(" AND ").appendTo(query, filters);
}
query.append(" ORDER BY TABLE_CATALOG, TABLE_SCHEM");
return select(query.toString());
}
@Override
public boolean supportsStoredFunctionsUsingCallSyntax()
throws SQLException
{
return false;
}
@Override
public boolean autoCommitFailureClosesAllResultSets()
throws SQLException
{
return false;
}
@Override
public ResultSet getClientInfoProperties()
throws SQLException
{
// TODO: implement this
throw new NotImplementedException("DatabaseMetaData", "getClientInfoProperties");
}
@Override
public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern)
throws SQLException
{
// TODO: implement this
throw new NotImplementedException("DatabaseMetaData", "getFunctions");
}
@Override
public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern)
throws SQLException
{
// TODO: implement this
throw new NotImplementedException("DatabaseMetaData", "getFunctionColumns");
}
@Override
public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern)
throws SQLException
{
// TODO: implement this
throw new NotImplementedException("DatabaseMetaData", "getPseudoColumns");
}
@Override
public boolean generatedKeyAlwaysReturned()
throws SQLException
{
return false;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrap(Class<T> iface)
throws SQLException
{
if (isWrapperFor(iface)) {
return (T) this;
}
throw new SQLException("No wrapper for " + iface);
}
@Override
public boolean isWrapperFor(Class<?> iface)
throws SQLException
{
return iface.isInstance(this);
}
private ResultSet select(String sql)
throws SQLException
{
try (Statement statement = getConnection().createStatement()) {
return statement.executeQuery(sql);
}
}
private static String stringColumnEquals(String columnName, String value)
{
StringBuilder filter = new StringBuilder();
filter.append(columnName).append(" = ");
quoteStringLiteral(filter, value);
return filter.toString();
}
private static String stringColumnLike(String columnName, String pattern)
{
StringBuilder filter = new StringBuilder();
filter.append(columnName).append(" LIKE ");
quoteStringLiteral(filter, pattern);
return filter.toString();
}
private static void quoteStringLiteral(StringBuilder out, String value)
{
out.append('\'');
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
out.append(c);
if (c == '\'') {
out.append('\'');
}
}
out.append('\'');
}
}
| |
/*
Copyright 2012 Radu Cernuta
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package serene.validation.handlers.error;
public class SynchronizedErrorHandlerPool extends ErrorHandlerPool{
private static volatile SynchronizedErrorHandlerPool instance;
int vehPoolFree;
int vehPoolMaxSize;
ValidatorErrorHandlerPool[] vehPools;
int validationErrorHAverageUse;
int validationErrorHMaxSize;
int validationErrorHFree;
ValidationErrorHandler[] validationErrorH;
int conflictErrorHAverageUse;
int conflictErrorHMaxSize;
int conflictErrorHFree;
ExternalConflictErrorHandler[] conflictErrorH;
int commonErrorHAverageUse;
int commonErrorHMaxSize;
int commonErrorHFree;
CommonErrorHandler[] commonErrorH;
int defaultErrorHAverageUse;
int defaultErrorHMaxSize;
int defaultErrorHFree;
DefaultErrorHandler[] defaultErrorH;
int startErrorHAverageUse;
int startErrorHMaxSize;
int startErrorHFree;
StartErrorHandler[] startErrorH;
SynchronizedErrorHandlerPool(){
super();
vehPoolFree = 0;
vehPools = new ValidatorErrorHandlerPool[10];
validationErrorHAverageUse = 0;
validationErrorHFree = 0;
validationErrorH = new ValidationErrorHandler[10];
conflictErrorHAverageUse = 0;
conflictErrorHFree = 0;
conflictErrorH = new ExternalConflictErrorHandler[10];
commonErrorHAverageUse = 0;
commonErrorHFree = 0;
commonErrorH = new CommonErrorHandler[10];
defaultErrorHAverageUse = 0;
defaultErrorHFree = 0;
defaultErrorH = new DefaultErrorHandler[10];
startErrorHAverageUse = 0;
startErrorHFree = 0;
startErrorH = new StartErrorHandler[10];
validationErrorHMaxSize = 40;
conflictErrorHMaxSize = 20;
commonErrorHMaxSize = 20;
defaultErrorHMaxSize = 20;
startErrorHMaxSize = 10;
}
public static SynchronizedErrorHandlerPool getInstance( ){
if(instance == null){
synchronized(ErrorHandlerPool.class){
if(instance == null){
instance = new SynchronizedErrorHandlerPool();
}
}
}
return instance;
}
public synchronized ValidatorErrorHandlerPool getValidatorErrorHandlerPool(){
if(vehPoolFree == 0){
ValidatorErrorHandlerPool vehp = new ValidatorErrorHandlerPool(this);
return vehp;
}else{
ValidatorErrorHandlerPool vehp = vehPools[--vehPoolFree];
return vehp;
}
}
public synchronized void recycle(ValidatorErrorHandlerPool vehp){
if(vehPoolFree == vehPoolMaxSize)return;
if(vehPoolFree == vehPools.length){
ValidatorErrorHandlerPool[] increased = new ValidatorErrorHandlerPool[10+vehPools.length];
System.arraycopy(vehPools, 0, increased, 0, vehPoolFree);
vehPools = increased;
}
vehPools[vehPoolFree++] = vehp;
}
synchronized void fill(ValidatorErrorHandlerPool pool,
ValidationErrorHandler[] validationErrorHToFill,
ExternalConflictErrorHandler[] conflictErrorHToFill,
CommonErrorHandler[] commonErrorHToFill,
DefaultErrorHandler[] defaultErrorHToFill,
StartErrorHandler[] startErrorHToFill){
int validationErrorHFillCount;
if(validationErrorHToFill== null || validationErrorHToFill.length < validationErrorHAverageUse){
validationErrorHToFill = new ValidationErrorHandler[validationErrorHAverageUse];
pool.validationErrorH = validationErrorHToFill;
}
if(validationErrorHFree > validationErrorHAverageUse){
validationErrorHFillCount = validationErrorHAverageUse;
validationErrorHFree = validationErrorHFree - validationErrorHAverageUse;
}else{
validationErrorHFillCount = validationErrorHFree;
validationErrorHFree = 0;
}
System.arraycopy(validationErrorH, validationErrorHFree,
validationErrorHToFill, 0, validationErrorHFillCount);
int conflictErrorHFillCount;
if(conflictErrorHToFill == null || conflictErrorHToFill.length < conflictErrorHAverageUse){
conflictErrorHToFill = new ExternalConflictErrorHandler[conflictErrorHAverageUse];
pool.conflictErrorH = conflictErrorHToFill;
}
if(conflictErrorHFree > conflictErrorHAverageUse){
conflictErrorHFillCount = conflictErrorHAverageUse;
conflictErrorHFree = conflictErrorHFree - conflictErrorHAverageUse;
}else{
conflictErrorHFillCount = conflictErrorHFree;
conflictErrorHFree = 0;
}
System.arraycopy(conflictErrorH, conflictErrorHFree,
conflictErrorHToFill, 0, conflictErrorHFillCount);
int commonErrorHFillCount;
if(commonErrorHToFill == null || commonErrorHToFill.length < commonErrorHAverageUse){
commonErrorHToFill = new CommonErrorHandler[commonErrorHAverageUse];
pool.commonErrorH = commonErrorHToFill;
}
if(commonErrorHFree > commonErrorHAverageUse){
commonErrorHFillCount = commonErrorHAverageUse;
commonErrorHFree = commonErrorHFree - commonErrorHAverageUse;
}else{
commonErrorHFillCount = commonErrorHFree;
commonErrorHFree = 0;
}
System.arraycopy(commonErrorH, commonErrorHFree,
commonErrorHToFill, 0, commonErrorHFillCount);
int defaultErrorHFillCount;
if(defaultErrorHToFill == null || defaultErrorHToFill.length < defaultErrorHAverageUse){
defaultErrorHToFill = new DefaultErrorHandler[defaultErrorHAverageUse];
pool.defaultErrorH = defaultErrorHToFill;
}
if(defaultErrorHFree > defaultErrorHAverageUse){
defaultErrorHFillCount = defaultErrorHAverageUse;
defaultErrorHFree = defaultErrorHFree - defaultErrorHAverageUse;
}else{
defaultErrorHFillCount = defaultErrorHFree;
defaultErrorHFree = 0;
}
System.arraycopy(defaultErrorH, defaultErrorHFree,
defaultErrorHToFill, 0, defaultErrorHFillCount);
int startErrorHFillCount;
if(startErrorHToFill == null || startErrorHToFill.length < startErrorHAverageUse){
startErrorHToFill = new StartErrorHandler[startErrorHAverageUse];
pool.startErrorH = startErrorHToFill;
}
if(startErrorHFree > startErrorHAverageUse){
startErrorHFillCount = startErrorHAverageUse;
startErrorHFree = startErrorHFree - startErrorHAverageUse;
}else{
startErrorHFillCount = startErrorHFree;
startErrorHFree = 0;
}
System.arraycopy(startErrorH, startErrorHFree,
startErrorHToFill, 0, startErrorHFillCount);
pool.initFilled(validationErrorHFillCount,
conflictErrorHFillCount,
commonErrorHFillCount,
defaultErrorHFillCount,
startErrorHFillCount);
}
synchronized void recycle(int validationErrorHRecycledCount,
int validationErrorHEffectivellyUsed,
ValidationErrorHandler[] validationErrorHRecycled,
int conflictErrorHRecycledCount,
int conflictErrorHEffectivellyUsed,
ExternalConflictErrorHandler[] conflictErrorHRecycled,
int commonErrorHRecycledCount,
int commonErrorHEffectivellyUsed,
CommonErrorHandler[] commonErrorHRecycled,
int defaultErrorHRecycledCount,
int defaultErrorHEffectivellyUsed,
DefaultErrorHandler[] defaultErrorHRecycled,
int startErrorHRecycledCount,
int startErrorHEffectivellyUsed,
StartErrorHandler[] startErrorHRecycled){
int neededLength = validationErrorHFree + validationErrorHRecycledCount;
if(neededLength > validationErrorH.length){
if(neededLength > validationErrorHMaxSize){
neededLength = validationErrorHMaxSize;
ValidationErrorHandler[] increased = new ValidationErrorHandler[neededLength];
System.arraycopy(validationErrorH, 0, increased, 0, validationErrorH.length);
validationErrorH = increased;
System.arraycopy(validationErrorHRecycled, 0, validationErrorH, validationErrorHFree, validationErrorHMaxSize - validationErrorHFree);
validationErrorHFree = validationErrorHMaxSize;
}else{
ValidationErrorHandler[] increased = new ValidationErrorHandler[neededLength];
System.arraycopy(validationErrorH, 0, increased, 0, validationErrorH.length);
validationErrorH = increased;
System.arraycopy(validationErrorHRecycled, 0, validationErrorH, validationErrorHFree, validationErrorHRecycledCount);
validationErrorHFree += validationErrorHRecycledCount;
}
}else{
System.arraycopy(validationErrorHRecycled, 0, validationErrorH, validationErrorHFree, validationErrorHRecycledCount);
validationErrorHFree += validationErrorHRecycledCount;
}
if(validationErrorHAverageUse != 0)validationErrorHAverageUse = (validationErrorHAverageUse + validationErrorHEffectivellyUsed)/2;
else validationErrorHAverageUse = validationErrorHEffectivellyUsed;// this relies on the fact that the individual pools are smaller or equal to the common pool
for(int i = 0; i < validationErrorHRecycled.length; i++){
validationErrorHRecycled[i] = null;
}
neededLength = commonErrorHFree + commonErrorHRecycledCount;
if(neededLength > commonErrorH.length){
if(neededLength > commonErrorHMaxSize){
neededLength = commonErrorHMaxSize;
CommonErrorHandler[] increased = new CommonErrorHandler[neededLength];
System.arraycopy(commonErrorH, 0, increased, 0, commonErrorH.length);
commonErrorH = increased;
System.arraycopy(commonErrorHRecycled, 0, commonErrorH, commonErrorHFree, commonErrorHMaxSize - commonErrorHFree);
commonErrorHFree = commonErrorHMaxSize;
}else{
CommonErrorHandler[] increased = new CommonErrorHandler[neededLength];
System.arraycopy(commonErrorH, 0, increased, 0, commonErrorH.length);
commonErrorH = increased;
System.arraycopy(commonErrorHRecycled, 0, commonErrorH, commonErrorHFree, commonErrorHRecycledCount);
commonErrorHFree += commonErrorHRecycledCount;
}
}else{
System.arraycopy(commonErrorHRecycled, 0, commonErrorH, commonErrorHFree, commonErrorHRecycledCount);
commonErrorHFree += commonErrorHRecycledCount;
}
if(commonErrorHAverageUse != 0)commonErrorHAverageUse = (commonErrorHAverageUse + commonErrorHEffectivellyUsed)/2;
else commonErrorHAverageUse = commonErrorHEffectivellyUsed;// this relies on the fact that the individual pools are smaller or equal to the common pool
for(int i = 0; i < commonErrorHRecycled.length; i++){
commonErrorHRecycled[i] = null;
}
neededLength = conflictErrorHFree + conflictErrorHRecycledCount;
if(neededLength > conflictErrorH.length){
if(neededLength > conflictErrorHMaxSize){
neededLength = conflictErrorHMaxSize;
ExternalConflictErrorHandler[] increased = new ExternalConflictErrorHandler[neededLength];
System.arraycopy(conflictErrorH, 0, increased, 0, conflictErrorH.length);
conflictErrorH = increased;
System.arraycopy(conflictErrorHRecycled, 0, conflictErrorH, conflictErrorHFree, conflictErrorHMaxSize - conflictErrorHFree);
conflictErrorHFree = conflictErrorHMaxSize;
}else{
ExternalConflictErrorHandler[] increased = new ExternalConflictErrorHandler[neededLength];
System.arraycopy(conflictErrorH, 0, increased, 0, conflictErrorH.length);
conflictErrorH = increased;
System.arraycopy(conflictErrorHRecycled, 0, conflictErrorH, conflictErrorHFree, conflictErrorHRecycledCount);
conflictErrorHFree += conflictErrorHRecycledCount;
}
}else{
System.arraycopy(conflictErrorHRecycled, 0, conflictErrorH, conflictErrorHFree, conflictErrorHRecycledCount);
conflictErrorHFree += conflictErrorHRecycledCount;
}
if(conflictErrorHAverageUse != 0)conflictErrorHAverageUse = (conflictErrorHAverageUse + conflictErrorHEffectivellyUsed)/2;
else conflictErrorHAverageUse = conflictErrorHEffectivellyUsed;// this relies on the fact that the individual pools are smaller or equal to the common pool
for(int i = 0; i < conflictErrorHRecycled.length; i++){
conflictErrorHRecycled[i] = null;
}
neededLength = defaultErrorHFree + defaultErrorHRecycledCount;
if(neededLength > defaultErrorH.length){
if(neededLength > defaultErrorHMaxSize){
neededLength = defaultErrorHMaxSize;
DefaultErrorHandler[] increased = new DefaultErrorHandler[neededLength];
System.arraycopy(defaultErrorH, 0, increased, 0, defaultErrorH.length);
defaultErrorH = increased;
System.arraycopy(defaultErrorHRecycled, 0, defaultErrorH, defaultErrorHFree, defaultErrorHMaxSize - defaultErrorHFree);
defaultErrorHFree = defaultErrorHMaxSize;
}else{
DefaultErrorHandler[] increased = new DefaultErrorHandler[neededLength];
System.arraycopy(defaultErrorH, 0, increased, 0, defaultErrorH.length);
defaultErrorH = increased;
System.arraycopy(defaultErrorHRecycled, 0, defaultErrorH, defaultErrorHFree, defaultErrorHRecycledCount);
defaultErrorHFree += defaultErrorHRecycledCount;
}
}else{
System.arraycopy(defaultErrorHRecycled, 0, defaultErrorH, defaultErrorHFree, defaultErrorHRecycledCount);
defaultErrorHFree += defaultErrorHRecycledCount;
}
if(defaultErrorHAverageUse != 0)defaultErrorHAverageUse = (defaultErrorHAverageUse + defaultErrorHEffectivellyUsed)/2;
else defaultErrorHAverageUse = defaultErrorHEffectivellyUsed;// this relies on the fact that the individual pools are smaller or equal to the common pool
for(int i = 0; i < defaultErrorHRecycled.length; i++){
defaultErrorHRecycled[i] = null;
}
neededLength = startErrorHFree + startErrorHRecycledCount;
if(neededLength > startErrorH.length){
if(neededLength > startErrorHMaxSize){
neededLength = startErrorHMaxSize;
StartErrorHandler[] increased = new StartErrorHandler[neededLength];
System.arraycopy(startErrorH, 0, increased, 0, startErrorH.length);
startErrorH = increased;
System.arraycopy(startErrorHRecycled, 0, startErrorH, startErrorHFree, startErrorHMaxSize - startErrorHFree);
startErrorHFree = startErrorHMaxSize;
}else{
StartErrorHandler[] increased = new StartErrorHandler[neededLength];
System.arraycopy(startErrorH, 0, increased, 0, startErrorH.length);
startErrorH = increased;
System.arraycopy(startErrorHRecycled, 0, startErrorH, startErrorHFree, startErrorHRecycledCount);
startErrorHFree += startErrorHRecycledCount;
}
}else{
System.arraycopy(startErrorHRecycled, 0, startErrorH, startErrorHFree, startErrorHRecycledCount);
startErrorHFree += startErrorHRecycledCount;
}
if(startErrorHAverageUse != 0)startErrorHAverageUse = (startErrorHAverageUse + startErrorHEffectivellyUsed)/2;
else startErrorHAverageUse = startErrorHEffectivellyUsed;// this relies on the fact that the individual pools are smaller or equal to the common pool
for(int i = 0; i < startErrorHRecycled.length; i++){
startErrorHRecycled[i] = null;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.analytics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Test;
public class NoFacetTest extends SolrAnalyticsTestCase {
@BeforeClass
public static void populate() throws Exception {
for (int j = 0; j < NUM_LOOPS; ++j) {
int i = j % INT;
long l = j % LONG;
float f = j % FLOAT;
double d = j % DOUBLE;
String dt = (1800 + j % DATE) + "-12-31T23:59:59Z";
String dtm = (1800 + j % DATE + 10) + "-12-31T23:59:59Z";
String s = "str" + (j % STRING);
List<String> fields = new ArrayList<>();
fields.add("id");
fields.add("1000" + j);
if (i != 0) {
fields.add("int_i");
fields.add("" + i);
fields.add("int_im");
fields.add("" + i);
fields.add("int_im");
fields.add("" + (i + 10));
}
if (l != 0l) {
fields.add("long_l");
fields.add("" + l);
fields.add("long_lm");
fields.add("" + l);
fields.add("long_lm");
fields.add("" + (l + 10));
}
if (f != 0.0f) {
fields.add("float_f");
fields.add("" + f);
fields.add("float_fm");
fields.add("" + f);
fields.add("float_fm");
fields.add("" + (f + 10));
}
if (d != 0.0d) {
fields.add("double_d");
fields.add("" + d);
fields.add("double_dm");
fields.add("" + d);
fields.add("double_dm");
fields.add("" + (d + 10));
}
if ((j % DATE) != 0) {
fields.add("date_dt");
fields.add(dt);
fields.add("date_dtm");
fields.add(dt);
fields.add("date_dtm");
fields.add(dtm);
}
if ((j % STRING) != 0) {
fields.add("string_s");
fields.add(s);
fields.add("string_sm");
fields.add(s);
fields.add("string_sm");
fields.add(s + "_second");
}
addDoc(fields);
}
commitDocs();
}
public static final int INT = 7;
public static final int LONG = 2;
public static final int FLOAT = 6;
public static final int DOUBLE = 5;
public static final int DATE = 3;
public static final int STRING = 4;
public static final int NUM_LOOPS = 20;
@Test
public void countTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("single", new ETP("count(long_l)", 10L));
expressions.put("multi", new ETP("count(string_sm)", 30L));
testExpressions(expressions);
}
@Test
public void docCountTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("single", new ETP("doc_count(date_dt)", 13L));
expressions.put("multi", new ETP("doc_count(float_fm)", 16L));
testExpressions(expressions);
}
@Test
public void missingTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("single", new ETP("missing(string_s)", 5L));
expressions.put("multi", new ETP("missing(date_dtm)", 7L));
testExpressions(expressions);
}
@Test
public void uniqueTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("int", new ETP("unique(int_i)", 6L));
expressions.put("longs", new ETP("unique(long_lm)", 2L));
expressions.put("float", new ETP("unique(float_f)", 5L));
expressions.put("doubles", new ETP("unique(double_dm)", 8L));
expressions.put("dates", new ETP("unique(date_dt)", 2L));
expressions.put("strings", new ETP("unique(string_sm)", 6L));
testExpressions(expressions);
}
@Test
public void minTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("int", new ETP("min(int_i)", 1));
expressions.put("longs", new ETP("min(long_lm)", 1L));
expressions.put("float", new ETP("min(float_f)", 1.0F));
expressions.put("doubles", new ETP("min(double_dm)", 1.0));
expressions.put("dates", new ETP("min(date_dt)", "1801-12-31T23:59:59Z"));
expressions.put("strings", new ETP("min(string_sm)", "str1"));
testExpressions(expressions);
}
@Test
public void maxTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("int", new ETP("max(int_i)", 6));
expressions.put("longs", new ETP("max(long_lm)", 11L));
expressions.put("float", new ETP("max(float_f)", 5.0F));
expressions.put("doubles", new ETP("max(double_dm)", 14.0));
expressions.put("dates", new ETP("max(date_dt)", "1802-12-31T23:59:59Z"));
expressions.put("strings", new ETP("max(string_sm)", "str3_second"));
testExpressions(expressions);
}
@Test
public void sumTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("single", new ETP("sum(int_i)", 57.0));
expressions.put("multi", new ETP("sum(long_lm)", 120.0));
testExpressions(expressions);
}
@Test
public void meanTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("single", new ETP("mean(int_i)", 3.3529411764));
expressions.put("multi", new ETP("mean(long_lm)", 6.0));
testExpressions(expressions);
}
@Test
public void weightedMeanTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("single", new ETP("wmean(int_i, long_l)", 3.33333333333));
expressions.put("multi", new ETP("wmean(double_d, float_f)", 2.470588235));
testExpressions(expressions);
}
@Test
public void sumOfSquaresTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("single", new ETP("sumofsquares(int_i)", 237.0));
expressions.put("multi", new ETP("sumofsquares(long_lm)", 1220.0));
testExpressions(expressions);
}
@Test
public void varianceTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("single", new ETP("variance(int_i)", 2.6989619377162));
expressions.put("multi", new ETP("variance(long_lm)", 25.0));
testExpressions(expressions);
}
@Test
public void standardDeviationTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("single", new ETP("stddev(int_i)", 1.6428517698551));
expressions.put("multi", new ETP("stddev(long_lm)", 5.0));
testExpressions(expressions);
}
@Test
public void medianTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("int", new ETP("median(int_i)", 3.0));
expressions.put("longs", new ETP("median(long_lm)", 6.0));
expressions.put("float", new ETP("median(float_f)", 3.0));
expressions.put("doubles", new ETP("median(double_dm)", 7.5));
expressions.put("dates", new ETP("median(date_dt)", "1801-12-31T23:59:59Z"));
testExpressions(expressions);
}
@Test
public void percentileTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("int", new ETP("percentile(20,int_i)", 2));
expressions.put("longs", new ETP("percentile(80,long_lm)", 11L));
expressions.put("float", new ETP("percentile(40,float_f)", 2.0F));
expressions.put("doubles", new ETP("percentile(50,double_dm)", 11.0));
expressions.put("dates", new ETP("percentile(0,date_dt)", "1801-12-31T23:59:59Z"));
expressions.put("strings", new ETP("percentile(99.99,string_sm)", "str3_second"));
testExpressions(expressions);
}
@Test
public void ordinalTest() throws Exception {
Map<String, ETP> expressions = new HashMap<>();
expressions.put("int", new ETP("ordinal(15,int_i)", 5));
expressions.put("longs", new ETP("ordinal(11,long_lm)", 11L));
expressions.put("float", new ETP("ordinal(-5,float_f)", 4.0F));
expressions.put("doubles", new ETP("ordinal(1,double_dm)", 1.0));
expressions.put("dates", new ETP("ordinal(-1,date_dt)", "1802-12-31T23:59:59Z"));
expressions.put("strings", new ETP("ordinal(6,string_sm)", "str1_second"));
testExpressions(expressions);
}
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.gradle.internal.info;
import org.apache.commons.io.IOUtils;
import org.elasticsearch.gradle.internal.BwcVersions;
import org.elasticsearch.gradle.OS;
import org.elasticsearch.gradle.internal.util.Util;
import org.gradle.api.GradleException;
import org.gradle.api.JavaVersion;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.provider.Provider;
import org.gradle.api.provider.ProviderFactory;
import org.gradle.internal.jvm.Jvm;
import org.gradle.internal.jvm.inspection.JvmInstallationMetadata;
import org.gradle.internal.jvm.inspection.JvmMetadataDetector;
import org.gradle.internal.jvm.inspection.JvmVendor;
import org.gradle.jvm.toolchain.internal.InstallationLocation;
import org.gradle.jvm.toolchain.internal.JavaInstallationRegistry;
import org.gradle.util.GradleVersion;
import javax.inject.Inject;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class GlobalBuildInfoPlugin implements Plugin<Project> {
private static final Logger LOGGER = Logging.getLogger(GlobalBuildInfoPlugin.class);
private static final String DEFAULT_VERSION_JAVA_FILE_PATH = "server/src/main/java/org/elasticsearch/Version.java";
private static Integer _defaultParallel = null;
private final JavaInstallationRegistry javaInstallationRegistry;
private final JvmMetadataDetector metadataDetector;
private final ProviderFactory providers;
@Inject
public GlobalBuildInfoPlugin(
JavaInstallationRegistry javaInstallationRegistry,
JvmMetadataDetector metadataDetector,
ProviderFactory providers
) {
this.javaInstallationRegistry = javaInstallationRegistry;
this.metadataDetector = metadataDetector;
this.providers = providers;
}
@Override
public void apply(Project project) {
if (project != project.getRootProject()) {
throw new IllegalStateException(this.getClass().getName() + " can only be applied to the root project.");
}
GradleVersion minimumGradleVersion = GradleVersion.version(Util.getResourceContents("/minimumGradleVersion"));
if (GradleVersion.current().compareTo(minimumGradleVersion) < 0) {
throw new GradleException("Gradle " + minimumGradleVersion.getVersion() + "+ is required");
}
JavaVersion minimumCompilerVersion = JavaVersion.toVersion(Util.getResourceContents("/minimumCompilerVersion"));
JavaVersion minimumRuntimeVersion = JavaVersion.toVersion(Util.getResourceContents("/minimumRuntimeVersion"));
File runtimeJavaHome = findRuntimeJavaHome();
File rootDir = project.getRootDir();
GitInfo gitInfo = gitInfo(rootDir);
BuildParams.init(params -> {
// Initialize global build parameters
boolean isInternal = GlobalBuildInfoPlugin.class.getResource("/buildSrc.marker") != null;
params.reset();
params.setRuntimeJavaHome(runtimeJavaHome);
params.setRuntimeJavaVersion(determineJavaVersion("runtime java.home", runtimeJavaHome, minimumRuntimeVersion));
params.setIsRuntimeJavaHomeSet(Jvm.current().getJavaHome().equals(runtimeJavaHome) == false);
JvmInstallationMetadata runtimeJdkMetaData = metadataDetector.getMetadata(getJavaInstallation(runtimeJavaHome).getLocation());
params.setRuntimeJavaDetails(formatJavaVendorDetails(runtimeJdkMetaData));
params.setJavaVersions(getAvailableJavaVersions());
params.setMinimumCompilerVersion(minimumCompilerVersion);
params.setMinimumRuntimeVersion(minimumRuntimeVersion);
params.setGradleJavaVersion(Jvm.current().getJavaVersion());
params.setGitRevision(gitInfo.getRevision());
params.setGitOrigin(gitInfo.getOrigin());
params.setBuildDate(ZonedDateTime.now(ZoneOffset.UTC));
params.setTestSeed(getTestSeed());
params.setIsCi(System.getenv("JENKINS_URL") != null);
params.setIsInternal(isInternal);
params.setDefaultParallel(findDefaultParallel(project));
params.setInFipsJvm(Util.getBooleanProperty("tests.fips.enabled", false));
params.setIsSnapshotBuild(Util.getBooleanProperty("build.snapshot", true));
if (isInternal) {
params.setBwcVersions(resolveBwcVersions(rootDir));
}
});
// When building Elasticsearch, enforce the minimum compiler version
BuildParams.withInternalBuild(() -> assertMinimumCompilerVersion(minimumCompilerVersion));
// Print global build info header just before task execution
project.getGradle().getTaskGraph().whenReady(graph -> logGlobalBuildInfo());
}
private String formatJavaVendorDetails(JvmInstallationMetadata runtimeJdkMetaData) {
JvmVendor vendor = runtimeJdkMetaData.getVendor();
return runtimeJdkMetaData.getVendor().getKnownVendor().name() + "/" + vendor.getRawVendor();
}
/* Introspect all versions of ES that may be tested against for backwards
* compatibility. It is *super* important that this logic is the same as the
* logic in VersionUtils.java. */
private static BwcVersions resolveBwcVersions(File root) {
File versionsFile = new File(root, DEFAULT_VERSION_JAVA_FILE_PATH);
try {
List<String> versionLines = IOUtils.readLines(new FileInputStream(versionsFile), "UTF-8");
return new BwcVersions(versionLines);
} catch (IOException e) {
throw new IllegalStateException("Unable to resolve to resolve bwc versions from versionsFile.", e);
}
}
private void logGlobalBuildInfo() {
final String osName = System.getProperty("os.name");
final String osVersion = System.getProperty("os.version");
final String osArch = System.getProperty("os.arch");
final Jvm gradleJvm = Jvm.current();
JvmInstallationMetadata gradleJvmMetadata = metadataDetector.getMetadata(gradleJvm.getJavaHome());
final String gradleJvmVendorDetails = gradleJvmMetadata.getVendor().getDisplayName();
LOGGER.quiet("=======================================");
LOGGER.quiet("Elasticsearch Build Hamster says Hello!");
LOGGER.quiet(" Gradle Version : " + GradleVersion.current().getVersion());
LOGGER.quiet(" OS Info : " + osName + " " + osVersion + " (" + osArch + ")");
if (BuildParams.getIsRuntimeJavaHomeSet()) {
final String runtimeJvmVendorDetails = metadataDetector.getMetadata(BuildParams.getRuntimeJavaHome())
.getVendor()
.getDisplayName();
LOGGER.quiet(" Runtime JDK Version : " + BuildParams.getRuntimeJavaVersion() + " (" + runtimeJvmVendorDetails + ")");
LOGGER.quiet(" Runtime java.home : " + BuildParams.getRuntimeJavaHome());
LOGGER.quiet(" Gradle JDK Version : " + gradleJvm.getJavaVersion() + " (" + gradleJvmVendorDetails + ")");
LOGGER.quiet(" Gradle java.home : " + gradleJvm.getJavaHome());
} else {
LOGGER.quiet(" JDK Version : " + gradleJvm.getJavaVersion() + " (" + gradleJvmVendorDetails + ")");
LOGGER.quiet(" JAVA_HOME : " + gradleJvm.getJavaHome());
}
LOGGER.quiet(" Random Testing Seed : " + BuildParams.getTestSeed());
LOGGER.quiet(" In FIPS 140 mode : " + BuildParams.isInFipsJvm());
LOGGER.quiet("=======================================");
}
private JavaVersion determineJavaVersion(String description, File javaHome, JavaVersion requiredVersion) {
InstallationLocation installation = getJavaInstallation(javaHome);
JavaVersion actualVersion = metadataDetector.getMetadata(installation.getLocation()).getLanguageVersion();
if (actualVersion.isCompatibleWith(requiredVersion) == false) {
throwInvalidJavaHomeException(
description,
javaHome,
Integer.parseInt(requiredVersion.getMajorVersion()),
Integer.parseInt(actualVersion.getMajorVersion())
);
}
return actualVersion;
}
private InstallationLocation getJavaInstallation(File javaHome) {
return getAvailableJavaInstallationLocationSteam().filter(installationLocation -> isSameFile(javaHome, installationLocation))
.findFirst()
.orElseThrow(() -> new GradleException("Could not locate available Java installation in Gradle registry at: " + javaHome));
}
private boolean isSameFile(File javaHome, InstallationLocation installationLocation) {
try {
return Files.isSameFile(installationLocation.getLocation().toPath(), javaHome.toPath());
} catch (IOException ioException) {
throw new UncheckedIOException(ioException);
}
}
/**
* We resolve all available java versions using auto detected by gradles tool chain
* To make transition more reliable we only take env var provided installations into account for now
*/
private List<JavaHome> getAvailableJavaVersions() {
return getAvailableJavaInstallationLocationSteam().map(installationLocation -> {
File installationDir = installationLocation.getLocation();
JvmInstallationMetadata metadata = metadataDetector.getMetadata(installationDir);
int actualVersion = Integer.parseInt(metadata.getLanguageVersion().getMajorVersion());
return JavaHome.of(actualVersion, providers.provider(() -> installationDir));
}).collect(Collectors.toList());
}
private Stream<InstallationLocation> getAvailableJavaInstallationLocationSteam() {
return Stream.concat(
javaInstallationRegistry.listInstallations().stream(),
Stream.of(new InstallationLocation(Jvm.current().getJavaHome(), "Current JVM"))
);
}
private static String getTestSeed() {
String testSeedProperty = System.getProperty("tests.seed");
final String testSeed;
if (testSeedProperty == null) {
long seed = new Random(System.currentTimeMillis()).nextLong();
testSeed = Long.toUnsignedString(seed, 16).toUpperCase(Locale.ROOT);
} else {
testSeed = testSeedProperty;
}
return testSeed;
}
private static void throwInvalidJavaHomeException(String description, File javaHome, int expectedVersion, int actualVersion) {
String message = String.format(
Locale.ROOT,
"The %s must be set to a JDK installation directory for Java %d but is [%s] corresponding to [%s]",
description,
expectedVersion,
javaHome,
actualVersion
);
throw new GradleException(message);
}
private static void assertMinimumCompilerVersion(JavaVersion minimumCompilerVersion) {
JavaVersion currentVersion = Jvm.current().getJavaVersion();
if (minimumCompilerVersion.compareTo(currentVersion) > 0) {
throw new GradleException(
"Project requires Java version of " + minimumCompilerVersion + " or newer but Gradle JAVA_HOME is " + currentVersion
);
}
}
private File findRuntimeJavaHome() {
String runtimeJavaProperty = System.getProperty("runtime.java");
if (runtimeJavaProperty != null) {
return new File(findJavaHome(runtimeJavaProperty));
}
return System.getenv("RUNTIME_JAVA_HOME") == null ? Jvm.current().getJavaHome() : new File(System.getenv("RUNTIME_JAVA_HOME"));
}
private String findJavaHome(String version) {
Provider<String> javaHomeNames = providers.gradleProperty("org.gradle.java.installations.fromEnv").forUseAtConfigurationTime();
String javaHomeEnvVar = getJavaHomeEnvVarName(version);
// Provide a useful error if we're looking for a Java home version that we haven't told Gradle about yet
Arrays.stream(javaHomeNames.get().split(","))
.filter(s -> s.equals(javaHomeEnvVar))
.findFirst()
.orElseThrow(
() -> new GradleException(
"Environment variable '"
+ javaHomeEnvVar
+ "' is not registered with Gradle installation supplier. Ensure 'org.gradle.java.installations.fromEnv' is "
+ "updated in gradle.properties file."
)
);
String versionedJavaHome = System.getenv(javaHomeEnvVar);
if (versionedJavaHome == null) {
final String exceptionMessage = String.format(
Locale.ROOT,
"$%s must be set to build Elasticsearch. "
+ "Note that if the variable was just set you "
+ "might have to run `./gradlew --stop` for "
+ "it to be picked up. See https://github.com/elastic/elasticsearch/issues/31399 details.",
javaHomeEnvVar
);
throw new GradleException(exceptionMessage);
}
return versionedJavaHome;
}
private static String getJavaHomeEnvVarName(String version) {
return "JAVA" + version + "_HOME";
}
private static int findDefaultParallel(Project project) {
// Since it costs IO to compute this, and is done at configuration time we want to cache this if possible
// It's safe to store this in a static variable since it's just a primitive so leaking memory isn't an issue
if (_defaultParallel == null) {
File cpuInfoFile = new File("/proc/cpuinfo");
if (cpuInfoFile.exists()) {
// Count physical cores on any Linux distro ( don't count hyper-threading )
Map<String, Integer> socketToCore = new HashMap<>();
String currentID = "";
try (BufferedReader reader = new BufferedReader(new FileReader(cpuInfoFile))) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
if (line.contains(":")) {
List<String> parts = Arrays.stream(line.split(":", 2)).map(String::trim).collect(Collectors.toList());
String name = parts.get(0);
String value = parts.get(1);
// the ID of the CPU socket
if (name.equals("physical id")) {
currentID = value;
}
// Number of cores not including hyper-threading
if (name.equals("cpu cores")) {
assert currentID.isEmpty() == false;
socketToCore.put("currentID", Integer.valueOf(value));
currentID = "";
}
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
_defaultParallel = socketToCore.values().stream().mapToInt(i -> i).sum();
} else if (OS.current() == OS.MAC) {
// Ask macOS to count physical CPUs for us
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
project.exec(spec -> {
spec.setExecutable("sysctl");
spec.args("-n", "hw.physicalcpu");
spec.setStandardOutput(stdout);
});
_defaultParallel = Integer.parseInt(stdout.toString().trim());
}
_defaultParallel = Runtime.getRuntime().availableProcessors() / 2;
}
return _defaultParallel;
}
public static GitInfo gitInfo(File rootDir) {
try {
/*
* We want to avoid forking another process to run git rev-parse HEAD. Instead, we will read the refs manually. The
* documentation for this follows from https://git-scm.com/docs/gitrepository-layout and https://git-scm.com/docs/git-worktree.
*
* There are two cases to consider:
* - a plain repository with .git directory at the root of the working tree
* - a worktree with a plain text .git file at the root of the working tree
*
* In each case, our goal is to parse the HEAD file to get either a ref or a bare revision (in the case of being in detached
* HEAD state).
*
* In the case of a plain repository, we can read the HEAD file directly, resolved directly from the .git directory.
*
* In the case of a worktree, we read the gitdir from the plain text .git file. This resolves to a directory from which we read
* the HEAD file and resolve commondir to the plain git repository.
*/
final Path dotGit = rootDir.toPath().resolve(".git");
final String revision;
if (Files.exists(dotGit) == false) {
return new GitInfo("unknown", "unknown");
}
final Path head;
final Path gitDir;
if (Files.isDirectory(dotGit)) {
// this is a git repository, we can read HEAD directly
head = dotGit.resolve("HEAD");
gitDir = dotGit;
} else {
// this is a git worktree, follow the pointer to the repository
final Path workTree = Paths.get(readFirstLine(dotGit).substring("gitdir:".length()).trim());
if (Files.exists(workTree) == false) {
return new GitInfo("unknown", "unknown");
}
head = workTree.resolve("HEAD");
final Path commonDir = Paths.get(readFirstLine(workTree.resolve("commondir")));
if (commonDir.isAbsolute()) {
gitDir = commonDir;
} else {
// this is the common case
gitDir = workTree.resolve(commonDir);
}
}
final String ref = readFirstLine(head);
if (ref.startsWith("ref:")) {
String refName = ref.substring("ref:".length()).trim();
Path refFile = gitDir.resolve(refName);
if (Files.exists(refFile)) {
revision = readFirstLine(refFile);
} else if (Files.exists(gitDir.resolve("packed-refs"))) {
// Check packed references for commit ID
Pattern p = Pattern.compile("^([a-f0-9]{40}) " + refName + "$");
try (Stream<String> lines = Files.lines(gitDir.resolve("packed-refs"))) {
revision = lines.map(p::matcher)
.filter(Matcher::matches)
.map(m -> m.group(1))
.findFirst()
.orElseThrow(() -> new IOException("Packed reference not found for refName " + refName));
}
} else {
File refsDir = gitDir.resolve("refs").toFile();
if (refsDir.exists()) {
String foundRefs = Arrays.stream(refsDir.listFiles()).map(f -> f.getName()).collect(Collectors.joining("\n"));
Logging.getLogger(GlobalBuildInfoPlugin.class).error("Found git refs\n" + foundRefs);
} else {
Logging.getLogger(GlobalBuildInfoPlugin.class).error("No git refs dir found");
}
throw new GradleException("Can't find revision for refName " + refName);
}
} else {
// we are in detached HEAD state
revision = ref;
}
return new GitInfo(revision, findOriginUrl(gitDir.resolve("config")));
} catch (final IOException e) {
// for now, do not be lenient until we have better understanding of real-world scenarios where this happens
throw new GradleException("unable to read the git revision", e);
}
}
private static String findOriginUrl(final Path configFile) throws IOException {
Map<String, String> props = new HashMap<>();
try (Stream<String> stream = Files.lines(configFile, StandardCharsets.UTF_8)) {
Iterator<String> lines = stream.iterator();
boolean foundOrigin = false;
while (lines.hasNext()) {
String line = lines.next().trim();
if (line.startsWith(";") || line.startsWith("#")) {
// ignore comments
continue;
}
if (foundOrigin) {
if (line.startsWith("[")) {
// we're on to the next config item so stop looking
break;
}
String[] pair = line.trim().split("=", 2);
props.put(pair[0].trim(), pair[1].trim());
} else {
if (line.equals("[remote \"origin\"]")) {
foundOrigin = true;
}
}
}
}
String originUrl = props.get("url");
return originUrl == null ? "unknown" : originUrl;
}
private static String readFirstLine(final Path path) throws IOException {
String firstLine;
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
firstLine = lines.findFirst().orElseThrow(() -> new IOException("file [" + path + "] is empty"));
}
return firstLine;
}
public static class GitInfo {
private final String revision;
private final String origin;
GitInfo(String revision, String origin) {
this.revision = revision;
this.origin = origin;
}
public String getRevision() {
return revision;
}
public String getOrigin() {
return origin;
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.List;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.io.IVersionedSerializer;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.HeapAllocator;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.thrift.ConsistencyLevel;
public class CounterMutation implements IMutation
{
private static final Logger logger = LoggerFactory.getLogger(CounterMutation.class);
private static final CounterMutationSerializer serializer = new CounterMutationSerializer();
private final RowMutation rowMutation;
private final ConsistencyLevel consistency;
public CounterMutation(RowMutation rowMutation, ConsistencyLevel consistency)
{
this.rowMutation = rowMutation;
this.consistency = consistency;
}
public String getTable()
{
return rowMutation.getTable();
}
public Collection<Integer> getColumnFamilyIds()
{
return rowMutation.getColumnFamilyIds();
}
public ByteBuffer key()
{
return rowMutation.key();
}
public RowMutation rowMutation()
{
return rowMutation;
}
public ConsistencyLevel consistency()
{
return consistency;
}
public static CounterMutationSerializer serializer()
{
return serializer;
}
public RowMutation makeReplicationMutation() throws IOException
{
List<ReadCommand> readCommands = new LinkedList<ReadCommand>();
for (ColumnFamily columnFamily : rowMutation.getColumnFamilies())
{
if (!columnFamily.metadata().getReplicateOnWrite())
continue;
addReadCommandFromColumnFamily(rowMutation.getTable(), rowMutation.key(), columnFamily, readCommands);
}
// create a replication RowMutation
RowMutation replicationMutation = new RowMutation(rowMutation.getTable(), rowMutation.key());
for (ReadCommand readCommand : readCommands)
{
Table table = Table.open(readCommand.table);
Row row = readCommand.getRow(table);
if (row == null || row.cf == null)
continue;
row = mergeOldShards(readCommand.table, row);
ColumnFamily cf = row.cf;
if (cf.isSuper())
cf.retainAll(rowMutation.getColumnFamily(cf.metadata().cfId));
replicationMutation.add(cf);
}
return replicationMutation;
}
private void addReadCommandFromColumnFamily(String table, ByteBuffer key, ColumnFamily columnFamily, List<ReadCommand> commands)
{
QueryPath queryPath = new QueryPath(columnFamily.metadata().cfName);
commands.add(new SliceByNamesReadCommand(table, key, queryPath, columnFamily.getColumnNames()));
}
private Row mergeOldShards(String table, Row row) throws IOException
{
ColumnFamily cf = row.cf;
// random check for merging to allow lessening the performance impact
if (cf.metadata().getMergeShardsChance() > FBUtilities.threadLocalRandom().nextDouble())
{
ColumnFamily merger = computeShardMerger(cf);
if (merger != null)
{
RowMutation localMutation = new RowMutation(table, row.key.key);
localMutation.add(merger);
localMutation.apply();
cf.addAll(merger, HeapAllocator.instance);
}
}
return row;
}
private ColumnFamily computeShardMerger(ColumnFamily cf)
{
ColumnFamily merger = null;
// CF type: regular
if (!cf.isSuper())
{
for (IColumn column : cf)
{
if (!(column instanceof CounterColumn))
continue;
IColumn c = ((CounterColumn)column).computeOldShardMerger();
if (c != null)
{
if (merger == null)
merger = cf.cloneMeShallow();
merger.addColumn(c);
}
}
}
else // CF type: super
{
for (IColumn superColumn : cf)
{
IColumn mergerSuper = null;
for (IColumn column : superColumn.getSubColumns())
{
if (!(column instanceof CounterColumn))
continue;
IColumn c = ((CounterColumn)column).computeOldShardMerger();
if (c != null)
{
if (mergerSuper == null)
mergerSuper = ((SuperColumn)superColumn).cloneMeShallow();
mergerSuper.addColumn(c);
}
}
if (mergerSuper != null)
{
if (merger == null)
merger = cf.cloneMeShallow();
merger.addColumn(mergerSuper);
}
}
}
return merger;
}
public Message makeMutationMessage(int version) throws IOException
{
byte[] bytes = FBUtilities.serialize(this, serializer, version);
return new Message(FBUtilities.getBroadcastAddress(), StorageService.Verb.COUNTER_MUTATION, bytes, version);
}
public boolean shouldReplicateOnWrite()
{
for (ColumnFamily cf : rowMutation.getColumnFamilies())
if (cf.metadata().getReplicateOnWrite())
return true;
return false;
}
public void apply() throws IOException
{
// transform all CounterUpdateColumn to CounterColumn: accomplished by localCopy
RowMutation rm = new RowMutation(rowMutation.getTable(), ByteBufferUtil.clone(rowMutation.key()));
Table table = Table.open(rm.getTable());
for (ColumnFamily cf_ : rowMutation.getColumnFamilies())
{
ColumnFamily cf = cf_.cloneMeShallow();
ColumnFamilyStore cfs = table.getColumnFamilyStore(cf.id());
for (IColumn column : cf_)
{
cf.addColumn(column.localCopy(cfs), HeapAllocator.instance);
}
rm.add(cf);
}
rm.apply();
}
@Override
public String toString()
{
return toString(false);
}
public String toString(boolean shallow)
{
StringBuilder buff = new StringBuilder("CounterMutation(");
buff.append(rowMutation.toString(shallow));
buff.append(", ").append(consistency.toString());
return buff.append(")").toString();
}
}
class CounterMutationSerializer implements IVersionedSerializer<CounterMutation>
{
public void serialize(CounterMutation cm, DataOutput dos, int version) throws IOException
{
RowMutation.serializer().serialize(cm.rowMutation(), dos, version);
dos.writeUTF(cm.consistency().name());
}
public CounterMutation deserialize(DataInput dis, int version) throws IOException
{
RowMutation rm = RowMutation.serializer().deserialize(dis, version);
ConsistencyLevel consistency = Enum.valueOf(ConsistencyLevel.class, dis.readUTF());
return new CounterMutation(rm, consistency);
}
public long serializedSize(CounterMutation cm, int version)
{
return RowMutation.serializer().serializedSize(cm.rowMutation(), version)
+ DBConstants.shortSize + FBUtilities.encodedUTF8Length(cm.consistency().name());
}
}
| |
package ocelot;
import static ocelot.JVMValue.entry;
import ocelot.classfile.OtKlassParser;
import static ocelot.classfile.OtKlassParser.ACC_PRIVATE;
import static ocelot.classfile.OtKlassParser.ACC_PUBLIC;
import static ocelot.classfile.OtKlassParser.ACC_STATIC;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import ocelot.rt.SharedKlassRepo;
import ocelot.rt.OtKlass;
import ocelot.rt.OtMethod;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author ben
*/
public class TestInterp {
private InterpMain im;
private SharedKlassRepo repo;
@Before
public void setup() {
repo = SharedKlassRepo.of();
}
private byte[] buf;
@Test
@Ignore
public void hello_world_loaded_from_file_executes() throws Exception {
String fName = "Println.class";
buf = Utils.pullBytes(fName);
OtKlass klass = OtKlassParser.of(null, buf, fName);
repo.add(klass);
im = new InterpMain(repo);
OtMethod meth = klass.getMethodByName("main:([Ljava/lang/String;)V");
assertEquals("Flags should be public, static", meth.getFlags(), ACC_PUBLIC | ACC_STATIC);
assertNull("Hello World should execute", im.execMethod(meth));
}
@Test
public void simple_branching_executes() throws Exception {
String fName = "optjava/bc/SimpleTests.class";
buf = Utils.pullBytes(fName);
OtKlass klass = OtKlassParser.of(null, buf, fName);
repo.add(klass);
im = new InterpMain(repo);
OtMethod meth = klass.getMethodByName("if_bc:()I");
assertEquals("Flags should be public", ACC_PUBLIC, meth.getFlags());
JVMValue res = im.execMethod(meth);
assertEquals("Return type should be int", JVMType.I, res.type);
assertEquals("Return value should be 2", 2, (int) res.value);
}
@Test
public void simple_static_calls_executes() throws Exception {
String fName = "octest/StaticCalls.class";
buf = Utils.pullBytes(fName);
OtKlass klass = OtKlassParser.of(null, buf, fName);
repo.add(klass);
im = new InterpMain(repo);
OtMethod meth = klass.getMethodByName("call1:()I"); // "main:([Ljava/lang/String;)V");
assertEquals("Flags should be public, static", ACC_PUBLIC | ACC_STATIC, meth.getFlags());
JVMValue res = im.execMethod(meth);
assertEquals("Return type should be int", JVMType.I, res.type);
assertEquals("Return value should be 23", 23, (int) res.value);
meth = klass.getMethodByName("call4:()I");
assertEquals("Flags should be public, static", ACC_PUBLIC | ACC_STATIC, meth.getFlags());
res = im.execMethod(meth);
assertEquals("Return type should be int", JVMType.I, res.type);
assertEquals("Return value should be 47", 47, (int) res.value);
meth = klass.getMethodByName("adder:(II)I");
assertEquals("Flags should be public, static", ACC_PUBLIC | ACC_STATIC, meth.getFlags());
InterpLocalVars lv = new InterpLocalVars();
JVMValue[] vars = new JVMValue[2];
vars[0] = entry(5);
vars[1] = entry(7);
lv.setup(vars);
res = im.execMethod(meth, lv);
assertEquals("Return type should be int", JVMType.I, res.type);
assertEquals("Return value should be 12", 12, (int) res.value);
}
@Test
public void simple_calls_modify_static_fields() throws Exception {
String fName = "octest/StaticCalls.class";
buf = Utils.pullBytes(fName);
OtKlass klass = OtKlassParser.of(null, buf, fName);
repo.add(klass);
im = new InterpMain(repo);
OtMethod meth = klass.getMethodByName("setJ:(I)V");
assertEquals("Flags should be public, static", ACC_PUBLIC | ACC_STATIC, meth.getFlags());
InterpLocalVars lvt = new InterpLocalVars();
JVMValue[] vs = new JVMValue[1];
vs[0] = new JVMValue(JVMType.I, 13L);
lvt.setup(vs);
JVMValue res = im.execMethod(meth, lvt);
assertNull("Call to setter should be return null", res);
meth = klass.getMethodByName("getJ:()I");
assertEquals("Flags should be public, static", ACC_PUBLIC | ACC_STATIC, meth.getFlags());
res = im.execMethod(meth);
assertEquals("Return type should be int", JVMType.I, res.type);
assertEquals("Return value should be 13", 13, (int) res.value);
meth = klass.getMethodByName("incJ:()V");
assertEquals("Flags should be public, static", ACC_PUBLIC | ACC_STATIC, meth.getFlags());
res = im.execMethod(meth);
assertNull("Call to incJ() should be return null", res);
meth = klass.getMethodByName("getJ:()I");
res = im.execMethod(meth);
assertEquals("Return type should be int", JVMType.I, res.type);
assertEquals("Return value should be 14", 14, (int) res.value);
}
@Test
public void simple_executes() throws Exception {
String fName = "octest/Simple.class";
buf = Utils.pullBytes(fName);
OtKlass klass = OtKlassParser.of(null, buf, fName);
repo.add(klass);
im = new InterpMain(repo);
OtMethod meth = klass.getMethodByName("simple:()I");
assertEquals("Flags should be private, static", ACC_PRIVATE | ACC_STATIC, meth.getFlags());
JVMValue res = im.execMethod(meth);
assertEquals("Return type should be int", JVMType.I, res.type);
assertEquals("Return value should be 23", 23, (int) res.value);
}
@Test
public void simple_invoke() throws Exception {
String fName = "SampleInvoke.class";
buf = Utils.pullBytes(fName);
OtKlass klass = OtKlassParser.of(null, buf, fName);
repo.add(klass);
im = new InterpMain(repo);
OtMethod meth = klass.getMethodByName("foo:()I");
assertEquals("Flags should be public, static", ACC_PUBLIC | ACC_STATIC, meth.getFlags());
JVMValue res = im.execMethod(meth);
assertEquals("Return type should be int", JVMType.I, res.type);
assertEquals("Return value should be 9", 9, (int) res.value);
}
@Test
public void simple_new_field_executes() throws Exception {
String fName = "octest/MyInteger.class";
buf = Utils.pullBytes(fName);
OtKlass klass = OtKlassParser.of(null, buf, fName);
repo.add(klass);
im = new InterpMain(repo);
fName = "octest/IndirectMyI.class";
buf = Utils.pullBytes(fName);
klass = OtKlassParser.of(im, buf, fName);
repo.add(klass);
fName = "octest/UseMyI.class";
buf = Utils.pullBytes(fName);
klass = OtKlassParser.of(im, buf, fName);
repo.add(klass);
OtMethod meth = klass.getMethodByName("run:()I");
JVMValue res = im.execMethod(meth);
assertEquals("Try to exec the ctor", 42, res.value);
meth = klass.getMethodByName("run2:()I");
res = im.execMethod(meth);
assertEquals("Use an extra level of indirection", 1337, res.value);
meth = klass.getMethodByName("runC:()I");
res = im.execMethod(meth);
assertEquals("Try to exec the invokevirtual", 42, res.value);
meth = klass.getMethodByName("run2C:()I");
res = im.execMethod(meth);
assertEquals("Try to exec the invokevirtual", 1337, res.value);
}
@Test
@Ignore
public void simple_invokevirtual() throws Exception {
String fName = "octest/SonOfMyInteger.class";
buf = Utils.pullBytes(fName);
OtKlass klass = OtKlassParser.of(null, buf, fName);
repo.add(klass);
im = new InterpMain(repo);
OtMethod meth = klass.getMethodByName("getValue2:()I");
assertEquals("Flags should be public", ACC_PUBLIC, meth.getFlags());
JVMValue res = im.execMethod(meth);
assertEquals("Return type should be int", JVMType.I, res.type);
assertEquals("Return value should be 9", 9, (int) res.value);
}
}
| |
package nl.jqno.equalsverifier.internal.reflection;
import static nl.jqno.equalsverifier.internal.util.Rethrow.rethrow;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Set;
import java.util.function.Predicate;
import nl.jqno.equalsverifier.internal.prefabvalues.PrefabValues;
import nl.jqno.equalsverifier.internal.prefabvalues.TypeTag;
import nl.jqno.equalsverifier.internal.reflection.annotations.AnnotationCache;
import nl.jqno.equalsverifier.internal.reflection.annotations.NonnullAnnotationVerifier;
/**
* Instantiates and populates objects of a given class. {@link ClassAccessor} can create two
* different instances of T, which are guaranteed not to be equal to each other, and which contain
* no null values.
*
* @param <T> A class.
*/
public class ClassAccessor<T> {
private final Class<T> type;
private final PrefabValues prefabValues;
/** Private constructor. Call {@link #of(Class, PrefabValues)} instead. */
ClassAccessor(Class<T> type, PrefabValues prefabValues) {
this.type = type;
this.prefabValues = prefabValues;
}
/**
* Factory method.
*
* @param <T> The class on which {@link ClassAccessor} operates.
* @param type The class on which {@link ClassAccessor} operates. Should be the same as T.
* @param prefabValues Prefabricated values with which to fill instantiated objects.
* @return A {@link ClassAccessor} for T.
*/
public static <T> ClassAccessor<T> of(Class<T> type, PrefabValues prefabValues) {
return new ClassAccessor<>(type, prefabValues);
}
/** @return The class on which {@link ClassAccessor} operates. */
public Class<T> getType() {
return type;
}
/**
* Determines whether T is a Java Record.
*
* @return true if T is a Java Record.
*/
public boolean isRecord() {
return RecordsHelper.isRecord(type);
}
/**
* Determines whether T is a sealed class.
*
* @return true if T is a sealed class
*/
public boolean isSealed() {
return SealedClassesHelper.isSealed(type);
}
/**
* Determines whether T declares a field. This does not include inherited fields.
*
* @param field The field that we want to detect.
* @return True if T declares the field.
*/
public boolean declaresField(Field field) {
try {
type.getDeclaredField(field.getName());
return true;
} catch (NoSuchFieldException e) {
return false;
}
}
/**
* Determines whether T has an {@code equals} method.
*
* @return True if T has an {@code equals} method.
*/
public boolean declaresEquals() {
return declaresMethod("equals", Object.class);
}
/**
* Determines whether T has an {@code hashCode} method.
*
* @return True if T has an {@code hashCode} method.
*/
public boolean declaresHashCode() {
return declaresMethod("hashCode");
}
private boolean declaresMethod(String name, Class<?>... parameterTypes) {
try {
type.getDeclaredMethod(name, parameterTypes);
return true;
} catch (NoSuchMethodException e) {
return false;
}
}
/**
* Determines whether T's {@code equals} method is abstract.
*
* @return True if T's {@code equals} method is abstract.
*/
public boolean isEqualsAbstract() {
return isMethodAbstract("equals", Object.class);
}
/**
* Determines whether T's {@code hashCode} method is abstract.
*
* @return True if T's {@code hashCode} method is abstract.
*/
public boolean isHashCodeAbstract() {
return isMethodAbstract("hashCode");
}
private boolean isMethodAbstract(String name, Class<?>... parameterTypes) {
return rethrow(() ->
Modifier.isAbstract(type.getMethod(name, parameterTypes).getModifiers())
);
}
/**
* Determines whether T's {@code equals} method is inherited from {@link Object}.
*
* @return true if T's {@code equals} method is inherited from {@link Object}; false if it is
* overridden in T or in any of its superclasses (except {@link Object}).
*/
public boolean isEqualsInheritedFromObject() {
ClassAccessor<? super T> i = this;
while (i.getType() != Object.class) {
if (i.declaresEquals() && !i.isEqualsAbstract()) {
return false;
}
i = i.getSuperAccessor();
}
return true;
}
/**
* Returns an accessor for T's superclass.
*
* @return An accessor for T's superclass.
*/
public ClassAccessor<? super T> getSuperAccessor() {
return ClassAccessor.of(type.getSuperclass(), prefabValues);
}
/**
* Returns an instance of T that is not equal to the instance of T returned by {@link
* #getBlueObject(TypeTag)}.
*
* @param enclosingType Describes the type that contains this object as a field, to determine
* any generic parameters it may contain.
* @return An instance of T.
*/
public T getRedObject(TypeTag enclosingType) {
return getRedAccessor(enclosingType).get();
}
/**
* Returns an {@link ObjectAccessor} for {@link #getRedObject(TypeTag)}.
*
* @param enclosingType Describes the type that contains this object as a field, to determine
* any generic parameters it may contain.
* @return An {@link ObjectAccessor} for {@link #getRedObject(TypeTag)}.
*/
public ObjectAccessor<T> getRedAccessor(TypeTag enclosingType) {
return buildObjectAccessor().scramble(prefabValues, enclosingType);
}
/**
* Returns an instance of T that is not equal to the instance of T returned by {@link
* #getRedObject(TypeTag)}.
*
* @param enclosingType Describes the type that contains this object as a field, to determine
* any generic parameters it may contain.
* @return An instance of T.
*/
public T getBlueObject(TypeTag enclosingType) {
return getBlueAccessor(enclosingType).get();
}
/**
* Returns an {@link ObjectAccessor} for {@link #getBlueObject(TypeTag)}.
*
* @param enclosingType Describes the type that contains this object as a field, to determine
* any generic parameters it may contain.
* @return An {@link ObjectAccessor} for {@link #getBlueObject(TypeTag)}.
*/
public ObjectAccessor<T> getBlueAccessor(TypeTag enclosingType) {
return buildObjectAccessor()
.scramble(prefabValues, enclosingType)
.scramble(prefabValues, enclosingType);
}
/**
* Returns an {@link ObjectAccessor} for an instance of T where all the fields are initialized
* to their default values. I.e., 0 for ints, and null for objects (except when the field is
* marked with a NonNull annotation).
*
* @param enclosingType Describes the type that contains this object as a field, to determine
* any generic parameters it may contain.
* @param nonnullFields Fields which are not allowed to be set to null.
* @param annotationCache To check for any NonNull annotations.
* @return An {@link ObjectAccessor} for an instance of T where all the fields are initialized
* to their default values.
*/
public ObjectAccessor<T> getDefaultValuesAccessor(
TypeTag enclosingType,
Set<String> nonnullFields,
AnnotationCache annotationCache
) {
Predicate<Field> canBeDefault = f ->
!NonnullAnnotationVerifier.fieldIsNonnull(f, annotationCache) &&
!nonnullFields.contains(f.getName());
return buildObjectAccessor().clear(canBeDefault, prefabValues, enclosingType);
}
private ObjectAccessor<T> buildObjectAccessor() {
T object = Instantiator.of(type).instantiate();
return ObjectAccessor.of(object);
}
}
| |
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.android.desugar.io;
import com.google.common.collect.ImmutableList;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
/**
* Class loader that can "load" classes from header Jars. This class loader stubs in missing code
* attributes on the fly to make {@link ClassLoader#defineClass} happy. Classes loaded are unusable
* other than to resolve method references, so this class loader should only be used to process or
* inspect classes, not to execute their code. Also note that the resulting classes may be missing
* private members, which header Jars may omit.
*
* @see java.net.URLClassLoader
*/
public class HeaderClassLoader extends ClassLoader {
private final IndexedInputs indexedInputs;
private final CoreLibraryRewriter rewriter;
public HeaderClassLoader(
IndexedInputs indexedInputs, CoreLibraryRewriter rewriter, ClassLoader parent) {
super(parent);
this.rewriter = rewriter;
this.indexedInputs = indexedInputs;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String filename = rewriter.unprefix(name.replace('.', '/') + ".class");
InputFileProvider inputFileProvider = indexedInputs.getInputFileProvider(filename);
if (inputFileProvider == null) {
throw new ClassNotFoundException("Class " + name + " not found");
}
byte[] bytecode;
try (InputStream content = inputFileProvider.getInputStream(filename)) {
ClassReader reader = rewriter.reader(content);
// Have ASM compute maxs so we don't need to figure out how many formal parameters there are
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
ImmutableList<FieldInfo> interfaceFieldNames = getFieldsIfReaderIsInterface(reader);
// TODO(kmb): Consider SKIP_CODE and stubbing everything so class loader doesn't verify code
reader.accept(new CodeStubber(writer, interfaceFieldNames), ClassReader.SKIP_DEBUG);
bytecode = writer.toByteArray();
} catch (IOException e) {
throw new IOError(e);
}
return defineClass(name, bytecode, 0, bytecode.length);
}
/**
* If the {@code reader} is an interface, then extract all the declared fields in it. Otherwise,
* return an empty list.
*/
private static ImmutableList<FieldInfo> getFieldsIfReaderIsInterface(ClassReader reader) {
if (BitFlags.isSet(reader.getAccess(), Opcodes.ACC_INTERFACE)) {
NonPrimitiveFieldCollector collector = new NonPrimitiveFieldCollector();
reader.accept(collector, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
return collector.declaredNonPrimitiveFields.build();
}
return ImmutableList.of();
}
/** Collect the fields defined in a class. */
private static class NonPrimitiveFieldCollector extends ClassVisitor {
final ImmutableList.Builder<FieldInfo> declaredNonPrimitiveFields = ImmutableList.builder();
private String internalName;
public NonPrimitiveFieldCollector() {
super(Opcodes.ASM7);
}
@Override
public void visit(
int version,
int access,
String name,
String signature,
String superName,
String[] interfaces) {
super.visit(version, access, name, signature, superName, interfaces);
this.internalName = name;
}
@Override
public FieldVisitor visitField(
int access, String name, String desc, String signature, Object value) {
if (isNonPrimitiveType(desc)) {
declaredNonPrimitiveFields.add(FieldInfo.create(internalName, name, desc));
}
return null;
}
private static boolean isNonPrimitiveType(String type) {
char firstChar = type.charAt(0);
return firstChar == '[' || firstChar == 'L';
}
}
/**
* Class visitor that stubs in missing code attributes, and erases the body of the static
* initializer of functional interfaces if the interfaces have default methods. The erasion of the
* clinit is mainly because when we are desugaring lambdas, we need to load the functional
* interfaces via class loaders, and since the interfaces have default methods, according to the
* JVM spec, these interfaces will be executed. This should be prevented due to security concerns.
*/
private static class CodeStubber extends ClassVisitor {
private String internalName;
private boolean isInterface;
private final ImmutableList<FieldInfo> interfaceFields;
public CodeStubber(ClassVisitor cv, ImmutableList<FieldInfo> interfaceFields) {
super(Opcodes.ASM7, cv);
this.interfaceFields = interfaceFields;
}
@Override
public void visit(
int version,
int access,
String name,
String signature,
String superName,
String[] interfaces) {
super.visit(version, access, name, signature, superName, interfaces);
isInterface = BitFlags.isSet(access, Opcodes.ACC_INTERFACE);
internalName = name;
}
@Override
public MethodVisitor visitMethod(
int access, String name, String desc, String signature, String[] exceptions) {
MethodVisitor dest = super.visitMethod(access, name, desc, signature, exceptions);
if ((access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0) {
// No need to stub out abstract or native methods
return dest;
}
if (isInterface && "<clinit>".equals(name)) {
// Delete class initializers, to avoid code gets executed when we desugar lambdas.
// See b/62184142
return new InterfaceInitializerEraser(dest, internalName, interfaceFields);
}
return new BodyStubber(dest);
}
}
/**
* Erase the static initializer of an interface. Given an interface with non-primitive fields,
* this eraser discards the original body of clinit, and initializes each non-primitive field to
* null
*/
private static class InterfaceInitializerEraser extends MethodVisitor {
private final MethodVisitor dest;
private final ImmutableList<FieldInfo> interfaceFields;
public InterfaceInitializerEraser(
MethodVisitor mv, String internalName, ImmutableList<FieldInfo> interfaceFields) {
super(Opcodes.ASM7);
dest = mv;
this.interfaceFields = interfaceFields;
}
@Override
public void visitCode() {
dest.visitCode();
}
@Override
public void visitEnd() {
for (FieldInfo fieldInfo : interfaceFields) {
dest.visitInsn(Opcodes.ACONST_NULL);
dest.visitFieldInsn(
Opcodes.PUTSTATIC, fieldInfo.owner(), fieldInfo.name(), fieldInfo.desc());
}
dest.visitInsn(Opcodes.RETURN);
dest.visitMaxs(0, 0);
dest.visitEnd();
}
}
/** Method visitor used by {@link CodeStubber} to put code into methods without code. */
private static class BodyStubber extends MethodVisitor {
private static final String EXCEPTION_INTERNAL_NAME = "java/lang/UnsupportedOperationException";
private boolean hasCode = false;
public BodyStubber(MethodVisitor mv) {
super(Opcodes.ASM7, mv);
}
@Override
public void visitCode() {
hasCode = true;
super.visitCode();
}
@Override
public void visitEnd() {
if (!hasCode) {
super.visitTypeInsn(Opcodes.NEW, EXCEPTION_INTERNAL_NAME);
super.visitInsn(Opcodes.DUP);
super.visitMethodInsn(
Opcodes.INVOKESPECIAL, EXCEPTION_INTERNAL_NAME, "<init>", "()V", /*itf*/ false);
super.visitInsn(Opcodes.ATHROW);
super.visitMaxs(0, 0); // triggers computation of the actual max's
}
super.visitEnd();
}
}
}
| |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.channel.local;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.EventLoopGroup;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.EventExecutorGroup;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicReference;
public class LocalTransportThreadModelTest {
private static EventLoopGroup group;
private static LocalAddress localAddr;
@BeforeClass
public static void init() {
// Configure a test server
group = new DefaultEventLoopGroup();
ServerBootstrap sb = new ServerBootstrap();
sb.group(group)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// Discard
ReferenceCountUtil.release(msg);
}
});
}
});
localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress();
}
@AfterClass
public static void destroy() throws Exception {
group.shutdownGracefully().sync();
}
@Test(timeout = 30000)
@Ignore("regression test")
public void testStagedExecutionMultiple() throws Throwable {
for (int i = 0; i < 10; i ++) {
testStagedExecution();
}
}
@Test(timeout = 5000)
public void testStagedExecution() throws Throwable {
EventLoopGroup l = new DefaultEventLoopGroup(4, new DefaultThreadFactory("l"));
EventExecutorGroup e1 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e1"));
EventExecutorGroup e2 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e2"));
ThreadNameAuditor h1 = new ThreadNameAuditor();
ThreadNameAuditor h2 = new ThreadNameAuditor();
ThreadNameAuditor h3 = new ThreadNameAuditor(true);
Channel ch = new LocalChannel();
// With no EventExecutor specified, h1 will be always invoked by EventLoop 'l'.
ch.pipeline().addLast(h1);
// h2 will be always invoked by EventExecutor 'e1'.
ch.pipeline().addLast(e1, h2);
// h3 will be always invoked by EventExecutor 'e2'.
ch.pipeline().addLast(e2, h3);
l.register(ch).sync().channel().connect(localAddr).sync();
// Fire inbound events from all possible starting points.
ch.pipeline().fireChannelRead("1");
ch.pipeline().context(h1).fireChannelRead("2");
ch.pipeline().context(h2).fireChannelRead("3");
ch.pipeline().context(h3).fireChannelRead("4");
// Fire outbound events from all possible starting points.
ch.pipeline().write("5");
ch.pipeline().context(h3).write("6");
ch.pipeline().context(h2).write("7");
ch.pipeline().context(h1).writeAndFlush("8").sync();
ch.close().sync();
// Wait until all events are handled completely.
while (h1.outboundThreadNames.size() < 3 || h3.inboundThreadNames.size() < 3 ||
h1.removalThreadNames.size() < 1) {
if (h1.exception.get() != null) {
throw h1.exception.get();
}
if (h2.exception.get() != null) {
throw h2.exception.get();
}
if (h3.exception.get() != null) {
throw h3.exception.get();
}
Thread.sleep(10);
}
String currentName = Thread.currentThread().getName();
try {
// Events should never be handled from the current thread.
Assert.assertFalse(h1.inboundThreadNames.contains(currentName));
Assert.assertFalse(h2.inboundThreadNames.contains(currentName));
Assert.assertFalse(h3.inboundThreadNames.contains(currentName));
Assert.assertFalse(h1.outboundThreadNames.contains(currentName));
Assert.assertFalse(h2.outboundThreadNames.contains(currentName));
Assert.assertFalse(h3.outboundThreadNames.contains(currentName));
Assert.assertFalse(h1.removalThreadNames.contains(currentName));
Assert.assertFalse(h2.removalThreadNames.contains(currentName));
Assert.assertFalse(h3.removalThreadNames.contains(currentName));
// Assert that events were handled by the correct executor.
for (String name: h1.inboundThreadNames) {
Assert.assertTrue(name.startsWith("l-"));
}
for (String name: h2.inboundThreadNames) {
Assert.assertTrue(name.startsWith("e1-"));
}
for (String name: h3.inboundThreadNames) {
Assert.assertTrue(name.startsWith("e2-"));
}
for (String name: h1.outboundThreadNames) {
Assert.assertTrue(name.startsWith("l-"));
}
for (String name: h2.outboundThreadNames) {
Assert.assertTrue(name.startsWith("e1-"));
}
for (String name: h3.outboundThreadNames) {
Assert.assertTrue(name.startsWith("e2-"));
}
for (String name: h1.removalThreadNames) {
Assert.assertTrue(name.startsWith("l-"));
}
for (String name: h2.removalThreadNames) {
Assert.assertTrue(name.startsWith("e1-"));
}
for (String name: h3.removalThreadNames) {
Assert.assertTrue(name.startsWith("e2-"));
}
// Assert that the events for the same handler were handled by the same thread.
Set<String> names = new HashSet<String>();
names.addAll(h1.inboundThreadNames);
names.addAll(h1.outboundThreadNames);
names.addAll(h1.removalThreadNames);
Assert.assertEquals(1, names.size());
names.clear();
names.addAll(h2.inboundThreadNames);
names.addAll(h2.outboundThreadNames);
names.addAll(h2.removalThreadNames);
Assert.assertEquals(1, names.size());
names.clear();
names.addAll(h3.inboundThreadNames);
names.addAll(h3.outboundThreadNames);
names.addAll(h3.removalThreadNames);
Assert.assertEquals(1, names.size());
// Count the number of events
Assert.assertEquals(1, h1.inboundThreadNames.size());
Assert.assertEquals(2, h2.inboundThreadNames.size());
Assert.assertEquals(3, h3.inboundThreadNames.size());
Assert.assertEquals(3, h1.outboundThreadNames.size());
Assert.assertEquals(2, h2.outboundThreadNames.size());
Assert.assertEquals(1, h3.outboundThreadNames.size());
Assert.assertEquals(1, h1.removalThreadNames.size());
Assert.assertEquals(1, h2.removalThreadNames.size());
Assert.assertEquals(1, h3.removalThreadNames.size());
} catch (AssertionError e) {
System.out.println("H1I: " + h1.inboundThreadNames);
System.out.println("H2I: " + h2.inboundThreadNames);
System.out.println("H3I: " + h3.inboundThreadNames);
System.out.println("H1O: " + h1.outboundThreadNames);
System.out.println("H2O: " + h2.outboundThreadNames);
System.out.println("H3O: " + h3.outboundThreadNames);
System.out.println("H1R: " + h1.removalThreadNames);
System.out.println("H2R: " + h2.removalThreadNames);
System.out.println("H3R: " + h3.removalThreadNames);
throw e;
} finally {
l.shutdownGracefully();
e1.shutdownGracefully();
e2.shutdownGracefully();
l.terminationFuture().sync();
e1.terminationFuture().sync();
e2.terminationFuture().sync();
}
}
@Test(timeout = 30000)
@Ignore
public void testConcurrentMessageBufferAccess() throws Throwable {
EventLoopGroup l = new DefaultEventLoopGroup(4, new DefaultThreadFactory("l"));
EventExecutorGroup e1 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e1"));
EventExecutorGroup e2 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e2"));
EventExecutorGroup e3 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e3"));
EventExecutorGroup e4 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e4"));
EventExecutorGroup e5 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e5"));
try {
final MessageForwarder1 h1 = new MessageForwarder1();
final MessageForwarder2 h2 = new MessageForwarder2();
final MessageForwarder3 h3 = new MessageForwarder3();
final MessageForwarder1 h4 = new MessageForwarder1();
final MessageForwarder2 h5 = new MessageForwarder2();
final MessageDiscarder h6 = new MessageDiscarder();
final Channel ch = new LocalChannel();
// inbound: int -> byte[4] -> int -> int -> byte[4] -> int -> /dev/null
// outbound: int -> int -> byte[4] -> int -> int -> byte[4] -> /dev/null
ch.pipeline().addLast(h1)
.addLast(e1, h2)
.addLast(e2, h3)
.addLast(e3, h4)
.addLast(e4, h5)
.addLast(e5, h6);
l.register(ch).sync().channel().connect(localAddr).sync();
final int ROUNDS = 1024;
final int ELEMS_PER_ROUNDS = 8192;
final int TOTAL_CNT = ROUNDS * ELEMS_PER_ROUNDS;
for (int i = 0; i < TOTAL_CNT;) {
final int start = i;
final int end = i + ELEMS_PER_ROUNDS;
i = end;
ch.eventLoop().execute(new Runnable() {
@Override
public void run() {
for (int j = start; j < end; j ++) {
ch.pipeline().fireChannelRead(Integer.valueOf(j));
}
}
});
}
while (h1.inCnt < TOTAL_CNT || h2.inCnt < TOTAL_CNT || h3.inCnt < TOTAL_CNT ||
h4.inCnt < TOTAL_CNT || h5.inCnt < TOTAL_CNT || h6.inCnt < TOTAL_CNT) {
if (h1.exception.get() != null) {
throw h1.exception.get();
}
if (h2.exception.get() != null) {
throw h2.exception.get();
}
if (h3.exception.get() != null) {
throw h3.exception.get();
}
if (h4.exception.get() != null) {
throw h4.exception.get();
}
if (h5.exception.get() != null) {
throw h5.exception.get();
}
if (h6.exception.get() != null) {
throw h6.exception.get();
}
Thread.sleep(10);
}
for (int i = 0; i < TOTAL_CNT;) {
final int start = i;
final int end = i + ELEMS_PER_ROUNDS;
i = end;
ch.pipeline().context(h6).executor().execute(new Runnable() {
@Override
public void run() {
for (int j = start; j < end; j ++) {
ch.write(Integer.valueOf(j));
}
ch.flush();
}
});
}
while (h1.outCnt < TOTAL_CNT || h2.outCnt < TOTAL_CNT || h3.outCnt < TOTAL_CNT ||
h4.outCnt < TOTAL_CNT || h5.outCnt < TOTAL_CNT || h6.outCnt < TOTAL_CNT) {
if (h1.exception.get() != null) {
throw h1.exception.get();
}
if (h2.exception.get() != null) {
throw h2.exception.get();
}
if (h3.exception.get() != null) {
throw h3.exception.get();
}
if (h4.exception.get() != null) {
throw h4.exception.get();
}
if (h5.exception.get() != null) {
throw h5.exception.get();
}
if (h6.exception.get() != null) {
throw h6.exception.get();
}
Thread.sleep(10);
}
ch.close().sync();
} finally {
l.shutdownGracefully();
e1.shutdownGracefully();
e2.shutdownGracefully();
e3.shutdownGracefully();
e4.shutdownGracefully();
e5.shutdownGracefully();
l.terminationFuture().sync();
e1.terminationFuture().sync();
e2.terminationFuture().sync();
e3.terminationFuture().sync();
e4.terminationFuture().sync();
e5.terminationFuture().sync();
}
}
private static class ThreadNameAuditor extends ChannelDuplexHandler {
private final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
private final Queue<String> inboundThreadNames = new ConcurrentLinkedQueue<String>();
private final Queue<String> outboundThreadNames = new ConcurrentLinkedQueue<String>();
private final Queue<String> removalThreadNames = new ConcurrentLinkedQueue<String>();
private final boolean discard;
ThreadNameAuditor() {
this(false);
}
ThreadNameAuditor(boolean discard) {
this.discard = discard;
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
removalThreadNames.add(Thread.currentThread().getName());
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
inboundThreadNames.add(Thread.currentThread().getName());
if (!discard) {
ctx.fireChannelRead(msg);
}
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
outboundThreadNames.add(Thread.currentThread().getName());
ctx.write(msg, promise);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
exception.compareAndSet(null, cause);
System.err.print('[' + Thread.currentThread().getName() + "] ");
cause.printStackTrace();
super.exceptionCaught(ctx, cause);
}
}
/**
* Converts integers into a binary stream.
*/
private static class MessageForwarder1 extends ChannelDuplexHandler {
private final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
private volatile int inCnt;
private volatile int outCnt;
private volatile Thread t;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Thread t = this.t;
if (t == null) {
this.t = Thread.currentThread();
} else {
Assert.assertSame(t, Thread.currentThread());
}
ByteBuf out = ctx.alloc().buffer(4);
int m = ((Integer) msg).intValue();
int expected = inCnt ++;
Assert.assertEquals(expected, m);
out.writeInt(m);
ctx.fireChannelRead(out);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
Assert.assertSame(t, Thread.currentThread());
// Don't let the write request go to the server-side channel - just swallow.
boolean swallow = this == ctx.pipeline().first();
ByteBuf m = (ByteBuf) msg;
int count = m.readableBytes() / 4;
for (int j = 0; j < count; j ++) {
int actual = m.readInt();
int expected = outCnt ++;
Assert.assertEquals(expected, actual);
if (!swallow) {
ctx.write(actual);
}
}
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER, promise);
m.release();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
exception.compareAndSet(null, cause);
//System.err.print("[" + Thread.currentThread().getName() + "] ");
//cause.printStackTrace();
super.exceptionCaught(ctx, cause);
}
}
/**
* Converts a binary stream into integers.
*/
private static class MessageForwarder2 extends ChannelDuplexHandler {
private final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
private volatile int inCnt;
private volatile int outCnt;
private volatile Thread t;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Thread t = this.t;
if (t == null) {
this.t = Thread.currentThread();
} else {
Assert.assertSame(t, Thread.currentThread());
}
ByteBuf m = (ByteBuf) msg;
int count = m.readableBytes() / 4;
for (int j = 0; j < count; j ++) {
int actual = m.readInt();
int expected = inCnt ++;
Assert.assertEquals(expected, actual);
ctx.fireChannelRead(actual);
}
m.release();
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
Assert.assertSame(t, Thread.currentThread());
ByteBuf out = ctx.alloc().buffer(4);
int m = (Integer) msg;
int expected = outCnt ++;
Assert.assertEquals(expected, m);
out.writeInt(m);
ctx.write(out, promise);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
exception.compareAndSet(null, cause);
//System.err.print("[" + Thread.currentThread().getName() + "] ");
//cause.printStackTrace();
super.exceptionCaught(ctx, cause);
}
}
/**
* Simply forwards the received object to the next handler.
*/
private static class MessageForwarder3 extends ChannelDuplexHandler {
private final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
private volatile int inCnt;
private volatile int outCnt;
private volatile Thread t;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Thread t = this.t;
if (t == null) {
this.t = Thread.currentThread();
} else {
Assert.assertSame(t, Thread.currentThread());
}
int actual = (Integer) msg;
int expected = inCnt ++;
Assert.assertEquals(expected, actual);
ctx.fireChannelRead(msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
Assert.assertSame(t, Thread.currentThread());
int actual = (Integer) msg;
int expected = outCnt ++;
Assert.assertEquals(expected, actual);
ctx.write(msg, promise);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
exception.compareAndSet(null, cause);
System.err.print('[' + Thread.currentThread().getName() + "] ");
cause.printStackTrace();
super.exceptionCaught(ctx, cause);
}
}
/**
* Discards all received messages.
*/
private static class MessageDiscarder extends ChannelDuplexHandler {
private final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
private volatile int inCnt;
private volatile int outCnt;
private volatile Thread t;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Thread t = this.t;
if (t == null) {
this.t = Thread.currentThread();
} else {
Assert.assertSame(t, Thread.currentThread());
}
int actual = (Integer) msg;
int expected = inCnt ++;
Assert.assertEquals(expected, actual);
}
@Override
public void write(
ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
Assert.assertSame(t, Thread.currentThread());
int actual = (Integer) msg;
int expected = outCnt ++;
Assert.assertEquals(expected, actual);
ctx.write(msg, promise);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
exception.compareAndSet(null, cause);
//System.err.print("[" + Thread.currentThread().getName() + "] ");
//cause.printStackTrace();
super.exceptionCaught(ctx, cause);
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search;
import com.carrotsearch.hppc.ObjectOpenHashSet;
import com.carrotsearch.hppc.ObjectSet;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.search.TopDocs;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.cache.recycler.PageCacheRecycler;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.common.util.concurrent.ConcurrentMapLong;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.IndexFieldDataService;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.FieldMapper.Loading;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.query.TemplateQueryParser;
import org.elasticsearch.index.search.stats.StatsGroupsParseElement;
import org.elasticsearch.index.service.IndexService;
import org.elasticsearch.index.shard.service.IndexShard;
import org.elasticsearch.indices.IndicesLifecycle;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.indices.cache.query.IndicesQueryCache;
import org.elasticsearch.indices.warmer.IndicesWarmer;
import org.elasticsearch.indices.warmer.IndicesWarmer.WarmerContext;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.dfs.CachedDfSource;
import org.elasticsearch.search.dfs.DfsPhase;
import org.elasticsearch.search.dfs.DfsSearchResult;
import org.elasticsearch.search.fetch.*;
import org.elasticsearch.search.internal.*;
import org.elasticsearch.search.internal.SearchContext.Lifetime;
import org.elasticsearch.search.query.*;
import org.elasticsearch.search.warmer.IndexWarmersMetaData;
import org.elasticsearch.threadpool.ThreadPool;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicLong;
import static org.elasticsearch.common.Strings.hasLength;
import static org.elasticsearch.common.unit.TimeValue.timeValueMinutes;
/**
*
*/
public class SearchService extends AbstractLifecycleComponent<SearchService> {
public static final String NORMS_LOADING_KEY = "index.norms.loading";
private static final String DEFAUTL_KEEPALIVE_COMPONENENT_KEY = "default_keep_alive";
public static final String DEFAUTL_KEEPALIVE_KEY = "search." + DEFAUTL_KEEPALIVE_COMPONENENT_KEY;
private static final String KEEPALIVE_INTERVAL_COMPONENENT_KEY = "keep_alive_interval";
public static final String KEEPALIVE_INTERVAL_KEY = "search." + KEEPALIVE_INTERVAL_COMPONENENT_KEY;
private final ThreadPool threadPool;
private final ClusterService clusterService;
private final IndicesService indicesService;
private final IndicesWarmer indicesWarmer;
private final ScriptService scriptService;
private final PageCacheRecycler pageCacheRecycler;
private final BigArrays bigArrays;
private final DfsPhase dfsPhase;
private final QueryPhase queryPhase;
private final FetchPhase fetchPhase;
private final IndicesQueryCache indicesQueryCache;
private final long defaultKeepAlive;
private final ScheduledFuture<?> keepAliveReaper;
private final AtomicLong idGenerator = new AtomicLong();
private final ConcurrentMapLong<SearchContext> activeContexts = ConcurrentCollections.newConcurrentMapLongWithAggressiveConcurrency();
private final ImmutableMap<String, SearchParseElement> elementParsers;
@Inject
public SearchService(Settings settings, ClusterService clusterService, IndicesService indicesService, IndicesLifecycle indicesLifecycle, IndicesWarmer indicesWarmer, ThreadPool threadPool,
ScriptService scriptService, PageCacheRecycler pageCacheRecycler, BigArrays bigArrays, DfsPhase dfsPhase, QueryPhase queryPhase, FetchPhase fetchPhase,
IndicesQueryCache indicesQueryCache) {
super(settings);
this.threadPool = threadPool;
this.clusterService = clusterService;
this.indicesService = indicesService;
this.indicesWarmer = indicesWarmer;
this.scriptService = scriptService;
this.pageCacheRecycler = pageCacheRecycler;
this.bigArrays = bigArrays;
this.dfsPhase = dfsPhase;
this.queryPhase = queryPhase;
this.fetchPhase = fetchPhase;
this.indicesQueryCache = indicesQueryCache;
TimeValue keepAliveInterval = componentSettings.getAsTime(KEEPALIVE_INTERVAL_COMPONENENT_KEY, timeValueMinutes(1));
// we can have 5 minutes here, since we make sure to clean with search requests and when shard/index closes
this.defaultKeepAlive = componentSettings.getAsTime(DEFAUTL_KEEPALIVE_COMPONENENT_KEY, timeValueMinutes(5)).millis();
Map<String, SearchParseElement> elementParsers = new HashMap<>();
elementParsers.putAll(dfsPhase.parseElements());
elementParsers.putAll(queryPhase.parseElements());
elementParsers.putAll(fetchPhase.parseElements());
elementParsers.put("stats", new StatsGroupsParseElement());
this.elementParsers = ImmutableMap.copyOf(elementParsers);
this.keepAliveReaper = threadPool.scheduleWithFixedDelay(new Reaper(), keepAliveInterval);
this.indicesWarmer.addListener(new NormsWarmer());
this.indicesWarmer.addListener(new FieldDataWarmer());
this.indicesWarmer.addListener(new SearchWarmer());
}
@Override
protected void doStart() throws ElasticsearchException {
}
@Override
protected void doStop() throws ElasticsearchException {
for (final SearchContext context : activeContexts.values()) {
freeContext(context.id());
}
activeContexts.clear();
}
@Override
protected void doClose() throws ElasticsearchException {
keepAliveReaper.cancel(false);
}
public DfsSearchResult executeDfsPhase(ShardSearchRequest request) throws ElasticsearchException {
final SearchContext context = createAndPutContext(request);
try {
contextProcessing(context);
dfsPhase.execute(context);
contextProcessedSuccessfully(context);
return context.dfsResult();
} catch (Throwable e) {
logger.trace("Dfs phase failed", e);
freeContext(context.id());
throw ExceptionsHelper.convertToRuntime(e);
} finally {
cleanContext(context);
}
}
public QuerySearchResult executeScan(ShardSearchRequest request) throws ElasticsearchException {
final SearchContext context = createAndPutContext(request);
try {
if (context.aggregations() != null) {
throw new ElasticsearchIllegalArgumentException("aggregations are not supported with search_type=scan");
}
assert context.searchType() == SearchType.SCAN;
context.searchType(SearchType.COUNT); // move to COUNT, and then, when scrolling, move to SCAN
assert context.searchType() == SearchType.COUNT;
if (context.scroll() == null) {
throw new ElasticsearchException("Scroll must be provided when scanning...");
}
contextProcessing(context);
queryPhase.execute(context);
contextProcessedSuccessfully(context);
return context.queryResult();
} catch (Throwable e) {
logger.trace("Scan phase failed", e);
freeContext(context.id());
throw ExceptionsHelper.convertToRuntime(e);
} finally {
cleanContext(context);
}
}
public ScrollQueryFetchSearchResult executeScan(InternalScrollSearchRequest request) throws ElasticsearchException {
final SearchContext context = findContext(request.id());
contextProcessing(context);
try {
processScroll(request, context);
if (context.searchType() == SearchType.COUNT) {
// first scanning, reset the from to 0
context.searchType(SearchType.SCAN);
context.from(0);
}
queryPhase.execute(context);
shortcutDocIdsToLoadForScanning(context);
fetchPhase.execute(context);
if (context.scroll() == null || context.fetchResult().hits().hits().length < context.size()) {
freeContext(request.id());
} else {
contextProcessedSuccessfully(context);
}
return new ScrollQueryFetchSearchResult(new QueryFetchSearchResult(context.queryResult(), context.fetchResult()), context.shardTarget());
} catch (Throwable e) {
logger.trace("Scan phase failed", e);
freeContext(context.id());
throw ExceptionsHelper.convertToRuntime(e);
} finally {
cleanContext(context);
}
}
public QuerySearchResultProvider executeQueryPhase(ShardSearchRequest request) throws ElasticsearchException {
final SearchContext context = createAndPutContext(request);
try {
context.indexShard().searchService().onPreQueryPhase(context);
long time = System.nanoTime();
contextProcessing(context);
QuerySearchResultProvider result;
boolean canCache = indicesQueryCache.canCache(request, context);
if (canCache) {
result = indicesQueryCache.load(request, context, queryPhase);
} else {
queryPhase.execute(context);
result = context.queryResult();
}
if (context.searchType() == SearchType.COUNT) {
freeContext(context.id());
} else {
contextProcessedSuccessfully(context);
}
context.indexShard().searchService().onQueryPhase(context, System.nanoTime() - time);
return result;
} catch (Throwable e) {
// execution exception can happen while loading the cache, strip it
if (e instanceof ExecutionException) {
e = e.getCause();
}
context.indexShard().searchService().onFailedQueryPhase(context);
logger.trace("Query phase failed", e);
freeContext(context.id());
throw ExceptionsHelper.convertToRuntime(e);
} finally {
cleanContext(context);
}
}
public ScrollQuerySearchResult executeQueryPhase(InternalScrollSearchRequest request) throws ElasticsearchException {
final SearchContext context = findContext(request.id());
try {
context.indexShard().searchService().onPreQueryPhase(context);
long time = System.nanoTime();
contextProcessing(context);
processScroll(request, context);
queryPhase.execute(context);
contextProcessedSuccessfully(context);
context.indexShard().searchService().onQueryPhase(context, System.nanoTime() - time);
return new ScrollQuerySearchResult(context.queryResult(), context.shardTarget());
} catch (Throwable e) {
context.indexShard().searchService().onFailedQueryPhase(context);
logger.trace("Query phase failed", e);
freeContext(context.id());
throw ExceptionsHelper.convertToRuntime(e);
} finally {
cleanContext(context);
}
}
public QuerySearchResult executeQueryPhase(QuerySearchRequest request) throws ElasticsearchException {
final SearchContext context = findContext(request.id());
contextProcessing(context);
try {
context.searcher().dfSource(new CachedDfSource(context.searcher().getIndexReader(), request.dfs(), context.similarityService().similarity()));
} catch (Throwable e) {
freeContext(context.id());
cleanContext(context);
throw new QueryPhaseExecutionException(context, "Failed to set aggregated df", e);
}
try {
context.indexShard().searchService().onPreQueryPhase(context);
long time = System.nanoTime();
queryPhase.execute(context);
contextProcessedSuccessfully(context);
context.indexShard().searchService().onQueryPhase(context, System.nanoTime() - time);
return context.queryResult();
} catch (Throwable e) {
context.indexShard().searchService().onFailedQueryPhase(context);
logger.trace("Query phase failed", e);
freeContext(context.id());
throw ExceptionsHelper.convertToRuntime(e);
} finally {
cleanContext(context);
}
}
public QueryFetchSearchResult executeFetchPhase(ShardSearchRequest request) throws ElasticsearchException {
final SearchContext context = createAndPutContext(request);
contextProcessing(context);
try {
context.indexShard().searchService().onPreQueryPhase(context);
long time = System.nanoTime();
try {
queryPhase.execute(context);
} catch (Throwable e) {
context.indexShard().searchService().onFailedQueryPhase(context);
throw ExceptionsHelper.convertToRuntime(e);
}
long time2 = System.nanoTime();
context.indexShard().searchService().onQueryPhase(context, time2 - time);
context.indexShard().searchService().onPreFetchPhase(context);
try {
shortcutDocIdsToLoad(context);
fetchPhase.execute(context);
if (context.scroll() == null) {
freeContext(context.id());
} else {
contextProcessedSuccessfully(context);
}
} catch (Throwable e) {
context.indexShard().searchService().onFailedFetchPhase(context);
throw ExceptionsHelper.convertToRuntime(e);
}
context.indexShard().searchService().onFetchPhase(context, System.nanoTime() - time2);
return new QueryFetchSearchResult(context.queryResult(), context.fetchResult());
} catch (Throwable e) {
logger.trace("Fetch phase failed", e);
freeContext(context.id());
throw ExceptionsHelper.convertToRuntime(e);
} finally {
cleanContext(context);
}
}
public QueryFetchSearchResult executeFetchPhase(QuerySearchRequest request) throws ElasticsearchException {
final SearchContext context = findContext(request.id());
contextProcessing(context);
try {
context.searcher().dfSource(new CachedDfSource(context.searcher().getIndexReader(), request.dfs(), context.similarityService().similarity()));
} catch (Throwable e) {
freeContext(context.id());
cleanContext(context);
throw new QueryPhaseExecutionException(context, "Failed to set aggregated df", e);
}
try {
context.indexShard().searchService().onPreQueryPhase(context);
long time = System.nanoTime();
try {
queryPhase.execute(context);
} catch (Throwable e) {
context.indexShard().searchService().onFailedQueryPhase(context);
throw ExceptionsHelper.convertToRuntime(e);
}
long time2 = System.nanoTime();
context.indexShard().searchService().onQueryPhase(context, time2 - time);
context.indexShard().searchService().onPreFetchPhase(context);
try {
shortcutDocIdsToLoad(context);
fetchPhase.execute(context);
if (context.scroll() == null) {
freeContext(request.id());
} else {
contextProcessedSuccessfully(context);
}
} catch (Throwable e) {
context.indexShard().searchService().onFailedFetchPhase(context);
throw ExceptionsHelper.convertToRuntime(e);
}
context.indexShard().searchService().onFetchPhase(context, System.nanoTime() - time2);
return new QueryFetchSearchResult(context.queryResult(), context.fetchResult());
} catch (Throwable e) {
logger.trace("Fetch phase failed", e);
freeContext(context.id());
throw ExceptionsHelper.convertToRuntime(e);
} finally {
cleanContext(context);
}
}
public ScrollQueryFetchSearchResult executeFetchPhase(InternalScrollSearchRequest request) throws ElasticsearchException {
final SearchContext context = findContext(request.id());
contextProcessing(context);
try {
processScroll(request, context);
context.indexShard().searchService().onPreQueryPhase(context);
long time = System.nanoTime();
try {
queryPhase.execute(context);
} catch (Throwable e) {
context.indexShard().searchService().onFailedQueryPhase(context);
throw ExceptionsHelper.convertToRuntime(e);
}
long time2 = System.nanoTime();
context.indexShard().searchService().onQueryPhase(context, time2 - time);
context.indexShard().searchService().onPreFetchPhase(context);
try {
shortcutDocIdsToLoad(context);
fetchPhase.execute(context);
if (context.scroll() == null) {
freeContext(request.id());
} else {
contextProcessedSuccessfully(context);
}
} catch (Throwable e) {
context.indexShard().searchService().onFailedFetchPhase(context);
throw ExceptionsHelper.convertToRuntime(e);
}
context.indexShard().searchService().onFetchPhase(context, System.nanoTime() - time2);
return new ScrollQueryFetchSearchResult(new QueryFetchSearchResult(context.queryResult(), context.fetchResult()), context.shardTarget());
} catch (Throwable e) {
logger.trace("Fetch phase failed", e);
freeContext(context.id());
throw ExceptionsHelper.convertToRuntime(e);
} finally {
cleanContext(context);
}
}
public FetchSearchResult executeFetchPhase(ShardFetchRequest request) throws ElasticsearchException {
final SearchContext context = findContext(request.id());
contextProcessing(context);
try {
if (request.lastEmittedDoc() != null) {
context.lastEmittedDoc(request.lastEmittedDoc());
}
context.docIdsToLoad(request.docIds(), 0, request.docIdsSize());
context.indexShard().searchService().onPreFetchPhase(context);
long time = System.nanoTime();
fetchPhase.execute(context);
if (context.scroll() == null) {
freeContext(request.id());
} else {
contextProcessedSuccessfully(context);
}
context.indexShard().searchService().onFetchPhase(context, System.nanoTime() - time);
return context.fetchResult();
} catch (Throwable e) {
context.indexShard().searchService().onFailedFetchPhase(context);
logger.trace("Fetch phase failed", e);
freeContext(context.id()); // we just try to make sure this is freed - rethrow orig exception.
throw ExceptionsHelper.convertToRuntime(e);
} finally {
cleanContext(context);
}
}
private SearchContext findContext(long id) throws SearchContextMissingException {
SearchContext context = activeContexts.get(id);
if (context == null) {
throw new SearchContextMissingException(id);
}
SearchContext.setCurrent(context);
return context;
}
final SearchContext createAndPutContext(ShardSearchRequest request) throws ElasticsearchException {
SearchContext context = createContext(request, null);
boolean success = false;
try {
activeContexts.put(context.id(), context);
context.indexShard().searchService().onNewContext(context);
success = true;
return context;
} finally {
if (!success) {
freeContext(context.id());
}
}
}
final SearchContext createContext(ShardSearchRequest request, @Nullable Engine.Searcher searcher) throws ElasticsearchException {
IndexService indexService = indicesService.indexServiceSafe(request.index());
IndexShard indexShard = indexService.shardSafe(request.shardId());
SearchShardTarget shardTarget = new SearchShardTarget(clusterService.localNode().id(), request.index(), request.shardId());
Engine.Searcher engineSearcher = searcher == null ? indexShard.acquireSearcher("search") : searcher;
SearchContext context = new DefaultSearchContext(idGenerator.incrementAndGet(), request, shardTarget, engineSearcher, indexService, indexShard, scriptService, pageCacheRecycler, bigArrays, threadPool.estimatedTimeInMillisCounter());
SearchContext.setCurrent(context);
try {
context.scroll(request.scroll());
context.useSlowScroll(request.useSlowScroll());
parseTemplate(request);
parseSource(context, request.source());
parseSource(context, request.extraSource());
// if the from and size are still not set, default them
if (context.from() == -1) {
context.from(0);
}
if (context.size() == -1) {
context.size(10);
}
// pre process
dfsPhase.preProcess(context);
queryPhase.preProcess(context);
fetchPhase.preProcess(context);
// compute the context keep alive
long keepAlive = defaultKeepAlive;
if (request.scroll() != null && request.scroll().keepAlive() != null) {
keepAlive = request.scroll().keepAlive().millis();
}
context.keepAlive(keepAlive);
} catch (Throwable e) {
context.close();
throw ExceptionsHelper.convertToRuntime(e);
}
return context;
}
public boolean freeContext(long id) {
final SearchContext context = activeContexts.remove(id);
if (context != null) {
try {
context.indexShard().searchService().onFreeContext(context);
} finally {
context.close();
}
return true;
}
return false;
}
public void freeAllScrollContexts() {
for (SearchContext searchContext : activeContexts.values()) {
if (searchContext.scroll() != null) {
freeContext(searchContext.id());
}
}
}
private void contextProcessing(SearchContext context) {
// disable timeout while executing a search
context.accessed(-1);
}
private void contextProcessedSuccessfully(SearchContext context) {
context.accessed(threadPool.estimatedTimeInMillis());
}
private void cleanContext(SearchContext context) {
assert context == SearchContext.current();
context.clearReleasables(Lifetime.PHASE);
SearchContext.removeCurrent();
}
private void parseTemplate(ShardSearchRequest request) {
final ExecutableScript executable;
if (hasLength(request.templateName())) {
executable = this.scriptService.executable("mustache", request.templateName(), request.templateType(), request.templateParams());
} else {
if (!hasLength(request.templateSource())) {
return;
}
XContentParser parser = null;
TemplateQueryParser.TemplateContext templateContext = null;
try {
parser = XContentFactory.xContent(request.templateSource()).createParser(request.templateSource());
templateContext = TemplateQueryParser.parse(parser, "params", "template");
if (templateContext.scriptType().equals(ScriptService.ScriptType.INLINE)) {
//Try to double parse for nested template id/file
parser = null;
try {
byte[] templateBytes = templateContext.template().getBytes(Charsets.UTF_8);
parser = XContentFactory.xContent(templateBytes).createParser(templateBytes);
} catch (ElasticsearchParseException epe) {
//This was an non-nested template, the parse failure was due to this, it is safe to assume this refers to a file
//for backwards compatibility and keep going
templateContext = new TemplateQueryParser.TemplateContext(ScriptService.ScriptType.FILE, templateContext.template(), templateContext.params());
}
if (parser != null) {
TemplateQueryParser.TemplateContext innerContext = TemplateQueryParser.parse(parser, "params");
if (hasLength(innerContext.template()) && !innerContext.scriptType().equals(ScriptService.ScriptType.INLINE)) {
//An inner template referring to a filename or id
templateContext = new TemplateQueryParser.TemplateContext(innerContext.scriptType(), innerContext.template(), templateContext.params());
}
}
}
} catch (IOException e) {
throw new ElasticsearchParseException("Failed to parse template", e);
} finally {
Releasables.closeWhileHandlingException(parser);
}
if (templateContext == null || !hasLength(templateContext.template())) {
throw new ElasticsearchParseException("Template must have [template] field configured");
}
executable = this.scriptService.executable("mustache", templateContext.template(), templateContext.scriptType(), templateContext.params());
}
BytesReference processedQuery = (BytesReference) executable.run();
request.source(processedQuery);
}
private void parseSource(SearchContext context, BytesReference source) throws SearchParseException {
// nothing to parse...
if (source == null || source.length() == 0) {
return;
}
XContentParser parser = null;
try {
parser = XContentFactory.xContent(source).createParser(source);
XContentParser.Token token;
token = parser.nextToken();
if (token != XContentParser.Token.START_OBJECT) {
throw new ElasticsearchParseException("Expected START_OBJECT but got " + token.name() + " " + parser.currentName());
}
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
String fieldName = parser.currentName();
parser.nextToken();
SearchParseElement element = elementParsers.get(fieldName);
if (element == null) {
throw new SearchParseException(context, "No parser for element [" + fieldName + "]");
}
element.parse(parser, context);
} else {
if (token == null) {
throw new ElasticsearchParseException("End of query source reached but query is not complete.");
} else {
throw new ElasticsearchParseException("Expected field name but got " + token.name() + " \"" + parser.currentName() + "\"");
}
}
}
} catch (Throwable e) {
String sSource = "_na_";
try {
sSource = XContentHelper.convertToJson(source, false);
} catch (Throwable e1) {
// ignore
}
throw new SearchParseException(context, "Failed to parse source [" + sSource + "]", e);
} finally {
if (parser != null) {
parser.close();
}
}
}
private static final int[] EMPTY_DOC_IDS = new int[0];
/**
* Shortcut ids to load, we load only "from" and up to "size". The phase controller
* handles this as well since the result is always size * shards for Q_A_F
*/
private void shortcutDocIdsToLoad(SearchContext context) {
if (!context.useSlowScroll() && context.request().scroll() != null) {
TopDocs topDocs = context.queryResult().topDocs();
int[] docIdsToLoad = new int[topDocs.scoreDocs.length];
for (int i = 0; i < topDocs.scoreDocs.length; i++) {
docIdsToLoad[i] = topDocs.scoreDocs[i].doc;
}
context.docIdsToLoad(docIdsToLoad, 0, docIdsToLoad.length);
} else {
TopDocs topDocs = context.queryResult().topDocs();
if (topDocs.scoreDocs.length < context.from()) {
// no more docs...
context.docIdsToLoad(EMPTY_DOC_IDS, 0, 0);
return;
}
int totalSize = context.from() + context.size();
int[] docIdsToLoad = new int[Math.min(topDocs.scoreDocs.length - context.from(), context.size())];
int counter = 0;
for (int i = context.from(); i < totalSize; i++) {
if (i < topDocs.scoreDocs.length) {
docIdsToLoad[counter] = topDocs.scoreDocs[i].doc;
} else {
break;
}
counter++;
}
context.docIdsToLoad(docIdsToLoad, 0, counter);
}
}
private void shortcutDocIdsToLoadForScanning(SearchContext context) {
TopDocs topDocs = context.queryResult().topDocs();
if (topDocs.scoreDocs.length == 0) {
// no more docs...
context.docIdsToLoad(EMPTY_DOC_IDS, 0, 0);
return;
}
int[] docIdsToLoad = new int[topDocs.scoreDocs.length];
for (int i = 0; i < docIdsToLoad.length; i++) {
docIdsToLoad[i] = topDocs.scoreDocs[i].doc;
}
context.docIdsToLoad(docIdsToLoad, 0, docIdsToLoad.length);
}
private void processScroll(InternalScrollSearchRequest request, SearchContext context) {
// process scroll
context.from(context.from() + context.size());
context.scroll(request.scroll());
// update the context keep alive based on the new scroll value
if (request.scroll() != null && request.scroll().keepAlive() != null) {
context.keepAlive(request.scroll().keepAlive().millis());
}
}
static class NormsWarmer extends IndicesWarmer.Listener {
@Override
public TerminationHandle warmNewReaders(final IndexShard indexShard, IndexMetaData indexMetaData, final WarmerContext context, ThreadPool threadPool) {
final Loading defaultLoading = Loading.parse(indexMetaData.settings().get(NORMS_LOADING_KEY), Loading.LAZY);
final MapperService mapperService = indexShard.mapperService();
final ObjectSet<String> warmUp = new ObjectOpenHashSet<>();
for (DocumentMapper docMapper : mapperService.docMappers(false)) {
for (FieldMapper<?> fieldMapper : docMapper.mappers()) {
final String indexName = fieldMapper.names().indexName();
if (fieldMapper.fieldType().indexed() && !fieldMapper.fieldType().omitNorms() && fieldMapper.normsLoading(defaultLoading) == Loading.EAGER) {
warmUp.add(indexName);
}
}
}
final CountDownLatch latch = new CountDownLatch(1);
// Norms loading may be I/O intensive but is not CPU intensive, so we execute it in a single task
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
try {
for (Iterator<ObjectCursor<String>> it = warmUp.iterator(); it.hasNext(); ) {
final String indexName = it.next().value;
final long start = System.nanoTime();
for (final AtomicReaderContext ctx : context.searcher().reader().leaves()) {
final NumericDocValues values = ctx.reader().getNormValues(indexName);
if (values != null) {
values.get(0);
}
}
if (indexShard.warmerService().logger().isTraceEnabled()) {
indexShard.warmerService().logger().trace("warmed norms for [{}], took [{}]", indexName, TimeValue.timeValueNanos(System.nanoTime() - start));
}
}
} catch (Throwable t) {
indexShard.warmerService().logger().warn("failed to warm-up norms", t);
} finally {
latch.countDown();
}
}
});
return new TerminationHandle() {
@Override
public void awaitTermination() throws InterruptedException {
latch.await();
}
};
}
@Override
public TerminationHandle warmTopReader(IndexShard indexShard, IndexMetaData indexMetaData, WarmerContext context, ThreadPool threadPool) {
return TerminationHandle.NO_WAIT;
}
}
static class FieldDataWarmer extends IndicesWarmer.Listener {
@Override
public TerminationHandle warmNewReaders(final IndexShard indexShard, IndexMetaData indexMetaData, final WarmerContext context, ThreadPool threadPool) {
final MapperService mapperService = indexShard.mapperService();
final Map<String, FieldMapper<?>> warmUp = new HashMap<>();
for (DocumentMapper docMapper : mapperService.docMappers(false)) {
for (FieldMapper<?> fieldMapper : docMapper.mappers()) {
final FieldDataType fieldDataType = fieldMapper.fieldDataType();
if (fieldDataType == null) {
continue;
}
if (fieldDataType.getLoading() == Loading.LAZY) {
continue;
}
final String indexName = fieldMapper.names().indexName();
if (warmUp.containsKey(indexName)) {
continue;
}
warmUp.put(indexName, fieldMapper);
}
}
final IndexFieldDataService indexFieldDataService = indexShard.indexFieldDataService();
final Executor executor = threadPool.executor(executor());
final CountDownLatch latch = new CountDownLatch(context.searcher().reader().leaves().size() * warmUp.size());
for (final AtomicReaderContext ctx : context.searcher().reader().leaves()) {
for (final FieldMapper<?> fieldMapper : warmUp.values()) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
final long start = System.nanoTime();
indexFieldDataService.getForField(fieldMapper).load(ctx);
if (indexShard.warmerService().logger().isTraceEnabled()) {
indexShard.warmerService().logger().trace("warmed fielddata for [{}], took [{}]", fieldMapper.names().name(), TimeValue.timeValueNanos(System.nanoTime() - start));
}
} catch (Throwable t) {
indexShard.warmerService().logger().warn("failed to warm-up fielddata for [{}]", t, fieldMapper.names().name());
} finally {
latch.countDown();
}
}
});
}
}
return new TerminationHandle() {
@Override
public void awaitTermination() throws InterruptedException {
latch.await();
}
};
}
@Override
public TerminationHandle warmTopReader(final IndexShard indexShard, IndexMetaData indexMetaData, final WarmerContext context, ThreadPool threadPool) {
final MapperService mapperService = indexShard.mapperService();
final Map<String, FieldMapper<?>> warmUpGlobalOrdinals = new HashMap<>();
for (DocumentMapper docMapper : mapperService.docMappers(false)) {
for (FieldMapper<?> fieldMapper : docMapper.mappers()) {
final FieldDataType fieldDataType = fieldMapper.fieldDataType();
if (fieldDataType == null) {
continue;
}
if (fieldDataType.getLoading() != Loading.EAGER_GLOBAL_ORDINALS) {
continue;
}
final String indexName = fieldMapper.names().indexName();
if (warmUpGlobalOrdinals.containsKey(indexName)) {
continue;
}
warmUpGlobalOrdinals.put(indexName, fieldMapper);
}
}
final IndexFieldDataService indexFieldDataService = indexShard.indexFieldDataService();
final Executor executor = threadPool.executor(executor());
final CountDownLatch latch = new CountDownLatch(warmUpGlobalOrdinals.size());
for (final FieldMapper<?> fieldMapper : warmUpGlobalOrdinals.values()) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
final long start = System.nanoTime();
IndexFieldData.Global ifd = indexFieldDataService.getForField(fieldMapper);
ifd.loadGlobal(context.reader());
if (indexShard.warmerService().logger().isTraceEnabled()) {
indexShard.warmerService().logger().trace("warmed global ordinals for [{}], took [{}]", fieldMapper.names().name(), TimeValue.timeValueNanos(System.nanoTime() - start));
}
} catch (Throwable t) {
indexShard.warmerService().logger().warn("failed to warm-up global ordinals for [{}]", t, fieldMapper.names().name());
} finally {
latch.countDown();
}
}
});
}
return new TerminationHandle() {
@Override
public void awaitTermination() throws InterruptedException {
latch.await();
}
};
}
}
class SearchWarmer extends IndicesWarmer.Listener {
@Override
public TerminationHandle warmNewReaders(IndexShard indexShard, IndexMetaData indexMetaData, WarmerContext context, ThreadPool threadPool) {
return internalWarm(indexShard, indexMetaData, context, threadPool, false);
}
@Override
public TerminationHandle warmTopReader(IndexShard indexShard, IndexMetaData indexMetaData, WarmerContext context, ThreadPool threadPool) {
return internalWarm(indexShard, indexMetaData, context, threadPool, true);
}
public TerminationHandle internalWarm(final IndexShard indexShard, final IndexMetaData indexMetaData, final IndicesWarmer.WarmerContext warmerContext, ThreadPool threadPool, final boolean top) {
IndexWarmersMetaData custom = indexMetaData.custom(IndexWarmersMetaData.TYPE);
if (custom == null) {
return TerminationHandle.NO_WAIT;
}
final Executor executor = threadPool.executor(executor());
final CountDownLatch latch = new CountDownLatch(custom.entries().size());
for (final IndexWarmersMetaData.Entry entry : custom.entries()) {
executor.execute(new Runnable() {
@Override
public void run() {
SearchContext context = null;
try {
long now = System.nanoTime();
ShardSearchRequest request = new ShardSearchRequest(indexShard.shardId().index().name(), indexShard.shardId().id(), indexMetaData.numberOfShards(),
SearchType.QUERY_THEN_FETCH)
.source(entry.source())
.types(entry.types())
.queryCache(entry.queryCache());
context = createContext(request, warmerContext.searcher());
// if we use sort, we need to do query to sort on it and load relevant field data
// if not, we might as well use COUNT (and cache if needed)
if (context.sort() == null) {
context.searchType(SearchType.COUNT);
}
boolean canCache = indicesQueryCache.canCache(request, context);
// early terminate when we can cache, since we can only do proper caching on top level searcher
// also, if we can't cache, and its top, we don't need to execute it, since we already did when its not top
if (canCache != top) {
return;
}
if (canCache) {
indicesQueryCache.load(request, context, queryPhase);
} else {
queryPhase.execute(context);
}
long took = System.nanoTime() - now;
if (indexShard.warmerService().logger().isTraceEnabled()) {
indexShard.warmerService().logger().trace("warmed [{}], took [{}]", entry.name(), TimeValue.timeValueNanos(took));
}
} catch (Throwable t) {
indexShard.warmerService().logger().warn("warmer [{}] failed", t, entry.name());
} finally {
try {
if (context != null) {
freeContext(context.id());
cleanContext(context);
}
} finally {
latch.countDown();
}
}
}
});
}
return new TerminationHandle() {
@Override
public void awaitTermination() throws InterruptedException {
latch.await();
}
};
}
}
class Reaper implements Runnable {
@Override
public void run() {
final long time = threadPool.estimatedTimeInMillis();
for (SearchContext context : activeContexts.values()) {
// Use the same value for both checks since lastAccessTime can
// be modified by another thread between checks!
final long lastAccessTime = context.lastAccessTime();
if (lastAccessTime == -1l) { // its being processed or timeout is disabled
continue;
}
if ((time - lastAccessTime > context.keepAlive())) {
logger.debug("freeing search context [{}], time [{}], lastAccessTime [{}], keepAlive [{}]", context.id(), time, lastAccessTime, context.keepAlive());
freeContext(context.id());
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.