answer
stringlengths 17
10.2M
|
|---|
package org.jboss.as.server.deployment;
/**
* An enumeration of the phases of a deployment unit's processing cycle.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public enum Phase {
/* == TEMPLATE ==
* Upon entry, this phase performs the following actions:
* <ul>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
/**
* This phase creates the initial root structure. Depending on the service for this phase will ensure that the
* deployment unit's initial root structure is available and accessible.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The primary deployment root is mounted (during {@link #STRUCTURE_MOUNT})</li>
* <li>Other internal deployment roots are mounted (during {@link #STRUCTURE_NESTED_JAR})</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments:
* <ul>
* <li>{@link Attachments#DEPLOYMENT_ROOT} - the mounted deployment root for this deployment unit</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* </ul>
* <p>
*/
STRUCTURE(null),
/**
* This phase assembles information from the root structure to prepare for adding and processing additional external
* structure, such as from class path entries and other similar mechanisms.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The root content's MANIFEST is read and made available during {@link #PARSE_MANIFEST}.</li>
* <li>The annotation index for the root structure is calculated during {@link #STRUCTURE_ANNOTATION_INDEX}.</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#MANIFEST} - the parsed manifest of the root structure</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#CLASS_PATH_ENTRIES} - class path entries found in the manifest and elsewhere.</li>
* <li>{@link Attachments#EXTENSION_LIST_ENTRIES} - extension-list entries found in the manifest and elsewhere.</li>
* </ul>
* <p>
*/
PARSE(null),
/**
* In this phase, the full structure of the deployment unit is made available and module dependencies may be assembled.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>Any additional external structure is mounted during {@link #XXX}</li>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
DEPENDENCIES(null),
CONFIGURE_MODULE(null),
POST_MODULE(null),
INSTALL(null),
CLEANUP(null),
;
/**
* This is the key for the attachment to use as the phase's "value". The attachment is taken from
* the deployment unit. If a phase doesn't have a single defining "value", {@code null} is specified.
*/
private final AttachmentKey<?> phaseKey;
private Phase(final AttachmentKey<?> key) {
phaseKey = key;
}
/**
* Get the next phase, or {@code null} if none.
*
* @return the next phase, or {@code null} if there is none
*/
public Phase next() {
final int ord = ordinal() + 1;
final Phase[] phases = Phase.values();
return ord == phases.length ? null : phases[ord];
}
/**
* Get the attachment key of the {@code DeploymentUnit} attachment that represents the result value
* of this phase.
*
* @return the key
*/
public AttachmentKey<?> getPhaseKey() {
return phaseKey;
}
// STRUCTURE
public static final int STRUCTURE_MOUNT = 0x0000;
public static final int STRUCTURE_MANIFEST = 0x0100;
// must be before osgi
public static final int STRUCTURE_JDBC_DRIVER = 0x0150;
public static final int STRUCTURE_OSGI_MANIFEST = 0x0200;
public static final int STRUCTURE_RAR = 0x0300;
public static final int STRUCTURE_WAR_DEPLOYMENT_INIT = 0x0400;
public static final int STRUCTURE_WAR = 0x0500;
public static final int STRUCTURE_EAR_DEPLOYMENT_INIT = 0x0600;
public static final int STRUCTURE_EAR_APP_XML_PARSE = 0x0700;
public static final int STRUCTURE_EAR_JBOSS_APP_XML_PARSE = 0x0800;
public static final int STRUCTURE_EAR = 0x0900;
public static final int STRUCTURE_SERVICE_MODULE_LOADER = 0x0A00;
public static final int STRUCTURE_ANNOTATION_INDEX = 0x0B00;
public static final int STRUCTURE_EJB_JAR_IN_EAR = 0x0C00;
public static final int STRUCTURE_MANAGED_BEAN_JAR_IN_EAR = 0x0C01;
public static final int STRUCTURE_SAR_SUB_DEPLOY_CHECK = 0x0D00;
public static final int STRUCTURE_ADDITIONAL_MANIFEST = 0x0E00;
public static final int STRUCTURE_SUB_DEPLOYMENT = 0x0F00;
public static final int STRUCTURE_MODULE_IDENTIFIERS = 0x1000;
public static final int STRUCTURE_EE_MODULE_INIT = 0x1100;
// PARSE
public static final int PARSE_EE_MODULE_NAME = 0x0100;
public static final int PARSE_STRUCTURE_DESCRIPTOR = 0x0200;
public static final int PARSE_COMPOSITE_ANNOTATION_INDEX = 0x0300;
public static final int PARSE_EAR_LIB_CLASS_PATH = 0x0400;
public static final int PARSE_ADDITIONAL_MODULES = 0x0500;
public static final int PARSE_CLASS_PATH = 0x0600;
public static final int PARSE_EXTENSION_LIST = 0x0700;
public static final int PARSE_EXTENSION_NAME = 0x0800;
public static final int PARSE_OSGI_BUNDLE_INFO = 0x0900;
public static final int PARSE_OSGI_PROPERTIES = 0x0A00;
public static final int PARSE_WEB_DEPLOYMENT = 0x0B00;
public static final int PARSE_WEB_DEPLOYMENT_FRAGMENT = 0x0C00;
public static final int PARSE_ANNOTATION_WAR = 0x0D00;
public static final int PARSE_JBOSS_WEB_DEPLOYMENT = 0x0E00;
public static final int PARSE_TLD_DEPLOYMENT = 0x0F00;
public static final int PARSE_EAR_CONTEXT_ROOT = 0x1000;
// create and attach EJB metadata for EJB deployments
public static final int PARSE_EJB_DEPLOYMENT = 0x1100;
public static final int PARSE_EJB_CREATE_COMPONENT_DESCRIPTIONS = 0x1150;
public static final int PARSE_EJB_SESSION_BEAN_DD = 0x1200;
public static final int PARSE_EJB_MDB_DD = 0x1300;
// create and attach the component description out of EJB annotations
public static final int PARSE_EJB_ANNOTATION = 0x1400;
public static final int PARSE_MESSAGE_DRIVEN_ANNOTATION = 0x1500;
public static final int PARSE_EJB_TRANSACTION_MANAGEMENT = 0x1600;
public static final int PARSE_EJB_BUSINESS_VIEW_ANNOTATION = 0x1700;
public static final int PARSE_EJB_STARTUP_ANNOTATION = 0x1800;
public static final int PARSE_EJB_CONCURRENCY_MANAGEMENT_ANNOTATION = 0x1900;
public static final int PARSE_EJB_APPLICATION_EXCEPTION_ANNOTATION = 0x1901;
public static final int PARSE_REMOVE_METHOD_ANNOTAION = 0x1902;
// should be after ConcurrencyManagement annotation processor
public static final int PARSE_EJB_LOCK_ANNOTATION = 0x1A00;
// should be after ConcurrencyManagement annotation processor
public static final int PARSE_EJB_ACCESS_TIMEOUT_ANNOTATION = 0x1B00;
// should be after all views are known
public static final int PARSE_EJB_TRANSACTION_ATTR_ANNOTATION = 0x1C00;
public static final int PARSE_EJB_SESSION_SYNCHRONIZATION = 0x1C50;
public static final int PARSE_EJB_RESOURCE_ADAPTER_ANNOTATION = 0x1D00;
public static final int PARSE_EJB_ASYNCHRONOUS_ANNOTATION = 0x1E00;
public static final int PARSE_WEB_COMPONENTS = 0x1F00;
public static final int PARSE_WEB_MERGE_METADATA = 0x2000;
public static final int PARSE_RA_DEPLOYMENT = 0x2100;
public static final int PARSE_SERVICE_LOADER_DEPLOYMENT = 0x2200;
public static final int PARSE_SERVICE_DEPLOYMENT = 0x2300;
public static final int PARSE_MC_BEAN_DEPLOYMENT = 0x2400;
public static final int PARSE_IRON_JACAMAR_DEPLOYMENT = 0x2500;
public static final int PARSE_RESOURCE_ADAPTERS = 0x2600;
public static final int PARSE_DATA_SOURCES = 0x2700;
public static final int PARSE_ARQUILLIAN_RUNWITH = 0x2800;
public static final int PARSE_MANAGED_BEAN_ANNOTATION = 0x2900;
public static final int PARSE_JAXRS_ANNOTATIONS = 0x2A00;
public static final int PARSE_WELD_DEPLOYMENT = 0x2B00;
public static final int PARSE_WELD_WEB_INTEGRATION = 0x2B10;
public static final int PARSE_WEBSERVICES_XML = 0x2C00;
public static final int PARSE_DATA_SOURCE_DEFINITION = 0x2D00;
public static final int PARSE_EJB_CONTEXT_BINDING = 0x2E00;
public static final int PARSE_EJB_TIMERSERVICE_BINDING = 0x2E01;
public static final int PARSE_PERSISTENCE_UNIT = 0x2F00;
public static final int PARSE_PERSISTENCE_ANNOTATION = 0x3000;
public static final int PARSE_INTERCEPTORS_ANNOTATION = 0x3100;
public static final int PARSE_LIEFCYCLE_ANNOTATION = 0x3200;
public static final int PARSE_AROUNDINVOKE_ANNOTATION = 0x3300;
public static final int PARSE_RESOURCE_INJECTION_WEBSERVICE_CONTEXT_ANNOTATION = 0x3401;
public static final int PARSE_EJB_DD_INTERCEPTORS = 0x3500;
public static final int PARSE_EJB_ASSEMBLY_DESC_DD = 0x3600;
// should be after all components are known
public static final int PARSE_EJB_INJECTION_ANNOTATION = 0x3700;
public static final int PARSE_WEB_SERVICE_INJECTION_ANNOTATION = 0x3800;
// DEPENDENCIES
public static final int DEPENDENCIES_EJB = 0x0000;
public static final int DEPENDENCIES_MODULE = 0x0100;
public static final int DEPENDENCIES_DS = 0x0200;
public static final int DEPENDENCIES_RAR_CONFIG = 0x0300;
public static final int DEPENDENCIES_MANAGED_BEAN = 0x0400;
public static final int DEPENDENCIES_SAR_MODULE = 0x0500;
public static final int DEPENDENCIES_WAR_MODULE = 0x0600;
public static final int DEPENDENCIES_ARQUILLIAN = 0x0700;
public static final int DEPENDENCIES_CLASS_PATH = 0x0800;
public static final int DEPENDENCIES_EXTENSION_LIST = 0x0900;
public static final int DEPENDENCIES_WELD = 0x0A00;
public static final int DEPENDENCIES_SEAM = 0x0A01;
public static final int DEPENDENCIES_NAMING = 0x0B00;
public static final int DEPENDENCIES_WS = 0x0C00;
public static final int DEPENDENCIES_JAXRS = 0x0D00;
public static final int DEPENDENCIES_SUB_DEPLOYMENTS = 0x0E00;
// Sets up appropriate module dependencies for EJB deployments
public static final int DEPENDENCIES_JPA = 0x1000;
public static final int DEPENDENCIES_GLOBAL_MODULES = 0x1100;
// CONFIGURE_MODULE
public static final int CONFIGURE_MODULE_SPEC = 0x0100;
// POST_MODULE
public static final int POST_MODULE_INJECTION_ANNOTATION = 0x0100;
public static final int POST_MODULE_REFLECTION_INDEX = 0x0200;
public static final int POST_MODULE_JSF_MANAGED_BEANS = 0x0300;
public static final int POST_MODULE_EJB_DD_METHOD_RESOLUTION = 0x0400;
public static final int POST_MODULE_EJB_DD_REMOVE_METHOD = 0x0500;
public static final int POST_MODULE_EJB_DD_INTERCEPTORS = 0x0600;
public static final int POST_MODULE_WELD_EJB_INTERCEPTORS_INTEGRATION = 0x0700;
public static final int POST_MODULE_WELD_COMPONENT_INTEGRATION = 0x0800;
public static final int POST_MODULE_AGGREGATE_COMPONENT_INDEX = 0x0900;
public static final int POST_MODULE_INSTALL_EXTENSION = 0x0A00;
public static final int POST_MODULE_VALIDATOR_FACTORY = 0x0B00;
public static final int POST_MODULE_EAR_DEPENDENCY = 0x0C00;
public static final int POST_MODULE_WELD_BEAN_ARCHIVE = 0x0D00;
public static final int POST_MODULE_WELD_PORTABLE_EXTENSIONS = 0x0E00;
public static final int POST_MODULE_WS_EJB_INTEGRATION = 0x0F00;
// should come before ejb jndi bindings processor
public static final int POST_MODULE_EJB_IMPLICIT_NO_INTERFACE_VIEW = 0x1000;
public static final int POST_MODULE_EJB_JNDI_BINDINGS = 0x1100;
public static final int POST_MODULE_EJB_MODULE_CONFIGURATION = 0x1200;
public static final int POST_INITIALIZE_IN_ORDER = 0x1300;
// INSTALL
public static final int INSTALL_JAXRS_SCANNING = 0x0200;
public static final int INSTALL_APP_CONTEXT = 0x0300;
public static final int INSTALL_MODULE_CONTEXT = 0x0400;
public static final int INSTALL_SERVICE_ACTIVATOR = 0x0500;
public static final int INSTALL_OSGI_DEPLOYMENT = 0x0600;
public static final int INSTALL_WAR_METADATA = 0x0700; //this needs to be removed, however WSDeploymentActivator still uses it
public static final int INSTALL_RA_DEPLOYMENT = 0x0800;
public static final int INSTALL_SERVICE_DEPLOYMENT = 0x0900;
public static final int INSTALL_MC_BEAN_DEPLOYMENT = 0x0A00;
public static final int INSTALL_RA_XML_DEPLOYMENT = 0x0B00;
public static final int INSTALL_EE_COMP_LAZY_BINDING_SOURCE_HANDLER = 0x0C00;
public static final int INSTALL_WS_LAZY_BINDING_SOURCE_HANDLER = 0x0D00;
public static final int INSTALL_ENV_ENTRY = 0x0E00;
public static final int INSTALL_EJB_REF = 0x0F00;
public static final int INSTALL_PERSISTENCE_REF = 0x1000;
public static final int INSTALL_EE_MODULE_CONFIG = 0x1100;
public static final int INSTALL_MODULE_JNDI_BINDINGS = 0x1200;
public static final int INSTALL_DEPENDS_ON_ANNOTATION = 0x1210;
public static final int INSTALL_EE_COMPONENT = 0x1230;
public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x1300;
public static final int INSTALL_JAXRS_COMPONENT = 0x1400;
public static final int INSTALL_JAXRS_DEPLOYMENT = 0x1500;
public static final int INSTALL_JSF_ANNOTATIONS = 0x1600;
public static final int INSTALL_ARQUILLIAN_DEPLOYMENT = 0x1700;
public static final int INSTALL_JDBC_DRIVER = 0x1800;
public static final int INSTALL_TRANSACTION_BINDINGS = 0x1900;
public static final int INSTALL_PERSISTENCE_PROVIDER = 0x1A00;
public static final int INSTALL_PERSISTENTUNIT = 0x1A50;
public static final int INSTALL_WELD_DEPLOYMENT = 0x1B00;
public static final int INSTALL_WELD_BEAN_MANAGER = 0x1C00;
public static final int INSTALL_WAR_DEPLOYMENT = 0x1D00;
// CLEANUP
public static final int CLEANUP_REFLECTION_INDEX = 0x0100;
}
|
package io.spine.server.entity;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.protobuf.Timestamp;
import io.spine.base.EntityState;
import io.spine.base.Identifier;
import io.spine.base.Time;
import io.spine.core.Version;
import io.spine.core.Versions;
import io.spine.server.entity.model.EntityClass;
import io.spine.testing.ReflectiveBuilder;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import java.lang.reflect.Constructor;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.spine.server.entity.model.EntityClass.asEntityClass;
/**
* Utility class for building entities for tests.
*
* @param <E> the type of the entity to build
* @param <I> the type of the entity identifier
* @param <S> the type of the entity state
*/
@VisibleForTesting
public abstract class EntityBuilder<E extends AbstractEntity<I, S>, I, S extends EntityState>
extends ReflectiveBuilder<E> {
/**
* The class of the entity to build.
*
* <p>Is null until {@link #setResultClass(Class)} is called.
*/
private @MonotonicNonNull EntityClass<E> entityClass;
/** The ID of the entity. If not set, a value default to the type will be used. */
private @MonotonicNonNull I id;
/** The entity state. If not set, a default instance will be used. */
private @MonotonicNonNull S state;
/** The entity version. Or zero if not set. */
private int version;
/** The entity timestamp or {@code null} if not set. */
private @MonotonicNonNull Timestamp whenModified;
/**
* Creates new instance of the builder.
*/
protected EntityBuilder() {
super();
// Have the constructor for finding usages easier.
}
@CanIgnoreReturnValue
@Override
public EntityBuilder<E, I, S> setResultClass(Class<E> entityClass) {
super.setResultClass(entityClass);
this.entityClass = modelClassOf(entityClass);
return this;
}
protected EntityClass<E> modelClassOf(Class<E> entityClass) {
return asEntityClass(entityClass);
}
public EntityBuilder<E, I, S> withId(I id) {
this.id = checkNotNull(id);
return this;
}
public EntityBuilder<E, I, S> withState(S state) {
this.state = checkNotNull(state);
return this;
}
public EntityBuilder<E, I, S> withVersion(int version) {
this.version = version;
return this;
}
public EntityBuilder<E, I, S> modifiedOn(Timestamp whenModified) {
this.whenModified = checkNotNull(whenModified);
return this;
}
protected EntityClass<E> entityClass() {
checkState(entityClass != null);
return entityClass;
}
/** Returns the class of IDs used by entities. */
@SuppressWarnings("unchecked") // The cast is protected by generic parameters of the builder.
public Class<I> idClass() {
return (Class<I>) entityClass().idClass();
}
private I createDefaultId() {
return Identifier.defaultValue(idClass());
}
@Override
public E build() {
I id = id();
E result = createEntity(id);
S state = state();
Timestamp timestamp = timestamp();
Version version = Versions.newVersion(this.version, timestamp);
setState(result, state, version);
return result;
}
protected abstract void setState(E result, S state, Version version);
/**
* Returns ID if it was previously set or default value if it was not.
*/
protected I id() {
return this.id != null
? this.id
: createDefaultId();
}
/**
* Returns state if it was set or the default value if it was not.
*/
protected S state() {
if (state != null) {
return state;
}
checkNotNull(entityClass, "Entity class is not set");
@SuppressWarnings("unchecked") // The cast is preserved by generic params of this class.
S result = (S) entityClass.defaultState();
return result;
}
/**
* Returns timestamp if it was set or the default value if it was not.
*/
protected Timestamp timestamp() {
return this.whenModified != null
? this.whenModified
: Time.currentTime();
}
@Override
protected Constructor<E> constructor() {
Constructor<E> constructor = entityClass().constructor();
constructor.setAccessible(true);
return constructor;
}
/**
* Creates an empty entity instance.
*/
protected E createEntity(I id) {
E result = entityClass().create(id);
return result;
}
}
|
package io.spine.server.event;
import com.google.common.collect.ImmutableSet;
import com.google.protobuf.Int32Value;
import com.google.protobuf.Message;
import io.spine.core.Event;
import io.spine.core.EventClass;
import io.spine.core.EventContext;
import io.spine.core.EventEnvelope;
import io.spine.core.EventId;
import io.spine.core.Events;
import io.spine.core.Subscribe;
import io.spine.server.BoundedContext;
import io.spine.server.bus.EnvelopeValidator;
import io.spine.server.delivery.Consumers;
import io.spine.server.event.given.EventBusTestEnv.GivenEvent;
import io.spine.server.storage.StorageFactory;
import io.spine.server.storage.memory.InMemoryStorageFactory;
import io.spine.test.event.ProjectCreated;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Deque;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import static com.google.common.collect.Lists.newLinkedList;
import static com.google.common.collect.Maps.newHashMap;
import static io.spine.protobuf.AnyPacker.pack;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
public class EventBusShould {
private EventBus eventBus;
private EventBus eventBusWithPosponedExecution;
private PostponedDispatcherEventDelivery postponedDispatcherDelivery;
private Executor delegateDispatcherExecutor;
private StorageFactory storageFactory;
@Before
public void setUp() {
setUp(null);
}
private void setUp(@Nullable EventEnricher enricher) {
final BoundedContext bc = BoundedContext.newBuilder()
.setMultitenant(true)
.build();
this.storageFactory = bc.getStorageFactory();
/**
* Cannot use {@link com.google.common.util.concurrent.MoreExecutors#directExecutor()
* MoreExecutors.directExecutor()} because it's impossible to spy on {@code final} classes.
*/
this.delegateDispatcherExecutor = spy(directExecutor());
this.postponedDispatcherDelivery =
new PostponedDispatcherEventDelivery(delegateDispatcherExecutor);
buildEventBus(enricher);
buildEventBusWithPostponedExecution(enricher);
}
@SuppressWarnings("MethodMayBeStatic") /* it cannot, as its result is used in {@code org.mockito.Mockito.spy() */
private Executor directExecutor() {
return new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
};
}
private void buildEventBusWithPostponedExecution(@Nullable EventEnricher enricher) {
final EventBus.Builder busBuilder =
EventBus.newBuilder()
.setStorageFactory(storageFactory)
.setDispatcherEventDelivery(postponedDispatcherDelivery);
if (enricher != null) {
busBuilder.setEnricher(enricher);
}
this.eventBusWithPosponedExecution = busBuilder.build();
}
private void buildEventBus(@Nullable EventEnricher enricher) {
final EventBus.Builder busBuilder = EventBus.newBuilder()
.setStorageFactory(storageFactory);
if (enricher != null) {
busBuilder.setEnricher(enricher);
}
this.eventBus = busBuilder.build();
}
@Test
public void have_builder() {
assertNotNull(EventBus.newBuilder());
}
@Test
public void return_associated_EventStore() {
final EventStore eventStore = mock(EventStore.class);
final EventBus result = EventBus.newBuilder()
.setEventStore(eventStore)
.build();
assertEquals(eventStore, result.getEventStore());
}
@Test(expected = IllegalArgumentException.class)
public void reject_object_with_no_subscriber_methods() {
// Pass just String instance.
eventBus.register(new EventSubscriber() {
});
}
@Test
public void produce_new_object_on_each_call_to_createFilterChain() {
final Deque<?> oldChain = eventBus.createFilterChain();
final Deque<?> newChain = eventBus.createFilterChain();
// Use LinkedList wrapping to ensure `equals()` implementation.
assertEquals(newLinkedList(oldChain), newLinkedList(newChain));
assertNotSame(oldChain, newChain);
}
@Test
public void register_event_subscriber() {
final EventSubscriber subscriberOne = new ProjectCreatedSubscriber();
final EventSubscriber subscriberTwo = new ProjectCreatedSubscriber();
eventBus.register(subscriberOne);
eventBus.register(subscriberTwo);
final EventClass eventClass = EventClass.of(ProjectCreated.class);
assertTrue(eventBus.hasDispatchers(eventClass));
final Collection<? extends EventDispatcher<?>> dispatchers =
eventBus.getDispatchers(eventClass);
assertTrue(dispatchers.contains(subscriberOne));
assertTrue(dispatchers.contains(subscriberTwo));
}
@Test
public void unregister_subscribers() {
final EventSubscriber subscriberOne = new ProjectCreatedSubscriber();
final EventSubscriber subscriberTwo = new ProjectCreatedSubscriber();
eventBus.register(subscriberOne);
eventBus.register(subscriberTwo);
final EventClass eventClass = EventClass.of(ProjectCreated.class);
eventBus.unregister(subscriberOne);
// Check that the 2nd subscriber with the same event subscriber method remains
// after the 1st subscriber unregisters.
final Collection<? extends EventDispatcher<?>> subscribers =
eventBus.getDispatchers(eventClass);
assertFalse(subscribers.contains(subscriberOne));
assertTrue(subscribers.contains(subscriberTwo));
// Check that after 2nd subscriber us unregisters he's no longer in
eventBus.unregister(subscriberTwo);
assertFalse(eventBus.getDispatchers(eventClass)
.contains(subscriberTwo));
}
@Test
public void call_subscriber_when_event_posted() {
final ProjectCreatedSubscriber subscriber = new ProjectCreatedSubscriber();
final Event event = GivenEvent.projectCreated();
eventBus.register(subscriber);
eventBus.post(event);
// Exclude event ID from comparison.
assertEquals(Events.getMessage(event), subscriber.getEventMessage());
assertEquals(event.getContext(), subscriber.getEventContext());
}
@Test
public void register_dispatchers() {
final EventDispatcher dispatcher = new BareDispatcher();
eventBus.register(dispatcher);
assertTrue(eventBus.getDispatchers(EventClass.of(ProjectCreated.class))
.contains(dispatcher));
}
@Test
public void call_dispatchers() {
final BareDispatcher dispatcher = new BareDispatcher();
eventBus.register(dispatcher);
eventBus.post(GivenEvent.projectCreated());
assertTrue(dispatcher.isDispatchCalled());
}
@Test
public void return_direct_DispatcherDelivery_if_none_customized() {
final DispatcherEventDelivery actual = eventBus.delivery();
assertTrue(actual instanceof DispatcherEventDelivery.DirectDelivery);
}
@Test
public void not_call_dispatchers_if_dispatcher_event_execution_postponed() {
final BareDispatcher dispatcher = new BareDispatcher();
eventBusWithPosponedExecution.register(dispatcher);
final Event event = GivenEvent.projectCreated();
eventBusWithPosponedExecution.post(event);
assertFalse(dispatcher.isDispatchCalled());
final boolean eventPostponed = postponedDispatcherDelivery.isPostponed(event, dispatcher);
assertTrue(eventPostponed);
}
@Test
public void deliver_postponed_event_to_dispatcher_using_configured_executor() {
final BareDispatcher dispatcher = new BareDispatcher();
eventBusWithPosponedExecution.register(dispatcher);
final Event event = GivenEvent.projectCreated();
eventBusWithPosponedExecution.post(event);
final Set<EventEnvelope> postponedEvents = postponedDispatcherDelivery.getPostponedEvents();
final EventEnvelope postponedEvent = postponedEvents.iterator()
.next();
verify(delegateDispatcherExecutor, never()).execute(any(Runnable.class));
postponedDispatcherDelivery.deliverNow(postponedEvent, Consumers.idOf(dispatcher));
assertTrue(dispatcher.isDispatchCalled());
verify(delegateDispatcherExecutor).execute(any(Runnable.class));
}
@Test
public void pick_proper_consumer_by_consumer_id_when_delivering_to_delegates_of_same_event() {
final FirstProjectCreatedDelegate first = new FirstProjectCreatedDelegate();
final AnotherProjectCreatedDelegate second = new AnotherProjectCreatedDelegate();
final DelegatingEventDispatcher<String> firstDispatcher =
DelegatingEventDispatcher.of(first);
final DelegatingEventDispatcher<String> secondDispatcher =
DelegatingEventDispatcher.of(second);
eventBusWithPosponedExecution.register(firstDispatcher);
eventBusWithPosponedExecution.register(secondDispatcher);
final Event event = GivenEvent.projectCreated();
eventBusWithPosponedExecution.post(event);
final Set<EventEnvelope> postponedEvents = postponedDispatcherDelivery.getPostponedEvents();
final EventEnvelope postponedEvent = postponedEvents.iterator()
.next();
verify(delegateDispatcherExecutor, never()).execute(any(Runnable.class));
postponedDispatcherDelivery.deliverNow(postponedEvent, Consumers.idOf(firstDispatcher));
assertTrue(first.isDispatchCalled());
verify(delegateDispatcherExecutor).execute(any(Runnable.class));
assertFalse(second.isDispatchCalled());
}
@Test
public void unregister_dispatchers() {
final EventDispatcher dispatcherOne = new BareDispatcher();
final EventDispatcher dispatcherTwo = new BareDispatcher();
final EventClass eventClass = EventClass.of(ProjectCreated.class);
eventBus.register(dispatcherOne);
eventBus.register(dispatcherTwo);
eventBus.unregister(dispatcherOne);
final Set<? extends EventDispatcher<?>> dispatchers = eventBus.getDispatchers(eventClass);
// Check we don't have 1st dispatcher, but have 2nd.
assertFalse(dispatchers.contains(dispatcherOne));
assertTrue(dispatchers.contains(dispatcherTwo));
eventBus.unregister(dispatcherTwo);
assertFalse(eventBus.getDispatchers(eventClass)
.contains(dispatcherTwo));
}
@Test
public void unregister_registries_on_close() throws Exception {
final EventStore eventStore = spy(mock(EventStore.class));
final EventBus eventBus = EventBus.newBuilder()
.setEventStore(eventStore)
.build();
eventBus.register(new BareDispatcher());
eventBus.register(new ProjectCreatedSubscriber());
final EventClass eventClass = EventClass.of(ProjectCreated.class);
eventBus.close();
assertTrue(eventBus.getDispatchers(eventClass)
.isEmpty());
verify(eventStore).close();
}
@Test
public void enrich_event_if_it_can_be_enriched() {
final EventEnricher enricher = mock(EventEnricher.class);
final EventEnvelope event = EventEnvelope.of(GivenEvent.projectCreated());
doReturn(true).when(enricher)
.canBeEnriched(any(EventEnvelope.class));
doReturn(event).when(enricher)
.enrich(any(EventEnvelope.class));
setUp(enricher);
eventBus.register(new ProjectCreatedSubscriber());
eventBus.post(event.getOuterObject());
verify(enricher).enrich(any(EventEnvelope.class));
}
@Test
public void do_not_enrich_event_if_it_cannot_be_enriched() {
final EventEnricher enricher = mock(EventEnricher.class);
doReturn(false).when(enricher)
.canBeEnriched(any(EventEnvelope.class));
setUp(enricher);
eventBus.register(new ProjectCreatedSubscriber());
eventBus.post(GivenEvent.projectCreated());
verify(enricher, never()).enrich(any(EventEnvelope.class));
}
@Test
public void create_validator_once() {
final EnvelopeValidator<EventEnvelope> validator = eventBus.getValidator();
assertNotNull(validator);
assertSame(validator, eventBus.getValidator());
}
@SuppressWarnings("MethodWithMultipleLoops") // OK for such test case.
@Ignore // This test is used only to diagnose EventBus malfunctions in concurrent environment.
// It's too long to execute this test per each build, so we leave it as is for now.
// Please see build log to find out if there were some errors during the test execution.
@Test
public void store_filters_regarding_possible_concurrent_modifications() throws InterruptedException {
final Thread[] threads = new Thread[50];
// "Random" more or less valid Event.
final Event event = Event.newBuilder()
.setId(EventId.newBuilder().setValue("123-1"))
.setMessage(pack(Int32Value.newBuilder()
.setValue(42)
.build()))
.build();
// Catch not-easily reproducible bugs.
for (int i = 0; i < 300; i++) {
final EventBus eventBus = EventBus.newBuilder()
.setStorageFactory(
InMemoryStorageFactory.newInstance("main",
false))
.build();
for (int j = 0; j < threads.length; j++) {
threads[j] = new Thread(new Runnable() {
@Override
public void run() {
eventBus.post(event);
}
});
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
// Let the system destroy all the native threads, clean up, etc.
Thread.sleep(100);
}
}
private static class ProjectCreatedSubscriber extends EventSubscriber {
private Message eventMessage;
private EventContext eventContext;
@Subscribe
public void on(ProjectCreated eventMsg, EventContext context) {
this.eventMessage = eventMsg;
this.eventContext = context;
}
public Message getEventMessage() {
return eventMessage;
}
public EventContext getEventContext() {
return eventContext;
}
}
/**
* A simple dispatcher class, which only dispatch and does not have own event
* subscribing methods.
*/
private static class BareDispatcher implements EventDispatcher<String> {
private boolean dispatchCalled = false;
@Override
public Set<EventClass> getMessageClasses() {
return ImmutableSet.of(EventClass.of(ProjectCreated.class));
}
@Override
public Set<String> dispatch(EventEnvelope event) {
dispatchCalled = true;
return Identity.of(this);
}
@Override
public void onError(EventEnvelope envelope, RuntimeException exception) {
// Do nothing.
}
private boolean isDispatchCalled() {
return dispatchCalled;
}
}
private static class PostponedDispatcherEventDelivery extends DispatcherEventDelivery {
private final Map<EventEnvelope,
Class<? extends EventDispatcher>> postponedExecutions = newHashMap();
private PostponedDispatcherEventDelivery(Executor delegate) {
super(delegate);
}
@Override
public boolean shouldPostponeDelivery(EventEnvelope event, EventDispatcher consumer) {
postponedExecutions.put(event, consumer.getClass());
return true;
}
private boolean isPostponed(Event event, EventDispatcher dispatcher) {
final EventEnvelope envelope = EventEnvelope.of(event);
final Class<? extends EventDispatcher> actualClass = postponedExecutions.get(envelope);
final boolean eventPostponed = actualClass != null;
final boolean dispatcherMatches = eventPostponed && dispatcher.getClass()
.equals(actualClass);
return dispatcherMatches;
}
private Set<EventEnvelope> getPostponedEvents() {
final Set<EventEnvelope> envelopes = postponedExecutions.keySet();
return envelopes;
}
}
/**
* A delegate, dispatching {@link ProjectCreated} events.
*/
private static class FirstProjectCreatedDelegate implements EventDispatcherDelegate<String> {
private boolean dispatchCalled = false;
@Override
public Set<EventClass> getEventClasses() {
return ImmutableSet.of(EventClass.of(ProjectCreated.class));
}
@Override
public Set<String> dispatchEvent(EventEnvelope envelope) {
dispatchCalled = true;
return ImmutableSet.of(toString());
}
@Override
public void onError(EventEnvelope envelope, RuntimeException exception) {
// Do nothing.
}
private boolean isDispatchCalled() {
return dispatchCalled;
}
}
/**
* Another delegate, dispatching {@link ProjectCreated} events.
*/
private static class AnotherProjectCreatedDelegate implements EventDispatcherDelegate<String> {
private boolean dispatchCalled = false;
@Override
public Set<EventClass> getEventClasses() {
return ImmutableSet.of(EventClass.of(ProjectCreated.class));
}
@Override
public Set<String> dispatchEvent(EventEnvelope envelope) {
dispatchCalled = true;
return ImmutableSet.of(toString());
}
@Override
public void onError(EventEnvelope envelope, RuntimeException exception) {
// Do nothing.
}
private boolean isDispatchCalled() {
return dispatchCalled;
}
}
}
|
package io.spine.server.model;
import com.google.common.collect.ImmutableSetMultimap;
import io.spine.server.event.model.SubscriberMethod;
import io.spine.server.event.model.SubscriberSignature;
import io.spine.server.model.given.map.ARejectionSubscriber;
import io.spine.server.model.given.map.FilteredSubscription;
import io.spine.string.StringifierRegistry;
import io.spine.string.Stringifiers;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static com.google.common.truth.Truth.assertThat;
import static io.spine.server.model.MethodScan.findMethodsBy;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DisplayName("`MethodScan` should")
class MethodScanTest {
/**
* Registers the stringifier for {@code Integer}, which is used for parsing filter field values.
*/
@BeforeAll
static void prepare() {
StringifierRegistry.instance()
.register(Stringifiers.forInteger(), Integer.TYPE);
}
@Test
@DisplayName("provide a map with filter-less keys")
void noFiltersInKeys() {
ImmutableSetMultimap<DispatchKey, SubscriberMethod> map =
findMethodsBy(FilteredSubscription.class, new SubscriberSignature());
map.keySet()
.forEach(key -> assertEquals(key.withoutFilter(), key));
}
@Test
@DisplayName("allow multiple rejection subscription methods with same names")
void multipleRejectionSubscriptions() {
ImmutableSetMultimap<DispatchKey, SubscriberMethod> map =
findMethodsBy(ARejectionSubscriber.class, new SubscriberSignature());
assertThat(map.keys()).hasSize(2);
}
}
|
package org.slc.sli.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.slc.sli.security.SLIPrincipal;
/**
* Class, which allows user to access security context
* @author svankina
*
*/
public class SecurityUtil {
private static Logger logger = LoggerFactory.getLogger(SecurityUtil.class);
public static UserDetails getPrincipal() {
return (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
public static String getToken() {
UserDetails user = getPrincipal();
logger.info("******** User.getUsername: " + user.getUsername());
if (user instanceof SLIPrincipal) {
logger.info("******** User.getId: " + ((SLIPrincipal) user).getId());
return ((SLIPrincipal) user).getId();
} else {
// gets here in mock server mode
return user.getUsername();
}
}
}
|
package org.umlg.sqlg.structure;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tinkerpop.gremlin.process.T;
import com.tinkerpop.gremlin.process.computer.GraphComputer;
import com.tinkerpop.gremlin.process.graph.GraphTraversal;
import com.tinkerpop.gremlin.process.graph.step.sideEffect.StartStep;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Graph;
import com.tinkerpop.gremlin.structure.Vertex;
import com.tinkerpop.gremlin.structure.util.ElementHelper;
import com.tinkerpop.gremlin.structure.util.FeatureDescriptor;
import com.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.umlg.sqlg.sql.dialect.SqlDialect;
import java.lang.reflect.Constructor;
import java.sql.*;
import java.util.*;
@Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_PERFORMANCE)
@Graph.OptIn(Graph.OptIn.SUITE_STRUCTURE_STANDARD)
@Graph.OptIn(Graph.OptIn.SUITE_PROCESS_STANDARD)
public class SqlgGraph implements Graph, Graph.Iterators {
private Logger logger = LoggerFactory.getLogger(SqlgGraph.class.getName());
private final SqlgTransaction sqlgTransaction;
private SchemaManager schemaManager;
private SqlDialect sqlDialect;
private String jdbcUrl;
private ObjectMapper mapper = new ObjectMapper();
private boolean implementForeignKeys;
private Configuration configuration = new BaseConfiguration();
public static <G extends Graph> G open(final Configuration configuration) {
if (null == configuration) throw Graph.Exceptions.argumentCanNotBeNull("configuration");
if (!configuration.containsKey("jdbc.url"))
throw new IllegalArgumentException(String.format("SqlgGraph configuration requires that the %s be set", "jdbc.url"));
return (G) new SqlgGraph(configuration);
}
public static <G extends Graph> G open(final String pathToSqlgProperties) {
if (null == pathToSqlgProperties) throw Graph.Exceptions.argumentCanNotBeNull("pathToSqlgProperties");
Configuration configuration;
try {
configuration = new PropertiesConfiguration(pathToSqlgProperties);
} catch (ConfigurationException e) {
throw new RuntimeException(e);
}
return open(configuration);
}
private SqlgGraph(final Configuration configuration) {
try {
Class<?> sqlDialectClass = findSqlGDialect();
logger.debug(String.format("Initializing Sqlg with %s dialect", sqlDialectClass.getSimpleName()));
Constructor<?> constructor = sqlDialectClass.getConstructor(Configuration.class);
this.sqlDialect = (SqlDialect) constructor.newInstance(configuration);
this.implementForeignKeys = configuration.getBoolean("implementForeignKeys", true);
this.configuration = configuration;
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
this.jdbcUrl = configuration.getString("jdbc.url");
SqlgDataSource.INSTANCE.setupDataSource(
sqlDialect.getJdbcDriver(),
configuration.getString("jdbc.url"),
configuration.getString("jdbc.username"),
configuration.getString("jdbc.password"));
this.sqlDialect.prepareDB(SqlgDataSource.INSTANCE.get(configuration.getString("jdbc.url")).getConnection());
} catch (Exception e) {
throw new RuntimeException(e);
}
this.sqlgTransaction = new SqlgTransaction(this);
this.tx().readWrite();
this.schemaManager = new SchemaManager(this, sqlDialect, configuration);
this.schemaManager.loadSchema();
if (!this.sqlDialect.supportSchemas() && !this.schemaManager.schemaExist(this.sqlDialect.getPublicSchema())) {
//This is for mariadb. Need to make sure a db called public exist
this.schemaManager.createSchema(this.sqlDialect.getPublicSchema());
}
this.schemaManager.ensureGlobalVerticesTableExist();
this.schemaManager.ensureGlobalEdgesTableExist();
this.tx().commit();
}
Configuration getConfiguration() {
return configuration;
}
public String getJdbcUrl() {
return jdbcUrl;
}
public SchemaManager getSchemaManager() {
return schemaManager;
}
public SqlDialect getSqlDialect() {
return sqlDialect;
}
@Override
public Iterators iterators() {
return this;
}
@Override
public Configuration configuration() {
return this.configuration;
}
public Vertex addVertex(String label, Map<String, Object> keyValues) {
Map<Object, Object> tmp = new HashMap<>(keyValues);
tmp.put(T.label, label);
return addVertex(SqlgUtil.mapTokeyValues(tmp));
}
@Override
public Vertex addVertex(Object... keyValues) {
ElementHelper.legalPropertyKeyValueArray(keyValues);
if (ElementHelper.getIdValue(keyValues).isPresent())
throw Vertex.Exceptions.userSuppliedIdsNotSupported();
int i = 0;
Object key = null;
Object value;
for (Object keyValue : keyValues) {
if (i++ % 2 == 0) {
key = keyValue;
} else {
value = keyValue;
if (!key.equals(T.label)) {
ElementHelper.validateProperty((String) key, value);
this.sqlDialect.validateProperty(key, value);
}
}
}
final String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL);
SchemaTable schemaTablePair = SqlgUtil.parseLabel(label, this.getSqlDialect().getPublicSchema());
this.tx().readWrite();
this.schemaManager.ensureVertexTableExist(schemaTablePair.getSchema(), schemaTablePair.getTable(), keyValues);
final SqlgVertex vertex = new SqlgVertex(this, schemaTablePair.getSchema(), schemaTablePair.getTable(), keyValues);
return vertex;
}
@Override
public GraphTraversal<Vertex, Vertex> V(final Object... vertexIds) {
this.tx().readWrite();
final SqlgGraphTraversal traversal = new SqlgGraphTraversal<Object, Vertex>();
traversal.addStep(new SqlgGraphStep(traversal, Vertex.class, this, vertexIds));
traversal.sideEffects().setGraph(this);
return traversal;
}
@Override
public GraphTraversal<Edge, Edge> E(final Object... edgeIds) {
this.tx().readWrite();
final SqlgGraphTraversal traversal = new SqlgGraphTraversal<Object, Vertex>();
traversal.addStep(new SqlgGraphStep(traversal, Edge.class, this, edgeIds));
traversal.sideEffects().setGraph(this);
return traversal;
}
@Override
public Iterator<Vertex> vertexIterator(final Object... vertexIds) {
this.tx().readWrite();
return _vertices(vertexIds).iterator();
}
@Override
public Iterator<Edge> edgeIterator(final Object... edgeIds) {
this.tx().readWrite();
return _edges(edgeIds).iterator();
}
@Override
public <S> GraphTraversal<S, S> of() {
final SqlgGraphTraversal traversal = new SqlgGraphTraversal<Object, Vertex>();
traversal.addStep(new StartStep<>(traversal));
traversal.sideEffects().setGraph(this);
return traversal;
}
public Vertex v(final Object id) {
GraphTraversal<Vertex, Vertex> t = this.V(id);
return t.hasNext() ? t.next() : null;
}
public Edge e(final Object id) {
GraphTraversal<Edge, Edge> t = this.E(id);
return t.hasNext() ? t.next() : null;
}
@Override
public GraphComputer compute(final Class... graphComputerClass) {
throw Graph.Exceptions.graphComputerNotSupported();
}
@Override
public SqlgTransaction tx() {
return this.sqlgTransaction;
}
@Override
public Variables variables() {
throw Graph.Exceptions.variablesNotSupported();
}
@Override
public void close() throws Exception {
if (this.tx().isOpen())
this.tx().close();
this.schemaManager.close();
SqlgDataSource.INSTANCE.close(this.getJdbcUrl());
}
public String toString() {
return StringFactory.graphString(this, "SqlGraph");
}
public ISqlGFeatures features() {
return new SqlGFeatures();
}
public interface ISqlGFeatures extends Features {
boolean supportsBatchMode();
}
public class SqlGFeatures implements ISqlGFeatures {
@Override
public GraphFeatures graph() {
return new GraphFeatures() {
@Override
public boolean supportsComputer() {
return false;
}
@Override
public VariableFeatures variables() {
return new SqlVariableFeatures();
}
@Override
public boolean supportsThreadedTransactions() {
return false;
}
};
}
@Override
public VertexFeatures vertex() {
return new SqlVertexFeatures();
}
@Override
public EdgeFeatures edge() {
return new SqlEdgeFeatures();
}
@Override
public String toString() {
return StringFactory.featureString(this);
}
@Override
public boolean supportsBatchMode() {
return getSqlDialect().supportsBatchMode();
}
public class SqlVertexFeatures implements VertexFeatures {
/**
* Determines if a {@link Vertex} can support multiple properties with the same key.
*/
@FeatureDescriptor(name = FEATURE_MULTI_PROPERTIES)
public boolean supportsMultiProperties() {
return false;
}
/**
* Determines if a {@link Vertex} can support properties on vertex properties. It is assumed that a
* graph will support all the same data types for meta-properties that are supported for regular
* properties.
*/
@FeatureDescriptor(name = FEATURE_META_PROPERTIES)
public boolean supportsMetaProperties() {
return false;
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public VertexPropertyFeatures properties() {
return new SqlGVertexPropertyFeatures();
}
}
public class SqlEdgeFeatures implements EdgeFeatures {
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public EdgePropertyFeatures properties() {
return new SqlEdgePropertyFeatures();
}
}
public class SqlGVertexPropertyFeatures implements VertexPropertyFeatures {
@Override
public boolean supportsMapValues() {
return false;
}
@Override
public boolean supportsMixedListValues() {
return false;
}
@Override
public boolean supportsSerializableValues() {
return false;
}
@Override
public boolean supportsUniformListValues() {
return false;
}
@Override
public boolean supportsByteValues() {
return false;
}
@Override
public boolean supportsFloatValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsFloatValues();
}
@Override
public boolean supportsBooleanArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsBooleanArrayValues();
}
@Override
public boolean supportsByteArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsByteArrayValues();
}
@Override
public boolean supportsDoubleArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsDoubleArrayValues();
}
@Override
public boolean supportsFloatArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsFloatArrayValues();
}
@Override
public boolean supportsIntegerArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsIntegerArrayValues();
}
@Override
public boolean supportsLongArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsLongArrayValues();
}
@Override
public boolean supportsStringArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsStringArrayValues();
}
}
public class SqlEdgePropertyFeatures implements EdgePropertyFeatures {
@Override
public boolean supportsMapValues() {
return false;
}
@Override
public boolean supportsMixedListValues() {
return false;
}
@Override
public boolean supportsSerializableValues() {
return false;
}
@Override
public boolean supportsUniformListValues() {
return false;
}
@Override
public boolean supportsByteValues() {
return false;
}
@Override
public boolean supportsFloatValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsFloatValues();
}
@Override
public boolean supportsBooleanArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsBooleanArrayValues();
}
@Override
public boolean supportsByteArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsByteArrayValues();
}
@Override
public boolean supportsDoubleArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsDoubleArrayValues();
}
@Override
public boolean supportsFloatArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsFloatArrayValues();
}
@Override
public boolean supportsIntegerArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsIntegerArrayValues();
}
@Override
public boolean supportsLongArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsLongArrayValues();
}
@Override
public boolean supportsStringArrayValues() {
return SqlgGraph.this.getSchemaManager().getSqlDialect().supportsStringArrayValues();
}
}
public class SqlVariableFeatures implements VariableFeatures {
@Override
public boolean supportsBooleanValues() {
return false;
}
@Override
public boolean supportsDoubleValues() {
return false;
}
@Override
public boolean supportsFloatValues() {
return false;
}
@Override
public boolean supportsIntegerValues() {
return false;
}
@Override
public boolean supportsLongValues() {
return false;
}
@Override
public boolean supportsMapValues() {
return false;
}
@Override
public boolean supportsMixedListValues() {
return false;
}
@Override
public boolean supportsByteValues() {
return false;
}
@Override
public boolean supportsBooleanArrayValues() {
return false;
}
@Override
public boolean supportsByteArrayValues() {
return false;
}
@Override
public boolean supportsDoubleArrayValues() {
return false;
}
@Override
public boolean supportsFloatArrayValues() {
return false;
}
@Override
public boolean supportsIntegerArrayValues() {
return false;
}
@Override
public boolean supportsLongArrayValues() {
return false;
}
@Override
public boolean supportsStringArrayValues() {
return false;
}
@Override
public boolean supportsSerializableValues() {
return false;
}
@Override
public boolean supportsStringValues() {
return false;
}
@Override
public boolean supportsUniformListValues() {
return false;
}
}
}
/**
* This is executes a sql query and returns the result as a json string.
*
* @param query The sql to execute.
* @return The query result as json.
*/
public String query(String query) {
try {
Connection conn = this.tx().getConnection();
ObjectNode result = this.mapper.createObjectNode();
ArrayNode dataNode = this.mapper.createArrayNode();
ArrayNode metaNode = this.mapper.createArrayNode();
Statement statement = conn.createStatement();
if (logger.isDebugEnabled()) {
logger.debug(query);
}
ResultSet rs = statement.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
boolean first = true;
while (rs.next()) {
int numColumns = rsmd.getColumnCount();
ObjectNode obj = this.mapper.createObjectNode();
for (int i = 1; i < numColumns + 1; i++) {
String columnName = rsmd.getColumnName(i);
Object o = rs.getObject(columnName);
int type = rsmd.getColumnType(i);
this.sqlDialect.putJsonObject(obj, columnName, type, o);
if (first) {
this.sqlDialect.putJsonMetaObject(this.mapper, metaNode, columnName, type, o);
}
}
first = false;
dataNode.add(obj);
}
result.put("data", dataNode);
result.put("meta", metaNode);
return result.toString();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
this.tx().rollback();
}
}
/**
* Executes a the given sql sql and returns the result as vertices.
* @param sql The sql to execute.
* @return A List of Vertex
*/
public List<Vertex> vertexQuery(String sql) {
List<Vertex> sqlgVertices = new ArrayList<>();
try {
Connection conn = this.tx().getConnection();
Statement statement = conn.createStatement();
sql = this.sqlDialect.wrapVertexQuery(sql);
if (logger.isDebugEnabled()) {
logger.debug(sql);
}
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
long id = resultSet.getLong("ID");
String schema = resultSet.getString(SchemaManager.VERTEX_SCHEMA);
String table = resultSet.getString(SchemaManager.VERTEX_TABLE);
SqlgVertex sqlgVertex = SqlgVertex.of(this, id, schema, table);
loadVertexAndLabels(sqlgVertices, resultSet, sqlgVertex);
}
return sqlgVertices;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//indexing
public void createUniqueConstraint(String label, String propertyKey) {
this.tx().readWrite();
// this.getSchemaManager().createUniqueConstraint(label, propertyKey);
}
public void createVertexLabeledIndex(String label, Object... dummykeyValues) {
int i = 0;
String key = "";
Object value;
for (Object keyValue : dummykeyValues) {
if (i++ % 2 == 0) {
key = (String) keyValue;
} else {
value = keyValue;
if (!key.equals(T.label)) {
ElementHelper.validateProperty(key, value);
this.sqlDialect.validateProperty(key, value);
}
}
}
this.tx().readWrite();
SchemaTable schemaTablePair = SqlgUtil.parseLabel(label, this.getSqlDialect().getPublicSchema());
this.getSchemaManager().createVertexIndex(schemaTablePair, dummykeyValues);
}
public void createEdgeLabeledIndex(String label, Object... dummykeyValues) {
int i = 0;
String key = "";
Object value;
for (Object keyValue : dummykeyValues) {
if (i++ % 2 == 0) {
key = (String) keyValue;
} else {
value = keyValue;
if (!key.equals(T.label)) {
ElementHelper.validateProperty(key, value);
this.sqlDialect.validateProperty(key, value);
}
}
}
this.tx().readWrite();
SchemaTable schemaTablePair = SqlgUtil.parseLabel(label, this.getSqlDialect().getPublicSchema());
this.getSchemaManager().createEdgeIndex(schemaTablePair, dummykeyValues);
}
public long countVertices() {
this.tx().readWrite();
Connection conn = this.tx().getConnection();
StringBuilder sql = new StringBuilder("select count(1) from ");
sql.append(this.getSqlDialect().maybeWrapInQoutes(this.getSqlDialect().getPublicSchema()));
sql.append(".");
sql.append(this.getSqlDialect().maybeWrapInQoutes(SchemaManager.VERTICES));
if (logger.isDebugEnabled()) {
logger.debug(sql.toString());
}
try (PreparedStatement preparedStatement = conn.prepareStatement(sql.toString())) {
ResultSet rs = preparedStatement.executeQuery();
rs.next();
return rs.getLong(1);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public long countEdges() {
this.tx().readWrite();
Connection conn = this.tx().getConnection();
StringBuilder sql = new StringBuilder("select count(1) from ");
sql.append(this.getSqlDialect().maybeWrapInQoutes(this.getSqlDialect().getPublicSchema()));
sql.append(".");
sql.append(this.getSqlDialect().maybeWrapInQoutes(SchemaManager.EDGES));
if (logger.isDebugEnabled()) {
logger.debug(sql.toString());
}
try (PreparedStatement preparedStatement = conn.prepareStatement(sql.toString())) {
ResultSet rs = preparedStatement.executeQuery();
rs.next();
return rs.getLong(1);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
boolean isImplementForeignKeys() {
return implementForeignKeys;
}
private Class<?> findSqlGDialect() {
try {
return Class.forName("org.umlg.sqlg.sql.dialect.PostgresDialect");
} catch (ClassNotFoundException e) {
}
try {
return Class.forName("org.umlg.sqlg.sql.dialect.MariaDbDialect");
} catch (ClassNotFoundException e) {
}
try {
return Class.forName("org.umlg.sqlg.sql.dialect.HsqldbDialect");
} catch (ClassNotFoundException e) {
}
throw new IllegalStateException("No sqlg dialect found!");
}
private Iterable<Vertex> _vertices(final Object... vertexId) {
List<Vertex> sqlGVertexes = new ArrayList<>();
StringBuilder sql = new StringBuilder("SELECT * FROM ");
sql.append(this.getSqlDialect().maybeWrapInQoutes(this.getSqlDialect().getPublicSchema()));
sql.append(".");
sql.append(this.getSqlDialect().maybeWrapInQoutes(SchemaManager.VERTICES));
boolean hasIds = vertexId.length > 0;
boolean validIdExist = false;
if (hasIds) {
sql.append(" WHERE ");
sql.append(this.sqlDialect.maybeWrapInQoutes("ID"));
sql.append(" IN (");
int count = 1;
for (Object o : vertexId) {
if (!(o instanceof Long)) {
count++;
continue;
}
validIdExist = true;
Long id = (Long) o;
sql.append(id.toString());
if (count++ < vertexId.length) {
sql.append(",");
}
}
sql.append(")");
}
if (!hasIds || (hasIds && validIdExist)) {
if (this.getSqlDialect().needsSemicolon()) {
sql.append(";");
}
Connection conn = this.tx().getConnection();
if (logger.isDebugEnabled()) {
logger.debug(sql.toString());
}
try (Statement statement = conn.createStatement()) {
statement.execute(sql.toString());
ResultSet resultSet = statement.getResultSet();
while (resultSet.next()) {
long id = resultSet.getLong("ID");
String schema = resultSet.getString(SchemaManager.VERTEX_SCHEMA);
String table = resultSet.getString(SchemaManager.VERTEX_TABLE);
SqlgVertex sqlgVertex = SqlgVertex.of(this, id, schema, table);
loadVertexAndLabels(sqlGVertexes, resultSet, sqlgVertex);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
return sqlGVertexes;
}
void loadVertexAndLabels(List<Vertex> sqlGVertexes, ResultSet resultSet, SqlgVertex sqlgVertex) throws SQLException {
Set<SchemaTable> labels = new HashSet<>();
String inCommaSeparatedLabels = resultSet.getString(SchemaManager.VERTEX_IN_LABELS);
this.getSchemaManager().convertVertexLabelToSet(labels, inCommaSeparatedLabels);
sqlgVertex.inLabelsForVertex = new HashSet<>();
sqlgVertex.inLabelsForVertex.addAll(labels);
String outCommaSeparatedLabels = resultSet.getString(SchemaManager.VERTEX_OUT_LABELS);
labels.clear();
this.getSchemaManager().convertVertexLabelToSet(labels, outCommaSeparatedLabels);
sqlgVertex.outLabelsForVertex = new HashSet<>();
sqlgVertex.outLabelsForVertex.addAll(labels);
sqlGVertexes.add(sqlgVertex);
}
private Iterable<Edge> _edges(final Object... edgeIds) {
List<Edge> sqlGEdges = new ArrayList<>();
StringBuilder sql = new StringBuilder("SELECT * FROM ");
sql.append(this.getSqlDialect().maybeWrapInQoutes(this.getSqlDialect().getPublicSchema()));
sql.append(".");
sql.append(this.getSqlDialect().maybeWrapInQoutes(SchemaManager.EDGES));
boolean hasIds = edgeIds.length > 0;
boolean validIdExist = false;
if (hasIds) {
sql.append("WHERE ");
sql.append(this.sqlDialect.maybeWrapInQoutes("ID"));
sql.append(" IN (");
int count = 1;
for (Object o : edgeIds) {
if (!(o instanceof Long)) {
count++;
continue;
}
validIdExist = true;
Long id = (Long) o;
sql.append(id.toString());
if (count++ < edgeIds.length) {
sql.append(",");
}
}
sql.append(")");
}
if (!hasIds || (hasIds && validIdExist)) {
if (this.getSqlDialect().needsSemicolon()) {
sql.append(";");
}
Connection conn = this.tx().getConnection();
if (logger.isDebugEnabled()) {
logger.debug(sql.toString());
}
try (Statement statement = conn.createStatement()) {
statement.execute(sql.toString());
ResultSet resultSet = statement.getResultSet();
while (resultSet.next()) {
long id = resultSet.getLong(1);
String schema = resultSet.getString(2);
String table = resultSet.getString(3);
SchemaTable schemaTablePair = SchemaTable.of(schema, table);
SqlgEdge sqlGEdge = new SqlgEdge(this, id, schemaTablePair.getSchema(), schemaTablePair.getTable());
sqlGEdges.add(sqlGEdge);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
return sqlGEdges;
}
}
|
package com.ForgeEssentials.commands;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import com.ForgeEssentials.commands.util.TickHandlerCommands;
import com.ForgeEssentials.core.PlayerInfo;
import com.ForgeEssentials.core.commands.ForgeEssentialsCommandBase;
import com.ForgeEssentials.permission.APIHelper;
import com.ForgeEssentials.permission.query.PermQueryPlayer;
import com.ForgeEssentials.util.DataStorage;
import com.ForgeEssentials.util.Localization;
import com.ForgeEssentials.util.OutputHandler;
/**
* Kit command with cooldown. Should also put armor in armor slots.
*
* @author Dries007
*/
public class CommandKit extends ForgeEssentialsCommandBase
{
@Override
public String getCommandName()
{
return "kit";
}
@Override
public void processCommandPlayer(EntityPlayer sender, String[] args)
{
NBTTagCompound kitData = DataStorage.getData("kitdata");
/*
* Print kits
*/
if (args.length == 0)
{
sender.sendChatToPlayer(Localization.get(Localization.KIT_LIST));
String msg = "";
for (Object temp : kitData.getTags())
{
NBTTagCompound kit = (NBTTagCompound) temp;
if (APIHelper.checkPermAllowed(new PermQueryPlayer(sender, getCommandPerm() + "." + kit.getName())))
{
msg = kit.getName() + ", " + msg;
}
}
sender.sendChatToPlayer(msg);
return;
}
/*
* Give kit
*/
if (args.length == 1)
{
if (kitData.hasKey(args[0].toLowerCase()))
{
if (APIHelper.checkPermAllowed(new PermQueryPlayer(sender, getCommandPerm() + "." + args[0].toLowerCase())))
{
giveKit(sender, kitData.getCompoundTag(args[0].toLowerCase()));
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_PERMDENIED));
}
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.KIT_NOTEXISTS));
}
return;
}
/*
* Make kit
*/
if (args[1].equalsIgnoreCase("set") && APIHelper.checkPermAllowed(new PermQueryPlayer(sender, getCommandPerm() + ".admin")))
{
if (args.length == 3)
{
if (!kitData.hasKey(args[0].toLowerCase()))
{
int cooldown = parseIntWithMin(sender, args[2], 0);
makeKit(sender, args[0].toLowerCase(), cooldown);
sender.sendChatToPlayer(Localization.get(Localization.KIT_MADE).replaceAll("%c", "" + cooldown));
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.KIT_ALREADYEXISTS));
}
return;
}
}
/*
* Delete kit
*/
if (args[1].equalsIgnoreCase("del") && APIHelper.checkPermAllowed(new PermQueryPlayer(sender, getCommandPerm() + ".admin")))
{
if (args.length == 2)
{
if (kitData.hasKey(args[0].toLowerCase()))
{
kitData.removeTag(args[0].toLowerCase());
sender.sendChatToPlayer(Localization.get(Localization.KIT_REMOVED));
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.KIT_NOTEXISTS));
}
return;
}
}
/*
* You're doing it wrong!
*/
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_BADSYNTAX) + getSyntaxPlayer(sender));
}
public void makeKit(EntityPlayer player, String name, int cooldown)
{
NBTTagCompound kitData = DataStorage.getData("kitdata");
NBTTagCompound kit = new NBTTagCompound(name);
kit.setInteger("cooldown", cooldown);
/*
* Main inv.
*/
NBTTagList items = new NBTTagList();
for (ItemStack stack : player.inventory.mainInventory)
{
if (stack != null)
{
NBTTagCompound item = new NBTTagCompound();
stack.writeToNBT(item);
items.appendTag(item);
}
}
kit.setTag("items", items);
/*
* Armor
*/
for (int i = 0; i < 4; i++)
{
ItemStack stack = player.inventory.armorInventory[i];
if (stack != null)
{
NBTTagCompound item = new NBTTagCompound();
stack.writeToNBT(item);
kit.setCompoundTag("armor" + i, item);
}
}
kitData.setCompoundTag(name, kit);
DataStorage.setData("kitdata", kitData);
}
public void giveKit(EntityPlayer player, NBTTagCompound kit)
{
if (PlayerInfo.getPlayerInfo(player.username).kitCooldown.containsKey(kit.getName()))
{
player.sendChatToPlayer(Localization.get(Localization.KIT_STILLINCOOLDOWN).replaceAll("%c",
"" + PlayerInfo.getPlayerInfo(player.username).kitCooldown.get(kit.getName())));
}
else
{
player.sendChatToPlayer(Localization.get(Localization.KIT_DONE));
if (!APIHelper.checkPermAllowed(new PermQueryPlayer(player, TickHandlerCommands.BYPASS_KIT_COOLDOWN)))
{
PlayerInfo.getPlayerInfo(player.username).kitCooldown.put(kit.getName(), kit.getInteger("cooldown"));
}
/*
* Main inv.
*/
for (int i = 0; kit.getTagList("items").tagCount() > i; i++)
{
ItemStack stack = new ItemStack(0, 0, 0);
stack.readFromNBT((NBTTagCompound) kit.getTagList("items").tagAt(i));
player.inventory.addItemStackToInventory(stack);
}
/*
* Armor
*/
for (int i = 0; i < 4; i++)
{
if (kit.hasKey("armor" + i))
{
ItemStack stack = new ItemStack(0, 0, 0);
stack.readFromNBT(kit.getCompoundTag("armor" + i));
if (player.inventory.armorInventory[i] == null)
{
player.inventory.armorInventory[i] = stack;
}
else
{
player.inventory.addItemStackToInventory(stack);
}
}
}
}
}
@Override
public void processCommandConsole(ICommandSender sender, String[] args)
{
}
@Override
public boolean canConsoleUseCommand()
{
return false;
}
@Override
public String getCommandPerm()
{
return "ForgeEssentials.BasicCommands." + getCommandName();
}
@Override
public List addTabCompletionOptions(ICommandSender sender, String[] args)
{
NBTTagCompound warps = DataStorage.getData("kitdata");
Iterator warpsIt = warps.getTags().iterator();
List<String> list = new ArrayList<String>();
while (warpsIt.hasNext())
{
NBTTagCompound buffer = (NBTTagCompound) warpsIt.next();
list.add(buffer.getName());
}
list.add("set");
list.add("del");
if (args.length == 1)
{
return getListOfStringsFromIterableMatchingLastWord(args, list);
}
else
{
return null;
}
}
}
|
package com.rat.hacker;
import java.net.Socket;
import java.net.ServerSocket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.IOException;
public class Rat {
private boolean isRunning = true;
private int port = 1000;
private Client[] clients = new Client[10];
public Rat() {
Scanner scan = new Scanner(System.in);
System.out.println("Type in some port:");
this.port = scan.nextInt();
try {
createConnection(this.port);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Rat r = new Rat();
}
/*
* Create socket listener.
* @param port
*/
private void createConnection(int port) throws IOException {
if (port < 1000 || port >= 1999) System.err.println("Invalid port.");
ServerSocket server = new ServerSocket(port);
System.out.println("[RAT] Server has started !");
while (isRunning) {
System.out.println("[RAT] Waiting connection ..");
Socket socket = server.accept();
System.out.println("[RAT] New client has connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
for (int i=0; i<clients.length; i++) {
if (clients[i] == null) {
Client c = new Client(this, i, in, out, socket);
c.start();
setClient(i, c);
break;
}
else if (i == clients.length) {
System.err.println("[" + i + "] There're no free slots.");
out.println("There're no free slots.");
out.flush();
socket.close();
break;
}
}
}
}
/*
* @param i
*/
public Client getClient(int i) {
return clients[i];
}
/*
* @param i
* @param c
*/
public void setClient(int i, Client c) {
clients[i] = c;
}
}
|
package com.cocoahero.android.essentials.graphics;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
/**
* This class is a specialized implementation of {@link android.util.LruCache}
* designed for caching {@link Bitmap}s.
*
* Instead of limiting the number of cached objects, it limits based on the
* amount of memory used by the cached bitmaps.
*/
public class BitmapCache extends LruCache<String, Bitmap> {
/**
* Constructs a new {@link BitmapCache} allowing you to specify the maximum
* amount of memory used by the cache.
*
* @param bytes The maximum amount of memory in bytes this cache should use.
*/
public BitmapCache(int bytes) {
super(bytes);
}
/**
* {@inheritDoc android.util.LruCache}
*/
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return (bitmap.getRowBytes() * bitmap.getHeight());
}
/**
* A factory for creating a {@link BitmapCache} based on the application's
* memory class.
*/
public static class BitmapCacheFactory {
/**
* Returns a new {@link BitmapCache} instance configured to use 1/8th of
* the application's memory class.
*
* @param context
* @return a new {@link BitmapCache} instance configured to use 1/8th of
* the application's memory class.
*/
public static BitmapCache getCache(Context context) {
return getCache(context, 0.125f);
}
/**
* Returns a new {@link BitmapCache} instance configured to use the
* specified percentage of the application's memory class.
*
* @param context
* @param percentage A floating value between 1.0f and 0.0f.
* @return a new {@link BitmapCache} instance configured to use the
* given percentage of the application's memory class.
*/
public static BitmapCache getCache(Context context, float percentage) {
ActivityManager mgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
final int memoryClass = mgr.getMemoryClass();
final int cacheSize = (int) (1048576 * memoryClass * percentage);
return new BitmapCache(cacheSize);
}
}
}
|
package com.xtremelabs.robolectric.bytecode;
import android.net.Uri;
import com.xtremelabs.robolectric.internal.DoNotStrip;
import javassist.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings({"UnusedDeclaration"})
public class AndroidTranslator implements Translator {
/**
* IMPORTANT -- increment this number when the bytecode generated for modified classes changes
* so the cache file can be invalidated.
*/
public static final int CACHE_VERSION = 19;
private static final List<ClassHandler> CLASS_HANDLERS = new ArrayList<ClassHandler>();
private ClassHandler classHandler;
private ClassCache classCache;
public AndroidTranslator(ClassHandler classHandler, ClassCache classCache) {
this.classHandler = classHandler;
this.classCache = classCache;
}
public static ClassHandler getClassHandler(int index) {
return CLASS_HANDLERS.get(index);
}
@Override
public void start(ClassPool classPool) throws NotFoundException, CannotCompileException {
injectClassHandlerToInstrumentedClasses(classPool);
}
private void injectClassHandlerToInstrumentedClasses(ClassPool classPool) throws NotFoundException, CannotCompileException {
int index;
synchronized (CLASS_HANDLERS) {
CLASS_HANDLERS.add(classHandler);
index = CLASS_HANDLERS.size() - 1;
}
CtClass robolectricInternalsCtClass = classPool.get(RobolectricInternals.class.getName());
robolectricInternalsCtClass.setModifiers(Modifier.PUBLIC);
robolectricInternalsCtClass.getClassInitializer().insertBefore("{\n" +
"classHandler = " + AndroidTranslator.class.getName() + ".getClassHandler(" + index + ");\n" +
"}");
}
@Override
public void onLoad(ClassPool classPool, String className) throws NotFoundException, CannotCompileException {
if (classCache.isWriting()) {
throw new IllegalStateException("shouldn't be modifying bytecode after we've started writing cache! class=" + className);
}
if (classHasFromAndroidEquivalent(className)) {
replaceClassWithFromAndroidEquivalent(classPool, className);
return;
}
boolean needsStripping =
className.startsWith("android.")
|| className.startsWith("com.google.android.maps")
|| className.equals("org.apache.http.impl.client.DefaultRequestDirector");
CtClass ctClass = classPool.get(className);
if (needsStripping && !ctClass.hasAnnotation(DoNotStrip.class)) {
int modifiers = ctClass.getModifiers();
if (Modifier.isFinal(modifiers)) {
ctClass.setModifiers(modifiers & ~Modifier.FINAL);
}
if (ctClass.isInterface()) return;
classHandler.instrument(ctClass);
fixConstructors(ctClass);
fixMethods(ctClass);
try {
classCache.addClass(className, ctClass.toBytecode());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private boolean classHasFromAndroidEquivalent(String className) {
return className.startsWith(Uri.class.getName());
}
private void replaceClassWithFromAndroidEquivalent(ClassPool classPool, String className) throws NotFoundException {
FromAndroidClassNameParts classNameParts = new FromAndroidClassNameParts(className);
if (classNameParts.isFromAndroid()) return;
String from = classNameParts.getNameWithFromAndroid();
CtClass ctClass = classPool.getAndRename(from, className);
ClassMap map = new ClassMap() {
@Override
public Object get(Object jvmClassName) {
FromAndroidClassNameParts classNameParts = new FromAndroidClassNameParts(jvmClassName.toString());
if (classNameParts.isFromAndroid()) {
return classNameParts.getNameWithoutFromAndroid();
} else {
return jvmClassName;
}
}
};
ctClass.replaceClassName(map);
}
class FromAndroidClassNameParts {
private static final String TOKEN = "__FromAndroid";
private String prefix;
private String suffix;
FromAndroidClassNameParts(String name) {
int dollarIndex = name.indexOf("$");
prefix = name;
suffix = "";
if (dollarIndex > -1) {
prefix = name.substring(0, dollarIndex);
suffix = name.substring(dollarIndex);
}
}
public boolean isFromAndroid() {
return prefix.endsWith(TOKEN);
}
public String getNameWithFromAndroid() {
return prefix + TOKEN + suffix;
}
public String getNameWithoutFromAndroid() {
return prefix.replace(TOKEN, "") + suffix;
}
}
private void addBypassShadowField(CtClass ctClass, String fieldName) {
try {
try {
ctClass.getField(fieldName);
} catch (NotFoundException e) {
CtField field = new CtField(CtClass.booleanType, fieldName, ctClass);
field.setModifiers(java.lang.reflect.Modifier.PUBLIC | java.lang.reflect.Modifier.STATIC);
ctClass.addField(field);
}
} catch (CannotCompileException e) {
throw new RuntimeException(e);
}
}
private void fixConstructors(CtClass ctClass) throws CannotCompileException, NotFoundException {
boolean hasDefault = false;
for (CtConstructor ctConstructor : ctClass.getConstructors()) {
try {
fixConstructor(ctClass, hasDefault, ctConstructor);
if (ctConstructor.getParameterTypes().length == 0) {
hasDefault = true;
}
} catch (Exception e) {
throw new RuntimeException("problem instrumenting " + ctConstructor, e);
}
}
if (!hasDefault) {
String methodBody = generateConstructorBody(ctClass, new CtClass[0]);
ctClass.addConstructor(CtNewConstructor.make(new CtClass[0], new CtClass[0], "{\n" + methodBody + "}\n", ctClass));
}
}
private boolean fixConstructor(CtClass ctClass, boolean needsDefault, CtConstructor ctConstructor) throws NotFoundException, CannotCompileException {
String methodBody = generateConstructorBody(ctClass, ctConstructor.getParameterTypes());
ctConstructor.setBody("{\n" + methodBody + "}\n");
return needsDefault;
}
private String generateConstructorBody(CtClass ctClass, CtClass[] parameterTypes) throws NotFoundException {
return generateMethodBody(ctClass,
new CtMethod(CtClass.voidType, "<init>", parameterTypes, ctClass),
CtClass.voidType,
Type.VOID,
false,
false);
}
private void fixMethods(CtClass ctClass) throws NotFoundException, CannotCompileException {
for (CtMethod ctMethod : ctClass.getDeclaredMethods()) {
fixMethod(ctClass, ctMethod, true);
}
CtMethod equalsMethod = ctClass.getMethod("equals", "(Ljava/lang/Object;)Z");
CtMethod hashCodeMethod = ctClass.getMethod("hashCode", "()I");
CtMethod toStringMethod = ctClass.getMethod("toString", "()Ljava/lang/String;");
fixMethod(ctClass, equalsMethod, false);
fixMethod(ctClass, hashCodeMethod, false);
fixMethod(ctClass, toStringMethod, false);
}
private String describe(CtMethod ctMethod) throws NotFoundException {
return Modifier.toString(ctMethod.getModifiers()) + " " + ctMethod.getReturnType().getSimpleName() + " " + ctMethod.getLongName();
}
private void fixMethod(CtClass ctClass, CtMethod ctMethod, boolean wasFoundInClass) throws NotFoundException {
String describeBefore = describe(ctMethod);
try {
CtClass declaringClass = ctMethod.getDeclaringClass();
int originalModifiers = ctMethod.getModifiers();
boolean wasNative = Modifier.isNative(originalModifiers);
boolean wasFinal = Modifier.isFinal(originalModifiers);
boolean wasAbstract = Modifier.isAbstract(originalModifiers);
boolean wasDeclaredInClass = ctClass == declaringClass;
if (wasFinal && ctClass.isEnum()) {
return;
}
int newModifiers = originalModifiers;
if (wasNative) {
newModifiers = Modifier.clear(newModifiers, Modifier.NATIVE);
}
if (wasFinal) {
newModifiers = Modifier.clear(newModifiers, Modifier.FINAL);
}
if (wasFoundInClass) {
ctMethod.setModifiers(newModifiers);
}
CtClass returnCtClass = ctMethod.getReturnType();
Type returnType = Type.find(returnCtClass);
String methodName = ctMethod.getName();
CtClass[] paramTypes = ctMethod.getParameterTypes();
// if (!isAbstract) {
// if (methodName.startsWith("set") && paramTypes.length == 1) {
// String fieldName = "__" + methodName.substring(3);
// if (declareField(ctClass, fieldName, paramTypes[0])) {
// methodBody = fieldName + " = $1;\n" + methodBody;
// } else if (methodName.startsWith("get") && paramTypes.length == 0) {
// String fieldName = "__" + methodName.substring(3);
// if (declareField(ctClass, fieldName, returnType)) {
// methodBody = "return " + fieldName + ";\n";
boolean isStatic = Modifier.isStatic(originalModifiers);
String methodBody = generateMethodBody(ctClass, ctMethod, wasNative, wasAbstract, returnCtClass, returnType, isStatic, !wasFoundInClass);
if (!wasFoundInClass) {
CtMethod newMethod = makeNewMethod(ctClass, ctMethod, returnCtClass, methodName, paramTypes, "{\n" + methodBody + generateCallToSuper(methodName, paramTypes) + "\n}");
newMethod.setModifiers(newModifiers);
if (wasDeclaredInClass) {
ctMethod.insertBefore("{\n" + methodBody + "}\n");
} else {
ctClass.addMethod(newMethod);
}
} else if (wasAbstract || wasNative) {
CtMethod newMethod = makeNewMethod(ctClass, ctMethod, returnCtClass, methodName, paramTypes, "{\n" + methodBody + "\n}");
ctMethod.setBody(newMethod, null);
} else {
ctMethod.insertBefore("{\n" + methodBody + "}\n");
}
} catch (Exception e) {
throw new RuntimeException("problem instrumenting " + describeBefore, e);
}
}
private CtMethod makeNewMethod(CtClass ctClass, CtMethod ctMethod, CtClass returnCtClass, String methodName, CtClass[] paramTypes, String methodBody) throws CannotCompileException, NotFoundException {
return CtNewMethod.make(
ctMethod.getModifiers(),
returnCtClass,
methodName,
paramTypes,
ctMethod.getExceptionTypes(),
methodBody,
ctClass);
}
public String generateCallToSuper(String methodName, CtClass[] paramTypes) {
return "return super." + methodName + "(" + makeParameterReplacementList(paramTypes.length) + ");";
}
public String makeParameterReplacementList(int length) {
if (length == 0) {
return "";
}
String parameterReplacementList = "$1";
for (int i = 2; i <= length; ++i) {
parameterReplacementList += ", $" + i;
}
return parameterReplacementList;
}
private String generateMethodBody(CtClass ctClass, CtMethod ctMethod, boolean wasNative, boolean wasAbstract, CtClass returnCtClass, Type returnType, boolean aStatic, boolean shouldGenerateCallToSuper) throws NotFoundException {
String methodBody;
if (wasAbstract) {
methodBody = returnType.isVoid() ? "" : "return " + returnType.defaultReturnString() + ";";
} else {
methodBody = generateMethodBody(ctClass, ctMethod, returnCtClass, returnType, aStatic, shouldGenerateCallToSuper);
}
if (wasNative) {
methodBody += returnType.isVoid() ? "" : "return " + returnType.defaultReturnString() + ";";
}
return methodBody;
}
public String generateMethodBody(CtClass ctClass, CtMethod ctMethod, CtClass returnCtClass, Type returnType, boolean isStatic, boolean shouldGenerateCallToSuper) throws NotFoundException {
boolean returnsVoid = returnType.isVoid();
String className = ctClass.getName();
String methodBody;
StringBuilder buf = new StringBuilder();
buf.append("if (!");
buf.append(RobolectricInternals.class.getName());
buf.append(".shouldCallDirectly(");
buf.append(isStatic ? className + ".class" : "this");
buf.append(")) {\n");
if (!returnsVoid) {
buf.append("Object x = ");
}
buf.append(RobolectricInternals.class.getName());
buf.append(".methodInvoked(\n ");
buf.append(className);
buf.append(".class, \"");
buf.append(ctMethod.getName());
buf.append("\", ");
if (!isStatic) {
buf.append("this");
} else {
buf.append("null");
}
buf.append(", ");
appendParamTypeArray(buf, ctMethod);
buf.append(", ");
appendParamArray(buf, ctMethod);
buf.append(")");
buf.append(";\n");
if (!returnsVoid) {
buf.append("if (x != null) return ((");
buf.append(returnType.nonPrimitiveClassName(returnCtClass));
buf.append(") x)");
buf.append(returnType.unboxString());
buf.append(";\n");
if (shouldGenerateCallToSuper) {
buf.append(generateCallToSuper(ctMethod.getName(), ctMethod.getParameterTypes()));
} else {
buf.append("return ");
buf.append(returnType.defaultReturnString());
buf.append(";\n");
}
} else {
buf.append("return;\n");
}
buf.append("}\n");
methodBody = buf.toString();
return methodBody;
}
private void appendParamTypeArray(StringBuilder buf, CtMethod ctMethod) throws NotFoundException {
CtClass[] parameterTypes = ctMethod.getParameterTypes();
if (parameterTypes.length == 0) {
buf.append("new String[0]");
} else {
buf.append("new String[] {");
for (int i = 0; i < parameterTypes.length; i++) {
if (i > 0) buf.append(", ");
buf.append("\"");
CtClass parameterType = parameterTypes[i];
buf.append(parameterType.getName());
buf.append("\"");
}
buf.append("}");
}
}
private void appendParamArray(StringBuilder buf, CtMethod ctMethod) throws NotFoundException {
int parameterCount = ctMethod.getParameterTypes().length;
if (parameterCount == 0) {
buf.append("new Object[0]");
} else {
buf.append("new Object[] {");
for (int i = 0; i < parameterCount; i++) {
if (i > 0) buf.append(", ");
buf.append(RobolectricInternals.class.getName());
buf.append(".autobox(");
buf.append("$").append(i + 1);
buf.append(")");
}
buf.append("}");
}
}
private boolean declareField(CtClass ctClass, String fieldName, CtClass fieldType) throws CannotCompileException, NotFoundException {
CtMethod ctMethod = getMethod(ctClass, "get" + fieldName, "");
if (ctMethod == null) {
return false;
}
CtClass getterFieldType = ctMethod.getReturnType();
if (!getterFieldType.equals(fieldType)) {
return false;
}
if (getField(ctClass, fieldName) == null) {
CtField field = new CtField(fieldType, fieldName, ctClass);
field.setModifiers(Modifier.PRIVATE);
ctClass.addField(field);
}
return true;
}
private CtField getField(CtClass ctClass, String fieldName) {
try {
return ctClass.getField(fieldName);
} catch (NotFoundException e) {
return null;
}
}
private CtMethod getMethod(CtClass ctClass, String methodName, String desc) {
try {
return ctClass.getMethod(methodName, desc);
} catch (NotFoundException e) {
return null;
}
}
}
|
package de.danoeh.antennapod.fragment;
import org.apache.commons.lang3.StringEscapeUtils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import com.actionbarsherlock.app.SherlockFragment;
import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.PodcastApp;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.feed.Feed;
import de.danoeh.antennapod.feed.FeedItem;
import de.danoeh.antennapod.feed.FeedManager;
/** Displays the description of a FeedItem in a Webview. */
public class ItemDescriptionFragment extends SherlockFragment {
private static final String TAG = "ItemDescriptionFragment";
private static final String ARG_FEED_ID = "arg.feedId";
private static final String ARG_FEEDITEM_ID = "arg.feedItemId";
private WebView webvDescription;
private FeedItem item;
private AsyncTask<Void, Void, Void> webViewLoader;
private String descriptionRef;
private String contentEncodedRef;
public static ItemDescriptionFragment newInstance(FeedItem item) {
ItemDescriptionFragment f = new ItemDescriptionFragment();
Bundle args = new Bundle();
args.putLong(ARG_FEED_ID, item.getFeed().getId());
args.putLong(ARG_FEEDITEM_ID, item.getId());
f.setArguments(args);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (AppConfig.DEBUG)
Log.d(TAG, "Creating view");
webvDescription = new WebView(getActivity());
if (PodcastApp.getThemeResourceId() == R.style.Theme_AntennaPod_Dark) {
webvDescription.setBackgroundColor(0);
}
webvDescription.getSettings().setUseWideViewPort(false);
return webvDescription;
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (AppConfig.DEBUG)
Log.d(TAG, "Fragment attached");
}
@Override
public void onDetach() {
super.onDetach();
if (AppConfig.DEBUG)
Log.d(TAG, "Fragment detached");
if (webViewLoader != null) {
webViewLoader.cancel(true);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (AppConfig.DEBUG)
Log.d(TAG, "Fragment destroyed");
if (webViewLoader != null) {
webViewLoader.cancel(true);
}
}
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (AppConfig.DEBUG)
Log.d(TAG, "Creating fragment");
setRetainInstance(true);
FeedManager manager = FeedManager.getInstance();
Bundle args = getArguments();
long feedId = args.getLong(ARG_FEED_ID, -1);
long itemId = args.getLong(ARG_FEEDITEM_ID, -1);
if (feedId != -1 && itemId != -1) {
Feed feed = manager.getFeed(feedId);
item = manager.getFeedItem(itemId, feed);
} else {
Log.e(TAG, TAG + " was called with invalid arguments");
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (item != null) {
if (item.getDescription() == null
&& item.getContentEncoded() == null) {
Log.i(TAG, "Loading data");
FeedManager.getInstance().loadExtraInformationOfItem(
getActivity(), item, new FeedManager.TaskCallback() {
@Override
public void onCompletion(Cursor result) {
if (item.getDescription() == null
&& item.getContentEncoded() == null) {
Log.e(TAG, "No description found");
}
startLoader();
}
});
} else {
Log.i(TAG, "Using cached data");
startLoader();
}
} else {
Log.e(TAG, "Error in onViewCreated: Item was null");
}
}
@Override
public void onResume() {
super.onResume();
}
@SuppressLint("NewApi")
private void startLoader() {
contentEncodedRef = item.getContentEncoded();
descriptionRef = item.getDescription();
webViewLoader = createLoader();
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
webViewLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
webViewLoader.execute();
}
}
/**
* Return the CSS style of the Webview.
*
* @param textColor
* the default color to use for the text in the webview. This
* value is inserted directly into the CSS String.
* */
private String getWebViewStyle(String textColor) {
final String WEBVIEW_STYLE = "<head><style type=\"text/css\"> * { color: %s; font-family: Helvetica; line-height: 1.5em; font-size: 12pt; } a { font-style: normal; text-decoration: none; font-weight: normal; color: #00A8DF; }</style></head>";
return String.format(WEBVIEW_STYLE, textColor);
}
private AsyncTask<Void, Void, Void> createLoader() {
return new AsyncTask<Void, Void, Void>() {
@Override
protected void onCancelled() {
super.onCancelled();
if (getSherlockActivity() != null) {
getSherlockActivity()
.setSupportProgressBarIndeterminateVisibility(false);
}
webViewLoader = null;
}
String data;
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// /webvDescription.loadData(url, "text/html", "utf-8");
webvDescription.loadDataWithBaseURL(null, data, "text/html",
"utf-8", "about:blank");
if (getSherlockActivity() != null) {
getSherlockActivity()
.setSupportProgressBarIndeterminateVisibility(false);
}
if (AppConfig.DEBUG)
Log.d(TAG, "Webview loaded");
webViewLoader = null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (getSherlockActivity() != null) {
getSherlockActivity()
.setSupportProgressBarIndeterminateVisibility(true);
}
}
@Override
protected Void doInBackground(Void... params) {
if (AppConfig.DEBUG)
Log.d(TAG, "Loading Webview");
data = "";
if (contentEncodedRef == null && descriptionRef != null) {
data = descriptionRef;
} else {
data = StringEscapeUtils.unescapeHtml4(contentEncodedRef);
}
TypedArray res = getActivity().getTheme()
.obtainStyledAttributes(
new int[] { android.R.attr.textColorPrimary });
int colorResource = res.getColor(0, 0);
String colorString = String.format("#%06X",
0xFFFFFF & colorResource);
Log.i(TAG, "text color: " + colorString);
res.recycle();
data = getWebViewStyle(colorString) + data;
return null;
}
};
}
}
|
package dr.inference.operators;
import dr.inference.distribution.DistributionLikelihood;
import dr.inference.distribution.MomentDistributionModel;
import dr.inference.model.*;
import dr.math.MathUtils;
import dr.math.distributions.MultivariateNormalDistribution;
import dr.math.distributions.NormalDistribution;
import dr.math.matrixAlgebra.CholeskyDecomposition;
import dr.math.matrixAlgebra.IllegalDimension;
import dr.math.matrixAlgebra.SymmetricMatrix;
import jebl.math.Random;
import java.util.ArrayList;
import java.util.ListIterator;
public class LoadingsGibbsTruncatedOperator extends SimpleMCMCOperator implements GibbsOperator{
MomentDistributionModel prior;
LatentFactorModel LFM;
ArrayList<double[][]> precisionArray;
ArrayList<double[]> meanMidArray;
ArrayList<double[]> meanArray;
boolean randomScan;
double pathParameter=1.0;
double priorPrecision;
double priorMeanPrecision;
MatrixParameterInterface loadings;
public LoadingsGibbsTruncatedOperator(LatentFactorModel LFM, MomentDistributionModel prior, double weight, boolean randomScan, MatrixParameterInterface loadings) {
setWeight(weight);
this.loadings=loadings;
this.prior = prior;
this.LFM = LFM;
precisionArray = new ArrayList<double[][]>();
double[][] temp;
this.randomScan = randomScan;
meanArray = new ArrayList<double[]>();
meanMidArray = new ArrayList<double[]>();
double[] tempMean;
if (!randomScan) {
for (int i = 0; i < LFM.getFactorDimension(); i++) {
temp = new double[i + 1][i + 1];
precisionArray.add(temp);
}
for (int i = 0; i < LFM.getFactorDimension(); i++) {
tempMean = new double[i + 1];
meanArray.add(tempMean);
}
for (int i = 0; i < LFM.getFactorDimension(); i++) {
tempMean = new double[i + 1];
meanMidArray.add(tempMean);
}
} else {
for (int i = 0; i < LFM.getFactorDimension(); i++) {
temp = new double[LFM.getFactorDimension() - i][LFM.getFactorDimension() - i];
precisionArray.add(temp);
}
for (int i = 0; i < LFM.getFactorDimension(); i++) {
tempMean = new double[LFM.getFactorDimension() - i];
meanArray.add(tempMean);
}
for (int i = 0; i < LFM.getFactorDimension(); i++) {
tempMean = new double[LFM.getFactorDimension() - i];
meanMidArray.add(tempMean);
}
}
// vectorProductAnswer=new MatrixParameter[LFM.getLoadings().getRowDimension()];
// for (int i = 0; i <vectorProductAnswer.length ; i++) {
// vectorProductAnswer[i]=new MatrixParameter(null);
// vectorProductAnswer[i].setDimensions(i+1, 1);
// priorMeanVector=new MatrixParameter[LFM.getLoadings().getRowDimension()];
// for (int i = 0; i <priorMeanVector.length ; i++) {
// priorMeanVector[i]=new MatrixParameter(null, i+1, 1, this.prior.getMean()/(this.prior.getSD()*this.prior.getSD()));
priorPrecision = (this.prior.getScaleMatrix()[0][0]);
priorMeanPrecision = this.prior.getMean()[0] * priorPrecision;
}
private void getPrecisionOfTruncated(MatrixParameterInterface full, int newRowDimension, int row, double[][] answer) {
// MatrixParameter answer=new MatrixParameter(null);
// answer.setDimensions(this.getRowDimension(), Right.getRowDimension());
// System.out.println(answer.getRowDimension());
// System.out.println(answer.getColumnDimension());
int p = full.getColumnDimension();
for (int i = 0; i < newRowDimension; i++) {
for (int j = i; j < newRowDimension; j++) {
double sum = 0;
for (int k = 0; k < p; k++)
sum += full.getParameterValue(i, k) * full.getParameterValue(j, k);
answer[i][j] = sum * LFM.getColumnPrecision().getParameterValue(row, row);
if (i == j) {
answer[i][j] =answer[i][j]*pathParameter+ priorPrecision;
} else {
answer[i][j]*=pathParameter;
answer[j][i] = answer[i][j];
}
}
}
}
private void getTruncatedMean(int newRowDimension, int dataColumn, double[][] variance, double[] midMean, double[] mean) {
// MatrixParameter answer=new MatrixParameter(null);
// answer.setDimensions(this.getRowDimension(), Right.getRowDimension());
// System.out.println(answer.getRowDimension());
// System.out.println(answer.getColumnDimension());
MatrixParameterInterface data = LFM.getScaledData();
MatrixParameterInterface Left = LFM.getFactors();
int p = data.getColumnDimension();
for (int i = 0; i < newRowDimension; i++) {
double sum = 0;
for (int k = 0; k < p; k++)
sum += Left.getParameterValue(i, k) * data.getParameterValue(dataColumn, k);
sum = sum * LFM.getColumnPrecision().getParameterValue(dataColumn, dataColumn);
sum += priorMeanPrecision;
midMean[i] = sum;
}
for (int i = 0; i < newRowDimension; i++) {
double sum = 0;
for (int k = 0; k < newRowDimension; k++)
sum += variance[i][k] * midMean[k];
mean[i] = sum;
}
}
private void getPrecision(int i, double[][] answer) {
int size = LFM.getFactorDimension();
if (i < size) {
getPrecisionOfTruncated(LFM.getFactors(), i + 1, i, answer);
} else {
getPrecisionOfTruncated(LFM.getFactors(), size, i, answer);
}
}
private void getMean(int i, double[][] variance, double[] midMean, double[] mean) {
// Matrix factors=null;
int size = LFM.getFactorDimension();
// double[] scaledDataColumn=LFM.getScaledData().getRowValues(i);
// Vector dataColumn=null;
// Vector priorVector=null;
// Vector temp=null;
// Matrix data=new Matrix(LFM.getScaledData().getParameterAsMatrix());
if (i < size) {
getTruncatedMean(i + 1, i, variance, midMean, mean);
// dataColumn=new Vector(data.toComponents()[i]);
// try {
// answer=precision.inverse().product(new Matrix(priorMeanVector[i].add(vectorProductAnswer[i]).getParameterAsMatrix()));
} else {
getTruncatedMean(size, i, variance, midMean, mean);
// dataColumn=new Vector(data.toComponents()[i]);
// try {
// answer=precision.inverse().product(new Matrix(priorMeanVector[size-1].add(vectorProductAnswer[size-1]).getParameterAsMatrix()));
}
for (int j = 0; j <mean.length ; j++) {//TODO implement for generic prior
mean[j]*=pathParameter;
}
}
private void copy(int i, double[] random) {
MatrixParameterInterface changing = loadings;
for (int j = 0; j < random.length; j++) {
changing.setParameterValueQuietly(i, j, random[j]);
}
}
private double[] getDraws(int row, double[] mean, double[][] Cholesky){
double[] temp = new double[mean.length];
double[] draws = new double[mean.length];
double lowCutoff;
double highCutoff;
double low;
double high;
NormalDistribution normal;
for (int i = 0; i < temp.length; i++) {
highCutoff = Math.sqrt(prior.getCutoff().getParameterValue(row * LFM.getLoadings().getColumnDimension() + i));
lowCutoff = -highCutoff;
for (int j = 0; j <= i; j++) {
// if(Cholesky[i][i] > 0) {
if (i != j) {
lowCutoff = lowCutoff - temp[j] * Cholesky[i][j];
highCutoff = highCutoff - temp[j] * Cholesky[i][j];
} else {
lowCutoff = lowCutoff / Cholesky[i][j];
highCutoff = highCutoff / Cholesky[i][j];
}
// else{
// if (i != j) {
// cutoffs = cutoffs + temp[j] * Cholesky[i][j];
// } else {
// cutoffs = cutoffs / Cholesky[i][j];
}
// System.out.println(cutoffs);
normal = new NormalDistribution(mean[i], 1);
low = normal.cdf(lowCutoff);
high = normal.cdf(highCutoff);
// System.out.println("low: " + low);
// System.out.println("high: " + high);
double proportion = low/(low + 1 - high);
if(Random.nextDouble()<proportion){
double quantile=Random.nextDouble() * low;
temp[i] = normal.quantile(quantile);
}
else{
double quantile=(1-high) * Random.nextDouble() + high;
temp[i] = normal.quantile(quantile);
}
}
for (int i = 0; i <mean.length ; i++) {
for (int j = 0; j <= i; j++) {
draws[i] += Cholesky[i][j] * temp[j];
// System.out.println("temp: " + temp[i]);
// System.out.println("Cholesky " + i + ", " + j +": " +Cholesky[i][j]);
}
if(Math.abs(draws[i])<Math.sqrt(prior.getCutoff().getParameterValue(row * LFM.getLoadings().getColumnDimension() + i))) {
System.out.println(Math.sqrt(prior.getCutoff().getParameterValue(row * LFM.getLoadings().getColumnDimension() + i)));
System.out.println("draws: " + draws[i]);
}
}
return draws;
}
private void drawI(int i, ListIterator<double[][]> currentPrecision, ListIterator<double[]> currentMidMean, ListIterator<double[]> currentMean) {
double[] draws = null;
double[][] precision = null;
double[][] variance;
double[] midMean = null;
double[] mean = null;
double[][] cholesky = null;
if (currentPrecision.hasNext()) {
precision = currentPrecision.next();
}
else
precision = currentPrecision.previous();
if (currentMidMean.hasNext()) {
midMean = currentMidMean.next();
}
else
midMean = currentMidMean.previous();
if (currentMean.hasNext()) {
mean = currentMean.next();
}
else
mean= currentMean.previous();
getPrecision(i, precision);
variance = (new SymmetricMatrix(precision)).inverse().toComponents();
try {
cholesky = new CholeskyDecomposition(variance).getL();
} catch (IllegalDimension illegalDimension) {
illegalDimension.printStackTrace();
}
getMean(i, variance, midMean, mean);
draws = getDraws(i, mean, cholesky);
// if(i<draws.length)
// while (draws[i] < 0) {
// draws = MultivariateNormalDistribution.nextMultivariateNormalCholesky(mean, cholesky);
if (i < draws.length) {
//if (draws[i] > 0) { TODO implement as option
copy(i, draws);
} else {
copy(i, draws);
}
// copy(i, draws);
}
@Override
public int getStepCount() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getPerformanceSuggestion() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getOperatorName() {
return "loadingsGibbsTruncatedOperator"; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public double doOperation() throws OperatorFailedException {
int size = LFM.getLoadings().getRowDimension();
if (!randomScan) {
ListIterator<double[][]> currentPrecision = precisionArray.listIterator();
ListIterator<double[]> currentMidMean = meanMidArray.listIterator();
ListIterator<double[]> currentMean = meanArray.listIterator();
for (int i = 0; i < size; i++) {
drawI(i, currentPrecision, currentMidMean, currentMean);
}
((Parameter) loadings).fireParameterChangedEvent();
} else {
int i = MathUtils.nextInt(LFM.getLoadings().getRowDimension());
ListIterator<double[][]> currentPrecision;
ListIterator<double[]> currentMidMean;
ListIterator<double[]> currentMean;
if (i < LFM.getFactorDimension()) {
currentPrecision = precisionArray.listIterator(LFM.getFactorDimension() - i - 1);
currentMidMean = meanMidArray.listIterator(LFM.getFactorDimension() - i - 1);
currentMean = meanArray.listIterator(LFM.getFactorDimension() - i - 1);
} else {
currentPrecision = precisionArray.listIterator();
currentMidMean = meanMidArray.listIterator();
currentMean = meanArray.listIterator();
}
drawI(i, currentPrecision, currentMidMean, currentMean);
LFM.getLoadings().fireParameterChangedEvent(i, null);
// LFM.getLoadings().fireParameterChangedEvent();
}
return 0;
}
public void setPathParameter(double beta){
pathParameter=beta;
}
}
|
package gov.nih.nci.ncicb.cadsr.loader.persister;
import gov.nih.nci.ncicb.cadsr.dao.*;
import gov.nih.nci.ncicb.cadsr.domain.*;
import gov.nih.nci.ncicb.cadsr.loader.ElementsLists;
import gov.nih.nci.ncicb.cadsr.spring.*;
import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults;
import gov.nih.nci.ncicb.cadsr.loader.util.*;
import gov.nih.nci.ncicb.cadsr.loader.event.*;
import org.apache.log4j.Logger;
import java.util.*;
/**
* This class will call the other UML Related Persisters
*
* @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a>
*/
public class UMLPersister implements Persister {
private static Logger logger = Logger.getLogger(UMLPersister.class.getName());
private static Map<String,String> vdMapping = DatatypeMapping.getMapping();
protected static AdminComponentDAO adminComponentDAO;
protected static AlternateNameDAO alternateNameDAO;
protected static DataElementDAO dataElementDAO;
protected static DataElementConceptDAO dataElementConceptDAO;
protected static ValueDomainDAO valueDomainDAO;
// protected static ValueMeaningDAO valueMeaningDAO;
protected static PropertyDAO propertyDAO;
protected static ObjectClassDAO objectClassDAO;
protected static ObjectClassRelationshipDAO objectClassRelationshipDAO;
protected static ClassificationSchemeDAO classificationSchemeDAO;
protected static ClassificationSchemeItemDAO classificationSchemeItemDAO;
protected static ClassSchemeClassSchemeItemDAO classSchemeClassSchemeItemDAO;
protected static ConceptDAO conceptDAO;
protected ElementsLists elements = ElementsLists.getInstance();
protected Map<String, ValueDomain> valueDomains = new HashMap<String, ValueDomain>();
protected UMLDefaults defaults = UMLDefaults.getInstance();
private ProgressListener progressListener = null;
public UMLPersister() {
this.elements = ElementsLists.getInstance();
}
public void persist() throws PersisterException {
initDAOs();
Persister persister = new PackagePersister();
persister.setProgressListener(progressListener);
persister.persist();
persister = new ConceptPersister();
persister.setProgressListener(progressListener);
persister.persist();
persister = new PropertyPersister();
persister.setProgressListener(progressListener);
persister.persist();
persister = new ObjectClassPersister();
persister.setProgressListener(progressListener);
persister.persist();
persister = new DECPersister();
persister.setProgressListener(progressListener);
persister.persist();
persister = new ValueDomainPersister();
persister.setProgressListener(progressListener);
persister.persist();
persister = new DEPersister();
persister.setProgressListener(progressListener);
persister.persist();
persister = new OcRecPersister();
persister.setProgressListener(progressListener);
persister.persist();
}
protected void sendProgressEvent(int status, int goal, String message) {
if(progressListener != null) {
ProgressEvent pEvent = new ProgressEvent();
pEvent.setMessage(message);
pEvent.setStatus(status);
pEvent.setGoal(goal);
progressListener.newProgressEvent(pEvent);
}
}
// protected ValueDomain lookupValueDomain(ValueDomain vd)
// throws PersisterException {
// if(vd.getLongName().startsWith("enum")) {
// vd.setLongName("java.lang.String");
// ValueDomain result = valueDomains.get(vd.getLongName());
// if (result == null) { // not in cache -- go to db
// List<ValueDomain> l = valueDomainDAO.find(vd);
// if (l.size() == 0) {
// throw new PersisterException("Value Domain " +
// vd.getLongName() + " does not exist.");
// } else {
// List<String> excludeContext = Arrays.asList(PropertyAccessor.getProperty("vd.exclude.contexts").split(","));
// String preferredContext = PropertyAccessor.getProperty("vd.preferred.contexts");
// // see if we find a VD in our preferred context
// for(ValueDomain v : l) {
// if(v.getContext().getName().equals(preferredContext)) {
// result = v;
// // store to cache
// valueDomains.put(result.getLongName(), result);
// // no VD in our preferred context, let's find one that's not in the list of banned contexts
// if(result == null)
// for(ValueDomain v : l) {
// if(!excludeContext.contains(v.getContext().getName())) {
// result = v;
// // store to cache
// valueDomains.put(result.getLongName(), result);
// if(result == null)
// throw new PersisterException
// ("Value Domain " +
// vd.getLongName() + " does not exist.");
// return result;
protected void addAlternateName(AdminComponent ac, String newName, String type, String packageName) {
// List<String> eager = new ArrayList<String>();
// eager.add("csCsis");
// List<AlternateName> altNames = adminComponentDAO.getAlternateNames(ac, eager);
AlternateName queryAN = DomainObjectFactory.newAlternateName();
queryAN.setName(newName);
queryAN.setType(type);
AlternateName foundAN = adminComponentDAO.getAlternateName(ac, queryAN);
boolean found = false;
ClassSchemeClassSchemeItem packageCsCsi = (ClassSchemeClassSchemeItem)defaults.getPackageCsCsis().get(packageName);
// for(AlternateName an : altNames) {
// if(an.getType().equals(type) && an.getName().equals(newName)) {
// found = true;
if(foundAN != null) {
logger.info(PropertyAccessor.getProperty(
"existed.altName", newName));
if(packageName == null)
return;
// boolean csFound = false;
// boolean parentFound = false;
ClassSchemeClassSchemeItem foundCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundAN, packageCsCsi);
ClassSchemeClassSchemeItem foundParentCsCsi = null;
if(packageCsCsi.getParent() != null)
foundParentCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundAN, packageCsCsi);
// for(ClassSchemeClassSchemeItem csCsi : an.getCsCsis()) {
// if(csCsi.getId().equals(packageCsCsi.getId())) {
// csFound = true;
// } else if(packageCsCsi.getParent() != null && csCsi.getId().equals(packageCsCsi.getParent().getId()))
// parentFound = true;
if(foundCsCsi == null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundAN, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
if((foundParentCsCsi == null) && packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundAN, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
}
if(foundAN == null) {
AlternateName altName = DomainObjectFactory.newAlternateName();
altName.setContext(defaults.getContext());
altName.setAudit(defaults.getAudit());
altName.setName(newName);
altName.setType(type);
altName.setId(adminComponentDAO.addAlternateName(ac, altName));
logger.info(PropertyAccessor.getProperty(
"added.altName",
new String[] {
altName.getName(),
ac.getLongName()
}));
if(packageName != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altName, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
if(packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altName, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
}
}
}
protected void addAlternateDefinition(AdminComponent ac, String newDef, String type, String packageName) {
// List<String> eager = new ArrayList<String>();
// eager.add("csCsis");
// List<Definition> altDefs = adminComponentDAO.getDefinitions(ac, eager);
// boolean found = false;
Definition queryDef = DomainObjectFactory.newDefinition();
queryDef.setDefinition(newDef);
queryDef.setType(type);
Definition foundDef = adminComponentDAO.getDefinition(ac, queryDef);
ClassSchemeClassSchemeItem packageCsCsi = (ClassSchemeClassSchemeItem)defaults.getPackageCsCsis().get(packageName);
// for(Definition def : altDefs) {
// if(def.getType() != null && def.getType().equals(type) && def.getDefinition().equals(newDef)) {
// found = true;
if(foundDef != null) {
logger.info(PropertyAccessor.getProperty(
"existed.altDef", newDef));
// boolean csFound = false;
// boolean parentFound = false;
ClassSchemeClassSchemeItem foundCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundDef, packageCsCsi);
ClassSchemeClassSchemeItem foundParentCsCsi = null;
if(packageCsCsi.getParent() != null)
foundParentCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundDef, packageCsCsi);
// for(ClassSchemeClassSchemeItem csCsi : def.getCsCsis()) {
// if(csCsi.getId().equals(packageCsCsi.getId())) {
// csFound = true;
// } else if(packageCsCsi.getParent() != null && csCsi.getId().equals(packageCsCsi.getParent().getId()))
// parentFound = true;
if(foundCsCsi == null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundDef, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
}
if((foundParentCsCsi == null) && packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundDef, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
}
if(foundDef == null) {
Definition altDef = DomainObjectFactory.newDefinition();
altDef.setContext(defaults.getContext());
altDef.setDefinition(newDef);
altDef.setAudit(defaults.getAudit());
altDef.setType(type);
altDef.setId(adminComponentDAO.addDefinition(ac, altDef));
logger.info(PropertyAccessor.getProperty(
"added.altDef",
new String[] {
altDef.getId(),
altDef.getDefinition(),
ac.getLongName()
}));
classSchemeClassSchemeItemDAO.addCsCsi(altDef, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
if(packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altDef, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
}
}
}
protected DataElementConcept lookupDec(String id) {
List decs = (List) elements.getElements(DomainObjectFactory.newDataElementConcept().getClass());
for (Iterator it = decs.iterator(); it.hasNext(); ) {
DataElementConcept o = (DataElementConcept) it.next();
if (o.getId().equals(id)) {
return o;
}
}
return null;
}
protected boolean isSameDefinition(String def, Concept[] concepts) {
if((def == null) || def.length() == 0)
return true;
StringBuffer sb = new StringBuffer();
for(int i=0; i < concepts.length; i++) {
if(sb.length() > 0)
sb.append("\n");
sb.append(concepts[i].getPreferredDefinition());
}
return def.equals(sb.toString());
}
protected void addPackageClassification(AdminComponent ac, String packageName) {
// List l = adminComponentDAO.getClassSchemeClassSchemeItems(ac);
ClassSchemeClassSchemeItem packageCsCsi = (ClassSchemeClassSchemeItem)defaults.getPackageCsCsis().get(packageName);
ClassSchemeClassSchemeItem foundCsCsi = adminComponentDAO.getClassSchemeClassSchemeItem(ac, packageCsCsi);
ClassSchemeClassSchemeItem foundParentCsCsi = null;
if(packageCsCsi.getParent() != null) {
foundParentCsCsi = adminComponentDAO.getClassSchemeClassSchemeItem(ac, packageCsCsi.getParent());
}
// // is projectCs linked?
// boolean found = false;
// boolean parentFound = false;
// for (ListIterator it = l.listIterator(); it.hasNext();) {
// ClassSchemeClassSchemeItem csCsi = (ClassSchemeClassSchemeItem) it.next();
// if(csCsi.getId().equals(packageCsCsi.getId()))
// found = true;
// else if(packageCsCsi.getParent() != null && csCsi.getId().equals(packageCsCsi.getParent().getId()))
// parentFound = true;
List csCsis = new ArrayList();
if (foundCsCsi == null) {
logger.info(PropertyAccessor.
getProperty("attach.package.classification"));
if (packageCsCsi != null) {
csCsis.add(packageCsCsi);
if((foundParentCsCsi == null) && packageCsCsi.getParent() != null)
csCsis.add(packageCsCsi.getParent());
adminComponentDAO.addClassSchemeClassSchemeItems(ac, csCsis);
logger.info(PropertyAccessor
.getProperty("added.package",
new String[] {
packageName,
ac.getLongName()}));
} else {
// PersistPackages should have taken care of it.
// We should not be here.
logger.error(PropertyAccessor.getProperty("missing.package", new String[] {packageName, ac.getLongName()}));
}
}
}
protected String getPackageName(AdminComponent ac) {
return
((AdminComponentClassSchemeClassSchemeItem)ac.getAcCsCsis().get(0)).getCsCsi().getCsi().getName();
}
private void initDAOs() {
adminComponentDAO = DAOAccessor.getAdminComponentDAO();
alternateNameDAO = DAOAccessor.getAlternateNameDAO();
dataElementDAO = DAOAccessor.getDataElementDAO();
dataElementConceptDAO = DAOAccessor.getDataElementConceptDAO();
valueDomainDAO = DAOAccessor.getValueDomainDAO();
// valueMeaningDAO = DAOAccessor.getValueMeaningDAO();
propertyDAO = DAOAccessor.getPropertyDAO();
objectClassDAO = DAOAccessor.getObjectClassDAO();
objectClassRelationshipDAO = DAOAccessor.getObjectClassRelationshipDAO();
classificationSchemeDAO = DAOAccessor.getClassificationSchemeDAO();
classificationSchemeItemDAO = DAOAccessor.getClassificationSchemeItemDAO();
classSchemeClassSchemeItemDAO = DAOAccessor.getClassSchemeClassSchemeItemDAO();
conceptDAO = DAOAccessor.getConceptDAO();
}
public void setProgressListener(ProgressListener listener) {
progressListener = listener;
}
// public static void main(String[] args) {
// UMLPersister pers = new UMLPersister();
// valueDomainDAO = DAOAccessor.getValueDomainDAO();
// ValueDomain vd = DomainObjectFactory.newValueDomain();;
// vd.setLongName("java.util.Date");
// try {
// vd = pers.lookupValueDomain(vd);
// } catch (PersisterException e){
// e.printStackTrace();
// } // end of try-catch
// System.out.println("publicID: " + vd.getPublicId());
// System.out.println("context: " + vd.getContext().getName());
}
|
package org.xins.client;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import org.xins.util.MandatoryArgumentChecker;
/**
* Grouping of function callers. This grouping is of a certain type (see
* {@link #getType()}) that sets the algorithm to be used to determine what
* underlying actual function caller is used to call the remote API
* implementation. A <code>CallTargetGroup</code> can contain other
* <code>CallTargetGroup</code> instances.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.41
*/
public abstract class CallTargetGroup
extends AbstractCompositeFunctionCaller {
// Class fields
/**
* The <em>ordered</em> call target group type. The name of this type is:
* <code>"ordered"</code>.
*/
public static final Type ORDERED_TYPE = new Type("ordered");
/**
* The <em>random</em> call target group type. The name of this type is:
* <code>"random"</code>.
*/
public static final Type RANDOM_TYPE = new Type("random");
// Class functions
public static final Type getTypeByName(String name)
throws IllegalArgumentException {
// Recognize existing types
if (ORDERED_TYPE.getName().equals(name)) {
return ORDERED_TYPE;
} else if (RANDOM_TYPE.getName().equals(name)) {
return RANDOM_TYPE;
// Fail if name is null
} else if (name == null) {
throw new IllegalArgumentException("name == null");
// Otherwise: not found, return null
} else {
return null;
}
}
public final static CallTargetGroup create(Type type, URL url)
throws IllegalArgumentException, SecurityException, UnknownHostException {
// Check preconditions
MandatoryArgumentChecker.check("type", type, "url", url);
List members = new ArrayList();
String hostName = url.getHost();
InetAddress[] addresses = InetAddress.getAllByName(hostName);
int addressCount = addresses.length;
try {
for (int i = 0; i < addressCount; i++) {
URL afcURL = new URL(url.getProtocol(), // protocol
addresses[i].getHostAddress(), // host
url.getPort(), // port
url.getFile()); // file
members.add(new ActualFunctionCaller(afcURL, hostName));
}
} catch (MalformedURLException mue) {
throw new InternalError("Caught MalformedURLException for a protocol that was previously accepted: \"" + url.getProtocol() + "\".");
} catch (MultipleIPAddressesException miae) {
throw new InternalError("Caught MultipleIPAddressesException while only using resolved IP addresses.");
}
return create(type, members);
}
public final static CallTargetGroup create(Type type, List members)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("type", type, "members", members);
// Return an instance of a CallTargetGroup subclass
if (type == ORDERED_TYPE) {
return new OrderedCallTargetGroup(members);
} else if (type == RANDOM_TYPE) {
return new RandomCallTargetGroup(members);
} else {
throw new InternalError("Type not recognized.");
}
}
// Constructors
CallTargetGroup(Type type, List members) throws IllegalArgumentException {
super(members);
// Check preconditions
MandatoryArgumentChecker.check("type", type);
// Initialize fields
_type = type;
_actualFunctionCallersByURL = new HashMap();
addActualFunctionCallers(members);
}
// Fields
/**
* The type of this group. This field cannot be <code>null</code>.
*/
private final Type _type;
/**
* Mappings from URLs to <code>ActualFunctionCaller</code>. The URLs are
* stored as {@link String} instances. This {@link Map} cannot be
* <code>null</code>.
*/
private final Map _actualFunctionCallersByURL;
// Methods
private final void addActualFunctionCallers(List members)
throws IllegalArgumentException {
int memberCount = members == null ? 0 : members.size();
for (int i = 0; i < memberCount; i++) {
FunctionCaller member;
// Get the member and make sure it is a FunctionCaller instance
try {
member = (FunctionCaller) members.get(i);
if (member == null) {
throw new IllegalArgumentException("members.get(" + i + ") == null");
}
} catch (ClassCastException cce) {
throw new IllegalArgumentException("members.get(" + i + ") is an instance of " + members.get(i).getClass().getName() + '.');
}
// If the member is an actual function caller, store a reference
if (member instanceof ActualFunctionCaller) {
ActualFunctionCaller afc = (ActualFunctionCaller) member;
String url = afc.getURL().toString();
_actualFunctionCallersByURL.put(url, afc);
// If the member is composite, get all its members
} else if (member instanceof CompositeFunctionCaller) {
CompositeFunctionCaller cfc = (CompositeFunctionCaller) member;
addActualFunctionCallers(cfc.getMembers());
}
}
}
/**
* Returns the type of this group.
*
* @return
* the type of this group, either {@link #ORDERED_TYPE}, or
* {@link #RANDOM_TYPE}.
*/
public final Type getType() {
return _type;
}
public final ActualFunctionCaller getActualFunctionCaller(String url)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("url", url);
return (ActualFunctionCaller) _actualFunctionCallersByURL.get(url);
}
public final CallResult call(String sessionID,
String functionName,
Map parameters)
throws IllegalArgumentException, IOException, InvalidCallResultException {
MandatoryArgumentChecker.check("functionName", functionName);
return callImpl(sessionID, functionName, parameters);
}
/**
* Calls the specified API function with the specified parameters (actual
* implementation). The type (see {@link #getType()}) determines what
* actual function caller will be used.
*
* @param sessionID
* the session identifier, if any, or <code>null</code> if the function
* is session-less.
*
* @param functionName
* the name of the function to be called, guaranteed not to be
* <code>null</code>.
*
* @param parameters
* the parameters to be passed to that function, or
* <code>null</code>; keys must be {@link String Strings}, values can be
* of any class.
*
* @return
* the call result, never <code>null</code>.
*
* @throws IOException
* if the API could not be contacted due to an I/O error.
*
* @throws InvalidCallResultException
* if the calling of the function failed or if the result from the
* function was invalid.
*/
abstract CallResult callImpl(String sessionID,
String functionName,
Map parameters)
throws IOException, InvalidCallResultException;
/**
* Attempts to call the specified <code>FunctionCaller</code>. If the call
* succeeds, then the {@link CallResult} will be returned. If it fails,
* then the {@link Throwable} exception will be returned.
*
* @param caller
* the {@link FunctionCaller} to call, not <code>null</code>.
*
* @param sessionID
* the session identifier, or <code>null</code>.
*
* @param functionName
* the name of the function to call, not <code>null</code>.
*
* @param parameters
* the parameters to be passed to the function, or <code>null</code>;
* keys must be {@link String Strings}, values can be of any class.
*
* @return
* a {@link Throwable} if
* <code>caller.</code>{@link FunctionCaller#call(String,String,Map)}
* throws an exception, otherwise the return value of that call, but
* never <code>null</code>.
*
* @throws InternalError
* if <code>caller.</code>{@link FunctionCaller#call(String,String,Map)}
* returned <code>null</code>.
*/
final Object tryCall(FunctionCaller caller,
String sessionID,
String functionName,
Map parameters)
throws InternalError {
// Perform the call
CallResult result;
try {
result = caller.call(sessionID, functionName, parameters);
// If there was an exception, return it...
} catch (Throwable exception) {
return exception;
}
// otherwise if the result was null, then throw an error...
if (result == null) {
throw new InternalError(caller.getClass().getName() + ".call(String,String,Map) returned null.");
}
// otherwise return the CallResult object
return result;
}
final CallResult callImplResult(Object result)
throws IllegalArgumentException, IOException, InvalidCallResultException {
MandatoryArgumentChecker.check("result", result);
if (result instanceof CallResult) {
return (CallResult) result;
} else if (result instanceof IOException) {
throw (IOException) result;
} else if (result instanceof InvalidCallResultException) {
throw (InvalidCallResultException) result;
} else if (result instanceof Error) {
throw (Error) result;
} else if (result instanceof RuntimeException) {
throw (RuntimeException) result;
} else {
throw new InternalError("CallTargetGroup.tryCall() returned an instance of class " + result.getClass().getName() + ", which is unsupported.");
}
}
// Inner classes
/**
* The type of a <code>CallTargetGroup</code>. The type determines the
* algorithm to be used to determine what underlying actual function caller
* is used to call the remote API implementation.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*/
public static final class Type extends Object {
// Constructors
private Type(String name) throws IllegalArgumentException {
MandatoryArgumentChecker.check("name", name);
_name = name;
}
// Fields
/**
* The name of this type.
*/
private final String _name;
// Methods
/**
* Returns the name of this type. The name uniquely identifies this
* type.
*
* @return
* the name of this type, not <code>null</code>.
*
* @since XINS 0.45
*/
public String getName() {
return _name;
}
public String toString() {
return _name;
}
}
}
|
package org.xins.server;
/**
* Constants referring to all existing <code>ResponderState</code>
* instances.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*/
public interface ResponderStates {
/**
* Uninitialized state. In this state no output can be written.
*/
static final ResponderState UNINITIALIZED = new ResponderState("UNINITIALIZED");
/**
* Initial state, before response output is started.
*/
static final ResponderState BEFORE_START = new ResponderState("BEFORE_START");
/**
* State active when the output parameters can be written. This states
* comes after {@link #BEFORE_START}.
*/
static final ResponderState WITHIN_PARAMS = new ResponderState("WITHIN_PARAMS");
/**
* State within the data section when a start tag has been opened, but not
* closed yet. This state comes after {@link #WITHIN_PARAMS}.
*/
static final ResponderState START_TAG_OPEN = new ResponderState("START_TAG_OPEN");
/**
* State within the data section after a start tag has been closed, but the
* root element has not been closed yet. This state comes after
* {@link #START_TAG_OPEN}.
*/
static final ResponderState WITHIN_ELEMENT = new ResponderState("WITHIN_ELEMENT");
/**
* Final state, after response output is finished.
*/
static final ResponderState AFTER_END = new ResponderState("AFTER_END");
/**
* Error state. Entered if an exception is thrown within an output method.
*/
static final ResponderState ERROR = new ResponderState("ERROR");
}
|
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.tools;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.samskivert.util.StringUtil;
import com.threerings.util.ActionScript;
/**
* Primitively parses an ActionScriptSource file, allows the addition and
* replacement of class members and handles writing out the file again.
*/
public class ActionScriptSource
{
/**
* Contains the name and text of a particular member declaration.
*/
public static class Member
{
public String name;
public String comment = "";
public String definition;
public String body = "";
public boolean noreplace = false;
public Member (String name, String definition) {
this.name = name;
this.definition = definition;
}
public void setInitialValue (String initValue) {
// if we're a typed array and we're being set to "new Something[0]"
// then convert that
if (definition.indexOf("TypedArray") != -1) {
Matcher m = ARRAYINIT.matcher(initValue);
if (m.matches()) {
initValue = "TypedArray.create(" + m.group(1) + ")";
}
}
// do not-very-smart array conversion
initValue = initValue.replaceAll("\\{", "[");
initValue = initValue.replaceAll("\\}", "]");
// stick the initial value before the semicolon
definition = definition.substring(0, definition.length()-1) +
" = " + initValue + ";";
}
public void setComment (String comment) {
if (comment.indexOf("@Override") != -1) {
if (comment.trim().startsWith("
// handle // @Override // comment
comment = comment.replaceFirst("
}
comment = comment.replaceAll("@Override ?", "");
definition = "override " + definition;
}
// trim blank lines from start
while (comment.startsWith("\n")) {
comment = comment.substring(1);
}
this.comment = StringUtil.isBlank(comment) ? "" : comment;
}
public void write (PrintWriter writer) {
writer.print(comment);
writer.println(" " + definition);
writer.print(body);
}
}
public String preamble = "";
public String packageName;
public String imports = "";
public String classComment = "";
public boolean isAbstract;
public String className;
public String superClassName;
public String[] implementedInterfaces;
public ArrayList<Member> publicConstants = new ArrayList<Member>();
public ArrayList<Member> publicFields = new ArrayList<Member>();
public ArrayList<Member> publicStaticMethods = new ArrayList<Member>();
public ArrayList<Member> publicConstructors = new ArrayList<Member>();
public ArrayList<Member> publicMethods = new ArrayList<Member>();
public ArrayList<Member> protectedConstructors = new ArrayList<Member>();
public ArrayList<Member> protectedMethods = new ArrayList<Member>();
public ArrayList<Member> protectedStaticMethods = new ArrayList<Member>();
public ArrayList<Member> protectedFields = new ArrayList<Member>();
public ArrayList<Member> protectedConstants = new ArrayList<Member>();
public static String toSimpleName (String name)
{
name = name.substring(name.lastIndexOf(".")+1);
// inner classes are not supported by ActionScript so we _
name = name.replaceAll("\\$", "_");
return name;
}
/**
* Creates and returns a declaration for a field equivalent to the supplied
* Java field in ActionScript.
*/
public static String createActionScriptDeclaration (
String name, Field field)
{
int mods = field.getModifiers();
StringBuilder builder = new StringBuilder();
// what's our visibility?
if (Modifier.isPublic(mods)) {
builder.append("public ");
} else if (Modifier.isProtected(mods)) {
builder.append("protected ");
} else if (Modifier.isPrivate(mods)) {
builder.append("private ");
}
// are we static?
if (Modifier.isStatic(mods)) {
builder.append("static ");
}
// const or variable?
builder.append(Modifier.isFinal(mods) ? "const " : "var ");
// next comes the name
builder.append(name).append(" :");
// now convert the type to an ActionScript type
builder.append(toActionScriptType(field.getType(),
!Modifier.isStatic(mods)));
builder.append(";");
return builder.toString();
}
public static String createActionScriptDeclaration (
Constructor ctor, boolean needsNoArg)
{
int mods = ctor.getModifiers();
StringBuilder builder = new StringBuilder();
// what's our visibility?
if (Modifier.isPublic(mods)) {
builder.append("public ");
} else if (Modifier.isProtected(mods)) {
builder.append("protected ");
} else if (Modifier.isPrivate(mods)) {
builder.append("private ");
}
// all constructors are functions
builder.append("function ");
// next comes the name
builder.append(toSimpleName(ctor.getName())).append(" (");
// now the parameters
int idx = 0;
for (Class<?> ptype : ctor.getParameterTypes()) {
if (idx++ > 0) {
builder.append(", ");
}
builder.append("arg").append(idx);
builder.append(" :").append(toActionScriptType(ptype, false));
if (needsNoArg) {
builder.append(" = undef");
}
}
builder.append(")");
return builder.toString();
}
public static String createActionScriptDeclaration (
String name, Method method)
{
int mods = method.getModifiers();
StringBuilder builder = new StringBuilder();
// TODO: override
// what's our visibility?
if (Modifier.isPublic(mods)) {
builder.append("public ");
} else if (Modifier.isProtected(mods)) {
builder.append("protected ");
} else if (Modifier.isPrivate(mods)) {
builder.append("private ");
}
// are we static const or variable?
if (Modifier.isStatic(mods)) {
builder.append("static ");
}
builder.append("function ");
// next comes the name
builder.append(name).append(" (");
// now the parameters
int idx = 0;
for (Class<?> ptype : method.getParameterTypes()) {
if (idx++ > 0) {
builder.append(", ");
}
builder.append("arg").append(idx);
builder.append(" :").append(toActionScriptType(ptype, false));
}
builder.append(") :");
builder.append(toActionScriptType(method.getReturnType(), false));
return builder.toString();
}
public static String toActionScriptType (Class type, boolean isField)
{
if (type.isArray()) {
if (Byte.TYPE.equals(type.getComponentType())) {
return "ByteArray";
}
return isField ? "TypedArray" : "Array";
}
if (Integer.class.equals(type) ||
Byte.TYPE.equals(type) ||
Short.TYPE.equals(type) ||
Character.TYPE.equals(type)) {
return "int";
}
if (Float.TYPE.equals(type) ||
Double.TYPE.equals(type)) {
return "Number";
}
if (Long.TYPE.equals(type)) {
return "Long";
}
if (Boolean.TYPE.equals(type)) {
return "Boolean";
}
return toSimpleName(type.getName());
}
public ActionScriptSource (Class jclass)
{
packageName = jclass.getPackage().getName();
className = jclass.getName().substring(packageName.length()+1);
Class sclass = jclass.getSuperclass();
if (sclass != null && !sclass.getName().equals("java.lang.Object")) {
superClassName = toSimpleName(sclass.getName());
}
isAbstract = ((jclass.getModifiers() & Modifier.ABSTRACT) != 0);
// note our implemented interfaces
ArrayList<String> ifaces = new ArrayList<String>();
for (Class iclass : jclass.getInterfaces()) {
// we cannot use the FooCodes interface pattern in ActionScript so we just nix it
if (iclass.getName().endsWith("Codes")) {
continue;
}
// we also nix Serializable and IsSerializable (hackity hack)
if (iclass.getName().endsWith("Serializable")) {
continue;
}
ifaces.add(toSimpleName(iclass.getName()));
}
// convert the field members
for (Field field : jclass.getDeclaredFields()) {
int mods = field.getModifiers();
ArrayList<Member> list;
if (Modifier.isStatic(mods)) {
list = Modifier.isPublic(mods) ?
publicConstants : protectedConstants;
} else {
list = Modifier.isPublic(mods) ? publicFields : protectedFields;
}
String name = field.getName();
ActionScript asa = field.getAnnotation(ActionScript.class);
if (asa != null) {
if (asa.omit()) {
continue;
}
if (!StringUtil.isBlank(asa.name())) {
name = asa.name();
}
}
String decl = createActionScriptDeclaration(name, field);
list.add(new Member(name, decl));
}
// ActionScript only supports one constructor so we find the one with the most arguments
// and we make a note whether or not we need a no argument constructor which we create
// using default arguments
Constructor<?> mainctor = null;
boolean needsNoArg = false;
for (Constructor<?> ctor : jclass.getConstructors()) {
ActionScript asa = ctor.getAnnotation(ActionScript.class);
if (asa != null && asa.omit()) {
continue;
}
int params = ctor.getParameterTypes().length;
if (mainctor == null ||
params > mainctor.getParameterTypes().length) {
mainctor = ctor;
}
needsNoArg = needsNoArg || (params == 0);
}
if (mainctor != null) {
int mods = mainctor.getModifiers();
ArrayList<Member> list;
list = Modifier.isPublic(mods) ?
publicConstructors : protectedConstructors;
Member mem = new Member(
toSimpleName(mainctor.getName()),
createActionScriptDeclaration(mainctor, needsNoArg));
mem.body = " {\n TODO: IMPLEMENT ME\n }\n";
list.add(mem);
}
for (Method method : jclass.getDeclaredMethods()) {
int mods = method.getModifiers();
ArrayList<Member> list;
if (Modifier.isStatic(mods)) {
list = Modifier.isPublic(mods) ?
publicStaticMethods : protectedStaticMethods;
} else {
list = Modifier.isPublic(mods) ?
publicMethods : protectedMethods;
}
String name = method.getName();
ActionScript asa = method.getAnnotation(ActionScript.class);
if (asa != null) {
if (asa.omit()) {
continue;
}
if (!StringUtil.isBlank(asa.name())) {
name = asa.name();
}
}
// see if we already have a member for this method name
Member mem = getMember(list, name);
String decl = createActionScriptDeclaration(name, method);
if (mem == null) {
mem = new Member(name, decl);
mem.body = " {\n TODO: IMPLEMENT ME\n }\n";
list.add(mem);
} else {
// TODO: only overwrite if we have more arguments
mem.definition = decl;
}
}
// if we override hashCode() then add Hashable to our interfaces
if (getMember(publicMethods, "hashCode") != null) {
ifaces.add("Hashable");
}
// finally turn our implemented interfaces into an array
implementedInterfaces = ifaces.toArray(new String[ifaces.size()]);
}
public void absorbJava (File jsource)
throws IOException
{
// parse our Java source file for niggling bits
BufferedReader bin = new BufferedReader(new FileReader(jsource));
String line = null;
Mode mode = Mode.PREAMBLE;
Matcher m;
int braceCount = 0;
boolean seenOpenBrace = false;
StringBuilder accum = new StringBuilder();
while ((line = bin.readLine()) != null) {
line = line.replaceAll("\\s+$", "");
switch (mode) {
case PREAMBLE:
// look for the package declaration
m = JPACKAGE.matcher(line);
if (m.matches()) {
preamble = accum.toString();
accum.setLength(0);
packageName = m.group(1);
mode = Mode.IMPORTS;
} else {
accum.append(line).append("\n");
}
break;
case IMPORTS:
// look for the start of the class comment
/**
* Writes our class definition to the supplied writer.
*/
public void write (PrintWriter writer)
{
writer.print(preamble);
writer.println("package " + packageName + " {");
writer.print(imports);
writer.print(classComment);
writer.print("public ");
if (isAbstract) {
writer.print("/*abstract*/ ");
}
writer.print("class " + className);
if (superClassName != null) {
writer.print(" extends " + superClassName);
}
writer.println("");
if (implementedInterfaces.length > 0) {
writer.print(" implements ");
for (int ii = 0; ii < implementedInterfaces.length; ii++) {
if (ii > 0) {
writer.print(", ");
}
writer.print(implementedInterfaces[ii]);
}
writer.println("");
}
writer.println("{"); // start class block
boolean writtenAnything = false;
for (Member member : publicConstants) {
writtenAnything = writeBlank(writtenAnything, writer);
member.write(writer);
}
for (Member member : publicFields) {
writtenAnything = writeBlank(writtenAnything, writer);
member.write(writer);
}
for (Member member : publicStaticMethods) {
writtenAnything = writeBlank(writtenAnything, writer);
member.write(writer);
}
for (Member member : publicConstructors) {
writtenAnything = writeBlank(writtenAnything, writer);
member.write(writer);
}
for (Member member : publicMethods) {
writtenAnything = writeBlank(writtenAnything, writer);
member.write(writer);
}
for (Member member : protectedConstructors) {
writtenAnything = writeBlank(writtenAnything, writer);
member.write(writer);
}
for (Member member : protectedMethods) {
writtenAnything = writeBlank(writtenAnything, writer);
member.write(writer);
}
for (Member member : protectedStaticMethods) {
writtenAnything = writeBlank(writtenAnything, writer);
member.write(writer);
}
for (Member member : protectedFields) {
writtenAnything = writeBlank(writtenAnything, writer);
member.write(writer);
}
for (Member member : protectedConstants) {
writtenAnything = writeBlank(writtenAnything, writer);
member.write(writer);
}
writer.println("}"); // end class block
writer.println("}"); // end package block
writer.flush();
}
public String toString ()
{
StringBuilder builder = new StringBuilder();
builder.append("public ");
if (isAbstract) {
builder.append("abstract ");
}
builder.append("class ").append(className);
if (superClassName != null) {
builder.append(" extends ").append(superClassName);
}
return builder.toString();
}
protected String slurpUntil (BufferedReader reader, String text, String token,
boolean stripNewlines)
throws IOException
{
int braces = countChars(text, '{') - countChars(text, '}');
String line;
while ((line = reader.readLine()) != null) {
braces += countChars(line, '{');
braces -= countChars(line, '}');
if (braces < 0) {
System.err.println(
"Too many close braces? [text=" + text + ", line=" + line + "].");
}
line = line.replaceAll("\\s+$", "");
if (!stripNewlines) {
text += "\n";
}
text += line;
if (braces <= 0 && line.indexOf(token) != -1) {
break;
}
}
return text;
}
protected int countChars (String text, char target)
{
int idx = -1, count = 0;
while ((idx = text.indexOf(target, idx+1)) != -1) {
count++;
}
return count;
}
protected boolean writeBlank (boolean writtenAnything, PrintWriter writer)
{
if (writtenAnything) {
writer.println("");
}
return true;
}
protected static enum Mode { PREAMBLE, IMPORTS, CLASSCOMMENT, CLASSDECL,
CLASSBODY, METHODBODY, POSTCLASS, POSTPKG };
protected static Pattern JPACKAGE = Pattern.compile("package\\s+(\\S+);");
protected static Pattern JFIELD = Pattern.compile(
"\\s+(?:public|protected|private)" +
"(?:\\s+static|\\s+final|\\s+transient)*" +
"\\s+(?:[a-zA-Z\\[\\]<>,]+)" + // type
"\\s+([_a-zA-Z]\\w*)(\\s+=.*|;)");
protected static Pattern JCONSTRUCTOR = Pattern.compile(
"\\s+(?:public|protected|private)\\s+([a-zA-Z]\\w*) \\(.*");
protected static Pattern JMETHOD = Pattern.compile(
"\\s+(?:public|protected|private).* ([a-zA-Z]\\w*) \\(.*");
protected static Pattern JANNOTATION = Pattern.compile(
".*@ActionScript\\(name=\"(\\w+)\"\\).*");
protected static Pattern ASFIELD = Pattern.compile(
"\\s+(?:public|protected|private)" +
"(?:\\s+static)?(?:\\s+var|\\s+const)?" +
"\\s+([_a-zA-Z]\\w*)" + // variable name
"\\s+(?::[a-zA-Z\\[\\]<>,]+)" + // type
"(\\s+=.*|;)");
protected static Pattern ASFUNCTION = Pattern.compile(
".*(?:public|protected)" +
"(?:\\s+static)?" +
"(?:\\s+/\\*\\s*abstract\\s*\\*/)?" +
"\\s+function\\s+([a-zA-Z]\\w*) \\(.*");
protected static Pattern ARRAYINIT = Pattern.compile("new (\\w+)\\[0\\]");
}
|
package org.antlr.intellij.plugin.profiler;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.ScrollingModel;
import com.intellij.openapi.editor.event.EditorMouseEvent;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.table.JBTable;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import org.antlr.intellij.plugin.ANTLRv4PluginController;
import org.antlr.intellij.plugin.preview.PreviewState;
import org.antlr.runtime.CommonToken;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.atn.AmbiguityInfo;
import org.antlr.v4.runtime.atn.ContextSensitivityInfo;
import org.antlr.v4.runtime.atn.DecisionEventInfo;
import org.antlr.v4.runtime.atn.DecisionInfo;
import org.antlr.v4.runtime.atn.DecisionState;
import org.antlr.v4.runtime.atn.ParseInfo;
import org.antlr.v4.runtime.atn.PredicateEvalInfo;
import org.antlr.v4.runtime.atn.SemanticContext;
import org.antlr.v4.runtime.misc.Interval;
import org.antlr.v4.tool.Grammar;
import org.antlr.v4.tool.Rule;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
public class ProfilerPanel {
/* TODO:
* TER: context-sens is when SLL fails but LL has no conflict in my book
* SLL fail is heuristic though. hmm...
*
* SAM: At the point of LL fallback, mine makes a note of the conflicting
* ATNConfigSet produced by SLL prediction, and then compares that set
* to the result provided by LL prediction. If SLL conflict resolution
* would not have produced the same result as LL prediction, I report
* the decision as context-sensitive.
*/
public static final Color AMBIGUITY_COLOR = new Color(138, 0, 0);
public static final Color FULLCTX_COLOR = new Color(255, 128, 0);
public static final Color PREDEVAL_COLOR = new Color(110, 139, 61);
public static final Color DEEPESTLOOK_COLOR = new Color(0, 128, 128);
public static final Key<DecisionEventInfo> DECISION_EVENT_INFO_KEY = Key.create("DECISION_EVENT_INFO");
public Project project;
public PreviewState previewState;
protected JPanel outerPanel;
protected JPanel statsPanel;
protected JLabel parseTimeField;
protected JLabel predictionTimeField;
protected JLabel lookaheadBurdenField;
protected JLabel cacheMissRateField;
protected JLabel inputSizeField;
protected JLabel numTokensField;
protected JCheckBox expertCheckBox;
protected JLabel ambiguityColorLabel;
protected JLabel contextSensitivityColorLabel;
protected JLabel predEvaluationColorLabel;
protected JBTable profilerDataTable;
protected JLabel deepestLookaheadLabel;
public void switchToGrammar(PreviewState previewState, VirtualFile grammarFile) {
DefaultTableModel model = new DefaultTableModel();
profilerDataTable.setModel(model);
profilerDataTable.setRowSorter(new TableRowSorter<AbstractTableModel>(model));
}
public void mouseEnteredGrammarEditorEvent(VirtualFile vfile, EditorMouseEvent e) {
MarkupModel markupModel = e.getEditor().getMarkupModel();
markupModel.removeAllHighlighters();
}
public JPanel getComponent() {
return outerPanel;
}
public JBTable getProfilerDataTable() {
return profilerDataTable;
}
public ProfilerPanel(Project project) {
this.project = project;
}
public void setProfilerData(PreviewState previewState,
long parseTime_ns) {
this.previewState = previewState;
Parser parser = previewState.parsingResult.parser;
ParseInfo parseInfo = parser.getParseInfo();
updateTableModelPerExpertCheckBox(parseInfo);
long parseTimeMS = (long)(parseTime_ns/(1000.0*1000.0));
parseTimeField.setText(String.valueOf(parseTimeMS));
int predTimeMS = (int)(parseInfo.getTotalTimeInPrediction()/(1000.0*1000.0));
predictionTimeField.setText(
String.format("%d = %3.2f%%", predTimeMS, 100*((double)predTimeMS)/parseTimeMS)
);
TokenStream tokens = parser.getInputStream();
int numTokens = tokens.size();
Token lastToken = tokens.get(numTokens-1);
int numChar = lastToken.getStopIndex();
int numLines = lastToken.getLine();
if ( lastToken.getType()==Token.EOF ) {
if ( numTokens<=1 ) {
numLines = 0;
}
else {
Token secondToLastToken = tokens.get(numTokens-2);
numLines = secondToLastToken.getLine();
}
}
inputSizeField.setText(String.format("%d char, %d lines",
numChar,
numLines));
numTokensField.setText(String.valueOf(numTokens));
double look = parseInfo.getTotalLookaheadOps();
lookaheadBurdenField.setText(
String.format("%d/%d = %3.2f", (long)look, numTokens, look/numTokens)
);
double atnLook = parseInfo.getTotalATNLookaheadOps();
cacheMissRateField.setText(
String.format("%d/%d = %3.2f%%", (long)atnLook, (long)look, atnLook*100.0/look)
);
}
public void updateTableModelPerExpertCheckBox(ParseInfo parseInfo) {
AbstractTableModel model;
if ( expertCheckBox.isSelected() ) {
model = new ExpertProfilerTableDataModel(parseInfo);
}
else {
model = new SimpleProfilerTableDataModel(parseInfo);
}
profilerDataTable.setModel(model);
profilerDataTable.setRowSorter(new TableRowSorter<AbstractTableModel>(model));
}
public void selectDecisionInGrammar(PreviewState previewState, int decision) {
ANTLRv4PluginController controller = ANTLRv4PluginController.getInstance(project);
Editor grammarEditor = controller.getCurrentGrammarEditor();
DecisionState decisionState = previewState.g.atn.getDecisionState(decision);
Interval region = previewState.g.getStateToGrammarRegion(decisionState.stateNumber);
if ( region==null ) {
System.err.println("decision "+decision+" has state "+decisionState.stateNumber+" but no region");
return;
}
MarkupModel markupModel = grammarEditor.getMarkupModel();
markupModel.removeAllHighlighters();
org.antlr.runtime.TokenStream tokens = previewState.g.tokenStream;
if ( region.a>=tokens.size()||region.b>=tokens.size() ) {
// System.out.println("out of range: " + region + " tokens.size()=" + tokens.size());
return;
}
CommonToken startToken = (CommonToken)tokens.get(region.a);
CommonToken stopToken = (CommonToken)tokens.get(region.b);
TextAttributes attr =
new TextAttributes(JBColor.BLACK, JBColor.WHITE, JBColor.darkGray,
EffectType.ROUNDED_BOX, Font.PLAIN);
markupModel.addRangeHighlighter(
startToken.getStartIndex(),
stopToken.getStopIndex()+1,
HighlighterLayer.SELECTION, // layer
attr,
HighlighterTargetArea.EXACT_RANGE
);
// System.out.println("dec " + decision + " from " + startToken + " to " + stopToken);
ScrollingModel scrollingModel = grammarEditor.getScrollingModel();
CaretModel caretModel = grammarEditor.getCaretModel();
caretModel.moveToOffset(startToken.getStartIndex());
scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE);
}
public void tagAmbiguousDecisionsInGrammar(PreviewState previewState) {
// ANTLRv4PluginController controller = ANTLRv4PluginController.getInstance(project);
// Editor grammarEditor = controller.getCurrentGrammarEditor();
// ParseInfo parseInfo = previewState.parsingResult.parser.getParseInfo();
// DecisionInfo[] decisionInfo = parseInfo.getDecisionInfo();
// for (DecisionState decisionState : previewState.g.atn.decisionToState) {
// if ( decisionInfo[decisionState.decision].ambiguities.size()==0 ) {
// continue;
// Interval region = previewState.g.getStateToGrammarRegion(decisionState.stateNumber);
// if ( region==null ) {
// System.err.println("decision "+decisionState.decision+" has state "+decisionState.stateNumber+" but no region");
// return;
// MarkupModel markupModel = grammarEditor.getMarkupModel();
// markupModel.removeAllHighlighters();
// org.antlr.runtime.TokenStream tokens = previewState.g.tokenStream;
// if ( region.a>=tokens.size()||region.b>=tokens.size() ) {
//// System.out.println("out of range: " + region + " tokens.size()=" + tokens.size());
// return;
// CommonToken startToken = (CommonToken)tokens.get(region.a);
// CommonToken stopToken = (CommonToken)tokens.get(region.b);
// TextAttributes attr =
// new TextAttributes(JBColor.BLACK, JBColor.WHITE, JBColor.darkGray,
// EffectType.ROUNDED_BOX, Font.PLAIN);
// markupModel.addRangeHighlighter(
// startToken.getStartIndex(),
// stopToken.getStopIndex()+1,
// HighlighterLayer.SELECTION, // layer
// attr,
// HighlighterTargetArea.EXACT_RANGE
//// System.out.println("dec " + decision + " from " + startToken + " to " + stopToken);
// ScrollingModel scrollingModel = grammarEditor.getScrollingModel();
// CaretModel caretModel = grammarEditor.getCaretModel();
// caretModel.moveToOffset(startToken.getStartIndex());
// scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE);
}
public void highlightPhrases(PreviewState previewState, int decision) {
if ( previewState.parsingResult==null ) {
return;
}
ParseInfo parseInfo = previewState.parsingResult.parser.getParseInfo();
Editor editor = previewState.getEditor();
ScrollingModel scrollingModel = editor.getScrollingModel();
CaretModel caretModel = editor.getCaretModel();
MarkupModel markupModel = editor.getMarkupModel();
markupModel.removeAllHighlighters();
DecisionInfo decisionInfo = parseInfo.getDecisionInfo()[decision];
Token firstToken = null;
// deepest lookahead
if ( decisionInfo.maxLookEvent!=null&&
(decisionInfo.maxLookEvent.stopIndex-decisionInfo.maxLookEvent.startIndex+1)>1 ) // ignore k=1
{
Token t = addDecisionEventHighlighter(previewState, markupModel,
decisionInfo.maxLookEvent,
DEEPESTLOOK_COLOR,
EffectType.BOLD_DOTTED_LINE);
firstToken = t;
// rangeHighlighter.setLineMarkerRenderer(
// new LineMarkerRenderer() {
// @Override
// public void paint(Editor editor, Graphics g, Rectangle r) {
// // draws left gutter range like for brace highlighting
// final EditorGutterComponentEx gutter = ((EditorEx)editor).getGutterComponentEx();
// g.setColor(DEEPESTLOOK_COLOR);
// final int endX = gutter.getWhitespaceSeparatorOffset();
// final int x = r.x+r.width-5;
// final int width = endX-x;
// if ( r.height>0 ) {
// g.fillRect(x, r.y, width, r.height);
// g.setColor(gutter.getOutlineColor(false));
// UIUtil.drawLine(g, x, r.y, x+width, r.y);
// UIUtil.drawLine(g, x, r.y, x, r.y+r.height-1);
// UIUtil.drawLine(g, x, r.y+r.height-1, x+width, r.y+r.height-1);
// else {
// final int[] xPoints = new int[]{x,
// x+width-1};
// final int[] yPoints = new int[]{r.y-4,
// r.y+4,
// g.fillPolygon(xPoints, yPoints, 3);
// g.setColor(gutter.getOutlineColor(false));
// g.drawPolygon(xPoints, yPoints, 3);
}
if ( decisionInfo.ambiguities.size()==0&&
decisionInfo.contextSensitivities.size()==0&&
decisionInfo.predicateEvals.size()==0&&
decisionInfo.maxLookEvent==null ) {
return;
}
// pred evals
for (PredicateEvalInfo predEvalInfo : decisionInfo.predicateEvals) {
Token t = addDecisionEventHighlighter(previewState, markupModel, predEvalInfo, PREDEVAL_COLOR, EffectType.ROUNDED_BOX);
if ( firstToken==null ) firstToken = t;
}
// context-sensitivities
for (ContextSensitivityInfo ctxSensitivityInfo : decisionInfo.contextSensitivities) {
Token t = addDecisionEventHighlighter(previewState, markupModel, ctxSensitivityInfo, FULLCTX_COLOR, EffectType.ROUNDED_BOX);
if ( firstToken==null ) firstToken = t;
}
// ambiguities (might overlay context-sensitivities)
for (AmbiguityInfo ambiguityInfo : decisionInfo.ambiguities) {
Token t = addDecisionEventHighlighter(previewState, markupModel, ambiguityInfo, AMBIGUITY_COLOR, EffectType.ROUNDED_BOX);
if ( firstToken==null ) firstToken = t;
}
if ( firstToken!=null ) {
caretModel.moveToOffset(firstToken.getStartIndex());
scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE);
// HighlightManager.getInstance(project).addRangeHighlight(
// editor,
// firstToken.getStartIndex(),
// firstToken.getStopIndex() + 1,
// textAttributes,
// false,
// false,
// null);
// HighlightManager.getInstance(project).addOccurrenceHighlight(
// editor,
// firstToken.getStartIndex(),
// firstToken.getStopIndex() + 1,
// textAttributes,
// HighlightManager.HIDE_BY_TEXT_CHANGE,
// new ArrayList<RangeHighlighter>() {{
// add(rangeHighlighter);
// AMBIGUITY_COLOR
}
}
public Token addDecisionEventHighlighter(PreviewState previewState, MarkupModel markupModel,
DecisionEventInfo info, Color errorStripeColor,
EffectType effectType)
{
TokenStream tokens = previewState.parsingResult.parser.getInputStream();
Token startToken = tokens.get(info.startIndex);
Token stopToken = tokens.get(info.stopIndex);
TextAttributes textAttributes =
new TextAttributes(JBColor.BLACK, JBColor.WHITE, errorStripeColor,
effectType, Font.PLAIN);
textAttributes.setErrorStripeColor(errorStripeColor);
final RangeHighlighter rangeHighlighter =
markupModel.addRangeHighlighter(
startToken.getStartIndex(), stopToken.getStopIndex()+1,
HighlighterLayer.ADDITIONAL_SYNTAX, textAttributes,
HighlighterTargetArea.EXACT_RANGE);
rangeHighlighter.putUserData(DECISION_EVENT_INFO_KEY, info);
rangeHighlighter.setErrorStripeMarkColor(errorStripeColor);
return startToken;
}
public static String getSemanticContextDisplayString(PredicateEvalInfo pred,
PreviewState previewState,
SemanticContext semctx,
int alt,
boolean result)
{
Grammar g = previewState.g;
String semanticContextDisplayString = g.getSemanticContextDisplayString(semctx);
if ( semctx instanceof SemanticContext.PrecedencePredicate ) {
int ruleIndex = previewState.parsingResult.parser.getATN().decisionToState.get(pred.decision).ruleIndex;
Rule rule = g.getRule(ruleIndex);
int precedence = ((SemanticContext.PrecedencePredicate)semctx).precedence;
// precedence = n - originalAlt + 1, So:
int originalAlt = rule.getOriginalNumberOfAlts()-precedence+1;
alt = originalAlt;
}
return semanticContextDisplayString+" => alt "+alt+" is "+result;
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
outerPanel = new JPanel();
outerPanel.setLayout(new BorderLayout(0, 0));
statsPanel = new JPanel();
statsPanel.setLayout(new GridLayoutManager(12, 3, new Insets(0, 5, 0, 0), -1, -1));
outerPanel.add(statsPanel, BorderLayout.EAST);
final JLabel label1 = new JLabel();
label1.setText("Parse time (ms):");
statsPanel.add(label1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(130, 16), null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("Prediction time (ms):");
statsPanel.add(label2, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(130, 16), null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("Lookahead burden:");
statsPanel.add(label3, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(130, 16), null, 0, false));
final JLabel label4 = new JLabel();
label4.setText("DFA cache miss rate:");
statsPanel.add(label4, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(130, 16), null, 0, false));
final Spacer spacer1 = new Spacer();
statsPanel.add(spacer1, new GridConstraints(11, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, new Dimension(-1, 14), null, 0, false));
final Spacer spacer2 = new Spacer();
statsPanel.add(spacer2, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
parseTimeField = new JLabel();
parseTimeField.setText("0");
statsPanel.add(parseTimeField, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
predictionTimeField = new JLabel();
predictionTimeField.setText("0");
statsPanel.add(predictionTimeField, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
lookaheadBurdenField = new JLabel();
lookaheadBurdenField.setText("0");
statsPanel.add(lookaheadBurdenField, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
cacheMissRateField = new JLabel();
cacheMissRateField.setText("0");
statsPanel.add(cacheMissRateField, new GridConstraints(5, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label5 = new JLabel();
label5.setText("Input size:");
statsPanel.add(label5, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(130, 16), null, 0, false));
inputSizeField = new JLabel();
inputSizeField.setText("0");
statsPanel.add(inputSizeField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label6 = new JLabel();
label6.setText("Number of tokens:");
statsPanel.add(label6, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
numTokensField = new JLabel();
numTokensField.setText("0");
statsPanel.add(numTokensField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(4, 1, new Insets(0, 0, 0, 0), -1, -1));
statsPanel.add(panel1, new GridConstraints(7, 0, 4, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
panel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), null));
ambiguityColorLabel.setText("Ambiguity");
panel1.add(ambiguityColorLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
contextSensitivityColorLabel.setText("Context-sensitivity");
panel1.add(contextSensitivityColorLabel, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
predEvaluationColorLabel.setText("Predicate evaluation");
panel1.add(predEvaluationColorLabel, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
deepestLookaheadLabel.setText("Deepest lookahead");
panel1.add(deepestLookaheadLabel, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
expertCheckBox.setText("Show expert columns");
statsPanel.add(expertCheckBox, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK|GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JScrollPane scrollPane1 = new JScrollPane();
outerPanel.add(scrollPane1, BorderLayout.CENTER);
profilerDataTable.setPreferredScrollableViewportSize(new Dimension(800, 400));
scrollPane1.setViewportView(profilerDataTable);
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return outerPanel;
}
class ProfileTableCellRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if ( previewState==null||previewState.parsingResult==null ) {
return c;
}
ParseInfo parseInfo = previewState.parsingResult.parser.getParseInfo();
int decision = profilerDataTable.convertRowIndexToModel(row);
DecisionInfo[] decisions = parseInfo.getDecisionInfo();
if ( decision>=decisions.length ) {
return c;
}
DecisionInfo decisionInfo = decisions[decision];
if ( decisionInfo.ambiguities.size()>0 ) {
setForeground(AMBIGUITY_COLOR);
}
else if ( decisionInfo.contextSensitivities.size()>0 ) {
setForeground(FULLCTX_COLOR);
}
else if ( decisionInfo.predicateEvals.size()>0 ) {
setForeground(PREDEVAL_COLOR);
}
return c;
}
}
private void createUIComponents() {
expertCheckBox = new JBCheckBox();
expertCheckBox.setSelected(false);
expertCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ParseInfo parseInfo = previewState.parsingResult.parser.getParseInfo();
updateTableModelPerExpertCheckBox(parseInfo);
}
});
profilerDataTable = new JBTable() {
@Override
protected JTableHeader createDefaultTableHeader() {
return new JTableHeader(columnModel) {
public String getToolTipText(MouseEvent e) {
Point p = e.getPoint();
int index = columnModel.getColumnIndexAtX(p.x);
int realIndex = columnModel.getColumn(index).getModelIndex();
TableModel model = getModel();
if ( model instanceof ProfilerTableDataModel ) {
return ((ProfilerTableDataModel)model).getColumnToolTips()[realIndex];
}
return model.getColumnName(realIndex);
}
};
}
@Override
public TableCellRenderer getDefaultRenderer(Class<?> columnClass) {
return new ProfileTableCellRenderer();
}
};
ListSelectionModel selectionModel = profilerDataTable.getSelectionModel();
selectionModel.addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
// previewState, project set later
if ( e.getValueIsAdjusting() ) {
return; // this seems to be "mouse down" but not mouse up
}
// get state for current grammar editor tab
if ( project==null ) {
return;
}
PreviewState previewState = ANTLRv4PluginController.getInstance(project).getPreviewState();
if ( previewState!=null&&profilerDataTable.getModel().getClass()!=DefaultTableModel.class ) {
int selectedRow = profilerDataTable.getSelectedRow();
if ( selectedRow==-1 ) {
selectedRow = 0;
}
int decision = profilerDataTable.convertRowIndexToModel(selectedRow);
int numberOfDecisions = previewState.g.atn.getNumberOfDecisions();
if ( decision<=numberOfDecisions ) {
selectDecisionInGrammar(previewState, decision);
highlightPhrases(previewState, decision);
}
}
}
}
);
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ambiguityColorLabel = new JBLabel("Ambiguity");
ambiguityColorLabel.setForeground(AMBIGUITY_COLOR);
contextSensitivityColorLabel = new JBLabel("Context sensitivity");
contextSensitivityColorLabel.setForeground(FULLCTX_COLOR);
predEvaluationColorLabel = new JBLabel("Predicate evaluation");
predEvaluationColorLabel.setForeground(PREDEVAL_COLOR);
deepestLookaheadLabel = new JBLabel("Deepest lookahead");
deepestLookaheadLabel.setForeground(DEEPESTLOOK_COLOR);
}
}
|
package org.apache.james.transport.mailets;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.james.services.JamesUser;
import org.apache.mailet.GenericMailet;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import org.apache.mailet.MailetConfig;
import org.apache.mailet.UsersRepository;
/**
* Receives a Mail from JamesSpoolManager and takes care of delivery of the
* message to local inboxes.
*/
public class LocalDelivery extends GenericMailet {
private boolean enableAliases;
private boolean enableForwarding;
private boolean ignoreCase;
private String inboxURI;
private UsersRepository localusers;
private String users;
/**
* Return a string describing this mailet.
*
* @return a string describing this mailet
*/
public String getMailetInfo() {
return "Local Delivery Mailet";
}
/**
* @see org.apache.mailet.Mailet#init(org.apache.mailet.MailetConfig)
*/
public void init(MailetConfig newConfig) throws MessagingException {
super.init(newConfig);
if (newConfig.getInitParameter("inboxURI") != null) {
inboxURI = newConfig.getInitParameter("inboxURI");
} else {
log("No inboxURI defined for LocalDelivery");
}
if (newConfig.getInitParameter("users") != null) {
users = newConfig.getInitParameter("users");
localusers = getMailetContext().getUserRepository(users);
} else {
log("No users repository defined for LocalDelivery");
}
if (newConfig.getInitParameter("ignoreCase") != null) {
ignoreCase = Boolean.valueOf(newConfig.getInitParameter("ignoreCase")).booleanValue();
} else {
ignoreCase = false;
}
if (newConfig.getInitParameter("enableAliases") != null) {
enableAliases = Boolean.valueOf(newConfig.getInitParameter("enableAliases")).booleanValue();
} else {
enableAliases = false;
}
if (newConfig.getInitParameter("enableForwarding") != null) {
enableForwarding = Boolean.valueOf(newConfig.getInitParameter("enableForwarding")).booleanValue();
} else {
enableForwarding = false;
}
}
/* MimeMessage that does NOT change the headers when we save it */
class LocalMimeMessage extends MimeMessage {
public LocalMimeMessage(MimeMessage source) throws MessagingException {
super(source);
}
protected void updateHeaders() throws MessagingException {
if (getMessageID() == null) super.updateHeaders();
else {
modified = false;
}
}
}
/**
* Delivers a mail to a local mailbox.
*
* @param mail the mail being processed
*
* @throws MessagingException if an error occurs while storing the mail
*/
public void service(Mail mail) throws MessagingException {
Collection recipients = mail.getRecipients();
Collection errors = new Vector();
if (mail == null) {
throw new IllegalArgumentException("Mail message to be stored cannot be null.");
}
MimeMessage message = mail.getMessage();
for (Iterator i = recipients.iterator(); i.hasNext();) {
MailAddress recipient = (MailAddress)i.next();
String username = null;
if (recipient == null) {
throw new IllegalArgumentException("Recipient for mail to be stored cannot be null.");
}
if (ignoreCase) {
username = localusers.getRealName(recipient.getUser());
} else if (localusers.contains(recipient.getUser())) {
username = recipient.getUser();
}
if (username == null) {
StringBuffer errorBuffer =
new StringBuffer(128).append("The inbox for user ").append(recipient.getUser()).append(
" was not found on this server.");
throw new MessagingException(errorBuffer.toString());
}
if ((JamesUser)localusers.getUserByName(username) instanceof JamesUser) {
JamesUser user = (JamesUser)localusers.getUserByName(username);
if (enableAliases || enableForwarding) {
if (enableAliases && user.getAliasing()) {
username = user.getAlias();
}
// Forwarding takes precedence over local aliases
if (enableForwarding && user.getForwarding()) {
MailAddress forwardTo = user.getForwardingDestination();
if (forwardTo == null) {
StringBuffer errorBuffer =
new StringBuffer(128).append("Forwarding was enabled for ").append(
username).append(
" but no forwarding address was set for this account.");
throw new MessagingException(errorBuffer.toString());
}
recipients = new HashSet();
recipients.add(forwardTo);
try {
getMailetContext().sendMail(mail.getSender(), recipients, localMessage);
StringBuffer logBuffer =
new StringBuffer(128).append("Mail for ").append(username).append(
" forwarded to ").append(
forwardTo.toString());
log(logBuffer.toString());
return;
} catch (MessagingException me) {
StringBuffer logBuffer =
new StringBuffer(128).append("Error forwarding mail to ").append(
forwardTo.toString()).append(
"attempting local delivery");
log(logBuffer.toString());
throw me;
}
}
}
}
try {
// Add qmail's de facto standard Delivered-To header
MimeMessage localMessage = new LocalMimeMessage(message);
localMessage.addHeader("Delivered-To", recipient.toString());
localMessage.saveChanges();
getMailetContext().getMailRepository(inboxURI + recipient.getUser() + "/").store(mail);
} catch (Exception ex) {
getMailetContext().log("Error while storing mail.", ex);
errors.add(recipient);
}
}
if (!errors.isEmpty()) {
// If there were errors, we redirect the email to the ERROR processor.
// In order for this server to meet the requirements of the SMTP specification,
// mails on the ERROR processor must be returned to the sender. Note that this
// email doesn't include any details regarding the details of the failure(s).
// In the future we may wish to address this.
getMailetContext().sendMail(mail.getSender(), errors, message, Mail.ERROR);
}
//We always consume this message
mail.setState(Mail.GHOST);
}
}
|
package org.apache.james.transport.mailets;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.james.services.JamesUser;
import org.apache.mailet.GenericMailet;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import org.apache.mailet.MailetConfig;
import org.apache.mailet.UsersRepository;
/**
* Receives a Mail from JamesSpoolManager and takes care of delivery of the
* message to local inboxes.
*/
public class LocalDelivery extends GenericMailet {
private boolean enableAliases;
private boolean enableForwarding;
private boolean ignoreCase;
private String inboxURI;
private UsersRepository localusers;
private String users;
/**
* Return a string describing this mailet.
*
* @return a string describing this mailet
*/
public String getMailetInfo() {
return "Local Delivery Mailet";
}
/**
* @see org.apache.mailet.Mailet#init(org.apache.mailet.MailetConfig)
*/
public void init(MailetConfig newConfig) throws MessagingException {
super.init(newConfig);
if (newConfig.getInitParameter("inboxURI") != null) {
inboxURI = newConfig.getInitParameter("inboxURI");
} else {
log("No inboxURI defined for LocalDelivery");
}
if (newConfig.getInitParameter("users") != null) {
users = newConfig.getInitParameter("users");
localusers = getMailetContext().getUserRepository(users);
} else {
log("No users repository defined for LocalDelivery");
}
if (newConfig.getInitParameter("ignoreCase") != null) {
ignoreCase = Boolean.valueOf(newConfig.getInitParameter("ignoreCase")).booleanValue();
} else {
ignoreCase = false;
}
if (newConfig.getInitParameter("enableAliases") != null) {
enableAliases = Boolean.valueOf(newConfig.getInitParameter("enableAliases")).booleanValue();
} else {
enableAliases = false;
}
if (newConfig.getInitParameter("enableForwarding") != null) {
enableForwarding = Boolean.valueOf(newConfig.getInitParameter("enableForwarding")).booleanValue();
} else {
enableForwarding = false;
}
}
/* MimeMessage that does NOT change the headers when we save it */
class LocalMimeMessage extends MimeMessage {
public LocalMimeMessage(MimeMessage source) throws MessagingException {
super(source);
}
protected void updateHeaders() throws MessagingException {
if (getMessageID() == null) super.updateHeaders();
else {
modified = false;
}
}
}
/**
* Delivers a mail to a local mailbox.
*
* @param mail the mail being processed
*
* @throws MessagingException if an error occurs while storing the mail
*/
public void service(Mail mail) throws MessagingException {
Collection recipients = mail.getRecipients();
Collection errors = new Vector();
if (mail == null) {
throw new IllegalArgumentException("Mail message to be stored cannot be null.");
}
MimeMessage message = mail.getMessage();
for (Iterator i = recipients.iterator(); i.hasNext();) {
MailAddress recipient = (MailAddress)i.next();
String username = null;
if (recipient == null) {
throw new IllegalArgumentException("Recipient for mail to be stored cannot be null.");
}
if (ignoreCase) {
username = localusers.getRealName(recipient.getUser());
} else if (localusers.contains(recipient.getUser())) {
username = recipient.getUser();
}
if (username == null) {
StringBuffer errorBuffer =
new StringBuffer(128).append("The inbox for user ").append(recipient.getUser()).append(
" was not found on this server.");
throw new MessagingException(errorBuffer.toString());
}
if ((JamesUser)localusers.getUserByName(username) instanceof JamesUser) {
JamesUser user = (JamesUser)localusers.getUserByName(username);
if (enableAliases || enableForwarding) {
if (enableAliases && user.getAliasing()) {
username = user.getAlias();
}
// Forwarding takes precedence over local aliases
if (enableForwarding && user.getForwarding()) {
MailAddress forwardTo = user.getForwardingDestination();
if (forwardTo == null) {
StringBuffer errorBuffer =
new StringBuffer(128).append("Forwarding was enabled for ").append(
username).append(
" but no forwarding address was set for this account.");
throw new MessagingException(errorBuffer.toString());
}
recipients = new HashSet();
recipients.add(forwardTo);
try {
getMailetContext().sendMail(mail.getSender(), recipients, message);
StringBuffer logBuffer =
new StringBuffer(128).append("Mail for ").append(username).append(
" forwarded to ").append(
forwardTo.toString());
log(logBuffer.toString());
return;
} catch (MessagingException me) {
StringBuffer logBuffer =
new StringBuffer(128).append("Error forwarding mail to ").append(
forwardTo.toString()).append(
"attempting local delivery");
log(logBuffer.toString());
throw me;
}
}
}
}
try {
// Add qmail's de facto standard Delivered-To header
MimeMessage localMessage = new LocalMimeMessage(message);
localMessage.addHeader("Delivered-To", recipient.toString());
localMessage.saveChanges();
getMailetContext().getMailRepository(inboxURI + recipient.getUser() + "/").store(mail);
} catch (Exception ex) {
getMailetContext().log("Error while storing mail.", ex);
errors.add(recipient);
}
}
if (!errors.isEmpty()) {
// If there were errors, we redirect the email to the ERROR processor.
// In order for this server to meet the requirements of the SMTP specification,
// mails on the ERROR processor must be returned to the sender. Note that this
// email doesn't include any details regarding the details of the failure(s).
// In the future we may wish to address this.
getMailetContext().sendMail(mail.getSender(), errors, message, Mail.ERROR);
}
//We always consume this message
mail.setState(Mail.GHOST);
}
}
|
package org.apache.lenya.cms.publication;
import java.io.File;
/**
* A typical CMS document.
*
* @author <a href="mailto:andreas.hartmann@wyona.org">Andreas Hartmann</a>
*/
public class DefaultDocument implements Document {
/** Creates a new instance of DefaultDocument */
public DefaultDocument(Publication publication, String id) {
assert id != null;
this.id = id;
assert publication != null;
this.publication = publication;
}
private String id;
private Publication publication;
/* (non-Javadoc)
* @see org.apache.lenya.cms.publication.Document#getFile()
*/
public String getId() {
return id;
}
/* (non-Javadoc)
* @see org.apache.lenya.cms.publication.Document#getPublication()
*/
public Publication getPublication() {
return publication;
}
/**
* Returns the file for this document in a certain area and language.
* @param area The area.
* @param language The language.
* @return A file object.
*/
public File getFile(String area, String language) {
return getPublication().getPathMapper().getFile(
getPublication(), area, getId(), language);
}
/**
* Returns the files for this document in a certain area and all languages.
* @param area The area.
* @return A file object.
*/
public File[] getFiles(String area) {
return getPublication().getPathMapper().getFiles(getPublication(), area, getId());
}
}
|
package org.jivesoftware.wildfire.ldap;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.Log;
import org.jivesoftware.wildfire.XMPPServer;
import org.jivesoftware.wildfire.group.Group;
import org.jivesoftware.wildfire.group.GroupNotFoundException;
import org.jivesoftware.wildfire.group.GroupProvider;
import org.jivesoftware.wildfire.user.UserManager;
import org.jivesoftware.wildfire.user.UserNotFoundException;
import org.xmpp.packet.JID;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.Control;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.SortControl;
import java.text.MessageFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* LDAP implementation of the GroupProvider interface. All data in the directory is treated as
* read-only so any set operations will result in an exception.
*
* @author Matt Tucker, Greg Ferguson and Cameron Moore
*/
public class LdapGroupProvider implements GroupProvider {
private LdapManager manager;
private UserManager userManager;
private String[] standardAttributes;
/**
* Constructs a new LDAP group provider.
*/
public LdapGroupProvider() {
manager = LdapManager.getInstance();
userManager = UserManager.getInstance();
standardAttributes = new String[3];
standardAttributes[0] = manager.getGroupNameField();
standardAttributes[1] = manager.getGroupDescriptionField();
standardAttributes[2] = manager.getGroupMemberField();
}
/**
* Always throws an UnsupportedOperationException because LDAP groups are read-only.
*
* @param name the name of the group to create.
* @throws UnsupportedOperationException when called.
*/
public Group createGroup(String name) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* Always throws an UnsupportedOperationException because LDAP groups are read-only.
*
* @param name the name of the group to delete
* @throws UnsupportedOperationException when called.
*/
public void deleteGroup(String name) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
public Group getGroup(String groupName) throws GroupNotFoundException {
LdapContext ctx = null;
try {
ctx = manager.getContext();
// Search for the dn based on the group name.
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
searchControls.setReturningAttributes(standardAttributes);
String filter = MessageFormat.format(manager.getGroupSearchFilter(), groupName);
NamingEnumeration<SearchResult> answer = ctx.search("", filter, searchControls);
Collection<Group> groups = populateGroups(answer);
// Close the enumeration.
answer.close();
if (groups.size() > 1) {
// If multiple groups found, throw exception.
throw new GroupNotFoundException("Too many groups with name " + groupName + " were found.");
}
else if (groups.isEmpty()) {
throw new GroupNotFoundException("Group with name " + groupName + " not found.");
}
else {
return groups.iterator().next();
}
}
catch (Exception e) {
Log.error(e);
throw new GroupNotFoundException(e);
}
finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
}
catch (Exception ignored) {
// Ignore.
}
}
}
/**
* Always throws an UnsupportedOperationException because LDAP groups are read-only.
*
* @param oldName the current name of the group.
* @param newName the desired new name of the group.
* @throws UnsupportedOperationException when called.
*/
public void setName(String oldName, String newName) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* Always throws an UnsupportedOperationException because LDAP groups are read-only.
*
* @param name the group name.
* @param description the group description.
* @throws UnsupportedOperationException when called.
*/
public void setDescription(String name, String description)
throws UnsupportedOperationException
{
throw new UnsupportedOperationException();
}
public int getGroupCount() {
if (manager.isDebugEnabled()) {
Log.debug("Trying to get the number of groups in the system.");
}
int count = 0;
LdapContext ctx = null;
try {
ctx = manager.getContext();
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
NamingEnumeration answer = ctx.search("", filter, searchControls);
while (answer.hasMoreElements()) {
answer.next();
count++;
}
// Close the enumeration.
answer.close();
}
catch (Exception e) {
Log.error(e);
}
finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
}
catch (Exception ignored) {
// Ignore.
}
}
return count;
}
public Collection<String> getGroupNames() {
List<String> groupNames = new ArrayList<String>();
LdapContext ctx = null;
try {
ctx = manager.getContext();
// Sort on group name field.
Control[] searchControl = new Control[]{
new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
};
ctx.setRequestControls(searchControl);
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
NamingEnumeration answer = ctx.search("", filter, searchControls);
while (answer.hasMoreElements()) {
// Get the next group.
String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
manager.getGroupNameField()).get();
// Escape group name and add to results.
groupNames.add(JID.escapeNode(groupName));
}
// Close the enumeration.
answer.close();
// If client-side sorting is enabled, sort.
if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
Collections.sort(groupNames);
}
}
catch (Exception e) {
Log.error(e);
}
finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
}
catch (Exception ignored) {
// Ignore.
}
}
return groupNames;
}
public Collection<String> getGroupNames(int startIndex, int numResults) {
List<String> groupNames = new ArrayList<String>();
LdapContext ctx = null;
try {
ctx = manager.getContext();
// Sort on group name field.
Control[] searchControl = new Control[]{
new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
};
ctx.setRequestControls(searchControl);
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
// TODO: used paged results if supported by LDAP server.
NamingEnumeration answer = ctx.search("", filter, searchControls);
for (int i=0; i < startIndex; i++) {
if (answer.hasMoreElements()) {
answer.next();
}
else {
return Collections.emptyList();
}
}
// Now read in desired number of results (or stop if we run out of results).
for (int i = 0; i < numResults; i++) {
if (answer.hasMoreElements()) {
// Get the next group.
String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
manager.getGroupNameField()).get();
// Escape group name and add to results.
groupNames.add(JID.escapeNode(groupName));
}
else {
break;
}
}
// Close the enumeration.
answer.close();
// If client-side sorting is enabled, sort.
if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
Collections.sort(groupNames);
}
}
catch (Exception e) {
Log.error(e);
}
finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
}
catch (Exception ignored) {
// Ignore.
}
}
return groupNames;
}
public Collection<String> getGroupNames(JID user) {
// Get DN of specified user
XMPPServer server = XMPPServer.getInstance();
String username;
if (!manager.isPosixMode()) {
// Check if the user exists (only if user is a local user)
if (!server.isLocal(user)) {
return Collections.emptyList();
}
username = JID.unescapeNode(user.getNode());
try {
username = manager.findUserDN(username) + "," + manager.getBaseDN();
}
catch (Exception e) {
Log.error("Could not find user in LDAP " + username);
return Collections.emptyList();
}
}
else {
username = server.isLocal(user) ? JID.unescapeNode(user.getNode()) : user.toString();
}
// Do nothing if the user is empty or null
if (username == null || "".equals(username)) {
return Collections.emptyList();
}
// Perform the LDAP query
List<String> groupNames = new ArrayList<String>();
LdapContext ctx = null;
try {
ctx = manager.getContext();
// Search for the dn based on the group name.
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
StringBuilder filter = new StringBuilder();
filter.append("(&");
filter.append(MessageFormat.format(manager.getGroupSearchFilter(), "*"));
filter.append("(").append(manager.getGroupMemberField()).append("=").append(username);
filter.append("))");
NamingEnumeration answer = ctx.search("", filter.toString(), searchControls);
while (answer.hasMoreElements()) {
// Get the next group.
String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
manager.getGroupNameField()).get();
// Escape group name and add to results.
groupNames.add(JID.escapeNode(groupName));
}
// Close the enumeration.
answer.close();
// If client-side sorting is enabled, sort.
if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
Collections.sort(groupNames);
}
}
catch (Exception e) {
Log.error("Error getting groups for user: " + user, e);
return Collections.emptyList();
}
finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
}
catch (Exception ignored) {
// Ignore.
}
}
return groupNames;
}
/**
* Always throws an UnsupportedOperationException because LDAP groups are read-only.
*
* @param groupName name of a group.
* @param user the JID of the user to add
* @param administrator true if is an administrator.
* @throws UnsupportedOperationException when called.
*/
public void addMember(String groupName, JID user, boolean administrator)
throws UnsupportedOperationException
{
throw new UnsupportedOperationException();
}
/**
* Always throws an UnsupportedOperationException because LDAP groups are read-only.
*
* @param groupName the naame of a group.
* @param user the JID of the user with new privileges
* @param administrator true if is an administrator.
* @throws UnsupportedOperationException when called.
*/
public void updateMember(String groupName, JID user, boolean administrator)
throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* Always throws an UnsupportedOperationException because LDAP groups are read-only.
*
* @param groupName the name of a group.
* @param user the JID of the user to delete.
* @throws UnsupportedOperationException when called.
*/
public void deleteMember(String groupName, JID user) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* Returns true because LDAP groups are read-only.
*
* @return true because all LDAP functions are read-only.
*/
public boolean isReadOnly() {
return true;
}
public Collection<String> search(String query) {
if (query == null || "".equals(query)) {
return Collections.emptyList();
}
// Make the query be a wildcard search by default. So, if the user searches for
// "Test", make the search be "Test*" instead.
if (!query.endsWith("*")) {
query = query + "*";
}
List<String> groupNames = new ArrayList<String>();
LdapContext ctx = null;
try {
ctx = manager.getContext();
// Sort on username field.
Control[] searchControl = new Control[]{
new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
};
ctx.setRequestControls(searchControl);
// Search for the dn based on the group name.
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
StringBuilder filter = new StringBuilder();
filter.append("(").append(manager.getGroupNameField()).append("=").append(query).append(")");
NamingEnumeration answer = ctx.search("", filter.toString(), searchControls);
while (answer.hasMoreElements()) {
// Get the next group.
String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
manager.getGroupNameField()).get();
// Escape group name and add to results.
groupNames.add(JID.escapeNode(groupName));
}
// Close the enumeration.
answer.close();
// If client-side sorting is enabled, sort.
if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
Collections.sort(groupNames);
}
}
catch (Exception e) {
Log.error(e);
}
finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
}
catch (Exception ignored) {
// Ignore.
}
}
return groupNames;
}
public Collection<String> search(String query, int startIndex, int numResults) {
if (query == null || "".equals(query)) {
return Collections.emptyList();
}
// Make the query be a wildcard search by default. So, if the user searches for
// "Test", make the search be "Test*" instead.
if (!query.endsWith("*")) {
query = query + "*";
}
List<String> groupNames = new ArrayList<String>();
LdapContext ctx = null;
try {
ctx = manager.getContext();
// Sort on username field.
Control[] searchControl = new Control[]{
new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
};
ctx.setRequestControls(searchControl);
// Search for the dn based on the group name.
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
searchControls.setReturningAttributes(new String[] { manager.getGroupNameField() });
StringBuilder filter = new StringBuilder();
filter.append("(").append(manager.getGroupNameField()).append("=").append(query).append(")");
// TODO: used paged results if supported by LDAP server.
NamingEnumeration answer = ctx.search("", filter.toString(), searchControls);
for (int i=0; i < startIndex; i++) {
if (answer.hasMoreElements()) {
answer.next();
}
else {
return Collections.emptyList();
}
}
// Now read in desired number of results (or stop if we run out of results).
for (int i = 0; i < numResults; i++) {
if (answer.hasMoreElements()) {
// Get the next group.
String groupName = (String)((SearchResult)answer.next()).getAttributes().get(
manager.getGroupNameField()).get();
// Escape group name and add to results.
groupNames.add(JID.escapeNode(groupName));
}
else {
break;
}
}
// Close the enumeration.
answer.close();
// If client-side sorting is enabled, sort.
if (Boolean.valueOf(JiveGlobals.getXMLProperty("ldap.clientSideSorting"))) {
Collections.sort(groupNames);
}
}
catch (Exception e) {
Log.error(e);
}
finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
}
catch (Exception ignored) {
// Ignore.
}
}
return groupNames;
}
public boolean isSearchSupported() {
return true;
}
/**
* An auxilary method used to populate LDAP groups based on a provided LDAP search result.
*
* @param answer LDAP search result.
* @return a collection of groups.
* @throws javax.naming.NamingException
*/
private Collection<Group> populateGroups(Enumeration<SearchResult> answer) throws NamingException {
if (manager.isDebugEnabled()) {
Log.debug("Starting to populate groups with users.");
}
DirContext ctx = null;
try {
TreeMap<String, Group> groups = new TreeMap<String, Group>();
ctx = manager.getContext();
SearchControls searchControls = new SearchControls();
searchControls.setReturningAttributes(new String[] { manager.getUsernameField() });
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
XMPPServer server = XMPPServer.getInstance();
String serverName = server.getServerInfo().getName();
// Build 3 groups.
// group 1: uid=
// group 2: rest of the text until first comma
// group 3: rest of the text
Pattern pattern =
Pattern.compile("(?i)(^" + manager.getUsernameField() + "=)([^,]+)(.+)");
while (answer.hasMoreElements()) {
String name = "";
try {
Attributes a = answer.nextElement().getAttributes();
String description;
try {
name = ((String)((a.get(manager.getGroupNameField())).get()));
description =
((String)((a.get(manager.getGroupDescriptionField())).get()));
}
catch (Exception e) {
description = "";
}
Set<JID> members = new TreeSet<JID>();
Attribute memberField = a.get(manager.getGroupMemberField());
if (memberField != null) {
NamingEnumeration ne = memberField.getAll();
while (ne.hasMore()) {
String username = (String) ne.next();
// If not posix mode, each group member is stored as a full DN.
if (!manager.isPosixMode()) {
try {
// Try to find the username with a regex pattern match.
Matcher matcher = pattern.matcher(username);
if (matcher.matches() && matcher.groupCount() == 3) {
// The username is in the DN, no additional search needed
username = matcher.group(2);
}
// The regex pattern match failed. This will happen if the
// the member DN's don't use the standard username field. For
// example, Active Directory has a username field of
// sAMAccountName, but stores group members as "CN=...".
else {
// Create an LDAP name with the full DN.
LdapName ldapName = new LdapName(username);
// Turn the LDAP name into something we can use in a
// search by stripping off the comma.
String userDNPart = ldapName.get(ldapName.size() - 1);
NamingEnumeration usrAnswer = ctx.search("",
userDNPart, searchControls);
if (usrAnswer.hasMoreElements()) {
username = (String) ((SearchResult) usrAnswer.next())
.getAttributes().get(
manager.getUsernameField()).get();
}
// Close the enumeration.
usrAnswer.close();
}
}
catch (Exception e) {
Log.error(e);
}
}
// A search filter may have been defined in the LdapUserProvider.
// Therefore, we have to try to load each user we found to see if
// it passes the filter.
try {
JID userJID;
int position = username.indexOf("@" + serverName);
// Create JID of local user if JID does not match a component's JID
if (position == -1) {
// In order to lookup a username from the manager, the username
// must be a properly escaped JID node.
String escapedUsername = JID.escapeNode(username);
if (!escapedUsername.equals(username)) {
// Check if escaped username is valid
userManager.getUser(escapedUsername);
}
// No exception, so the user must exist. Add the user as a group
// member using the escaped username.
userJID = server.createJID(escapedUsername, null);
}
else {
// This is a JID of a component or node of a server's component
String node = username.substring(0, position);
String escapedUsername = JID.escapeNode(node);
userJID = new JID(escapedUsername + "@" + serverName);
}
members.add(userJID);
}
catch (UserNotFoundException e) {
// We can safely ignore this error. It likely means that
// the user didn't pass the search filter that's defined.
// So, we want to simply ignore the user as a group member.
if (manager.isDebugEnabled()) {
Log.debug("User not found: " + username);
}
}
}
// Close the enumeration.
ne.close();
}
if (manager.isDebugEnabled()) {
Log.debug("Adding group \"" + name + "\" with " + members.size() +
" members.");
}
Collection<JID> admins = Collections.emptyList();
Group group = new Group(name, description, members, admins);
groups.put(name, group);
}
catch (Exception e) {
e.printStackTrace();
if (manager.isDebugEnabled()) {
Log.debug("Error while populating group, " + name + ".", e);
}
}
}
if (manager.isDebugEnabled()) {
Log.debug("Finished populating group(s) with users.");
}
return groups.values();
}
finally {
try {
if (ctx != null) {
ctx.close();
}
}
catch (Exception e) {
// Ignore.
}
}
}
}
|
package test.org.relique.jdbc.csv;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import org.relique.io.FileSetInputStream;
public class TestFileSetInputStream extends TestCase {
private String filePath;
public static final String SAMPLE_FILES_LOCATION_PROPERTY = "sample.files.location";
protected void setUp() {
filePath = System.getProperty(SAMPLE_FILES_LOCATION_PROPERTY);
if (filePath == null)
filePath = RunTests.DEFAULT_FILEPATH;
assertNotNull("Sample files location property not set !", filePath);
filePath = filePath + "/";
// load CSV driver
try {
Class.forName("org.relique.jdbc.csv.CsvDriver");
} catch (ClassNotFoundException e) {
fail("Driver is not in the CLASSPATH -> " + e);
}
}
public void testGlueAsTrailing() throws IOException {
BufferedReader inputRef = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath + "test-glued-trailing.txt")));
BufferedReader inputTest = new BufferedReader(new InputStreamReader(
new FileSetInputStream(filePath,
"test-([0-9]{3})-([0-9]{8}).txt", new String[] {
"location", "file_date" }, ',', false, false, null, 0)));
Set<String> refSet = new HashSet<String>();
Set<String> testSet = new HashSet<String>();
inputRef.readLine();
inputTest.readLine();
String lineRef, lineTest;
do {
lineRef = inputRef.readLine();
lineTest = inputTest.readLine();
refSet.add(lineRef);
testSet.add(lineTest);
} while (lineRef != null && lineTest != null);
assertTrue("refSet contains testSet", refSet.containsAll(testSet));
assertTrue("testSet contains refSet", testSet.containsAll(refSet));
}
public void testGlueAsLeading() throws IOException {
BufferedReader inputRef = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath + "test-glued-leading.txt")));
BufferedReader inputTest = new BufferedReader(new InputStreamReader(
new FileSetInputStream(filePath,
"test-([0-9]{3})-([0-9]{8}).txt", new String[] {
"location", "file_date" }, ',', true, false, null, 0)));
Set<String> refSet = new HashSet<String>();
Set<String> testSet = new HashSet<String>();
inputRef.readLine();
inputTest.readLine();
String lineRef, lineTest;
do {
lineRef = inputRef.readLine();
lineTest = inputTest.readLine();
refSet.add(lineRef);
testSet.add(lineTest);
} while (lineRef != null && lineTest != null);
assertTrue("refSet contains testSet", refSet.containsAll(testSet));
assertTrue("testSet contains refSet", testSet.containsAll(refSet));
}
public void testGlueAsLeadingHeaderless() throws IOException {
BufferedReader inputRef = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath + "headerless-glued-leading.txt")));
BufferedReader inputTest = new BufferedReader(new InputStreamReader(
new FileSetInputStream(filePath,
"headerless-([0-9]{3})-([0-9]{8}).txt", new String[] {
"location", "file_date" }, ',', true, true, null, 0)));
Set<String> refSet = new HashSet<String>();
Set<String> testSet = new HashSet<String>();
String lineRef, lineTest;
do {
lineRef = inputRef.readLine();
lineTest = inputTest.readLine();
refSet.add(lineRef);
testSet.add(lineTest);
} while (lineRef != null && lineTest != null);
assertTrue("refSet contains testSet", refSet.containsAll(testSet));
assertTrue("testSet contains refSet", testSet.containsAll(refSet));
}
public void testGlueAsEmpty() throws IOException {
BufferedReader inputRef = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath + "empty-glued.txt")));
BufferedReader inputTest = new BufferedReader(new InputStreamReader(
new FileSetInputStream(filePath,
"empty-([0-9]+).txt", new String[] {
"EMPTY_ID"}, ',', false, false, null, 0)));
Set<String> refSet = new HashSet<String>();
Set<String> testSet = new HashSet<String>();
String lineRef, lineTest;
do {
lineRef = inputRef.readLine();
lineTest = inputTest.readLine();
refSet.add(lineRef);
testSet.add(lineTest);
} while (lineRef != null && lineTest != null);
assertTrue("refSet contains testSet", refSet.containsAll(testSet));
assertTrue("testSet contains refSet", testSet.containsAll(refSet));
}
}
|
package application.controllers;
import application.TreeItem;
import application.TreeMain;
import application.TreeParser;
import application.fxobjects.ZoomBox;
import application.fxobjects.graph.Graph;
import application.fxobjects.graph.Model;
import application.fxobjects.graph.cell.BaseLayout;
import application.fxobjects.graph.cell.CellLayout;
import application.fxobjects.graph.cell.CellType;
import core.Node;
import core.Parser;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.MenuBar;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.*;
/**
* Controller class, used when creating other controllers.
*
* @author Daphne van Tetering.
* @version 1.0
* @since 26-04-2016
*/
public class GraphViewController extends Controller<StackPane> {
private Graph graph;
private MenuController menuController;
private HashMap<Integer, Node> nodeMap;
private ZoomController zoomController;
private ZoomBox zoomBox;
@FXML
StackPane screen;
@FXML
MenuBar menuBar;
/**
* Constructor: generate a Controller.
*/
public GraphViewController() {
super(new StackPane());
loadFXMLfile("/application/fxml/graphview.fxml");
this.graph = new Graph();
zoomController = graph.getZoomController();
zoomBox = zoomController.getZoomBox();
}
/**
* Method to initialize.
*
* @param location
* @param resources
*/
public void initialize(URL location, ResourceBundle resources) {
graph = new Graph();
BorderPane root = graph.getZoomController().getPane();
HBox hbox = new HBox();
menuController = new MenuController(this, menuBar);
hbox.getChildren().addAll(screen, menuBar);
screen.getChildren().setAll();
root.setTop(hbox);
addGraphComponents();
//addPhylogeneticTree();
CellLayout layout = new BaseLayout(graph, 100);
layout.execute();
this.getRoot().getChildren().addAll(root);
}
/**
* Method that adds all nodes to the Model.
*/
public void addGraphComponents() {
Model model = graph.getModel();
graph.beginUpdate();
Parser parser = new Parser();
nodeMap = parser.readGFA("src/main/resources/TB10.gfa");
Node root = (nodeMap.get(1));
model.addCell(root.getId(), root.getSequence(), CellType.RECTANGLE);
for (int i = 1; i <= nodeMap.size(); i++) {
int numberOfLinks = nodeMap.get(i).getLinks().size();
for (int j : nodeMap.get(i).getLinks()) {
//Add next cell
if (numberOfLinks == 1) {
model.addCell(nodeMap.get(j).getId(), nodeMap.get(j).getSequence(), CellType.RECTANGLE);
} else {
model.addCell(nodeMap.get(j).getId(), nodeMap.get(j).getSequence(), CellType.TRIANGLE);
}
//Add link from current cell to next cell
model.addEdge(nodeMap.get(i).getId(), nodeMap.get(j).getId());
}
}
//dfs(root,1,new boolean[nodeMap.size()],model);
graph.endUpdate();
}
public void addPhylogeneticTree() {
try {
//TreeMain tm = new TreeMain();
setup();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Implementing phylogenetic tree here.
*/
TreeItem current;
int current_depth = 0;
void setup() throws IOException {
File f = new File("src/main/resources/340tree.rooted.TKK.nwk");
BufferedReader r = new BufferedReader(new FileReader(f));
String t = r.readLine();
current = TreeParser.parse(t);
Model model = graph.getModel();
graph.beginUpdate();
int i = 1;
Queue<TreeItem> q = new LinkedList<>();
ArrayList<Integer> done = new ArrayList<>();
System.out.println((current.getName()));
q.add(current);
model.addCell(i,current.getName(),CellType.PHYLOGENETIC);
System.out.println("Cell added: " + i);
while (!q.isEmpty()) {
current = q.poll();
//From node
int j = i;
for (TreeItem child : current.getChildren()) {
model.addCell(++i, child.getName(), CellType.PHYLOGENETIC);
System.out.println("Cell added: " + i);
model.addEdge(j, i);
System.out.println("Link added: " + j + ", "+ i);
//System.out.println("Link added: " + j + ", "+ i);
q.add(child);
}
//done.add(i);
}
graph.endUpdate();
}
/**
* Getter for the graph.
*
* @return the graph.
*/
public Graph getGraph() {
return graph;
}
}
|
package application.fxobjects.cell.graph;
import core.graph.cell.CellType;
import javafx.geometry.Pos;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javax.swing.*;
/**
* Class representing a collapsed bubble.
*/
public class BubbleCell extends GraphCell {
/**
* Bubble cell constructor.
*
* @param id The ID of a cell.
* @param nucleotides The amount of nucleotides contained in this cell.
* @param collapseLevel The collapse level of this cell.
*/
public BubbleCell(int id, int nucleotides, String collapseLevel) {
this(id, nucleotides, new StackPane(), new Text(collapseLevel));
}
/**
* Bubble cell constructor.
*
* @param id The ID of a cell.
* @param nucleotides The amount of nucleotides contained in this cell.
* @param pane A given stack pane.
* @param text A given text element.
*/
public BubbleCell(int id, int nucleotides, StackPane pane, Text text) {
super(id);
shape = new Circle(Math.min(10.0 + ((double) nucleotides) / 80000, 100));
shape.setStroke(Color.YELLOW);
shape.setStrokeWidth(1);
shape.setFill(Color.YELLOW);
pane.getChildren().addAll(shape, text);
text.setTextAlignment(TextAlignment.CENTER);
setView(pane);
type = CellType.BUBBLE;
}
/**
* Method to reset the focus.
*/
public void resetFocus() {
this.setEffect(null);
shape.setStroke(Color.YELLOW);
shape.setStrokeWidth(1);
}
}
|
package br.com.dbsoft.ui.component.dialog;
import java.util.Arrays;
import java.util.Collection;
import javax.faces.component.FacesComponent;
import javax.faces.component.NamingContainer;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.PostAddToViewEvent;
import javax.faces.event.SystemEvent;
import javax.faces.event.SystemEventListener;
import br.com.dbsoft.message.IDBSMessages;
import br.com.dbsoft.ui.component.DBSUIOutput;
import br.com.dbsoft.ui.core.DBSFaces;
import br.com.dbsoft.util.DBSNumber;
@FacesComponent(DBSDialog.COMPONENT_TYPE)
public class DBSDialog extends DBSUIOutput implements NamingContainer, SystemEventListener{
public final static String COMPONENT_TYPE = DBSFaces.DOMAIN_UI_COMPONENT + "." + DBSFaces.ID.DIALOG;
public final static String RENDERER_TYPE = COMPONENT_TYPE;
public final static String FACET_HEADER_LEFT = "headerleft";
public final static String FACET_HEADER_RIGHT = "headerright";
public final static String FACET_FOOTER = "footer";
public final static String FACET_TOOLBAR = "toolbar";
public final static String FACET_CONTENT = "content";
public final static String INPUT_MSGKEY = "msgkey";
public final static String BUTTON_OK = "btok";
public final static String BUTTON_YES = "btyes";
public final static String BUTTON_NO = "btno";
protected enum PropertyKeys {
type,
caption,
iconClass,
position,
contentStyleClass,
contentAlignment,
contentSize,
contentPadding,
closeTimeout,
msgType,
msgFor,
open,
//Atributos internos
dbsmessages;
String toString;
PropertyKeys(String toString) {
this.toString = toString;
}
PropertyKeys() {}
@Override
public String toString() {
return ((this.toString != null) ? this.toString : super.toString());
}
}
public static enum TYPE {
NAV ("nav"),
MOD ("mod"),
MSG ("msg");
private String wName;
private TYPE(String pName) {
this.wName = pName;
}
public String getName() {
return wName;
}
public static TYPE get(String pCode) {
if (pCode == null){
return MSG;
}
pCode = pCode.trim().toLowerCase();
for (TYPE xT:TYPE.values()) {
if (xT.getName().equals(pCode)){
return xT;
}
}
return null;
}
}
public static enum POSITION {
TOP ("t"),
BOTTOM ("b"),
LEFT ("l"),
RIGHT ("r"),
CENTER ("c");
private String wName;
private POSITION(String pName) {
this.wName = pName;
}
public String getName() {
return wName;
}
public static POSITION get(String pCode) {
if (pCode == null){
return CENTER;
}
pCode = pCode.trim().toLowerCase();
for (POSITION xP:POSITION.values()) {
if (xP.getName().equals(pCode)){
return xP;
}
}
return null;
}
}
public static enum CONTENT_SIZE {
SCREEN ("s"),
AUTO ("a");
private String wName;
private CONTENT_SIZE(String pName) {
this.wName = pName;
}
public String getName() {
return wName;
}
public String getStyleClass() {
return " -cs_" + wName;
}
public static CONTENT_SIZE get(String pCode) {
if (pCode == null){
return AUTO;
}
pCode = pCode.trim().toLowerCase();
for (CONTENT_SIZE xCS:CONTENT_SIZE.values()) {
if (xCS.getName().equals(pCode)){
return xCS;
}
}
return null;
// switch (pCode) {
// case "s":
// return SCREEN;
// case "a":
// return AUTO;
// default:
// return null;
}
}
public static enum CONTENT_ALIGNMENT {
TOP ("t"),
BOTTOM ("b"),
LEFT ("l"),
RIGHT ("r"),
CENTER ("c");
private String wName;
private CONTENT_ALIGNMENT(String pName) {
this.wName = pName;
}
public String getName() {
return wName;
}
public static CONTENT_ALIGNMENT get(String pCode) {
if (pCode == null){
return CENTER;
}
pCode = pCode.trim().toLowerCase();
for (CONTENT_ALIGNMENT xCA:CONTENT_ALIGNMENT.values()) {
if (xCA.getName().equals(pCode)){
return xCA;
}
}
return null;
// switch (pCode) {
// case "t":
// return TOP;
// case "b":
// return BOTTOM;
// case "l":
// return LEFT;
// case "r":
// return RIGHT;
// case "c":
// return CENTER;
// default:
// return null;
}
}
public DBSDialog(){
setRendererType(DBSDialog.RENDERER_TYPE);
FacesContext xContext = FacesContext.getCurrentInstance();
xContext.getViewRoot().subscribeToViewEvent(PostAddToViewEvent.class, this);
}
public String getType() {
return (String) getStateHelper().eval(PropertyKeys.type, TYPE.NAV.getName());
}
public void setType(String pType) {
TYPE xType = TYPE.get(pType);
if (xType == null){
System.out.println("Type invalid\t:" + pType);
return;
}
getStateHelper().put(PropertyKeys.type, pType);
handleAttribute("type", pType);
}
public String getCaption() {
return (String) getStateHelper().eval(PropertyKeys.caption, null);
}
public void setCaption(String pCaption) {
getStateHelper().put(PropertyKeys.caption, pCaption);
handleAttribute("caption", pCaption);
}
public String getIconClass() {
return (String) getStateHelper().eval(PropertyKeys.iconClass, null);
}
public void setIconClass(String pIconClass) {
getStateHelper().put(PropertyKeys.iconClass, pIconClass);
handleAttribute("iconClass", pIconClass);
}
public Boolean getOpen() {
return (Boolean) getStateHelper().eval(PropertyKeys.open, false);
}
public void setOpen(Boolean pOpen) {
getStateHelper().put(PropertyKeys.open, pOpen);
handleAttribute("open", pOpen);
}
public String getPosition() {
return (String) getStateHelper().eval(PropertyKeys.position, POSITION.CENTER.getName());
}
public void setPosition(String pPosition) {
POSITION xP = POSITION.get(pPosition);
if (xP == null){
System.out.println("Position invalid\t:" + pPosition);
return;
}
getStateHelper().put(PropertyKeys.position, pPosition);
handleAttribute("position", pPosition);
}
public String getContentSize() {
return (String) getStateHelper().eval(PropertyKeys.contentSize, CONTENT_SIZE.AUTO.getName());
}
public void setContentSize(String pContentSize) {
CONTENT_SIZE xCS = CONTENT_SIZE.get(pContentSize);
if (xCS == null){
System.out.println("ContentSize invalid\t:" + pContentSize);
return;
}
getStateHelper().put(PropertyKeys.contentSize, pContentSize);
handleAttribute("contentSize", pContentSize);
}
public String getContentAlignment() {
return (String) getStateHelper().eval(PropertyKeys.contentAlignment, CONTENT_ALIGNMENT.TOP.getName());
}
public void setContentAlignment(String pContentAlignment) {
if (CONTENT_ALIGNMENT.get(pContentAlignment) == null){
System.out.println("ContentAlignment invalid\t:" + pContentAlignment);
return;
}
getStateHelper().put(PropertyKeys.contentAlignment, pContentAlignment);
handleAttribute("contentAlignment", pContentAlignment);
}
public String getMsgType() {
return (String) getStateHelper().eval(PropertyKeys.msgType, null);
}
public void setMsgType(String pMsgType) {
getStateHelper().put(PropertyKeys.msgType, pMsgType);
handleAttribute("msgType", pMsgType);
}
public String getMsgFor() {
return (String) getStateHelper().eval(PropertyKeys.msgFor, null);
}
public void setMsgFor(String pMsgFor) {
if (pMsgFor != null && pMsgFor.length() > 0){
pMsgFor = pMsgFor.trim().toLowerCase();
}
getStateHelper().put(PropertyKeys.msgFor, pMsgFor);
handleAttribute("msgFor", pMsgFor);
}
public String getCloseTimeout() {
return (String) getStateHelper().eval(PropertyKeys.closeTimeout, "0");
}
public void setCloseTimeout(String pCloseTimeout) {
String xCloseTimeout = "0";
if (pCloseTimeout != null && pCloseTimeout.length() > 0){
pCloseTimeout = pCloseTimeout.trim().toLowerCase();
if (DBSNumber.isNumber(pCloseTimeout)
|| pCloseTimeout.substring(0,1).equals("a")){
xCloseTimeout = pCloseTimeout;
}
}
getStateHelper().put(PropertyKeys.closeTimeout, xCloseTimeout);
handleAttribute("closeTimeout", xCloseTimeout);
}
public String getContentPadding() {
return (String) getStateHelper().eval(PropertyKeys.contentPadding, "0.4em");
}
public void setContentPadding(String pContentPadding) {
getStateHelper().put(PropertyKeys.contentPadding, pContentPadding);
handleAttribute("contentPadding", pContentPadding);
}
public String getContentStyleClass() {
return (String) getStateHelper().eval(PropertyKeys.contentStyleClass, "");
}
public void setContentStyleClass(String pContentStyleClass) {
getStateHelper().put(PropertyKeys.contentStyleClass, pContentStyleClass);
handleAttribute("contentStyleClass", pContentStyleClass);
}
public IDBSMessages getDBSMessages() {
return (IDBSMessages) getStateHelper().eval(PropertyKeys.dbsmessages, null);
}
public void setDBSMessages(IDBSMessages pDBSMessages) {
getStateHelper().put(PropertyKeys.dbsmessages, pDBSMessages);
handleAttribute("dbsmessages", pDBSMessages);
}
/**
* Retorna se possui mensagem
* @return
*/
public boolean hasMessage(){
if (getDBSMessages() != null){
return getDBSMessages().hasMessages();
}
return false;
}
@Override
public String getDefaultEventName()
{
return "click";
}
@Override
public Collection<String> getEventNames() {
return Arrays.asList("click", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup");
}
@Override
public void processEvent(SystemEvent pEvent) throws AbortProcessingException {
DBSDialogContent xContent = (DBSDialogContent) getFacet(FACET_CONTENT);
if (xContent == null){
xContent = (DBSDialogContent) FacesContext.getCurrentInstance().getApplication().createComponent(DBSDialogContent.COMPONENT_TYPE);
xContent.setId(FACET_CONTENT);
getFacets().put(FACET_CONTENT, xContent);
}
}
@Override
public boolean isListenerForSource(Object pSource) {
return pSource.equals(this);
}
}
|
package com.akiban.server.types3.common.funcs;
import com.akiban.server.error.InvalidOperationException;
import com.akiban.server.error.InvalidParameterValueException;
import com.akiban.server.expression.std.Matcher;
import com.akiban.server.expression.std.Matchers;
import com.akiban.server.types3.LazyList;
import com.akiban.server.types3.TClass;
import com.akiban.server.types3.TExecutionContext;
import com.akiban.server.types3.TOverload;
import com.akiban.server.types3.TOverloadResult;
import com.akiban.server.types3.aksql.aktypes.AkBool;
import com.akiban.server.types3.pvalue.PValueSource;
import com.akiban.server.types3.pvalue.PValueTarget;
import com.akiban.server.types3.texpressions.TInputSetBuilder;
import com.akiban.server.types3.texpressions.TOverloadBase;
public class TLike extends TOverloadBase
{
/**
*
* @param stringType
* @return an arrays of all OverLoads available for the LIKE function
* with this specifict string type (type: akString vs Mstring, etc)
*/
public static TOverload[] create(TClass stringType)
{
TLike ret[] = new TLike[LikeType.values().length * 2];
int n = 0;
for (LikeType t : LikeType.values())
{
ret[n++] = new TLike(new int[] {0, 1}, stringType, t);
// optional escape char
ret[n++] = new TLike(new int[] {0, 1, 2}, stringType, t);
}
return ret;
}
static enum LikeType
{
BLIKE, // case sensitive
LIKE, // ditto
ILIKE // case insensitive
}
// caching positions
private static final int MATCHER_INDEX = 0;
private final int coverage[];
private final TClass stringType;
private final LikeType likeType;
TLike (int c[], TClass sType, LikeType lType)
{
coverage = c;
stringType = sType;
likeType = lType;
}
@Override
protected void buildInputSets(TInputSetBuilder builder)
{
builder.covers(stringType, coverage);
}
@Override
protected void doEvaluate(TExecutionContext context, LazyList<? extends PValueSource> inputs, PValueTarget output)
{
String left = inputs.get(0).getString();
String right = inputs.get(1).getString();
char esca = '\\';
if (inputs.size() == 3)
{
String escapeString = inputs.get(2).getString();
if (escapeString.length() != 1)
throw new InvalidParameterValueException("Invalid escape character: " + escapeString);
esca = escapeString.charAt(0);
}
// gret the cached matcher
Matcher matcher = (Matcher) context.exectimeObjectAt(MATCHER_INDEX);
if (matcher == null
// || check whether right is a literal, if not, just compile a new pattern
|| !matcher.sameState(right, esca)
)
context.putExectimeObject(MATCHER_INDEX,
matcher = Matchers.getMatcher(right, esca, likeType == LikeType.ILIKE));
try
{
output.putBool(matcher.match(left, 1) >= 0);
}
catch (InvalidOperationException e)
{
// TODO:
// What's the new way of issuing a warning?
output.putNull();
}
}
@Override
public String displayName()
{
return likeType.name();
}
@Override
public TOverloadResult resultType()
{
return TOverloadResult.fixed(AkBool.INSTANCE);
}
}
|
package com.arjuna.playground.templates;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
@Path("/")
@Stateless
public class TemplatesWS
{
private static final Logger logger = Logger.getLogger(TemplatesWS.class.getName());
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public List<TemplateFieldDescriptionDTO> getTemplateFieldDescriptions(@PathParam("id") String id)
{
logger.log(Level.FINE, "TemplatesWS.getTemplateFieldDescriptions: [" + id + "]");
try
{
Map<String, List<TemplateFieldDescriptionDTO>> templateFieldDescriptionsMap = createTemplateFieldDescriptionsMap();
return templateFieldDescriptionsMap.get(id);
}
catch (Throwable throwable)
{
logger.log(Level.WARNING, "getTemplateFieldDescriptions: Unable get template field descriptions", throwable);
return Collections.emptyList();
}
}
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public List<TemplateDescriptionDTO> getTemplateDescriptions()
{
logger.log(Level.FINE, "TemplatesWS.getTemplateDescriptions");
try
{
List<TemplateDescriptionDTO> templateDescriptions = createTemplateDescriptions();
return templateDescriptions;
}
catch (Throwable throwable)
{
logger.log(Level.WARNING, "getTemplateDescriptions: Unable get template descriptions", throwable);
return Collections.emptyList();
}
}
private List<TemplateDescriptionDTO> createTemplateDescriptions()
{
List<TemplateDescriptionDTO> templateDescriptions = new LinkedList<>();
String requestURL = _request.getRequestURL().toString();
if (! requestURL.endsWith("/"))
requestURL = requestURL + "/";
TemplateDescriptionDTO templateDescription01 = new TemplateDescriptionDTO();
templateDescription01.setURL(requestURL + "3f7e5ba2-1e03-4641-b477-36d3ecb18de8");
templateDescription01.setName("XML Real-time internal agreement");
templateDescription01.setPurpose("Create an agreement with an internal party to supply real-time XML data.");
templateDescriptions.add(templateDescription01);
TemplateDescriptionDTO templateDescription02 = new TemplateDescriptionDTO();
templateDescription02.setURL(requestURL + "6e5747ef-41da-4344-a15e-e386695605f4");
templateDescription02.setName("JSON Real-time external agreement");
templateDescription02.setPurpose("Create an agreement with an external party to supply real-time JSON data.");
templateDescriptions.add(templateDescription02);
TemplateDescriptionDTO templateDescription03 = new TemplateDescriptionDTO();
templateDescription03.setURL(requestURL + "8693f1cd-8a77-4bca-87b0-46b3568657d4");
templateDescription03.setName("XML Real-time internal agreement");
templateDescription03.setPurpose("Create an agreement with an internal party to supply real-time XML data.");
templateDescriptions.add(templateDescription03);
TemplateDescriptionDTO templateDescription04 = new TemplateDescriptionDTO();
templateDescription04.setURL(requestURL + "15bdb060-e2f3-4665-a231-fc325fb23e2b");
templateDescription04.setName("JSON Real-time external agreement");
templateDescription04.setPurpose("Create an agreement with an external party to supply real-time JSON data.");
templateDescriptions.add(templateDescription04);
return templateDescriptions;
}
private Map<String, List<TemplateFieldDescriptionDTO>> createTemplateFieldDescriptionsMap()
{
Map<String, List<TemplateFieldDescriptionDTO>> templateFieldDescriptionMap = new HashMap<>();
return templateFieldDescriptionMap;
}
@Context
private HttpServletRequest _request;
}
|
package com.carlosefonseca.common.utils;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.widget.Toast;
import com.carlosefonseca.common.CFApp;
import de.greenrobot.event.EventBus;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
public class AudioPlayer {
private static final String TAG = CodeUtils.getTag(AudioPlayer.class);
private static final Context c = CFApp.getContext();
public static final int STOPPED = 0;
public static final int PLAYING = 1;
public static final int PAUSED = 2;
@Nullable private static MediaPlayer currentMediaPlayer;
private static File currentFile;
private static Queue<MediaPlayerWrapper> queue = new LinkedList<>();
public static class AudioPlayerNotification {
public final Status status;
public final File file;
public final MediaPlayer mediaPlayer;
public enum Status { PLAY, PAUSE, STOP}
public AudioPlayerNotification(Status status, @Nullable File file, @Nullable MediaPlayer mediaPlayer) {
this.status = status;
this.file = file;
this.mediaPlayer = mediaPlayer;
}
@Override
public String toString() {
return String.format("AudioNotif:%-5s %s", status, file != null ? file.getName() : "");
}
public static void PostStart(@Nullable File file) {
EventBus.getDefault().postSticky(new AudioPlayerNotification(Status.PLAY, file, null));
}
public static void PostStart(@Nullable File file, MediaPlayer mediaPlayer) {
EventBus.getDefault().postSticky(new AudioPlayerNotification(Status.PLAY, file, mediaPlayer));
}
public static void PostPause(File file) {
EventBus.getDefault().postSticky(new AudioPlayerNotification(Status.PAUSE, file, null));
}
public static void PostPause(File file, MediaPlayer mediaPlayer) {
EventBus.getDefault().postSticky(new AudioPlayerNotification(Status.PAUSE, file, mediaPlayer));
}
public static void PostStop(File file) {
EventBus.getDefault().postSticky(new AudioPlayerNotification(Status.STOP, file, null));
}
public static void register(Object object) {
EventBus.getDefault().register(object);
}
public static void unregister(Object object) {
EventBus.getDefault().unregister(object);
}
}
// // SINGLETON CRAP
// static AudioPlayer instance = null;
// public static AudioPlayer getInstance() {
// if (instance == null) {
// instance = new AudioPlayer();
// return instance;
// END SINGLETON CRAP
static void play() {
Log.i(TAG, "Poping queue (Q size: " + queue.size() + ")");
MediaPlayerWrapper mediaPlayerWrapper = queue.poll();
if (mediaPlayerWrapper != null) play(mediaPlayerWrapper.mediaPlayer, mediaPlayerWrapper.file);
}
/**
* THE PLAY METHOD
*/
private static void play(@NonNull MediaPlayer mediaPlayer, @Nullable File file) {
stop();
currentFile = file;
currentMediaPlayer = mediaPlayer;
currentMediaPlayer.setOnCompletionListener(onEnd.instance);
currentMediaPlayer.start();
AudioPlayerNotification.PostStart(currentFile, mediaPlayer);
Log.v(TAG, "" + (file != null ? file.getName() : "???") + " Playing.");
}
/**
* Starts playing the file, stopping another that was playing.
*/
public static void playFile(File audioFile) {
if (!audioFile.exists()) {
Log.i(TAG, "File " + audioFile + " doesn't exist.");
CodeUtils.toast("File " + audioFile + " doesn't exist.");
return;
}
MediaPlayer mediaPlayerForFile = getMediaPlayerForFile(c, audioFile);
if (mediaPlayerForFile != null) {
play(mediaPlayerForFile, audioFile);
}
}
/**
* Starts playing the file, stopping another that was playing.
*/
public static void playOrResumeFile(File audioFile) {
// if (!audioFile.exists()) {
// Log.i(TAG, "File " + audioFile + " doesn't exist.");
// CodeUtils.toast("File " + audioFile + " doesn't exist.");
// return;
if (currentFile != null && currentFile.equals(audioFile) && currentMediaPlayer != null &&
!currentMediaPlayer.isPlaying()) {
resume();
} else {
MediaPlayer mediaPlayerForFile = getMediaPlayerForFile(c, audioFile);
if (mediaPlayerForFile != null) {
play(mediaPlayerForFile, audioFile);
}
}
}
public static void stop() {
if (isPlaying()) {
if (currentMediaPlayer != null) currentMediaPlayer.stop();
AudioPlayerNotification.PostStop(currentFile);
currentMediaPlayer = null;
currentFile = null;
queue.clear();
}
EventBus.getDefault().removeStickyEvent(AudioPlayer.AudioPlayerNotification.class);
}
/**
* Adds the file to the queue or simply plays the file is nothing is playing
*/
public static void queueFile(@NonNull File audioFile) {
if (!isPlaying()) {
playFile(audioFile);
} else {
if (!audioFile.exists()) {
Log.i(TAG, "" + audioFile + " doesn't exist.");
return;
}
MediaPlayerWrapper mp = getWrappedMediaPlayerForFile(c, audioFile);
if (mp != null) {
queue.add(mp);
Log.v(TAG, "" + audioFile.getName() + " queued. (Q size: "+queue.size()+")");
}
}
}
@Nullable
public static MediaPlayerWrapper getWrappedMediaPlayerForFile(Context c, File audioFile) {
if (!audioFile.exists()) {
Log.i(TAG, "" + audioFile + " doesn't exist.");
return null;
}
return new MediaPlayerWrapper(getMediaPlayerForFile(c, audioFile), audioFile);
}
/**
* Creates a MediaPlayer object.
*
* @return New media player or null if it couldn't be created.
*/
@Nullable
public static MediaPlayer getMediaPlayerForFile(Context c, File audioFile) {
if (audioFile.exists() && audioFile.isFile()) {
Log.v(TAG, "" + audioFile.getName() + " Setting up...");
MediaPlayer mediaPlayer = MediaPlayer.create(c, Uri.fromFile(audioFile));
if (mediaPlayer != null) {
mediaPlayer.setOnCompletionListener(onEnd.instance);
} else {
Log.e(TAG, new Exception("Failed to create MediaPlayer for audioFile " + audioFile.getName()));
}
return mediaPlayer;
} else if (UIL.existsOnPackage(audioFile.getName())) {
try {
AssetFileDescriptor afd = c.getAssets().openFd(audioFile.getName());
MediaPlayer player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
return player;
} catch (IOException e) {
Log.e(TAG, "" + e.getMessage(), e);
}
}
Log.i(TAG, "" + audioFile.getName() + " doesn't exist!");
Toast.makeText(c, "Audio File " + audioFile.getName() + " doesn't exist!", Toast.LENGTH_SHORT).show();
return null;
}
public static void pause() {
if (currentMediaPlayer == null) {
Log.e(TAG, new Exception("Media player not initialized"));
return;
}
currentMediaPlayer.pause();
AudioPlayerNotification.PostPause(currentFile, currentMediaPlayer);
}
public static void resume() {
if (currentMediaPlayer == null) {
Log.e(TAG, new Exception("Media player not initialized"));
return;
}
currentMediaPlayer.start();
AudioPlayerNotification.PostStart(currentFile, currentMediaPlayer);
}
/*
private void pauseAudio() {
if (currentMediaPlayer == null) {
Log.e(TAG, new Exception("Media player not initialized"));
return;
}
currentMediaPlayer.pause();
}
*/
public static boolean isPlaying() {
return currentMediaPlayer != null && currentMediaPlayer.isPlaying();
}
public static int getStatus() {
if (currentMediaPlayer != null) {
return currentMediaPlayer.isPlaying()
? PLAYING
: currentMediaPlayer.getCurrentPosition() < currentMediaPlayer.getDuration() ? PAUSED : STOPPED;
} else {
return STOPPED;
}
}
public static boolean isPlaying(@Nullable File file) {
return file != null && isPlaying() && currentFile.equals(file);
}
@Nullable
public static MediaPlayer getMediaPlayer() {
return currentMediaPlayer;
}
static class onEnd implements MediaPlayer.OnCompletionListener {
static onEnd instance = new onEnd();
private onEnd() { }
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
AudioPlayerNotification.PostStop(currentFile);
play();
}
}
public static File getCurrentFile() {
return currentFile;
}
@Nullable
public static File getPlayingFile() {
return isPlaying() ? currentFile : null;
}
static class MediaPlayerWrapper {
MediaPlayer mediaPlayer;
File file;
MediaPlayerWrapper(@Nullable MediaPlayer mediaPlayer, File file) {
this.mediaPlayer = mediaPlayer;
this.file = file;
}
}
}
|
package com.devicehive.client.websocket;
import com.devicehive.client.api.HiveClient;
import com.devicehive.client.model.exceptions.HiveException;
import com.devicehive.client.websocket.api.impl.HiveClientWebSocketImpl;
import com.devicehive.client.websocket.context.RestClientWIP;
import com.devicehive.client.websocket.context.WebSocketClient;
import java.net.URI;
public final class HiveFactory {
private HiveFactory() {
}
/**
* Creates an instance of {@link HiveClient} connected to the Device Hive server.
*
* @param restUri the Device Hive server RESTful API URI
* the server.
* @return an instance of {@link HiveClient}
* @throws HiveException if a connection error occurs
*/
// public static HiveClient createClient(URI restUri, boolean preferWebsockets) throws HiveException {
// if (preferWebsockets) {
// return new HiveClientWebSocketImpl(createWebsocketClientAgent(restUri));
// } else {
// return new HiveClientRestImpl(createRestAgent(restUri));
private static RestClientWIP createRestAgent(URI restUri) throws HiveException {
RestClientWIP agent = new RestClientWIP(restUri);
agent.connect();
return agent;
}
public static HiveClientWebSocketImpl createWSclient(URI restUri) throws HiveException {
return new HiveClientWebSocketImpl(createWebsocketClientAgent(restUri));
}
private static WebSocketClient createWebsocketClientAgent(URI restUri) throws HiveException {
WebSocketClient agent = new WebSocketClient(restUri);
agent.connect();
return agent;
}
}
|
package com.dmurph.mvc.model;
import com.dmurph.mvc.ICloneable;
import com.dmurph.mvc.IDirtyable;
/**
* Keeps track of if a model is dirty through calling the methods {@link #setDirty(boolean)}
* and {@link #firePropertyChange(String, Object, Object)}.
* @author Daniel Murphy
*/
public abstract class AbstractDirtyableModel extends AbstractModel implements IDirtyable, ICloneable {
private boolean dirty = false;
/**
* If the model is "dirty", or changed since last save.
* @see com.dmurph.mvc.IDirtyable#isDirty()
*/
@Override
public boolean isDirty(){
return dirty;
}
/**
* @see com.dmurph.mvc.IDirtyable#setDirty(boolean)
*/
@Override
public boolean setDirty(boolean argDirty){
boolean oldDirty = dirty;
dirty = argDirty;
return oldDirty;
}
/**
* @see com.dmurph.mvc.model.AbstractModel#firePropertyChange(java.lang.String, java.lang.Object, java.lang.Object)
*/
@Override
protected void firePropertyChange(String argPropertyName, Object argOldValue, Object argNewValue) {
if(argOldValue != null && !argOldValue.equals(argNewValue)){
dirty = true;
}else if(argNewValue == null && argNewValue != null){
dirty = true;
}
super.firePropertyChange(argPropertyName, argOldValue, argNewValue);
}
/**
* @see ICloneable#clone()
*/
public abstract ICloneable clone();
}
|
package com.emc.ecs.serviceBroker.model;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "base_url")
public class BaseUrlInfo {
private String id;
private Link link;
private String name;
private List<String> tags;
private String baseurl;
private Boolean namespaceInHost = false;
public BaseUrlInfo() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Link getLink() {
return link;
}
public void setLink(Link link) {
this.link = link;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public String getBaseurl() {
return baseurl;
}
public void setBaseurl(String baseurl) {
this.baseurl = baseurl;
}
@XmlElement(name = "get_namespace_in_host")
public Boolean getNamespaceInHost() {
return namespaceInHost;
}
public void setNamespaceInHost(Boolean namespaceInHost) {
this.namespaceInHost = namespaceInHost;
}
public String getNamespaceUrl(String namespace, boolean ssl) {
String scheme = ssl ? "https" : "http";
String port = ssl ? "9021" : "9020";
if (namespaceInHost) {
return scheme + "://" + namespace + "." + baseurl + ":" + port ;
} else {
return scheme + "://" + baseurl + ":" + port;
}
}
}
|
package com.gamingmesh.jobs.api;
import com.gamingmesh.jobs.container.Job;
import org.bukkit.OfflinePlayer;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public final class JobsPrePaymentEvent extends BaseEvent implements Cancellable {
private OfflinePlayer offlinePlayer;
private double money;
private double points;
private Job job;
private boolean cancelled = false;
public JobsPrePaymentEvent(OfflinePlayer offlinePlayer, Job job, double money, double points) {
this.job = job;
this.offlinePlayer = offlinePlayer;
this.money = money;
this.points = points;
}
public OfflinePlayer getPlayer() {
return offlinePlayer;
}
public double getAmount() {
return money;
}
public double getPoints() {
return points;
}
public Job getJob() {
return job;
}
public void setAmount(double money) {
this.money = money;
}
public void setPoints(double points) {
this.points = points;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}
|
package com.github.jaystgelais.jrpg.menu;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.utils.Align;
import com.github.jaystgelais.jrpg.graphics.GraphicsService;
import com.github.jaystgelais.jrpg.input.DelayedInput;
import com.github.jaystgelais.jrpg.input.InputService;
import com.github.jaystgelais.jrpg.input.Inputs;
import com.github.jaystgelais.jrpg.ui.AbstractContent;
import com.github.jaystgelais.jrpg.ui.Container;
import java.util.List;
public final class SelectList extends AbstractContent {
public static final int COLUMN_MARGIN = 32;
public static final int ROW_MARGIN = 10;
private final List<SelectItem> items;
private final int columns;
private final DelayedInput okInput = new DelayedInput(Inputs.OK);
private final DelayedInput downInput = new DelayedInput(Inputs.DOWN);
private final DelayedInput leftInput = new DelayedInput(Inputs.LEFT);
private final DelayedInput rightInput = new DelayedInput(Inputs.RIGHT);
private final DelayedInput upInput = new DelayedInput(Inputs.UP);
private int currentSelectionIndex = 0;
private Texture cursorSprite;
public SelectList(final Container parent, final List<SelectItem> items, final int columns) {
super(
parent.getContentPositionX(), parent.getContentPositionY(),
parent.getContentWidth(), parent.getContentHeight()
);
this.items = items;
this.columns = columns;
}
public SelectList(final Container parent, final List<SelectItem> items) {
this(parent, items, 1);
}
@Override
public void update(final long elapsedTime) {
}
@Override
public void handleInput(final InputService inputService) {
if (okInput.isPressed(inputService)) {
items.get(currentSelectionIndex).getAction().perform();
} else if (rightInput.isPressed(inputService)) {
currentSelectionIndex = Math.min(currentSelectionIndex + 1, items.size() - 1);
} else if (downInput.isPressed(inputService)) {
currentSelectionIndex = Math.min(currentSelectionIndex + columns, items.size() - 1);
} else if (leftInput.isPressed(inputService)) {
currentSelectionIndex = Math.max(currentSelectionIndex - 1, 0);
} else if (upInput.isPressed(inputService)) {
currentSelectionIndex = Math.max(currentSelectionIndex - columns, 0);
}
}
@Override
public void render(final GraphicsService graphicsService) {
int totalRows = ((items.size() - 1) / columns) + 1;
int columnWidth = (getWidth() - (COLUMN_MARGIN * (columns + 1))) / columns;
int rowHeight = (int) graphicsService.getFontSet().getTextFont().getLineHeight() + ROW_MARGIN;
int visibleRows = getHeight() / rowHeight;
int currentRow = currentSelectionIndex / columns;
int firstRow = Math.max(
0,
Math.min(
totalRows - visibleRows,
currentRow - (visibleRows / 2)
)
);
for (int rowIndex = firstRow; rowIndex < firstRow + Math.min(visibleRows, totalRows); rowIndex++) {
for (int colIndex = 0; colIndex < columns; colIndex++) {
final int itemIndex = (rowIndex * columns) + colIndex;
final int labelX = getScreenPositionX()
+ graphicsService.getCameraOffsetX()
+ COLUMN_MARGIN
+ (colIndex * (columnWidth + COLUMN_MARGIN));
final int labelY = getScreenPositionY()
+ graphicsService.getCameraOffsetY()
+ getHeight()
- (rowIndex * rowHeight);
graphicsService.getFontSet().getTextFont().draw(
graphicsService.getSpriteBatch(),
items.get(itemIndex).getLabel(),
labelX,
labelY,
columnWidth,
Align.left,
false
);
if (itemIndex == currentSelectionIndex) {
Texture cursor = getCursorSprite(graphicsService);
final BitmapFont font = graphicsService.getFontSet().getTextFont();
graphicsService.drawSprite(
cursor,
labelX - cursor.getWidth(),
labelY - (cursor.getHeight() / 2) - (font.getLineHeight() / 2) + 1
);
}
}
}
}
@Override
protected boolean canChangeMargins() {
return false;
}
@Override
public void dispose() {
}
private Texture getCursorSprite(final GraphicsService graphicsService) {
if (cursorSprite == null) {
if (!graphicsService.getAssetManager().isLoaded("assets/jrpg/panel/cursor.png", Texture.class)) {
graphicsService.getAssetManager().load("assets/jrpg/panel/cursor.png", Texture.class);
graphicsService.getAssetManager().finishLoading();
}
cursorSprite = graphicsService.getAssetManager().get("assets/jrpg/panel/cursor.png", Texture.class);
}
return cursorSprite;
}
}
|
package com.github.koraktor.mavanagaiata;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.maven.plugin.MojoExecutionException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevObject;
import org.eclipse.jgit.revwalk.RevTag;
import org.eclipse.jgit.revwalk.RevWalk;
/**
* This goal provides the most recent Git tag in the "mavanagaiata.tag" and
* "mvngit.tag" properties.
*
* @author Sebastian Staudt
* @goal tag
* @phase initialize
* @requiresProject
* @since 0.1.0
*/
public class GitTagMojo extends AbstractGitMojo {
private RevWalk revWalk;
private String tag;
private Map<RevCommit, String> tagCommits;
/**
* This will first read all tags and walk the commit hierarchy down from
* HEAD until it finds one of the tags. The name of that tag is written
* into "mavanagaiata.tag" and "mvngit.tag" respectively.
*
* @throws MojoExecutionException if the tags cannot be read
*/
public void execute() throws MojoExecutionException {
try {
RevCommit head = this.getHead();
this.revWalk = new RevWalk(this.repository);
Map<String, Ref> tags = this.repository.getTags();
this.tagCommits = new HashMap<RevCommit, String>();
for(Map.Entry<String, Ref> tag : tags.entrySet()) {
try {
RevTag revTag = this.revWalk.parseTag(tag.getValue().getObjectId());
RevObject object = revTag.getObject();
if(!(object instanceof RevCommit)) {
continue;
}
this.tagCommits.put((RevCommit) object, tag.getKey());
} catch(IncorrectObjectTypeException e) {
continue;
}
}
String abbrevId = this.repository.getObjectDatabase().newReader()
.abbreviate(head).name();
if(this.tagCommits.isEmpty()) {
this.addProperty("tag.describe", abbrevId);
this.addProperty("tag.name", "");
return;
}
int distance = this.walkCommits(head, 0);
if(distance > -1) {
this.addProperty("tag.name", this.tag);
if(distance == 0) {
this.addProperty("tag.describe", this.tag);
} else {
this.addProperty("tag.describe", this.tag + "-" + distance + "-g" + abbrevId);
}
}
} catch(IOException e) {
throw new MojoExecutionException("Unable to read Git tag", e);
}
}
/**
* Returns whether a specific commit has been tagged
*
* If the commit is tagged, the tag's name is saved as property "tag"
*
* @param commit The commit to check
* @see #addProperty(String, Object)
* @return <code>true</code> if this commit has been tagged
*/
private boolean isTagged(RevCommit commit) {
if(this.tagCommits.containsKey(commit)) {
this.tag = this.tagCommits.get(commit);
return true;
}
return false;
}
/**
* Walks the hierarchy of commits beginning with the given commit
*
* This method is called recursively until a tagged commit is found or the
* last commit in the hierarchy is reached.
*
* @param commit The commit to start with
* @param distance The distance walked in the commit hierarchy
* @return The distance at which the tag has been found, or <code>-1</code>
* if no tag is reachable from the given commit
* @throws IOException if an error occured while reading a commit
* @throws MissingObjectException if a commit is missing
* @see #isTagged(RevCommit)
* @see RevCommit#getParentCount()
* @see RevCommit#getParents()
*/
private int walkCommits(RevCommit commit, int distance) throws MissingObjectException, IOException {
commit = (RevCommit) this.revWalk.peel(commit);
if(this.isTagged(commit)) {
return distance;
}
for(RevCommit parent : commit.getParents()) {
int tagDistance = this.walkCommits(parent, distance + 1);
if(tagDistance > -1) {
return tagDistance;
}
}
return -1;
}
}
|
package com.github.onsdigital.florence.filter;
import com.github.davidcarboni.restolino.framework.Filter;
import com.github.onsdigital.florence.configuration.Configuration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
/**
* Routes all traffic to Babbage, Unless it is recognised as a florence file being requested.
*/
public class Proxy implements Filter {
private static final String florenceToken = "/florence";
private static final String zebedeeToken = "/zebedee";
private static final String babbageBaseUrl = Configuration.getBabbageUrl();
private static final String zebedeeBaseUrl = Configuration.getZebedeeUrl();
private static final List<String> florencePaths = Arrays.asList("");
@Override
public boolean filter(HttpServletRequest request, HttpServletResponse response) {
String requestUri = request.getRequestURI();
String requestQueryString = request.getQueryString() != null ? request.getQueryString() : "";
try {
if (florencePaths.contains(requestUri)
|| requestUri.startsWith(florenceToken)) {
return true; // carry on and serve the file from florence
}
String requestBaseUrl = babbageBaseUrl; // proxy to babbage by default.
if (requestUri.startsWith(zebedeeToken)) {
requestUri = requestUri.replace(zebedeeToken, "");
requestBaseUrl = zebedeeBaseUrl;
}
HttpRequestBase proxyRequest;
String requestUrl = requestBaseUrl + requestUri + "?" + requestQueryString;
//System.out.println("Proxy request from " + request.getRequestURI() + " to " + requestUrl);
switch (request.getMethod()) {
case "POST":
proxyRequest = new HttpPost(requestUrl);
((HttpPost) proxyRequest).setEntity(new BufferedHttpEntity(new InputStreamEntity(request.getInputStream())));
break;
case "PUT":
proxyRequest = new HttpPut(requestUrl);
((HttpPut) proxyRequest).setEntity(new BufferedHttpEntity(new InputStreamEntity(request.getInputStream())));
break;
case "DELETE":
proxyRequest = new HttpDelete(requestUrl);
break;
default:
proxyRequest = new HttpGet(requestUrl);
break;
}
CloseableHttpClient httpClient = HttpClients.custom().disableRedirectHandling().build();
// copy the request headers.
Enumeration<String> headerNames = request.getHeaderNames();
String accessToken = "";
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
if (StringUtils.equalsIgnoreCase(headerName, "Cookie") ||
StringUtils.equalsIgnoreCase(headerName, "Content-Type") ||
StringUtils.equalsIgnoreCase(headerName, "X-Florence-Token"))
proxyRequest.addHeader(headerName, request.getHeader(headerName));
}
if (request.getCookies() != null) {
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equals("access_token"))
accessToken = cookie.getValue();
}
}
if (requestBaseUrl == zebedeeBaseUrl && StringUtils.isNotEmpty(accessToken)) {
proxyRequest.addHeader("X-Florence-Token", accessToken);
}
CloseableHttpResponse proxyResponse = httpClient.execute(proxyRequest);
try {
HttpEntity responseEntity = proxyResponse.getEntity();
// copy headers from the response
for (Header header : proxyResponse.getAllHeaders()) {
response.setHeader(header.getName(), header.getValue());
}
response.setStatus(proxyResponse.getStatusLine().getStatusCode());
if (responseEntity != null && responseEntity.getContent() != null)
IOUtils.copy(responseEntity.getContent(), response.getOutputStream());
//System.out.println("Proxy response status :" + proxyResponse.getStatusLine().getStatusCode());
EntityUtils.consume(responseEntity);
} catch (IOException e) {
System.out.println("IOException " + e.getMessage());
e.printStackTrace();
} finally {
proxyResponse.close();
}
} catch (IOException e) {
System.out.println("IOException " + e.getMessage());
e.printStackTrace();
}
return false;
}
}
|
package com.impossibl.postgres.system.procs;
import static com.impossibl.postgres.utils.Factory.createInstance;
import static org.apache.commons.beanutils.BeanUtils.getProperty;
import static org.apache.commons.beanutils.BeanUtils.setProperty;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import com.impossibl.postgres.Context;
import com.impossibl.postgres.types.CompositeType;
import com.impossibl.postgres.types.CompositeType.Attribute;
import com.impossibl.postgres.types.Registry;
import com.impossibl.postgres.types.Type;
import com.impossibl.postgres.utils.DataInputStream;
import com.impossibl.postgres.utils.DataOutputStream;
public class Records extends SimpleProcProvider {
public Records() {
super(null, null, new Encoder(), new Decoder(), "record_");
}
static class Decoder implements Type.BinaryIO.Decoder {
public Object decode(Type type, DataInputStream stream, Context context) throws IOException {
CompositeType ctype = (CompositeType) type;
Object instance = createInstance(context.lookupInstanceType(type));
int lengthGiven = stream.readInt();
long writeStart = stream.getCount();
int itemCount = stream.readInt();
for (int c = 0; c < itemCount; ++c) {
Attribute attribute = ctype.getAttribute(c);
Type attributeType = Registry.loadType(stream.readInt());
if (attributeType.getId() != attribute.type.getId()) {
context.refreshType(attributeType.getId());
}
Object attributeVal = attributeType.getBinaryIO().decoder.decode(attributeType, stream, context);
Records.set(instance, attribute.name, attributeVal);
}
long lengthFound = stream.getCount() - writeStart;
if (lengthFound != lengthGiven) {
throw new IllegalStateException();
}
return instance;
}
}
static class Encoder implements Type.BinaryIO.Encoder {
public void encode(Type type, DataOutputStream stream, Object val, Context context) throws IOException {
if (val == null) {
stream.writeInt(-1);
}
else {
//Write to temp buffer
ByteArrayOutputStream recordByteStream = new ByteArrayOutputStream();
DataOutputStream recordDataStream = new DataOutputStream(recordByteStream);
CompositeType ctype = (CompositeType) type;
Collection<Attribute> attributes = ctype.getAttributes();
recordDataStream.writeInt(attributes.size());
for (Attribute attribute : attributes) {
Type attributeType = attribute.type;
recordDataStream.writeInt(attributeType.getId());
Object attributeVal = Records.get(val, attribute.name);
attributeType.getBinaryIO().encoder.encode(attributeType, recordDataStream, attributeVal, context);
}
//Write temp buffer
byte[] buffer = recordByteStream.toByteArray();
stream.writeInt(buffer.length);
stream.write(buffer);
}
}
}
@SuppressWarnings("unchecked")
protected static Object get(Object instance, String name) {
if (instance instanceof Map) {
return ((Map<Object, Object>) instance).get(name);
}
else {
try {
java.lang.reflect.Field field;
if ((field = instance.getClass().getField(name)) != null) {
return field.get(instance);
}
}
catch (ReflectiveOperationException | IllegalArgumentException e) {
try {
return getProperty(instance, name.toString());
}
catch (ReflectiveOperationException e1) {
}
}
}
throw new IllegalStateException("invalid poperty name/index");
}
@SuppressWarnings("unchecked")
protected static void set(Object instance, String name, Object value) {
if (instance instanceof Map) {
((Map<Object, Object>) instance).put(name, value);
return;
}
else {
try {
java.lang.reflect.Field field;
if ((field = instance.getClass().getField(name)) != null) {
field.set(instance, value);
return;
}
}
catch (ReflectiveOperationException | IllegalArgumentException e) {
try {
setProperty(instance, name.toString(), value);
return;
}
catch (ReflectiveOperationException e1) {
}
}
}
throw new IllegalStateException("invalid poperty name/index");
}
}
|
package com.laytonsmith.core.functions;
import com.laytonsmith.PureUtilities.Version;
import com.laytonsmith.annotations.api;
import com.laytonsmith.annotations.breakable;
import com.laytonsmith.annotations.core;
import com.laytonsmith.annotations.hide;
import com.laytonsmith.annotations.noboilerplate;
import com.laytonsmith.annotations.nolinking;
import com.laytonsmith.annotations.noprofile;
import com.laytonsmith.annotations.seealso;
import com.laytonsmith.annotations.unbreakable;
import com.laytonsmith.core.ArgumentValidation;
import com.laytonsmith.core.CHLog;
import com.laytonsmith.core.CHVersion;
import com.laytonsmith.core.Globals;
import com.laytonsmith.core.LogLevel;
import com.laytonsmith.core.MethodScriptCompiler;
import com.laytonsmith.core.Optimizable;
import com.laytonsmith.core.ParseTree;
import com.laytonsmith.core.Procedure;
import com.laytonsmith.core.Script;
import com.laytonsmith.core.Static;
import com.laytonsmith.core.compiler.FileOptions;
import com.laytonsmith.core.compiler.keywords.InKeyword;
import com.laytonsmith.core.constructs.CArray;
import com.laytonsmith.core.constructs.CBoolean;
import com.laytonsmith.core.constructs.CByteArray;
import com.laytonsmith.core.constructs.CClassType;
import com.laytonsmith.core.constructs.CClosure;
import com.laytonsmith.core.constructs.CDouble;
import com.laytonsmith.core.constructs.CFunction;
import com.laytonsmith.core.constructs.CIClosure;
import com.laytonsmith.core.constructs.CInt;
import com.laytonsmith.core.constructs.CKeyword;
import com.laytonsmith.core.constructs.CLabel;
import com.laytonsmith.core.constructs.CMutablePrimitive;
import com.laytonsmith.core.constructs.CNull;
import com.laytonsmith.core.constructs.CSlice;
import com.laytonsmith.core.constructs.CString;
import com.laytonsmith.core.constructs.CVoid;
import com.laytonsmith.core.constructs.Construct;
import com.laytonsmith.core.constructs.IVariable;
import com.laytonsmith.core.constructs.IVariableList;
import com.laytonsmith.core.constructs.InstanceofUtil;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.environments.CommandHelperEnvironment;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.environments.GlobalEnv;
import com.laytonsmith.core.exceptions.CancelCommandException;
import com.laytonsmith.core.exceptions.ConfigCompileException;
import com.laytonsmith.core.exceptions.ConfigCompileGroupException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.exceptions.FunctionReturnException;
import com.laytonsmith.core.exceptions.LoopBreakException;
import com.laytonsmith.core.exceptions.LoopContinueException;
import com.laytonsmith.core.functions.Exceptions.ExceptionType;
import com.laytonsmith.core.natives.interfaces.ArrayAccess;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
@core
public class DataHandling {
private static final String array_get = new ArrayHandling.array_get().getName();
private static final String array_set = new ArrayHandling.array_set().getName();
private static final String array_push = new ArrayHandling.array_push().getName();
public static String docs() {
return "This class provides various methods to control script data and program flow.";
}
@api
public static class array extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "array";
}
@Override
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
return new CArray(t, args);
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
@Override
public String docs() {
return "array {[var1, [var2...]]} Creates an array of values.";
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_0_1;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "assign(@array, array(1, 2, 3))\nmsg(@array)"),
new ExampleScript("Associative array creation", "assign(@array, array(one: 'apple', two: 'banana'))\nmsg(@array)"),};
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(OptimizationOption.OPTIMIZE_DYNAMIC);
}
FileOptions lastFileOptions = null;
@Override
public ParseTree optimizeDynamic(Target t, List<ParseTree> children, FileOptions fileOptions) throws ConfigCompileException, ConfigRuntimeException {
//We need to check here to ensure that
//we aren't getting a slice in a label, which is used in switch
//statements, but doesn't make sense here.
for (ParseTree child : children) {
if (child.getData() instanceof CFunction && new Compiler.centry().getName().equals(child.getData().val())) {
if (((CLabel) child.getChildAt(0).getData()).cVal() instanceof CSlice) {
throw new ConfigCompileException("Slices cannot be used as array indices", child.getChildAt(0).getTarget());
}
}
}
return null;
}
}
@api
public static class associative_array extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
CArray array = CArray.GetAssociativeArray(t, args);
return array;
}
@Override
public String getName() {
return "associative_array";
}
@Override
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
@Override
public String docs() {
return "array {[args...]} Works exactly like array(), except the array created will be an associative array, even"
+ " if the array has been created with no elements. This is the only use case where this is neccessary, vs"
+ " using the normal array() function, or in the case where you assign sequential keys anyways, and the same"
+ " array could have been created using array().";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Usage with an empty array", "assign(@array, associative_array())\nmsg(is_associative(@array))"),
new ExampleScript("Usage with an array with sequential keys", "assign(@array, array(0: '0', 1: '1'))\nmsg(is_associative(@array))\n"
+ "assign(@array, associative_array(0: '0', 1: '1'))\nmsg(is_associative(@array))"),};
}
}
@api
public static class assign extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "assign";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2, 3};
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
IVariableList list = env.getEnv(GlobalEnv.class).GetVarList();
int offset;
CClassType type;
String name;
if(args.length == 3){
offset = 1;
if(!(args[offset] instanceof IVariable)){
throw new ConfigRuntimeException(getName() +
" with 3 arguments only accepts an ivariable as the second argument.",
ExceptionType.CastException, t);
}
name = ((IVariable) args[offset]).getName();
if(list.has(name) && env.getEnv(GlobalEnv.class).GetFlag("no-check-duplicate-assign") == null){
if(env.getEnv(GlobalEnv.class).GetFlag("closure-warn-overwrite") != null){
CHLog.GetLogger().Log(CHLog.Tags.RUNTIME, LogLevel.ERROR,
"The variable " + name + " is hiding another value of the"
+ " same name in the main scope.", t);
} else {
CHLog.GetLogger().Log(CHLog.Tags.RUNTIME, LogLevel.ERROR, name + " was already defined at "
+ list.get(name, t, true).getDefinedTarget() + " but is being redefined.", t);
}
}
type = ArgumentValidation.getClassType(args[0], t);
} else {
offset = 0;
if(!(args[offset] instanceof IVariable)){
throw new ConfigRuntimeException(getName() +
" with 2 arguments only accepts an ivariable as the second argument.",
ExceptionType.CastException, t);
}
name = ((IVariable) args[offset]).getName();
type = list.get(name, t, true).getDefinedType();
}
Construct c = args[offset + 1];
while(c instanceof IVariable){
IVariable cur = (IVariable) c;
c = list.get(cur.getName(), cur.getTarget()).ival();
}
IVariable v = new IVariable(type, name, c, t);
list.set(v);
return v;
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
@Override
public String docs() {
return "ivariable {[type], ivar, mixed} Accepts an ivariable ivar as a parameter, and puts the specified value mixed in it."
+ " Returns the variable that was assigned. Operator syntax is also supported: <code>@a = 5;</code>."
+ " Other forms are supported as well, +=, -=, *=, /=, .=, which do multiple operations at once. Array assigns"
+ " are also supported: @array[5] = 'new value in index 5';";
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public boolean preResolveVariables() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_0_1;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.OPTIMIZE_CONSTANT,
OptimizationOption.OPTIMIZE_DYNAMIC
);
}
@Override
public Construct optimize(Target t, Construct... args) throws ConfigCompileException {
//We can't really optimize, but we can check that we are
//getting an ivariable.
int offset = 0;
if(args.length == 3){
offset = 1;
if(!(args[0] instanceof CClassType)){
throw new ConfigCompileException("Expecting a ClassType for parameter 1 to assign", t);
}
}
if (!(args[offset + 0] instanceof IVariable)) {
throw new ConfigCompileException("Expecting an ivar for argument 1 to assign", t);
}
return null;
}
@Override
public ParseTree optimizeDynamic(Target t, List<ParseTree> children, FileOptions fileOptions) throws ConfigCompileException, ConfigRuntimeException {
if (children.get(0).getData() instanceof IVariable
&& children.get(1).getData() instanceof IVariable) {
if (((IVariable) children.get(0).getData()).getName().equals(
((IVariable) children.get(1).getData()).getName())) {
CHLog.GetLogger().Log(CHLog.Tags.COMPILER, LogLevel.WARNING, "Assigning a variable to itself", t);
}
}
if (children.get(0).getData() instanceof CFunction && array_get.equals(children.get(0).getData().val())) {
if (children.get(0).getChildAt(1).getData() instanceof CSlice) {
CSlice cs = (CSlice) children.get(0).getChildAt(1).getData();
if (cs.getStart() == 0 && cs.getFinish() == -1) {
//Turn this into an array_push
ParseTree tree = new ParseTree(new CFunction(array_push, t), children.get(0).getFileOptions());
tree.addChild(children.get(0).getChildAt(0));
tree.addChild(children.get(1));
return tree;
}
//else, not really sure what's going on, so we'll just carry on, and probably there
//will be an error generated elsewhere
} else {
//Turn this into an array set instead
ParseTree tree = new ParseTree(new CFunction(array_set, t), children.get(0).getFileOptions());
tree.addChild(children.get(0).getChildAt(0));
tree.addChild(children.get(0).getChildAt(1));
tree.addChild(children.get(1));
return tree;
}
}
return null;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "assign(@variable, 5);\nmsg(@variable);"),
new ExampleScript("Array assignment", "assign(@variable, associative_array());\nassign(@variable['associative'], 5);\nmsg(@variable);"),
new ExampleScript("Operator syntax", "@variable = 5;\nmsg(@variable);"),
new ExampleScript("Operator syntax using combined operators", "@variable = 'string';\n@variable .= ' more string';\nmsg(@variable);"),
new ExampleScript("Operator syntax using combined operators", "@variable = 5;\n@variable += 10;\nmsg(@variable);"),
new ExampleScript("Operator syntax using combined operators", "@variable = 5;\n@variable -= 10;\nmsg(@variable);"),
new ExampleScript("Operator syntax using combined operators", "@variable = 5;\n@variable *= 10;\nmsg(@variable);"),
new ExampleScript("Operator syntax using combined operators", "@variable = 5;\n@variable /= 10;\nmsg(@variable);"),};
}
}
@api
@noboilerplate
@breakable
public static class _for extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "for";
}
@Override
public Integer[] numArgs() {
return new Integer[]{4};
}
@Override
public Construct exec(Target t, Environment env, Construct... args) {
return CVoid.VOID;
}
@Override
public boolean useSpecialExec() {
return true;
}
@Override
public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) {
return new forelse(true).execs(t, env, parent, nodes);
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
@Override
public String docs() {
return "void {assign, condition, expression1, expression2} Acts as a typical for loop. The assignment is first run. Then, a"
+ " condition is checked. If that condition is checked and returns true, expression2 is run. After that, expression1 is run. In java"
+ " syntax, this would be: for(assign; condition; expression1){expression2}. assign must be an ivariable, either a "
+ "pre defined one, or the results of the assign() function. condition must be a boolean.";
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_0_1;
}
//Doesn't matter, run out of state
@Override
public Boolean runAsync() {
return null;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "for(assign(@i, 0), @i < 5, @i++,\n\tmsg(@i)\n)"),
new ExampleScript("With braces", "for(assign(@i, 0), @i < 2, @i++){\n\tmsg(@i)\n}"),
new ExampleScript("With continue. (See continue() for more examples)", "for(assign(@i, 0), @i < 2, @i++){\n"
+ "\tif(@i == 1, continue())\n"
+ "\tmsg(@i)\n"
+ "}"),};
}
@Override
public LogLevel profileAt() {
return LogLevel.WARNING;
}
@Override
public String profileMessageS(List<ParseTree> args) {
return "Executing function: " + this.getName() + "("
+ args.get(0).toStringVerbose() + ", " + args.get(1).toStringVerbose()
+ ", " + args.get(2).toStringVerbose() + ", <code>)";
}
@Override
public ParseTree optimizeDynamic(Target t, List<ParseTree> children, FileOptions fileOptions) throws ConfigCompileException, ConfigRuntimeException {
//In for(@i = 0, @i < @x, @i++, ...), the @i++ is more optimally written as ++@i, but
//it is commonplace to use postfix operations, so if the condition is in fact that simple,
//let's reverse it.
boolean isInc;
try {
if (children.get(2).getData() instanceof CFunction
&& ((isInc = children.get(2).getData().val().equals("postinc"))
|| children.get(2).getData().val().equals("postdec"))
&& children.get(2).getChildAt(0).getData() instanceof IVariable) {
ParseTree pre = new ParseTree(new CFunction(isInc ? "inc" : "dec", t), children.get(2).getFileOptions());
pre.addChild(children.get(2).getChildAt(0));
children.set(2, pre);
}
} catch (IndexOutOfBoundsException e) {
//Just ignore it. It's a compile error, but we'll let the rest of the
//existing system sort that out.
}
return null;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(OptimizationOption.OPTIMIZE_DYNAMIC);
}
}
@api
@noboilerplate
@breakable
public static class forelse extends AbstractFunction {
public forelse() {
}
boolean runAsFor = false;
forelse(boolean runAsFor) {
this.runAsFor = runAsFor;
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public boolean useSpecialExec() {
return true;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
return null;
}
@Override
public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) throws ConfigRuntimeException {
ParseTree assign = nodes[0];
ParseTree condition = nodes[1];
ParseTree expression = nodes[2];
ParseTree runnable = nodes[3];
ParseTree elseCode = null;
if (!runAsFor) {
elseCode = nodes[4];
}
boolean hasRunOnce = false;
Construct counter = parent.eval(assign, env);
if (!(counter instanceof IVariable)) {
throw new ConfigRuntimeException("First parameter of for must be an ivariable", ExceptionType.CastException, t);
}
int _continue = 0;
while (true) {
boolean cond = Static.getBoolean(parent.seval(condition, env));
if (cond == false) {
break;
}
hasRunOnce = true;
if (_continue >= 1) {
--_continue;
parent.eval(expression, env);
continue;
}
try {
parent.eval(runnable, env);
} catch (LoopBreakException e) {
int num = e.getTimes();
if (num > 1) {
e.setTimes(--num);
throw e;
}
return CVoid.VOID;
} catch (LoopContinueException e) {
_continue = e.getTimes() - 1;
parent.eval(expression, env);
continue;
}
parent.eval(expression, env);
}
if (!hasRunOnce && !runAsFor && elseCode != null) {
parent.eval(elseCode, env);
}
return CVoid.VOID;
}
@Override
public String getName() {
return "forelse";
}
@Override
public Integer[] numArgs() {
return new Integer[]{5};
}
@Override
public String docs() {
return "void {assign, condition, expression1, expression2, else} Works like a normal for loop, but if upon checking the condition the first time,"
+ " it is determined that it is false (that is, NO code loops are going to be run) the else code is run instead. If the loop runs,"
+ " even once, it will NOT run the else branch. In general, brace syntax and use of for(){ } else { } syntax is preferred, instead"
+ " of using forelse directly.";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
}
@api(environments = CommandHelperEnvironment.class)
@breakable
public static class foreach extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "foreach";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2, 3, 4};
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
return CVoid.VOID;
}
@Override
public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) {
if(nodes.length < 3){
throw new ConfigRuntimeException("Insufficient arguments passed to " + getName(), ExceptionType.InsufficientArgumentsException, t);
}
ParseTree array = nodes[0];
ParseTree key = null;
int offset = 0;
if (nodes.length == 4) {
//Key and value provided
key = nodes[1];
offset = 1;
}
ParseTree value = nodes[1 + offset];
ParseTree code = nodes[2 + offset];
Construct arr = parent.seval(array, env);
Construct ik = null;
if (key != null) {
ik = parent.eval(key, env);
if (!(ik instanceof IVariable)) {
throw new ConfigRuntimeException("Parameter 2 of " + getName() + " must be an ivariable", ExceptionType.CastException, t);
}
}
Construct iv = parent.eval(value, env);
if (arr instanceof CSlice) {
long start = ((CSlice) arr).getStart();
long finish = ((CSlice) arr).getFinish();
if (finish < start) {
arr = new ArrayHandling.range().exec(t, env, new CInt(start, t), new CInt(finish - 1, t), new CInt(-1, t));
} else {
arr = new ArrayHandling.range().exec(t, env, new CInt(start, t), new CInt(finish + 1, t));
}
}
if (!(arr instanceof ArrayAccess)) {
throw new ConfigRuntimeException("Parameter 1 of " + getName() + " must be an array or array like data structure", ExceptionType.CastException, t);
}
if (!(iv instanceof IVariable)) {
throw new ConfigRuntimeException("Parameter " + (2 + offset) + " of " + getName() + " must be an ivariable", ExceptionType.CastException, t);
}
ArrayAccess one = (ArrayAccess) arr;
IVariable kkey = (IVariable) ik;
IVariable two = (IVariable) iv;
if (one.isAssociative()) {
//Iteration of an associative array is much easier, and we have
//special logic here to decrease the complexity.
//Clone the set, so changes in the array won't cause changes in
//the iteration order.
Set<Construct> keySet = new LinkedHashSet<>(one.keySet());
//Continues in an associative array are slightly different, so
//we have to track this differently. Basically, we skip the
//next element in the array key set.
int continues = 0;
for (Construct c : keySet) {
if (continues > 0) {
//If continues is greater than 0, continue in the loop,
//however many times necessary to make it 0.
continues
continue;
}
//If the key isn't null, set that in the variable table.
if (kkey != null) {
env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(kkey.getDefinedType(), kkey.getName(), c, t));
}
//Set the value in the variable table
env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(two.getDefinedType(), two.getName(), one.get(c.val(), t), t));
try {
//Execute the code
parent.eval(code, env);
//And handle any break/continues.
} catch (LoopBreakException e) {
int num = e.getTimes();
if (num > 1) {
e.setTimes(--num);
throw e;
}
return CVoid.VOID;
} catch (LoopContinueException e) {
// In associative arrays, (unlike with normal arrays) we need to decrement it by one, because the nature of
// the normal array is such that the counter is handled manually by our code. Because we are letting java
// handle our code though, this run actually counts as one run.
continues += e.getTimes() - 1;
}
}
return CVoid.VOID;
} else {
//It's not associative, so we have more complex handling. We will create an ArrayAccessIterator,
//and store that in the environment. As the array is iterated, underlying changes in the array
//will be reflected in the object, and we will adjust as necessary. The reason we use this mechanism
//is to avoid cloning the array, and iterating that. Arrays may be extremely large, and cloning the
//entire array is wasteful in that case. We are essentially tracking deltas this way, which prevents
//memory usage from getting out of hand.
ArrayAccess.ArrayAccessIterator iterator = new ArrayAccess.ArrayAccessIterator(one);
List<ArrayAccess.ArrayAccessIterator> arrayAccessList = env.getEnv(GlobalEnv.class).GetArrayAccessIterators();
try {
arrayAccessList.add(iterator);
int continues = 0;
while (true) {
int current = iterator.getCurrent();
if (continues > 0) {
//We have some continues to handle. Blacklisted
//values don't count for the continuing count, so
//we have to consider that when counting.
iterator.incrementCurrent();
if (iterator.isBlacklisted(current)) {
continue;
} else {
--continues;
continue;
}
}
if (current >= one.size()) {
//Done with the iterations.
break;
}
//If the item is blacklisted, we skip it.
if (!iterator.isBlacklisted(current)) {
if (kkey != null) {
env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(kkey.getDefinedType(), kkey.getName(), new CInt(current, t), t));
}
env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(two.getDefinedType(), two.getName(), one.get(current, t), t));
try {
parent.eval(code, env);
} catch (LoopBreakException e) {
int num = e.getTimes();
if (num > 1) {
e.setTimes(--num);
throw e;
}
return CVoid.VOID;
} catch (LoopContinueException e) {
continues += e.getTimes();
continue;
}
}
iterator.incrementCurrent();
}
} finally {
arrayAccessList.remove(iterator);
}
}
return CVoid.VOID;
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.RangeException};
}
@Override
public String docs() {
return "void {array, [key], ivar, code} Walks through array, setting ivar equal to each element in the array, then running code."
+ " In addition, foreach(1..4, @i, code()) is also valid, setting @i to 1, 2, 3, 4 each time. The same syntax is valid as"
+ " in an array slice. If key is set (it must be an ivariable) then the index of each iteration will be set to that."
+ " See the examples for a demonstration.
+ " Enhanced syntax may also be used in foreach, using the \"in\", \"as\" and \"else\" keywords. See the examples for"
+ " examples of each structure. Using these keywords makes the structure of the foreach read much better. For instance,"
+ " with foreach(@value in @array){ } the code very literally reads \"for each value in array\", making ascertaining"
+ " the behavior of the loop easier. The \"as\" keyword reads less plainly, and so is not recommended for use, but is"
+ " allowed. Note that the array and value are reversed with the \"as\" keyword. An \"else\" block may be used after"
+ " the foreach, which will only run if the array provided is empty, that is, the loop code would never run. This provides"
+ " a good way to provide \"default\" handling. Array modifications while iterating are supported, and are well defined."
+ " See [[CommandHelper/Staged/Array_iteration|the page documenting array iterations]] for full details.";
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_0_1;
}
//Doesn't matter, runs out of state anyways
@Override
public Boolean runAsync() {
return null;
}
@Override
public boolean useSpecialExec() {
return true;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Using \"in\" keyword", "@array = array(1, 2, 3);\n"
+ "foreach(@value in @array){\n"
+ "\tmsg(@value);\n"
+ "}"),
new ExampleScript("Using \"in\" keyword, with a key", "@array = array(1, 2, 3);\n"
+ "foreach(@key: @value in @array){\n"
+ "\tmsg(@key . ': ' . @value);\n"
+ "}"),
new ExampleScript("Using \"a\" keyword", "@array = array(1, 2, 3);\n"
+ "foreach(@array as @value){\n"
+ "\tmsg(@value);\n"
+ "}"),
new ExampleScript("Using \"as\" keyword, with a key", "@array = array(1, 2, 3);\n"
+ "foreach(@array as @key: @value){\n"
+ "\tmsg(@key . ': ' . @value);\n"
+ "}"),
new ExampleScript("With else clause", "@array = array() # Note empty array\n"
+ "foreach(@value in @array){\n"
+ "\tmsg(@value);\n"
+ "} else {\n"
+ "\tmsg('No values were in the array');\n"
+ "}"),
new ExampleScript("Basic functional usage", "assign(@array, array(1, 2, 3))\nforeach(@array, @i,\n\tmsg(@i)\n)"),
new ExampleScript("With braces", "assign(@array, array(1, 2, 3))\nforeach(@array, @i){\n\tmsg(@i)\n}"),
new ExampleScript("With a slice", "foreach(1..3, @i){\n\tmsg(@i)\n}"),
new ExampleScript("With a slice, counting down", "foreach(3..1, @i){\n\tmsg(@i)\n}"),
new ExampleScript("With array keys", "@array = array('one': 1, 'two': 2)\nforeach(@array, @key, @value){\n\tmsg(@key.':'.@value)\n}"),};
}
@Override
public LogLevel profileAt() {
return LogLevel.WARNING;
}
@Override
public String profileMessageS(List<ParseTree> args) {
return "Executing function: " + this.getName() + "("
+ args.get(0).toStringVerbose() + ", " + args.get(1).toStringVerbose()
+ ", <code>)";
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(OptimizationOption.OPTIMIZE_DYNAMIC);
}
private static final String CENTRY = new Compiler.centry().getName();
private static final String ASSIGN = new assign().getName();
private static final String SCONCAT = new StringHandling.sconcat().getName();
private static final String IN = new InKeyword().getKeywordName();
private boolean isFunction(ParseTree node, String function){
return node.getData() instanceof CFunction && node.getData().val().equals(function);
}
private boolean isKeyword(ParseTree node, String keyword){
return node.getData() instanceof CKeyword && node.getData().val().equals(keyword);
}
@Override
public ParseTree optimizeDynamic(Target t, List<ParseTree> children, FileOptions fileOptions) throws ConfigCompileException, ConfigRuntimeException {
if (children.size() < 2) {
throw new ConfigCompileException("Invalid number of arguments passed to " + getName(), t);
}
if (isFunction(children.get(0), CENTRY)) {
// This is what "@key: @value in @array" looks like initially. We'll refactor this so the next segment can take over properly.
ParseTree sconcat = new ParseTree(new CFunction(new StringHandling.sconcat().getName(), t), fileOptions);
sconcat.addChild(children.get(0).getChildAt(0));
for (int i = 0; i < children.get(0).getChildAt(1).numberOfChildren(); i++) {
sconcat.addChild(children.get(0).getChildAt(1).getChildAt(i));
}
children.set(0, sconcat);
}
if (children.get(0).getData() instanceof CFunction && children.get(0).getData().val().equals(new StringHandling.sconcat().getName())) {
// We may be looking at a "@value in @array" or "@array as @value" type
// structure, so we need to re-arrange this into the standard format.
ParseTree array = null;
ParseTree key = null;
ParseTree value = null;
List<ParseTree> c = children.get(0).getChildren();
if (c.size() == 3) {
// No key specified
switch (c.get(1).getData().val()) {
case "in":
// @value in @array
value = c.get(0);
array = c.get(2);
break;
case "as":
// @array as @value
value = c.get(2);
array = c.get(0);
break;
}
} else if (c.size() == 4) {
if ("in".equals(c.get(2).getData().val())) {
// @key: @value in @array
key = c.get(0);
value = c.get(1);
array = c.get(3);
} else if ("as".equals(c.get(1).getData().val())) {
// @array as @key: @value
array = c.get(0);
key = c.get(2);
value = c.get(3);
}
}
if (key != null && key.getData() instanceof CLabel) {
if (!(((CLabel) key.getData()).cVal() instanceof IVariable)
&& !(((CLabel)key.getData()).cVal() instanceof CFunction
&& ((CLabel)key.getData()).cVal().val().equals(ASSIGN))) {
throw new ConfigCompileException("Expected a variable for key, but \"" + key.getData().val() + "\" was found", t);
}
key.setData(((CLabel) key.getData()).cVal());
}
// Now set up the new tree, and return that. Since foreachelse overrides us, we
// need to accept all the arguments after the first, and put those in.
List<ParseTree> newChildren = new ArrayList<>();
newChildren.add(array);
if (key != null) {
newChildren.add(key);
}
newChildren.add(value);
for (int i = 1; i < children.size(); i++) {
newChildren.add(children.get(i));
}
children.clear();
children.addAll(newChildren);
// Change foreach(){ ... } else { ... } to a foreachelse.
if (children.get(children.size() - 1).getData() instanceof CFunction
&& children.get(children.size() - 1).getData().val().equals("else")) {
ParseTree foreachelse = new ParseTree(new CFunction(new foreachelse().getName(), t), fileOptions);
children.set(children.size() - 1, children.get(children.size() - 1).getChildAt(0));
foreachelse.setChildren(children);
return foreachelse;
}
}
return null;
}
}
@api
@noboilerplate
@breakable
@seealso({foreach.class})
public static class foreachelse extends foreach {
@Override
public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) {
ParseTree array = nodes[0];
//The last one
ParseTree elseCode = nodes[nodes.length - 1];
Construct data = parent.seval(array, env);
if (!(data instanceof CArray) && !(data instanceof CSlice)) {
throw new Exceptions.CastException(getName() + " expects an array for parameter 1", t);
}
if (((CArray) data).isEmpty()) {
parent.eval(elseCode, env);
} else {
ParseTree pass[] = new ParseTree[nodes.length - 1];
System.arraycopy(nodes, 0, pass, 0, nodes.length - 1);
nodes[0] = new ParseTree(data, null);
return super.execs(t, env, parent, pass);
}
return CVoid.VOID;
}
@Override
public String getName() {
return "foreachelse";
}
@Override
public Integer[] numArgs() {
return new Integer[]{4, 5};
}
@Override
public String docs() {
return "void {array, ivar, code, else} Works like a foreach, except if the array is empty, the else code runs instead. That is, if the code"
+ " would not run at all, the else condition would. In general, brace syntax and use of foreach(){ } else { } syntax is preferred, instead"
+ " of using foreachelse directly.";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage, with the else code not running",
"@array = array(1, 2, 3)\n"
+ "foreachelse(@array, @val,\n"
+ " msg(@val)\n"
+ ", #else \n"
+ " msg('No values in the array')\n"
+ ")"),
new ExampleScript("Empty array, so else block running",
"@array = array()\n"
+ "foreachelse(@array, @val,\n"
+ " msg(@val)\n"
+ ", #else \n"
+ " msg('No values in the array')\n"
+ ")"),};
}
}
@api
@noboilerplate
@breakable
public static class _while extends AbstractFunction {
@Override
public String getName() {
return "while";
}
@Override
public String docs() {
return "void {condition, [code]} While the condition is true, the code is executed. break and continue work"
+ " inside a dowhile, but continuing more than once is pointless, since the loop isn't inherently"
+ " keeping track of any counters anyways. Breaking multiple times still works however.";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2};
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) {
try {
while (Static.getBoolean(parent.seval(nodes[0], env))) {
//We allow while(thing()); to be done. This makes certain
//types of coding styles possible.
if (nodes.length > 1) {
try {
parent.seval(nodes[1], env);
} catch (LoopContinueException e) {
}
}
}
} catch (LoopBreakException e) {
if (e.getTimes() > 1) {
throw new LoopBreakException(e.getTimes() - 1, t);
}
}
return CVoid.VOID;
}
@Override
public boolean useSpecialExec() {
return true;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
return CNull.NULL;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "assign(@i, 5)\nwhile(@i > 0,\n"
+ "\tmsg(@i)\n"
+ "\t@i
+ ")"),
new ExampleScript("With a break", "assign(@i, 0)\nwhile(true,\n"
+ "\tmsg(@i)\n"
+ "\t@i++\n"
+ "\tif(@i > 5, break())\n"
+ ")"),};
}
@Override
public LogLevel profileAt() {
return LogLevel.WARNING;
}
@Override
public String profileMessageS(List<ParseTree> args) {
return "Executing function: " + this.getName() + "("
+ args.get(0).toStringVerbose() + ", <code>)";
}
}
@api
@noboilerplate
@breakable
public static class _dowhile extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
return CNull.NULL;
}
@Override
public String getName() {
return "dowhile";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2};
}
@Override
public String docs() {
return "void {code, condition} Like while, but always runs the code at least once. The condition is checked"
+ " after each run of the code, and if it is true, the code is run again. break and continue work"
+ " inside a dowhile, but continuing more than once is pointless, since the loop isn't inherently"
+ " keeping track of any counters anyways. Breaking multiple times still works however. In general, using brace"
+ " syntax is preferred: do { code(); } while(@condition); instead of using dowhile() directly.";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public boolean useSpecialExec() {
return true;
}
@Override
public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) {
try {
do {
try {
parent.seval(nodes[0], env);
} catch (LoopContinueException e) {
//ok. No matter how many times it tells us to continue, we're only going to continue once.
}
} while (Static.getBoolean(parent.seval(nodes[1], env)));
} catch (LoopBreakException e) {
if (e.getTimes() > 1) {
throw new LoopBreakException(e.getTimes() - 1, t);
}
}
return CVoid.VOID;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "do {\n"
+ "\tmsg('This will only run once');\n"
+ "} while(false);"),
new ExampleScript("Pure functional usage", "dowhile(\n"
+ "\tmsg('This will only run once')\n"
+ ", #while\n"
+ "false)")
};
}
@Override
public LogLevel profileAt() {
return LogLevel.WARNING;
}
@Override
public String profileMessageS(List<ParseTree> args) {
return "Executing function: " + this.getName() + "(<code>, "
+ args.get(1).toStringVerbose() + ")";
}
}
@api
public static class _break extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "break";
}
@Override
public Integer[] numArgs() {
return new Integer[]{0, 1};
}
@Override
public String docs() {
return "nothing {[int]} Stops the current loop. If int is specified, and is greater than 1, the break travels that many loops up. So, if you had"
+ " a loop embedded in a loop, and you wanted to break in both loops, you would call break(2). If this function is called outside a loop"
+ " (or the number specified would cause the break to travel up further than any loops are defined), the function will fail. If no"
+ " argument is specified, it is the same as calling break(1). This function has special compilation rules. The break number"
+ " must not be dynamic, or a compile error will occur. An integer must be hard coded into the function.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_1_0;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
int num = 1;
if (args.length == 1) {
num = Static.getInt32(args[0], t);
}
throw new LoopBreakException(num, t);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "for(assign(@i, 0), @i < 1000, @i++,\n"
+ "\tfor(assign(@j, 0), @j < 1000, @j++,\n"
+ "\t\tmsg('This will only display once')\n"
+ "\t\tbreak(2)\n"
+ "\t)"
+ ")"),
new ExampleScript("Invalid number", "for(assign(@i, 0), @i < 1000, @i++,\n"
+ "\tfor(assign(@j, 0), @j < 1000, @j++,\n"
+ "\t\tbreak(3) #There are only 2 loops to break out of\n"
+ "\t)"
+ ")"),};
}
@Override
public ParseTree optimizeDynamic(Target t, List<ParseTree> children, FileOptions fileOptions) throws ConfigCompileException, ConfigRuntimeException {
if (children.size() == 1) {
if (children.get(0).isDynamic()) {
//This is absolutely a bad design, if there is a variable here
//in the break. Due to optimization, this is a compile error.
throw new ConfigCompileException("The parameter sent to break() should"
+ " be hard coded, and should not be dynamically determinable, since this is always a sign"
+ " of loose code flow, which should be avoided.", t);
}
if(!(children.get(0).getData() instanceof CInt)){
throw new ConfigCompileException("break() only accepts integer values.", t);
}
}
return null;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(OptimizationOption.OPTIMIZE_DYNAMIC
//, OptimizationOption.TERMINAL This can't be added yet, because of things like switch, where code
//branches aren't considered correctly.
);
}
}
@api
public static class _continue extends AbstractFunction {
@Override
public String getName() {
return "continue";
}
@Override
public Integer[] numArgs() {
return new Integer[]{0, 1};
}
@Override
public String docs() {
return "void {[int]} Skips the rest of the code in this loop, and starts the loop over, with it continuing at the next index. If this function"
+ " is called outside of a loop, the command will fail. If int is set, it will skip 'int' repetitions. If no argument is specified,"
+ " 1 is used.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_1_0;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
int num = 1;
if (args.length == 1) {
num = Static.getInt32(args[0], t);
}
throw new LoopContinueException(num, t);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "for(assign(@i, 0), @i < 5, @i++){\n"
+ "\tif(@i == 2, continue())\n"
+ "\tmsg(@i)\n"
+ "}"),
new ExampleScript("Argument specified", "for(assign(@i, 0), @i < 5, @i++){\n"
+ "\tif(@i == 2, continue(2))\n"
+ "\tmsg(@i)\n"
+ "}"),};
}
}
@api
public static class is_stringable extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "is_stringable";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {item} Returns whether or not the item is convertable to a string. Everything but arrays can be used as strings.";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
return CBoolean.get(!(args[0] instanceof CArray));
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_stringable('yes')"),
new ExampleScript("True condition", "is_stringable(1) #This can be used as a string, yes"),
new ExampleScript("False condition", "is_stringable(array(1))"),};
}
}
@api
public static class is_string extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "is_string";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {item} Returns whether or not the item is actually a string datatype. If you just care if some data can be used as a string,"
+ " use is_stringable().";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
return CBoolean.get(args[0] instanceof CString);
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_string('yes')"),
new ExampleScript("False condition", "is_string(1) #is_stringable() would return true here"),};
}
}
@api
public static class is_bytearray extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "is_bytearray";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {item} Returns whether or not the item is actually a ByteArray datatype.";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
return CBoolean.get(args[0] instanceof CByteArray);
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_bytearray(string_get_bytes('yay'))"),
new ExampleScript("False condition", "is_bytearray('Nay')"),
new ExampleScript("False condition", "is_bytearray(123)"),};
}
}
@api
public static class is_array extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "is_array";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {item} Returns whether or not the item is an array";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_1_2;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
return CBoolean.get(args[0] instanceof CArray);
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_array(array(1))"),
new ExampleScript("True condition", "is_array(array(one: 1))"),
new ExampleScript("False condition", "is_array('no')"),};
}
}
@api
public static class is_number extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "is_number";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {item} Returns whether or not the given item is an integer or a double. Note that numeric strings can usually be used as integers and doubles,"
+ " however this function checks the actual datatype of the item. If you just want to see if an item can be used as a number,"
+ " use is_integral() or is_numeric() instead.";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
return CBoolean.get(args[0] instanceof CInt || args[0] instanceof CDouble);
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_number(1)"),
new ExampleScript("True condition", "is_number(1.0)"),
new ExampleScript("False condition", "is_number('1')"),
new ExampleScript("False condition", "is_number('1.0')")};
}
}
@api
public static class is_double extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "is_double";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {item} Returns whether or not the given item is a double. Note that numeric strings and integers"
+ " can usually be used as a double, however this function checks the actual datatype of the item. If"
+ " you just want to see if an item can be used as a number, use is_numeric() instead.";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_1_2;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
return CBoolean.get(args[0] instanceof CDouble);
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_double(1.0)"),
new ExampleScript("False condition", "is_double(1)"),};
}
}
@api
public static class is_integer extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "is_integer";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {item} Returns whether or not the given item is an integer. Note that numeric strings can usually be used as integers,"
+ " however this function checks the actual datatype of the item. If you just want to see if an item can be used as a number,"
+ " use is_integral() or is_numeric() instead.";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_1_2;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
return CBoolean.get(args[0] instanceof CInt);
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_integer(1)"),
new ExampleScript("False condition", "is_integer(1.0)"),};
}
}
@api
public static class is_boolean extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "is_boolean";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {item} Returns whether the given item is of the boolean datatype. Note that all datatypes can be used as booleans, however"
+ " this function checks the specific datatype of the given item.";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_1_2;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
return CBoolean.get(args[0] instanceof CBoolean);
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_boolean(false)"),
new ExampleScript("False condition", "is_boolean(0)"),};
}
}
@api
public static class is_null extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "is_null";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {item} Returns whether or not the given item is null.";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_1_2;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
return CBoolean.get(args[0] instanceof CNull);
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_null(null)"),
new ExampleScript("False condition", "is_null(0)"),};
}
}
@api
public static class is_numeric extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "is_numeric";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {item} Returns false if the item would fail if it were used as a numeric value."
+ " If it can be parsed or otherwise converted into a numeric value, true is returned.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
boolean b = true;
try {
Static.getNumber(args[0], t);
} catch (ConfigRuntimeException e) {
b = false;
}
return CBoolean.get(b);
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_numeric('1.0')"),
new ExampleScript("True condition", "is_numeric('1')"),
new ExampleScript("True condition", "is_numeric(1)"),
new ExampleScript("True condition", "is_numeric(1.5)"),
new ExampleScript("False condition", "is_numeric('string')"),
new ExampleScript("True condition, because null is coerced to 0.0, which is numeric.", "is_numeric(null)"),};
}
}
@api
public static class is_integral extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "is_integral";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {item} Returns true if the numeric value represented by "
+ " a given double or numeric string could be cast to an integer"
+ " without losing data (or if it's an integer). For instance,"
+ " is_numeric(4.5) would return true, and integer(4.5) would work,"
+ " however, equals(4.5, integer(4.5)) returns false, because the"
+ " value was narrowed to 4.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
double d;
try {
d = Static.getDouble(args[0], t);
} catch (ConfigRuntimeException e) {
return CBoolean.FALSE;
}
return CBoolean.get((long) d == d);
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_integral(1.0)"),
new ExampleScript("True condition", "is_integral(1)"),
new ExampleScript("True condition", "is_integral('5.0')"),
new ExampleScript("True condition", "is_integral('6')"),
new ExampleScript("False condition", "is_integral(1.5)"),
new ExampleScript("True condition, because null is coerced to 0, which is integral", "is_integral(null)"),};
}
}
@api
@unbreakable
public static class proc extends AbstractFunction {
@Override
public String getName() {
return "proc";
}
@Override
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
@Override
public String docs() {
return "void {[name], [ivar...], procCode} Creates a new user defined procedure (also known as \"function\") that can be called later in code. Please see the more detailed"
+ " documentation on procedures for more information. In general, brace syntax and keyword usage is preferred:"
+ " proc _myProc(@a, @b){ procCode(@a, @b); }";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public boolean preResolveVariables() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_1_3;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) {
Procedure myProc = getProcedure(t, env, parent, nodes);
env.getEnv(GlobalEnv.class).GetProcs().put(myProc.getName(), myProc);
return CVoid.VOID;
}
public static Procedure getProcedure(Target t, Environment env, Script parent, ParseTree... nodes) {
String name = "";
List<IVariable> vars = new ArrayList<>();
ParseTree tree = null;
List<String> varNames = new ArrayList<>();
boolean usesAssign = false;
CClassType returnType = CClassType.AUTO;
if(nodes[0].getData() instanceof CClassType){
returnType = (CClassType) nodes[0].getData();
ParseTree[] newNodes = new ParseTree[nodes.length - 1];
for(int i = 1; i < nodes.length; i++){
newNodes[i - 1] = nodes[i];
}
nodes = newNodes;
}
// We have to restore the variable list once we're done
IVariableList originalList = env.getEnv(GlobalEnv.class).GetVarList().clone();
for (int i = 0; i < nodes.length; i++) {
if (i == nodes.length - 1) {
tree = nodes[i];
} else {
boolean thisNodeIsAssign = false;
if (nodes[i].getData() instanceof CFunction) {
if (((CFunction) nodes[i].getData()).getValue().equals("assign")) {
thisNodeIsAssign = true;
if ((nodes[i].getChildren().size() == 3 && nodes[i].getChildAt(0).getData().isDynamic())
|| nodes[i].getChildAt(1).getData().isDynamic()) {
usesAssign = true;
}
}
}
env.getEnv(GlobalEnv.class).SetFlag("no-check-duplicate-assign", true);
Construct cons = parent.eval(nodes[i], env);
env.getEnv(GlobalEnv.class).ClearFlag("no-check-duplicate-assign");
if (i == 0 && cons instanceof IVariable) {
throw new ConfigRuntimeException("Anonymous Procedures are not allowed", ExceptionType.InvalidProcedureException, t);
} else {
if (i == 0 && !(cons instanceof IVariable)) {
name = cons.val();
} else {
if (!(cons instanceof IVariable)) {
throw new ConfigRuntimeException("You must use IVariables as the arguments", ExceptionType.InvalidProcedureException, t);
} else {
IVariable ivar = null;
try {
Construct c = cons;
if (c instanceof IVariable) {
String varName = ((IVariable) c).getName();
if (varNames.contains(varName)) {
throw new ConfigRuntimeException("Same variable name defined twice in " + name, ExceptionType.InvalidProcedureException, t);
}
varNames.add(varName);
}
while (c instanceof IVariable) {
c = env.getEnv(GlobalEnv.class).GetVarList().get(((IVariable) c).getName(), t, true).ival();
}
if (!thisNodeIsAssign) {
//This is required because otherwise a default value that's already in the environment
//would end up getting set to the existing value, thereby leaking in the global env
//into this proc, if the call to the proc didn't have a value in this slot.
c = new CString("", t);
}
ivar = new IVariable(((IVariable)cons).getDefinedType(), ((IVariable) cons).getName(), c.clone(), t);
} catch (CloneNotSupportedException ex) {
}
vars.add(ivar);
}
}
}
}
}
env.getEnv(GlobalEnv.class).SetVarList(originalList);
Procedure myProc = new Procedure(name, returnType, vars, tree, t);
if (usesAssign) {
myProc.definitelyNotConstant();
}
return myProc;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
return CVoid.VOID;
}
@Override
public boolean useSpecialExec() {
return true;
}
/**
* Returns either null to indicate that the procedure is not const, or
* returns a single Construct, which should replace the call to the
* procedure.
*
* @param t
* @param myProc
* @param children
* @return
* @throws ConfigRuntimeException
*/
public static Construct optimizeProcedure(Target t, Procedure myProc, List<ParseTree> children) throws ConfigRuntimeException {
if (myProc.isPossiblyConstant()) {
//Oooh, it's possibly constant. So, let's run it with our children.
try {
FileOptions options = new FileOptions(new HashMap<String, String>());
if (!children.isEmpty()) {
options = children.get(0).getFileOptions();
}
ParseTree root = new ParseTree(new CFunction("__autoconcat__", Target.UNKNOWN), options);
Script fakeScript = Script.GenerateScript(root, Static.GLOBAL_PERMISSION);
Environment env = Static.GenerateStandaloneEnvironment();
env.getEnv(GlobalEnv.class).SetScript(fakeScript);
Construct c = myProc.cexecute(children, env, t);
//Yup! It worked. It's a const proc.
return c;
} catch (ConfigRuntimeException e) {
if (e.getExceptionType() == ExceptionType.InvalidProcedureException) {
//This is the only valid exception that doesn't strictly mean it's a bad
//call.
return null;
}
throw e; //Rethrow it. Since the functions are all static, and we actually are
//running it with a mostly legit environment, this is a real runtime error,
//and we can safely convert it to a compile error upstream
} catch (Exception e) {
//Nope. Something is preventing us from running it statically.
//We don't really care. We just know it can't be optimized.
return null;
}
} else {
//Oh. Well, we tried.
return null;
}
}
// @Override
// public boolean canOptimizeDynamic() {
// return true;
// @Override
// public ParseTree optimizeDynamic(Target t, List<ParseTree> children) throws ConfigCompileException, ConfigRuntimeException {
// //We seriously lose out on the ability to optimize this procedure
// //if we are assigning a dynamic value as a default, but we have to check
// //that here. If we don't, we lose the information
// return ;
}
@api
public static class _return extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "return";
}
@Override
public Integer[] numArgs() {
return new Integer[]{0, 1};
}
@Override
public String docs() {
return "nothing {mixed} Returns the specified value from this procedure. It cannot be called outside a procedure.";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_2_0;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.TERMINAL
);
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
Construct ret = (args.length == 1 ? args[0] : CVoid.VOID);
throw new FunctionReturnException(ret, t);
}
}
@api
public static class include extends AbstractFunction /*implements Optimizable*/ {
// Can't currently optimize this, because it depends on knowing whether or not
// we are in cmdline mode, which is included with the environment, which doesn't
// exist in optimizations yet.
@Override
public String getName() {
return "include";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "void {path} Includes external code at the specified path.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.IncludeException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_2_0;
}
@Override
public Boolean runAsync() {
return true;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
return CVoid.VOID;
}
@Override
public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) {
ParseTree tree = nodes[0];
Construct arg = parent.seval(tree, env);
String location = arg.val();
File file = Static.GetFileFromArgument(location, env, t, null);
ParseTree include = IncludeCache.get(file, t);
if(include != null){
// It could be an empty file
parent.eval(include.getChildAt(0), env);
}
return CVoid.VOID;
}
@Override
public boolean useSpecialExec() {
return true;
}
// @Override
// public Set<OptimizationOption> optimizationOptions() {
// return EnumSet.of(
// OptimizationOption.OPTIMIZE_CONSTANT
// @Override
// public Construct optimize(Target t, Construct... args) throws ConfigCompileException {
// //We can't optimize per se, but if the path is constant, and the code is uncompilable, we
// //can give a warning, and go ahead and cache the tree.
// String path = args[0].val();
// File file = Static.GetFileFromArgument(path, env, t, null);
// IncludeCache.get(file, t);
// return null;
}
@api
public static class call_proc extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "call_proc";
}
@Override
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
@Override
public String docs() {
return "mixed {proc_name, [var1...]} Dynamically calls a user defined procedure. call_proc(_myProc, 'var1') is the equivalent of"
+ " _myProc('var1'), except you could dynamically build the procedure name if need be. This is useful for dynamic coding,"
+ " however, closures work best for callbacks. Throws an InvalidProcedureException if the procedure isn't defined. If you are"
+ " hardcoding the first parameter, a warning will be issued, because it is much more efficient and safe to directly use"
+ " a procedure if you know what its name is beforehand.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidProcedureException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public CHVersion since() {
return CHVersion.V3_2_0;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
if (args.length < 1) {
throw new ConfigRuntimeException("Expecting at least one argument to " + getName(), ExceptionType.InsufficientArgumentsException, t);
}
Procedure proc = env.getEnv(GlobalEnv.class).GetProcs().get(args[0].val());
if (proc != null) {
List<Construct> vars = new ArrayList<Construct>(Arrays.asList(args));
vars.remove(0);
Environment newEnv = null;
try {
newEnv = env.clone();
} catch (CloneNotSupportedException ex) {
throw new RuntimeException(ex);
}
return proc.execute(vars, newEnv, t);
}
throw new ConfigRuntimeException("Unknown procedure \"" + args[0].val() + "\"",
ExceptionType.InvalidProcedureException, t);
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(OptimizationOption.OPTIMIZE_DYNAMIC);
}
@Override
public ParseTree optimizeDynamic(Target t, List<ParseTree> children, FileOptions fileOptions) throws ConfigCompileException, ConfigRuntimeException {
if (children.size() < 1) {
throw new ConfigRuntimeException("Expecting at least one argument to " + getName(), ExceptionType.InsufficientArgumentsException, t);
}
if (children.get(0).isConst()) {
CHLog.GetLogger().Log(CHLog.Tags.COMPILER, LogLevel.WARNING, "Hardcoding procedure name in " + getName() + ", which is inefficient."
+ " Consider calling the procedure directly if the procedure name is known at compile time.", t);
}
return null;
}
}
@api
public static class call_proc_array extends call_proc {
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
CArray ca = Static.getArray(args[1], t);
if (ca.inAssociativeMode()) {
throw new Exceptions.CastException("Expected the array passed to " + getName() + " to be non-associative.", t);
}
Construct[] args2 = new Construct[(int) ca.size() + 1];
args2[0] = args[0];
for (int i = 1; i < args2.length; i++) {
args2[i] = ca.get(i - 1, t);
}
return super.exec(t, environment, args2);
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.InvalidProcedureException, ExceptionType.CastException};
}
@Override
public String getName() {
return "call_proc_array";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2};
}
@Override
public String docs() {
return "mixed {proc_name, array} Works like call_proc, but allows for variable or unknown number of arguments to be passed to"
+ " a proc. The array parameter is \"flattened\", and call_proc is essentially called. If the array is associative, an"
+ " exception is thrown.";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ParseTree optimizeDynamic(Target t, List<ParseTree> children, FileOptions fileOptions) throws ConfigCompileException, ConfigRuntimeException {
//If they hardcode the name, that's fine, because the variables may just be the only thing that's variable.
return null;
}
}
@api(environments = CommandHelperEnvironment.class)
public static class is_proc extends AbstractFunction {
@Override
public String getName() {
return "is_proc";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {procName} Returns whether or not the given procName is currently defined, i.e. if calling this proc wouldn't"
+ " throw an exception.";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public CHVersion since() {
return CHVersion.V3_2_0;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) {
return CBoolean.get(env.getEnv(GlobalEnv.class).GetProcs().get(args[0].val()) != null);
}
}
@api
public static class is_associative extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "is_associative";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {array} Returns whether or not the array is associative. If the parameter is not an array, throws a CastException.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
if (args[0] instanceof CArray) {
return CBoolean.get(((CArray) args[0]).inAssociativeMode());
} else {
throw new ConfigRuntimeException(this.getName() + " expects argument 1 to be an array", ExceptionType.CastException, t);
}
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_associative(array(one: 1, two: 2))"),
new ExampleScript("False condition", "is_associative(array(1, 2, 3))"),};
}
}
@api
public static class is_closure extends AbstractFunction {
@Override
public String getName() {
return "is_closure";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {arg} Returns true if the argument is a closure (could be executed)"
+ " or false otherwise";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
return CBoolean.get(args[0] instanceof CClosure);
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("True condition", "is_closure(closure(msg('code')))"),
new ExampleScript("False condition", "is_closure('a string')"),};
}
}
@api
@seealso({_export.class})
public static class _import extends AbstractFunction {
@Override
public String getName() {
return "import";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1,2};
}
@Override
public String docs() {
return "mixed {key, [default]} This function imports a value from the global value register. It looks for a"
+ " value stored with the specified key (using the export function), and returns that value."
+ " If specified key doesn't exist, it will return either null or the default value if specified."
+ " An array may be used as a key. It is converted into a string with the array values separated by"
+ " dots. import() is threadsafe.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.IllegalArgumentException, ExceptionType.IndexOverflowException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
String key;
if(args[0] instanceof CString){
key = args[0].val();
} else if(args[0] instanceof CArray){
key = GetNamespace((CArray) args[0], t);
} else {
throw new ConfigRuntimeException("Argument 1 in " + this.getName() + " must be a string or array.",
ExceptionType.IllegalArgumentException, t);
}
Construct c = Globals.GetGlobalConstruct(key);
if(args.length == 2 && c instanceof CNull){
c = args[1];
}
return c;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new _export().examples();
}
}
@api
@seealso({_import.class})
public static class _export extends AbstractFunction {
@Override
public String getName() {
return "export";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2};
}
@Override
public String docs() {
return "void {key, value} Stores a value in the global storage register."
+ " An arbitrary value is stored with the given key, and can be retreived using import."
+ " If the value is already stored, it is overwritten. See {{function|import}}."
+ " The reference to the value is stored, not a copy of the value, so in the case of"
+ " arrays, manipulating the contents of the array will manipulate the stored value. An array may"
+ " be used as a key. It is converted into a string with the array values separated by dots."
+ " export() is threadsafe.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.IllegalArgumentException, ExceptionType.IndexOverflowException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
String key;
if(args[0] instanceof CString){
key = args[0].val();
} else if(args[0] instanceof CArray){
key = GetNamespace((CArray) args[0], t);
} else {
throw new ConfigRuntimeException("Argument 1 in " + this.getName() + " must be a string or array.",
ExceptionType.IllegalArgumentException, t);
}
Construct c = args[1];
Globals.SetGlobal(key, c);
return CVoid.VOID;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "@var = 2;\n"
+ "export('custom.name', @var);\n"
+ "@var2 = import('custom.name');\n"
+ "msg(@var2);"),
new ExampleScript("Storage of references", "@array = array(1, 2, 3);\n"
+ "export('array', @array);\n"
+ "@array[0] = 4;\n"
+ "@array2 = import('array');\n"
+ "msg(@array2);"),
new ExampleScript("Array key usage", "@key = array(custom, name);\n"
+ "export(@key, 'value');\n"
+ "@value = import(@key);\n"
+ "msg(@value);"),
new ExampleScript("Default value usage", "export('custom.name', null);\n"
+ "@value = import('custom.name', 'default value');\n"
+ "msg(@value);")
};
}
}
@api(environments = CommandHelperEnvironment.class)
@unbreakable
public static class closure extends AbstractFunction {
@Override
public String getName() {
return "closure";
}
@Override
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
@Override
public String docs() {
return "closure {[varNames...,] code} Returns a closure on the provided code. A closure is"
+ " a datatype that represents some code as code, not the results of some"
+ " code after it is run. Code placed in a closure can be used as"
+ " a string, or executed by other functions using the eval() function."
+ " If a closure is \"to string'd\" it will not necessarily look like"
+ " the original code, but will be functionally equivalent. The current environment"
+ " is \"snapshotted\" and stored with the closure, however, this information is"
+ " only stored in memory, it isn't retained during a serialization operation."
+ " Also, the special variable @arguments is automatically created for you, and contains"
+ " an array of all the arguments passed to the closure, much like procedures."
+ " See the wiki article on [[CommandHelper/Staged/Closures|closures]] for more details"
+ " and examples.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public boolean preResolveVariables() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
return CVoid.VOID;
}
@Override
public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) {
if (nodes.length == 0) {
//Empty closure, do nothing.
return new CClosure(null, env, CClassType.AUTO, new String[]{}, new Construct[]{}, new CClassType[]{}, t);
}
// Handle the closure type first thing
CClassType returnType = CClassType.AUTO;
if(nodes[0].getData() instanceof CClassType){
returnType = (CClassType) nodes[0].getData();
ParseTree[] newNodes = new ParseTree[nodes.length - 1];
for(int i = 1; i < nodes.length; i++){
newNodes[i - 1] = nodes[i];
}
nodes = newNodes;
}
String[] names = new String[nodes.length - 1];
Construct[] defaults = new Construct[nodes.length - 1];
CClassType[] types = new CClassType[nodes.length - 1];
// We clone the enviornment at this point, because we don't want the values
// that are assigned here to overwrite values in the main scope.
Environment myEnv;
try {
myEnv = env.clone();
} catch (CloneNotSupportedException ex) {
myEnv = env;
}
for (int i = 0; i < nodes.length - 1; i++) {
ParseTree node = nodes[i];
ParseTree newNode = new ParseTree(new CFunction("g", t), node.getFileOptions());
List<ParseTree> children = new ArrayList<>();
children.add(node);
newNode.setChildren(children);
Script fakeScript = Script.GenerateScript(newNode, myEnv.getEnv(GlobalEnv.class).GetLabel());
myEnv.getEnv(GlobalEnv.class).SetFlag("closure-warn-overwrite", true);
Construct ret = MethodScriptCompiler.execute(newNode, myEnv, null, fakeScript);
myEnv.getEnv(GlobalEnv.class).ClearFlag("closure-warn-overwrite");
if (!(ret instanceof IVariable)) {
throw new ConfigRuntimeException("Arguments sent to " + getName() + " barring the last) must be ivariables", ExceptionType.CastException, t);
}
names[i] = ((IVariable) ret).getName();
try {
defaults[i] = ((IVariable) ret).ival().clone();
types[i] = ((IVariable)ret).getDefinedType();
} catch (CloneNotSupportedException ex) {
Logger.getLogger(DataHandling.class.getName()).log(Level.SEVERE, null, ex);
}
}
CClosure closure = new CClosure(nodes[nodes.length - 1], myEnv, returnType, names, defaults, types, t);
return closure;
}
@Override
public Version since() {
return CHVersion.V3_3_0;
}
@Override
public boolean useSpecialExec() {
return true;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Creates a closure", "closure(){\n"
+ "\tmsg('Hello World!');\n"
+ "};"),
new ExampleScript("Executes a closure", "execute(closure(){\n"
+ "\tmsg('Hello World!');\n"
+ "});")
};
}
}
@api
@unbreakable
public static class iclosure extends closure {
@Override
public String getName() {
return "iclosure";
}
@Override
public String docs() {
return "iclosure {[varNames...,] code} Returns a scope isolated closure on the provided code. An iclosure is"
+ " a datatype that represents some code as code, not the results of some"
+ " code after it is run. Code placed in an iclosure can be used as"
+ " a string, or executed by other functions using the execute() function."
+ " If a closure is \"to string'd\" it will not necessarily look like"
+ " the original code, but will be functionally equivalent. The current environment"
+ " is \"snapshotted\" and stored with the closure, however, this information is"
+ " only stored in memory, it isn't retained during a serialization operation. However,"
+ " the variable table of the parent scope is not retained, thus making this closure \"isolated\""
+ " from the parent code."
+ " The special variable @arguments is automatically created for you, and contains"
+ " an array of all the arguments passed to the closure, much like procedures."
+ " See the wiki article on [[CommandHelper/Staged/Closures|closures]] for more details"
+ " and examples.";
}
@Override
public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) {
if (nodes.length == 0) {
//Empty closure, do nothing.
return new CClosure(null, env, CClassType.AUTO, new String[]{}, new Construct[]{}, new CClassType[]{}, t);
}
// Handle the closure type first thing
CClassType returnType = CClassType.AUTO;
if(nodes[0].getData() instanceof CClassType){
returnType = (CClassType) nodes[0].getData();
ParseTree[] newNodes = new ParseTree[nodes.length - 1];
for(int i = 1; i < nodes.length; i++){
newNodes[i - 1] = nodes[i];
}
nodes = newNodes;
}
String[] names = new String[nodes.length - 1];
Construct[] defaults = new Construct[nodes.length - 1];
CClassType[] types = new CClassType[nodes.length - 1];
// We clone the enviornment at this point, because we don't want the values
// that are assigned here to overwrite values in the main scope.
Environment myEnv;
try {
myEnv = env.clone();
} catch (CloneNotSupportedException ex) {
myEnv = env;
}
for (int i = 0; i < nodes.length - 1; i++) {
ParseTree node = nodes[i];
ParseTree newNode = new ParseTree(new CFunction("g", t), node.getFileOptions());
List<ParseTree> children = new ArrayList<>();
children.add(node);
newNode.setChildren(children);
Script fakeScript = Script.GenerateScript(newNode, myEnv.getEnv(GlobalEnv.class).GetLabel());
myEnv.getEnv(GlobalEnv.class).SetFlag("closure-warn-overwrite", true);
Construct ret = MethodScriptCompiler.execute(newNode, myEnv, null, fakeScript);
myEnv.getEnv(GlobalEnv.class).ClearFlag("closure-warn-overwrite");
if (!(ret instanceof IVariable)) {
throw new ConfigRuntimeException("Arguments sent to " + getName() + " barring the last) must be ivariables", ExceptionType.CastException, t);
}
names[i] = ((IVariable) ret).getName();
try {
defaults[i] = ((IVariable) ret).ival().clone();
types[i] = ((IVariable)ret).getDefinedType();
} catch (CloneNotSupportedException ex) {
Logger.getLogger(DataHandling.class.getName()).log(Level.SEVERE, null, ex);
}
}
CIClosure closure = new CIClosure(nodes[nodes.length - 1], myEnv, returnType, names, defaults, types, t);
return closure;
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Creates an iclosure", "iclosure(){\n"
+ "\tmsg('Hello World!');\n"
+ "};"),
new ExampleScript("Executes an iclosure", "execute(iclosure(){\n"
+ "\tmsg('Hello World!');\n"
+ "});"),
new ExampleScript("Shows scoping", "@a = \'variable\';\n"
+ "msg('Outside of iclosure: '.reflect_pull('varlist'));\n"
+ "// Note that this is an iclosure\n"
+ "execute('val1', iclosure(@b){\n"
+ "\tmsg('Inside of iclosure: '.reflect_pull('varlist'));\n"
+ "});\n"
+ "// Note that this is a regular closure\n"
+ "execute('val2', closure(@c){\n"
+ "\tmsg('Insider of closure: '.reflect_pull('varlist'));\n"
+ "});")
};
}
}
@api
@hide("Until the Federation system is finished, this is hidden")
@unbreakable
@nolinking
public static class rclosure extends closure {
@Override
public String getName() {
return "rclosure";
}
@Override
public String docs() {
return "closure {[varNames...], code} Returns a non-linking closure on the provided code. The same rules apply"
+ " for closures, except the top level internal code does not check for proper linking at compile time,"
+ " and instead links at runtime. Lexer errors and some other compile time checks ARE done however, but"
+ " functions are not optimized or linked. This is used for remote code execution, since the remote platform"
+ " may have some functionality unavailable on this current platform.";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
}
@api
public static class execute extends AbstractFunction {
@Override
public String getName() {
return "execute";
}
@Override
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
@Override
public String docs() {
return "mixed {[values...,] closure} Executes the given closure. You can also send arguments"
+ " to the closure, which it may or may not use, depending on the particular closure's"
+ " definition. If the closure returns a value with return(), then that value will"
+ " be returned with execute. Otherwise, void is returned.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
if (args[args.length - 1] instanceof CClosure) {
Construct[] vals = new Construct[args.length - 1];
System.arraycopy(args, 0, vals, 0, args.length - 1);
CClosure closure = (CClosure) args[args.length - 1];
try {
closure.execute(vals);
} catch (FunctionReturnException e) {
return e.getReturn();
}
} else {
throw new ConfigRuntimeException("Only a closure (created from the closure function) can be sent to execute()", ExceptionType.CastException, t);
}
return CVoid.VOID;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
}
@api
public static class _boolean extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "boolean";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "boolean {item} Returns a new construct that has been cast to a boolean. The item is cast according to"
+ " the boolean conversion rules. Since all data types can be cast to a"
+ " a boolean, this function will never throw an exception.";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
return CBoolean.get(Static.getBoolean(args[0]));
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "boolean(1)"),
new ExampleScript("Basic usage", "boolean(0)"),
new ExampleScript("Basic usage", "boolean(array(1))"),
new ExampleScript("Basic usage", "boolean(array())"),
new ExampleScript("Basic usage", "boolean(null)"),
new ExampleScript("Basic usage", "boolean('string')"),
new ExampleScript("Basic usage", "boolean('')"),};
}
}
@api
public static class _integer extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "integer";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "integer {item} Returns a new construct that has been cast to an integer."
+ " This function will throw a CastException if is_numeric would return"
+ " false for this item, but otherwise, it will be cast properly. Data"
+ " may be lost in this conversion. For instance, 4.5 will be converted"
+ " to 4, by using integer truncation. You can use is_integral to see"
+ " if this data loss would occur.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
return new CInt((long) Static.getDouble(args[0], t), t);
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "integer(1.0)"),
new ExampleScript("Basic usage", "integer(1.5)"),
new ExampleScript("Failure", "assign(@var, 'string')\ninteger(@var)"),};
}
}
@api
public static class _double extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "double";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "double {item} Returns a new construct that has been cast to an double."
+ " This function will throw a CastException if is_numeric would return"
+ " false for this item, but otherwise, it will be cast properly.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
return new CDouble(Static.getDouble(args[0], t), t);
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "double(1)"),
new ExampleScript("Failure", "@var = 'string';\ndouble(@var);"),};
}
}
@api
public static class _string extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "string";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "string {item} Creates a new construct that is the \"toString\" of an item."
+ " For arrays, an human readable version is returned; this should not be"
+ " used directly, as the format is not guaranteed to remain consistent. Booleans return \"true\""
+ " or \"false\" and null returns \"null\".";
}
@Override
public ExceptionType[] thrown() {
return null;
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
return new CString(args[0].val(), t);
}
@Override
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(
OptimizationOption.CONSTANT_OFFLINE,
OptimizationOption.CACHE_RETURN
);
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "string(1)"),
new ExampleScript("Basic usage", "string(true)"),
new ExampleScript("Basic usage", "string(false)"),
new ExampleScript("Basic usage", "string(null)"),
new ExampleScript("Basic usage", "string(array(1, 2))"),
new ExampleScript("Basic usage", "string(array(one: 'one', two: 'two'))"),};
}
}
@api
@seealso(parse_int.class)
public static class to_radix extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.RangeException, ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
int radix = Static.getInt32(args[1], t);
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new Exceptions.RangeException("The radix must be between " + Character.MIN_RADIX + " and " + Character.MAX_RADIX + ", inclusive.", t);
}
return new CString(Long.toString(Static.getInt(args[0], t), radix), t);
}
@Override
public String getName() {
return "to_radix";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2};
}
@Override
public String docs() {
return "string {value, radix} Given an int and a radix, returns a string representation of the integer value"
+ " in the given base. A common use would be to output a hex or binary representation of a number, for"
+ " instance. ---- It is useful to note that all integers are stored internally by the computer as binary,"
+ " but since we usually represent numbers in text as base 10 numbers, we often times forget that both"
+ " base 16 'F' and base 10 '15' and base 2 '1111' are actually the same number, just represented differently"
+ " as strings in different bases. This doesn't change how the program behaves, since the base is just a way to represent"
+ " the number on paper. The 'radix' is the base. So, given to_radix(10, 10), that would return '10', because"
+ " in code, we wrote out our value '10' in base 10, and we convert it to base 10, so nothing changes. However,"
+ " if we write to_radix(15, 16) we are saying \"convert the base 10 value 15 to base 16\", so it returns 'F'."
+ " See {{function|parse_int}} for the opposite operation. The radix must be between " + Character.MIN_RADIX + " and "
+ Character.MAX_RADIX + ", inclusive, or a range exception is thrown. This is because there are only " + Character.MAX_RADIX
+ " characters that are normally used to represent different base numbers (that is, 0-9, a-z). The minimum radix is "
+ Character.MIN_RADIX + ", because it is impossible to represent any numbers with out at least a binary base.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("To a hex string", "to_radix(15, 16)"),
new ExampleScript("To a binary string", "to_radix(15, 2)"),
new ExampleScript("Using hex value in source", "to_radix(0xff, 16)"),
new ExampleScript("Using binary value in source", "to_radix(0b10101010, 2)")
};
}
}
@api
@seealso(to_radix.class)
public static class parse_int extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.RangeException, ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
String value = args[0].val();
int radix = Static.getInt32(args[1], t);
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new Exceptions.RangeException("The radix must be between " + Character.MIN_RADIX + " and " + Character.MAX_RADIX + ", inclusive.", t);
}
long ret;
try {
ret = Long.parseLong(value, radix);
} catch (NumberFormatException ex) {
throw new Exceptions.FormatException("The input string: \"" + value + "\" is improperly formatted. (Perhaps you're using a character greater than"
+ " the radix specified?)", t);
}
return new CInt(ret, t);
}
@Override
public String getName() {
return "parse_int";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2};
}
@Override
public String docs() {
return "int {value, radix} Converts a string representation of an integer to a real integer, given the value's"
+ " radix (base). See {{function|to_radix}} for a more detailed explanation of number theory. Radix must be"
+ " between " + Character.MIN_RADIX + " and " + Character.MAX_RADIX + ", inclusive.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("From hex string", "parse_int('F', 16)"),
new ExampleScript("From binary string", "parse_int('1111', 2)")
};
}
}
/**
* Generates the namespace for this value, given an array.
*
* @param array
* @return
*/
private static String GetNamespace(CArray array, Target t) {
boolean first = true;
StringBuilder b = new StringBuilder();
for (int i = 0; i < array.size(); i++) {
if (!first) {
b.append(".");
}
first = false;
b.append(array.get(i, t).val());
}
return b.toString();
}
@api
public static class typeof extends AbstractFunction implements Optimizable {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
try {
return new CClassType(args[0].typeof(), t);
} catch (IllegalArgumentException ex) {
throw new Error("Class " + args[0].getClass().getName() + " is not annotated with @typeof. Please report this"
+ " error to the developers.");
}
}
@Override
public String getName() {
return "typeof";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "ClassType {arg} Returns a string value of the typeof a value. For instance 'array' is returned"
+ " for typeof(array()). This is a generic replacement for the is_* series of functions.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage, typeof string", "typeof('value')"),
new ExampleScript("Basic usage, typeof int", "typeof(1)"),
new ExampleScript("Basic usage, typeof double", "typeof(1.0)"),
new ExampleScript("Basic usage, typeof closure", "typeof(closure(){ msg('test') })"),};
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(OptimizationOption.CONSTANT_OFFLINE);
}
}
@api
public static class eval extends AbstractFunction implements Optimizable {
@Override
public String getName() {
return "eval";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1};
}
@Override
public String docs() {
return "string {script_string} Executes arbitrary MethodScript. Note that this function is very experimental, and is subject to changing or "
+ "removal.";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public CHVersion since() {
return CHVersion.V3_1_0;
}
@Override
public Construct execs(Target t, Environment env, Script parent, ParseTree... nodes) {
boolean oldDynamicScriptMode = env.getEnv(GlobalEnv.class).GetDynamicScriptingMode();
ParseTree node = nodes[0];
try {
env.getEnv(GlobalEnv.class).SetDynamicScriptingMode(true);
Construct script = parent.seval(node, env);
if(script instanceof CClosure){
throw new Exceptions.CastException("Closures cannot be eval'd directly. Use execute() instead.", t);
}
ParseTree root = MethodScriptCompiler.compile(MethodScriptCompiler.lex(script.val(), t.file(), true));
StringBuilder b = new StringBuilder();
int count = 0;
for (ParseTree child : root.getChildren()) {
Construct s = parent.seval(child, env);
if (!s.val().trim().isEmpty()) {
if (count > 0) {
b.append(" ");
}
b.append(s.val());
}
count++;
}
return new CString(b.toString(), t);
} catch (ConfigCompileException e) {
throw new ConfigRuntimeException("Could not compile eval'd code: " + e.getMessage(), ExceptionType.FormatException, t);
} catch(ConfigCompileGroupException ex){
StringBuilder b = new StringBuilder();
b.append("Could not compile eval'd code: ");
for(ConfigCompileException e : ex.getList()){
b.append(e.getMessage()).append("\n");
}
throw new ConfigRuntimeException(b.toString(), ExceptionType.FormatException, t);
} finally {
env.getEnv(GlobalEnv.class).SetDynamicScriptingMode(oldDynamicScriptMode);
}
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
return CVoid.VOID;
}
//Doesn't matter, run out of state anyways
@Override
public Boolean runAsync() {
return null;
}
@Override
public boolean useSpecialExec() {
return true;
}
@Override
public Set<Optimizable.OptimizationOption> optimizationOptions() {
return EnumSet.of(Optimizable.OptimizationOption.OPTIMIZE_DYNAMIC);
}
@Override
public ParseTree optimizeDynamic(Target t, List<ParseTree> children, FileOptions fileOptions) throws ConfigCompileException, ConfigRuntimeException {
if(children.size() != 1){
throw new ConfigCompileException(getName() + " expects only one argument", t);
}
if(children.get(0).isConst()){
CHLog.GetLogger().Log(CHLog.Tags.COMPILER, LogLevel.WARNING, "Eval'd code is hardcoded, consider simply using the code directly, as wrapping"
+ " hardcoded code in " + getName() + " is much less efficient.", t);
}
return null;
}
}
@api
@noprofile
@hide("This will eventually be replaced by ; statements.")
public static class g extends AbstractFunction {
@Override
public String getName() {
return "g";
}
@Override
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
@Override
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
for (int i = 0; i < args.length; i++) {
args[i].val();
}
return CVoid.VOID;
}
@Override
public String docs() {
return "string {func1, [func2...]} Groups any number of functions together, and returns void. ";
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public CHVersion since() {
return CHVersion.V3_0_1;
}
@Override
public Boolean runAsync() {
return null;
}
}
/**
* For now, this feature works as is. However, I'm debating on whether or not I should just override assign() instead.
* The only issue with this is that if assign is overwritten, then a mutable_primitive will be "stuck" in the variable.
* So if later you wanted to make a value not a mutable primitive, there would be no way to do so. Another method could
* be introduced to "clear" the value out, but then there would be no way to tell if the value were actually mutable or
* not, so a third function would have to be added. The other point of concern is how to handle typeof() for a CMutablePrimitive.
* Should it return the underlying type, or mutable_primitive? If assignments are "sticky", then it would make sense to have
* it return the underlying type, but there's an issue with that, because then typeof wouldn't be useable for debug type
* situations. Given all these potential issues, it is still hidden, but available for experimental cases.
*/
@api
@hide("This is still experimental")
public static class mutable_primitive extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
Construct val = CNull.NULL;
if(args.length > 0){
val = args[0];
}
return new CMutablePrimitive(val, t);
}
@Override
public String getName() {
return "mutable_primitive";
}
@Override
public Integer[] numArgs() {
return new Integer[]{0, 1};
}
@Override
public String docs() {
return "mutable_primitive {[primitive_value]} Creates a mutable primitive object, initially setting the value of the object to"
+ " null, or the specified value. The value must be a primitive value, and cannot be an array or object.
+ " The underlying primitive value is used in all cases where a value can be inferred. In all other cases, you must convert"
+ " the primitive to the desired type, e.g. double(@mutable_primitive). Mutable primitives work like an array as well,"
+ " in some cases, but not others. In general, setting of the underlying values may be done with array_push(). Assigning"
+ " a new value to the variable works the same as assigning a new value to any other value, it overwrites the value with"
+ " the new type. Most array functions will work with the mutable primitive, however, they will return useless data, for"
+ " instance, array_resize() will simply set the value to the default value shown. array_size() is an exception to this"
+ " rule, it will not work, and will throw an exception. See the examples for more use cases. In general, this is meant"
+ " as a convenience feature for values that are passed to closures or procs, but should be passed by reference. Cloning the"
+ " mutable primitive with the array clone operation creates a distinct copy.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Basic usage", "@val = mutable_primitive(0);\n"
+ "msg('typeof: ' . typeof(@val));\n"
+ "msg('value: ' . @val);\n"
+ "msg('@val + 5: ' . (@val + 5)); // Works as if it were a primitive with most functions\n"
+ "(++@val); // As a special exception to how assignments work, increment/decrement works as well\n"
+ "msg(@val);
new ExampleScript("Basic usage with procs", "proc(_testWithMutable, @a){\n"
+ "\t@a[] = 5;\n"
+ "}\n\n"
+ ""
+ "proc(_testWithoutMutable, @a){\n"
+ "\t@a = 10;\n"
+ "}\n\n"
+ ""
+ "@a = mutable_primitive(0);\n"
+ "msg(@a); // The value starts out as 0\n"
+ "_testWithMutable(@a); // This will actually change the value\n"
+ "msg(@a); // Here, the value is 5\n"
+ "_testWithoutMutable(@a); // This will not change the value\n"
+ "msg(@a); // Still teh value is 5\n"),
new ExampleScript("Basic usage with closure", "@a = mutable_primitive(0);\n"
+ "execute(closure(){\n"
+ "\t@a++;\n"
+ "});\n"
+ "msg(@a);
new ExampleScript("Cloning the value", "@a = mutable_primitive(0);\n"
+ "@b = @a[];\n"
+ "@a[] = 5;\n"
+ "msg(@a);\n"
+ "msg(@b);\n")
};
}
}
@api
public static class _instanceof extends AbstractFunction implements Optimizable {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
@Override
public boolean isRestricted() {
return false;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
if(args[0] instanceof CNull){
return CBoolean.FALSE;
}
boolean b = InstanceofUtil.isInstanceof(args[0], args[1].val());
return CBoolean.get(b);
}
@Override
public String getName() {
return "instanceof";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2};
}
@Override
public String docs() {
return "boolean {value, type} Checks to see if the value is, extends, or implements the given type. Keyword usage is preferred:"
+ " @value instanceof int ---- Null is a special value, while any type may be assigned null, it does not extend"
+ " any type, and therefore \"null instanceof AnyType\" will always return false. Likewise, other than null, all"
+ " values extend \"mixed\", and therefore \"anyNonNullValue instanceof mixed\" will always return true.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(OptimizationOption.OPTIMIZE_DYNAMIC);
}
@Override
public ParseTree optimizeDynamic(Target t, List<ParseTree> children, FileOptions fileOptions) throws ConfigCompileException, ConfigRuntimeException {
// There are two specific cases here where we will give more precise error messages.
// If it's a string, yell at them
if(children.get(1).getData() instanceof CString){
throw new ConfigCompileException("Unexpected string type passed to \"instanceof\"", t);
}
// If it's a variable, also yell at them
if(children.get(1).getData() instanceof IVariable){
throw new ConfigCompileException("Variable types are not allowed in \"instanceof\"", t);
}
// Unknown error, but this is still never valid.
if(!(children.get(1).getData() instanceof CClassType)){
throw new ConfigCompileException("Unexpected type for \"instanceof\": " + children.get(1).getData(), t);
}
// null is technically a type, but instanceof shouldn't work with that
if(children.get(1).getData().val().equals("null")){
throw new ConfigCompileException("\"null\" cannot be compared against with instanceof", t);
}
// It's hardcoded, allow it, but optimize it out.
if(children.get(0).isConst()){
return new ParseTree(exec(t, null, children.get(0).getData(), children.get(1).getData()), fileOptions);
}
return null;
}
}
}
|
package com.minecraftedu.students;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraftforge.event.world.BlockEvent.BreakEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class BlockBreakMessage {
@SubscribeEvent
public void sendMessage(BreakEvent event) {
event.getPlayer()
.addChatComponentMessage(new ChatComponentText(EnumChatFormatting.GOLD + getCustomMessage()));
}
public String getCustomMessage() {
String message = "My first minecraft mod again";
return message;
}
}
|
package com.netease.xmpp.master.client;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
public class TaskExecutor {
private static Logger logger = Logger.getLogger(TaskExecutor.class);
private LinkedBlockingQueue<Runnable> clientTaskQueue = new LinkedBlockingQueue<Runnable>();
private LinkedBlockingQueue<Runnable> serverTaskQueue = new LinkedBlockingQueue<Runnable>();
private ThreadPoolExecutor threadPool;
public Thread clientTaskExecutor = null;
public Thread serverTaskExecutor = null;
private static TaskExecutor instance = null;
private TaskExecutor(int maxThreads) {
threadPool = new ThreadPoolExecutor(maxThreads * 2, maxThreads * 2, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());
clientTaskExecutor = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Runnable task = clientTaskQueue.take();
if (ClientGlobal.getIsUpdating()) {
synchronized (clientTaskExecutor) {
logger.debug("Client task waiting...");
clientTaskExecutor.wait();
}
}
logger.debug("Client task working...");
threadPool.execute(task);
} catch (InterruptedException e) {
logger.error(e.getMessage());
}
}
}
});
serverTaskExecutor = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Runnable task = serverTaskQueue.take();
if (ClientGlobal.getIsUpdating()) {
synchronized (serverTaskExecutor) {
logger.debug("Server task working...");
serverTaskExecutor.wait();
}
}
logger.debug("Server task working...");
threadPool.execute(task);
} catch (InterruptedException e) {
logger.error(e.getMessage());
}
}
}
});
}
public static TaskExecutor getInstance() {
if (instance == null) {
int maxThreads = Runtime.getRuntime().availableProcessors();
instance = new TaskExecutor(maxThreads);
}
return instance;
}
public void start() {
clientTaskExecutor.start();
serverTaskExecutor.start();
}
public void resume() {
synchronized (clientTaskExecutor) {
clientTaskExecutor.notify();
}
synchronized (serverTaskExecutor) {
serverTaskExecutor.notify();
}
}
public void addClientTask(Runnable task) {
if (!clientTaskQueue.offer(task)) {
logger.error("Add client task fail.");
}
}
public void addServerTask(Runnable task) {
if (!serverTaskQueue.offer(task)) {
logger.error("Add server task fail.");
}
}
}
|
package com.neverwinterdp.scribengin;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import kafka.api.FetchRequest;
import kafka.api.FetchRequestBuilder;
import kafka.api.PartitionOffsetRequestInfo;
import kafka.cluster.Broker;
import kafka.common.ErrorMapping;
import kafka.common.TopicAndPartition;
import kafka.javaapi.FetchResponse;
import kafka.javaapi.OffsetRequest;
import kafka.javaapi.OffsetResponse;
import kafka.javaapi.PartitionMetadata;
import kafka.javaapi.TopicMetadata;
import kafka.javaapi.TopicMetadataRequest;
import kafka.javaapi.consumer.SimpleConsumer;
import kafka.message.MessageAndOffset;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Logger;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
public class ScribeConsumer {
// Random comments:
// Unique define a partition. Client name + topic name + offset
// java -cp scribengin-uber-0.0.1-SNAPSHOT.jar com.neverwinterdp.scribengin.ScribeConsumer --broker-lst HOST1:PORT1,HOST2:PORT2 --checkpoint_interval 100 --partition 0 --topic scribe
// checkout src/main/java/com/neverwinterdp/scribengin/ScribeConsumer.java
// checkout org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter
// checkout EtlMultiOutputCommitter in Camus
// /usr/lib/kafka/bin/kafka-console-producer.sh --topic scribe --broker-list 10.0.2.15:9092
private static final String PRE_COMMIT_PATH_PREFIX = "/tmp";
private static final String COMMIT_PATH_PREFIX = "/user/kxae";
private static final Logger LOG = Logger.getLogger(ScribeConsumer.class.getName());
private String currTmpDataPath;
private String currDataPath;
private AbstractScribeCommitLogFactory scribeCommitLogFactory;
private AbstractFileSystemFactory fileSystemFactory;
private List<HostPort> replicaBrokers; // list of (host:port)s
@Parameter(names = {"-"+Constants.OPT_KAFKA_TOPIC, "--"+Constants.OPT_KAFKA_TOPIC})
private String topic;
@Parameter(names = {"-"+Constants.OPT_PARTITION, "--"+Constants.OPT_PARTITION})
private int partition;
private long lastCommittedOffset;
private long offset; // offset is on a per line basis. starts on the last valid offset
@Parameter(names = {"-"+Constants.OPT_BROKER_LIST, "--"+Constants.OPT_BROKER_LIST}, variableArity = true)
private List<HostPort> brokerList; // list of (host:port)s
@Parameter(names = {"-"+Constants.OPT_CHECK_POINT_TIMER, "--"+Constants.OPT_CHECK_POINT_TIMER}, description="Check point interval in milliseconds")
private long commitCheckPointInterval;
private SimpleConsumer consumer;
//private FileSystem fs;
private Timer checkPointIntervalTimer;
public ScribeConsumer() {
checkPointIntervalTimer = new Timer();
}
public void setScribeCommitLogFactory(AbstractScribeCommitLogFactory factory) {
scribeCommitLogFactory = factory;
}
public void setFileSystemFactory(AbstractFileSystemFactory factory) {
fileSystemFactory = factory;
}
public boolean init() throws IOException {
boolean r = true;
PartitionMetadata metadata = findLeader(brokerList, topic, partition);
if (metadata == null) {
r = false;
LOG.error("Can't find meta data for Topic: " + topic + " partition: " + partition + ". In fact, meta is null.");
}
if (metadata.leader() == null) {
r = false;
LOG.error("Can't find meta data for Topic: " + topic + " partition: " + partition);
}
if (r) {
storeReplicaBrokers(metadata);
consumer = new SimpleConsumer(
metadata.leader().host(),
metadata.leader().port(),
10000, // timeout
64*1024, // buffersize
getClientName());
scheduleCommitTimer();
}
return r;
}
private void scheduleCommitTimer() {
checkPointIntervalTimer.schedule(new TimerTask() {
@Override
public void run() {
commit();
}
}, commitCheckPointInterval);
}
private void commitData(String src, String dest) {
FileSystem fs = null;
try {
fs = fileSystemFactory.build();
fs.rename(new Path(src), new Path(dest));
} catch (IOException e) {
//TODO : LOG
e.printStackTrace();
} finally {
if (fs != null) {
try {
fs.close();
} catch (IOException e) {
//TODO : LOG
e.printStackTrace();
}
}
}
}
private synchronized void commit() {
System.out.println(">> committing");
if (lastCommittedOffset != offset) {
//Commit
try {
// First record the to-be taken action in the WAL.
// Then, mv the tmp data file to it's location.
long startOffset = lastCommittedOffset + 1;
long endOffset = offset;
System.out.println("\tstartOffset : " + String.valueOf(startOffset)); //xxx
System.out.println("\tendOffset : " + String.valueOf(endOffset)); //xxx
System.out.println("\ttmpDataPath : " + currTmpDataPath); //xxx
System.out.println("\tDataPath : " + currDataPath); //xxx
ScribeCommitLog log = scribeCommitLogFactory.build();
log.record(startOffset, endOffset, currTmpDataPath, currDataPath);
commitData(currTmpDataPath, currDataPath);
lastCommittedOffset = offset;
generateTmpAndDestDataPaths();
} catch (IOException e) {
// TODO : LOG this error
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO : LOG this error
e.printStackTrace();
}
}
scheduleCommitTimer();
}
private String getClientName() {
StringBuilder sb = new StringBuilder();
sb.append("scribe_");
sb.append(topic);
sb.append("_");
sb.append(partition);
String r = sb.toString();
return r;
}
private String getCommitLogAbsPath() {
return PRE_COMMIT_PATH_PREFIX + "/" + getClientName() + ".log";
}
private void generateTmpAndDestDataPaths() {
StringBuilder sb = new StringBuilder();
long ts = System.currentTimeMillis()/1000L;
sb.append(PRE_COMMIT_PATH_PREFIX)
.append("/scribe.data")
.append(".")
.append(ts);
this.currTmpDataPath = sb.toString();
sb = new StringBuilder();
sb.append(COMMIT_PATH_PREFIX)
.append("/scribe.data")
.append(".")
.append(ts);
this.currDataPath = sb.toString();
}
private String getTmpDataPathPattern() {
StringBuilder sb = new StringBuilder();
sb.append(PRE_COMMIT_PATH_PREFIX)
.append("/scribe.data")
.append(".")
.append("*");
return sb.toString();
}
private long getLatestOffsetFromKafka(String topic, int partition, long startTime) {
TopicAndPartition tp = new TopicAndPartition(topic, partition);
Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>();
requestInfo.put(tp, new PartitionOffsetRequestInfo(startTime, 1));
OffsetRequest req = new OffsetRequest(
requestInfo, kafka.api.OffsetRequest.CurrentVersion(), getClientName());
OffsetResponse resp = consumer.getOffsetsBefore(req);
if (resp.hasError()) {
System.out.println("error when fetching offset: " + resp.errorCode(topic, partition)); //xxx
// In case you wonder what the error code really means.
// System.out.println("OffsetOutOfRangeCode()" + ErrorMapping.OffsetOutOfRangeCode());
// System.out.println("BrokerNotAvailableCode()" + ErrorMapping.BrokerNotAvailableCode());
// System.out.println("InvalidFetchSizeCode()" + ErrorMapping.InvalidFetchSizeCode());
// System.out.println("InvalidMessageCode()" + ErrorMapping.InvalidMessageCode());
// System.out.println("LeaderNotAvailableCode()" + ErrorMapping.LeaderNotAvailableCode());
// System.out.println("MessageSizeTooLargeCode()" + ErrorMapping.MessageSizeTooLargeCode());
// System.out.println("NotLeaderForPartitionCode()" + ErrorMapping.NotLeaderForPartitionCode());
// System.out.println("OffsetMetadataTooLargeCode()" + ErrorMapping.OffsetMetadataTooLargeCode());
// System.out.println("ReplicaNotAvailableCode()" + ErrorMapping.ReplicaNotAvailableCode());
// System.out.println("RequestTimedOutCode()" + ErrorMapping.RequestTimedOutCode());
// System.out.println("StaleControllerEpochCode()" + ErrorMapping.StaleControllerEpochCode());
// System.out.println("UnknownCode()" + ErrorMapping.UnknownCode());
// System.out.println("UnknownTopicOrPartitionCode()" + ErrorMapping.UnknownTopicOrPartitionCode());
//LOG.error("error when fetching offset: " + resp.errorcode(topic, partition));
return 0;
}
return resp.offsets(topic, partition)[0];
}
private void DeleteUncommittedData() throws IOException
{
FileSystem fs = fileSystemFactory.build();
// Corrupted log file
// Clean up. Delete the tmp data file if present.
FileStatus[] fileStatusArry = fs.globStatus(new Path(getTmpDataPathPattern()));
for(int i = 0; i < fileStatusArry.length; i++) {
FileStatus fileStatus = fileStatusArry[i];
fs.delete( fileStatus.getPath() );
}
fs.close();
}
private ScribeLogEntry getLatestValidEntry(ScribeCommitLog log) {
ScribeLogEntry entry = null;
try {
do {
entry = log.getLatestEntry();
} while (entry != null && !entry.isCheckSumValid());
} catch (NoSuchAlgorithmException ex) {
//TODO log
}
return entry;
}
private long getLatestOffsetFromCommitLog() {
// Here's where we do recovery.
long r = -1;
ScribeLogEntry entry = null;
try {
ScribeCommitLog log = scribeCommitLogFactory.build();
log.read();
entry = log.getLatestEntry();
if (entry.isCheckSumValid()) {
FileSystem fs = fileSystemFactory.build();
String tmpDataFilePath = entry.getSrcPath();
if (fs.exists(new Path(tmpDataFilePath))) {
// mv to the dest
commitData(tmpDataFilePath, entry.getDestPath());
} else {
// Data has been committed
// Or, it never got around to write to the log.
// Delete tmp data file just in case.
DeleteUncommittedData();
}
} else {
DeleteUncommittedData();
entry = getLatestValidEntry(log);
}
} catch (IOException e) {
//TODO: log.warn
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
//TODO: log.warn
e.printStackTrace();
}
if (entry != null) {
r = entry.getEndOffset();
}
return r;
}
private long getLatestOffset(String topic, int partition, long startTime) {
long offsetFromCommitLog = getLatestOffsetFromCommitLog();
System.out.println(" getLatestOffsetFromCommitLog >>>> " + offsetFromCommitLog); //xxx
long offsetFromKafka = getLatestOffsetFromKafka(topic, partition, startTime);
long r;
if (offsetFromCommitLog == -1) {
r = offsetFromKafka;
} else if (offsetFromCommitLog < offsetFromKafka) {
r = offsetFromCommitLog;
} else if (offsetFromCommitLog == offsetFromKafka) {
r = offsetFromKafka;
} else { // offsetFromCommitLog > offsetFromKafka
// TODO: log.warn. Someone is screwing with kafka's offset
r = offsetFromKafka;
}
return r;
}
private PartitionMetadata findLeader(List<HostPort> seedBrokers, String topic, int partition) {
PartitionMetadata returnMetaData = null;
for (HostPort broker: seedBrokers) {
SimpleConsumer consumer = null;
String seed = broker.getHost();
int port = broker.getPort();
try {
consumer = new SimpleConsumer(seed, port, 100000, 64 * 1024, "leaderLookup");
List<String> topics = Collections.singletonList(topic);
TopicMetadataRequest req = new TopicMetadataRequest(topics);
kafka.javaapi.TopicMetadataResponse resp = consumer.send(req);
List<TopicMetadata> metaData = resp.topicsMetadata();
for (TopicMetadata item : metaData) {
for (PartitionMetadata part : item.partitionsMetadata()) {
if (part.partitionId() == partition) {
returnMetaData = part;
return returnMetaData;
}
}
}
} catch (Exception e) {
LOG.error("Error communicating with Broker " + seed + ":" + port + " while trying to find leader for " + topic
+ ", " + partition + " | Reason: " + e);
} finally {
if (consumer != null) consumer.close();
}
}
return returnMetaData;
}
private void storeReplicaBrokers(PartitionMetadata metadata) {
replicaBrokers.clear();
for (Broker replica: metadata.replicas()) {
replicaBrokers.add(new HostPort(replica.host(), replica.port()));
}
}
public void run() throws IOException {
generateTmpAndDestDataPaths();
lastCommittedOffset = getLatestOffset(topic, partition, kafka.api.OffsetRequest.LatestTime());
offset = lastCommittedOffset;
System.out.println(">> lastCommittedOffset: " + lastCommittedOffset); //xxx
while (true) {
System.out.println(">> offset: " + offset); //xxx
FetchRequest req = new FetchRequestBuilder()
.clientId(getClientName())
.addFetch(topic, partition, offset, 100000)
.build();
FetchResponse resp = consumer.fetch(req);
if (resp.hasError()) {
//TODO: if we got an invalid offset, reset it by asking for the last element.
// otherwise, find a new leader from the replica
System.out.println("has error"); //xxx
short code = resp.errorCode(topic, partition);
System.out.println("Reason: " + code);
if (code == ErrorMapping.OffsetOutOfRangeCode()) {
// We asked for an invalid offset. For simple case ask for the last element to reset
System.out.println("inside errormap");
offset = getLatestOffsetFromKafka(topic, partition, kafka.api.OffsetRequest.LatestTime());
continue;
}
}
long msgReadCnt = 0;
StringRecordWriter writer = new StringRecordWriter(currTmpDataPath);
synchronized(this) {
for (MessageAndOffset messageAndOffset : resp.messageSet(topic, partition)) {
long currentOffset = messageAndOffset.offset();
if (currentOffset < offset) {
System.out.println("Found an old offset: " + currentOffset + "Expecting: " + offset);
continue;
}
offset = messageAndOffset.nextOffset();
ByteBuffer payload = messageAndOffset.message().payload();
byte[] bytes = new byte[payload.limit()];
payload.get(bytes);
System.out.println(String.valueOf(messageAndOffset.offset()) + ": " + new String(bytes));
// Write to HDFS /tmp partition
writer.write(bytes);
msgReadCnt++;
}// for
}
writer.close();
if (msgReadCnt == 0) {
try {
Thread.sleep(1000); //Didn't read anything, so go to sleep for awhile.
} catch(InterruptedException e) {
}
}
} // while
}
public static void main(String[] args) throws IOException {
ScribeConsumer sc = new ScribeConsumer();
JCommander jc = new JCommander(sc);
jc.addConverterFactory(new CustomConvertFactory());
jc.parse(args);
sc.setScribeCommitLogFactory(ScribeCommitLogFactory.instance(sc.getCommitLogAbsPath()));
sc.setFileSystemFactory(FileSystemFactory.instance());
boolean proceed = sc.init();
if (proceed)
sc.run();
}
}
|
package com.rafaskoberg.gdx.typinglabel;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph;
import com.badlogic.gdx.graphics.g2d.BitmapFontCache;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.GlyphLayout.GlyphRun;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.IntArray;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.ObjectMap.Entry;
import com.badlogic.gdx.utils.StringBuilder;
import com.rafaskoberg.gdx.typinglabel.effects.Effect;
import com.rafaskoberg.gdx.typinglabel.effects.JumpEffect;
import com.rafaskoberg.gdx.typinglabel.effects.ShakeEffect;
import com.rafaskoberg.gdx.typinglabel.effects.WaveEffect;
/** An extension of {@link Label} that progressively shows the text as if it was being typed in real time, and allows the use of
* tokens in the following format: <tt>{TOKEN=PARAMETER}</tt>. */
public class TypingLabel extends Label {
// Collections
private final ObjectMap<String, String> variables = new ObjectMap<>();
protected final Array<TokenEntry> tokenEntries = new Array<>();
// Config
private Color clearColor = new Color(TypingConfig.DEFAULT_CLEAR_COLOR);
private TypingListener listener = null;
boolean forceMarkupColor = TypingConfig.FORCE_COLOR_MARKUP_BY_DEFAULT;
// Internal state
private final StringBuilder originalText = new StringBuilder();
private final Array<Glyph> glyphCache = new Array<Glyph>();
private final IntArray glyphRunCapacities = new IntArray();
private final IntArray offsetCache = new IntArray();
private final Array<Effect> activeEffects = new Array<Effect>();
private float textSpeed = TypingConfig.DEFAULT_SPEED_PER_CHAR;
private float charCooldown = textSpeed;
private int rawCharIndex = -1; // All chars, including color codes
private int glyphCharIndex = -1; // Only renderable chars, excludes color codes
private int cachedGlyphCharIndex = -1; // Last glyphCharIndex sent to the cache
private float lastLayoutX = 0, lastLayoutY = 0;
private boolean parsed = false;
private boolean paused = false;
private boolean ended = false;
private boolean skipping = false;
// Superclass mirroring
boolean wrap;
String ellipsis;
float lastPrefHeight;
boolean fontScaleChanged = false;
public TypingLabel (CharSequence text, LabelStyle style) {
super(text, style);
saveOriginalText();
}
public TypingLabel (CharSequence text, Skin skin, String fontName, Color color) {
super(text, skin, fontName, color);
saveOriginalText();
}
public TypingLabel (CharSequence text, Skin skin, String fontName, String colorName) {
super(text, skin, fontName, colorName);
saveOriginalText();
}
public TypingLabel (CharSequence text, Skin skin, String styleName) {
super(text, skin, styleName);
saveOriginalText();
}
public TypingLabel (CharSequence text, Skin skin) {
super(text, skin);
saveOriginalText();
}
/** Modifies the text of this label. If the char progression is already running, it's highly recommended to use
* {@link #restart(CharSequence)} instead. */
@Override
public void setText (CharSequence newText) {
this.setText(newText, true);
}
/** Sets the text of this label.
* @param modifyOriginalText Flag determining if the original text should be modified as well. If {@code false}, only the
* display text is changed while the original text is untouched.
* @see #restart(CharSequence) */
protected void setText (CharSequence newText, boolean modifyOriginalText) {
super.setText(newText);
if (modifyOriginalText) saveOriginalText();
}
/** Similar to {@link #getText()}, but returns the original text with all the tokens unchanged. */
public StringBuilder getOriginalText () {
return originalText;
}
/** Copies the content of {@link #getText()} to the {@link StringBuilder} containing the original text with all tokens
* unchanged. */
protected void saveOriginalText () {
originalText.setLength(0);
originalText.insert(0, this.getText());
originalText.trimToSize();
}
/** Restores the original text with all tokens unchanged to this label. Make sure to call {@link #parseTokens()} to parse the
* tokens again. */
protected void restoreOriginalText () {
super.setText(originalText);
this.parsed = false;
}
/** Returns the {@link TypingListener} associated with this label. May be {@code null}. */
public TypingListener getTypingListener () {
return listener;
}
/** Sets the {@link TypingListener} associated with this label, or {@code null} to remove the current one. */
public void setTypingListener (TypingListener listener) {
this.listener = listener;
}
/** Returns a {@link Color} instance with the color to be used on {@code CLEARCOLOR} tokens. Modify this instance to change the
* token color. Default value is specified by {@link TypingConfig}.
* @see TypingConfig#DEFAULT_CLEAR_COLOR */
public Color getClearColor () {
return clearColor;
}
/** Sets whether or not this instance should enable markup color by force.
* @see TypingConfig#FORCE_COLOR_MARKUP_BY_DEFAULT */
public void setForceMarkupColor (boolean forceMarkupColor) {
this.forceMarkupColor = forceMarkupColor;
}
/** Parses all tokens of this label. Use this after setting the text and any variables that should be replaced. */
public void parseTokens () {
Parser.parseTokens(this);
parsed = true;
}
/** Skips the char progression to the end, showing the entire label. Useful for when users don't want to wait for too long. */
public void skipToTheEnd () {
skipping = true;
}
/** Returns whether or not this label is paused. */
public boolean isPaused () {
return paused;
}
/** Pauses this label's character progression. */
public void pause () {
paused = true;
}
/** Resumes this label's character progression. */
public void resume () {
paused = false;
}
/** Returns whether or not this label's char progression has ended. */
public boolean hasEnded () {
return ended;
}
/** Restarts this label with the original text and starts the char progression right away. All tokens are automatically
* parsed. */
public void restart () {
restart(getOriginalText());
}
/** Restarts this label with the given text and starts the char progression right away. All tokens are automatically parsed. */
public void restart (CharSequence newText) {
// Reset cache collections
GlyphUtils.freeAll(glyphCache);
glyphCache.clear();
glyphRunCapacities.clear();
offsetCache.clear();
activeEffects.clear();
// Reset state
textSpeed = TypingConfig.DEFAULT_SPEED_PER_CHAR;
charCooldown = textSpeed;
rawCharIndex = -1;
glyphCharIndex = -1;
cachedGlyphCharIndex = -1;
lastLayoutX = 0;
lastLayoutY = 0;
parsed = false;
paused = false;
ended = false;
skipping = false;
// Set new text
this.setText(newText);
invalidate();
// Parse tokens
tokenEntries.clear();
parseTokens();
}
/** Returns an {@link ObjectMap} with all the variable names and their respective replacement values. */
public ObjectMap<String, String> getVariables () {
return variables;
}
/** Registers a variable and its respective replacement value to this label. */
public void setVariable (String var, String value) {
variables.put(var.toUpperCase(), value);
}
/** Registers a set of variables and their respective replacement values to this label. */
public void setVariables (ObjectMap<String, String> variableMap) {
this.variables.clear();
for (Entry<String, String> entry : variableMap.entries()) {
this.variables.put(entry.key.toUpperCase(), entry.value);
}
}
/** Registers a set of variables and their respective replacement values to this label. */
public void setVariables (java.util.Map<String, String> variableMap) {
this.variables.clear();
for (java.util.Map.Entry<String, String> entry : variableMap.entrySet()) {
this.variables.put(entry.getKey().toUpperCase(), entry.getValue());
}
}
/** Removes all variables from this label. */
public void clearVariables () {
this.variables.clear();
}
@Override
public void act (float delta) {
super.act(delta);
// Force token parsing
if (!parsed) {
parseTokens();
}
// Update cooldown and process char progression
if (skipping || (!ended && !paused)) {
if (skipping || (charCooldown -= delta) < 0.0f) {
processCharProgression();
}
}
// Restore glyph offsets
if (activeEffects.size > 0) {
for (int i = 0; i < glyphCache.size; i++) {
Glyph glyph = glyphCache.get(i);
glyph.xoffset = offsetCache.get(i * 2);
glyph.yoffset = offsetCache.get(i * 2 + 1);
}
}
// Apply effects
for (int i = activeEffects.size - 1; i >= 0; i
Effect effect = activeEffects.get(i);
effect.update(delta);
int start = effect.indexStart;
int end = effect.indexEnd >= 0 ? effect.indexEnd : glyphCharIndex;
// If effect is finished, remove it
if (effect.isFinished()) {
activeEffects.removeIndex(i);
continue;
}
// Apply effect to glyph
for (int j = start; j <= glyphCharIndex && j <= end && j < glyphCache.size; j++) {
Glyph glyph = glyphCache.get(j);
effect.apply(glyph, j);
}
}
}
/** Proccess char progression according to current cooldown and process all tokens in the current index. */
private void processCharProgression () {
// Keep a counter of how many chars we're processing in this tick.
int charCounter = 0;
// Process chars while there's room for it
while (skipping || charCooldown < 0.0f) {
rawCharIndex++;
// If char progression is finished, or if text is empty, notify listener and abort routine
int textLen = getText().length;
if (textLen == 0 || rawCharIndex > textLen) {
if (listener != null) listener.end();
ended = true;
return;
}
// Get next character and calculate cooldown increment
int safeIndex = MathUtils.clamp(rawCharIndex - 1, 0, getText().length);
char primitiveChar = getText().charAt(safeIndex);
Character ch = Character.valueOf(primitiveChar);
float intervalMultiplier = TypingConfig.INTERVAL_MULTIPLIERS_BY_CHAR.get(ch, 1);
charCooldown += textSpeed * intervalMultiplier;
// Increase glyph char index for all characters, except new lines.
if (primitiveChar != '\n') glyphCharIndex++;
// Process tokens according to the current index
while (tokenEntries.size > 0 && tokenEntries.peek().index == rawCharIndex) {
TokenEntry entry = tokenEntries.pop();
switch (entry.token) {
case WAIT:
charCooldown += entry.floatValue;
break;
case FASTER:
case FAST:
case NORMAL:
case SLOW:
case SLOWER:
case SPEED:
textSpeed = entry.floatValue;
break;
case SKIP:
if (entry.stringValue != null) {
rawCharIndex += entry.stringValue.length();
}
break;
case EVENT:
if (this.listener != null) {
listener.event(entry.stringValue);
}
break;
case SHAKE:
case WAVE:
case JUMP:
entry.effect.indexStart = glyphCharIndex;
activeEffects.add(entry.effect);
break;
case ENDSHAKE:
for (int i = 0; i < activeEffects.size; i++) {
Effect effect = activeEffects.get(i);
if (effect.indexEnd < 0) {
if (effect instanceof ShakeEffect) {
effect.indexEnd = glyphCharIndex;
}
}
}
break;
case ENDWAVE:
for (int i = 0; i < activeEffects.size; i++) {
Effect effect = activeEffects.get(i);
if (effect.indexEnd < 0) {
if (effect instanceof WaveEffect) {
effect.indexEnd = glyphCharIndex;
}
}
}
break;
case ENDJUMP:
for (int i = 0; i < activeEffects.size; i++) {
Effect effect = activeEffects.get(i);
if (effect.indexEnd < 0) {
if (effect instanceof JumpEffect) {
effect.indexEnd = glyphCharIndex;
}
}
}
break;
default:
break;
}
}
// Increment char counter and break loop if enough chars were processed
charCounter++;
int charLimit = TypingConfig.CHAR_LIMIT_PER_FRAME;
if (!skipping && charLimit > 0 && charCounter > charLimit) {
charCooldown = textSpeed;
break;
}
}
}
@Override
public BitmapFontCache getBitmapFontCache () {
return super.getBitmapFontCache();
}
@Override
public void setEllipsis (String ellipsis) {
// Mimics superclass but keeps an accessible reference
super.setEllipsis(ellipsis);
this.ellipsis = ellipsis;
}
@Override
public void setEllipsis (boolean ellipsis) {
// Mimics superclass but keeps an accessible reference
super.setEllipsis(ellipsis);
if (ellipsis)
this.ellipsis = "...";
else
this.ellipsis = null;
}
@Override
public void setWrap (boolean wrap) {
// Mimics superclass but keeps an accessible reference
super.setWrap(wrap);
this.wrap = wrap;
}
@Override
public void setFontScale (float fontScale) {
super.setFontScale(fontScale);
this.fontScaleChanged = true;
}
@Override
public void setFontScale (float fontScaleX, float fontScaleY) {
super.setFontScale(fontScaleX, fontScaleY);
this.fontScaleChanged = true;
}
@Override
public void setFontScaleX (float fontScaleX) {
super.setFontScaleX(fontScaleX);
this.fontScaleChanged = true;
}
@Override
public void setFontScaleY (float fontScaleY) {
super.setFontScaleY(fontScaleY);
this.fontScaleChanged = true;
}
@Override
public void layout () {
BitmapFontCache cache = getBitmapFontCache();
StringBuilder text = getText();
GlyphLayout layout = super.getGlyphLayout();
int lineAlign = getLineAlign();
int labelAlign = getLabelAlign();
LabelStyle style = getStyle();
BitmapFont font = cache.getFont();
float oldScaleX = font.getScaleX();
float oldScaleY = font.getScaleY();
if (fontScaleChanged) font.getData().setScale(getFontScaleX(), getFontScaleY());
boolean wrap = this.wrap && ellipsis == null;
if (wrap) {
float prefHeight = getPrefHeight();
if (prefHeight != lastPrefHeight) {
lastPrefHeight = prefHeight;
invalidateHierarchy();
}
}
float width = getWidth(), height = getHeight();
Drawable background = style.background;
float x = 0, y = 0;
if (background != null) {
x = background.getLeftWidth();
y = background.getBottomHeight();
width -= background.getLeftWidth() + background.getRightWidth();
height -= background.getBottomHeight() + background.getTopHeight();
}
float textWidth, textHeight;
// if (wrap || text.indexOf("\n") != -1)
{
// If the text can span multiple lines, determine the text's actual size so it can be aligned within the label.
layout.setText(font, text, 0, text.length, Color.WHITE, width, lineAlign, wrap, ellipsis);
textWidth = layout.width;
textHeight = layout.height;
if ((labelAlign & Align.left) == 0) {
if ((labelAlign & Align.right) != 0)
x += width - textWidth;
else
x += (width - textWidth) / 2;
}
// } else {
// textWidth = width;
// textHeight = font.getData().capHeight;
}
if ((labelAlign & Align.top) != 0) {
y += cache.getFont().isFlipped() ? 0 : height - textHeight;
y += style.font.getDescent();
} else if ((labelAlign & Align.bottom) != 0) {
y += cache.getFont().isFlipped() ? height - textHeight : 0;
y -= style.font.getDescent();
} else {
y += (height - textHeight) / 2;
}
if (!cache.getFont().isFlipped()) y += textHeight;
// Don't set the layout or cache now, since we progressively update both over time.
// layout.setText(font, text, 0, text.length, Color.WHITE, textWidth, lineAlign, wrap, ellipsis);
// cache.setText(layout, x, y);
if (fontScaleChanged) font.getData().setScale(oldScaleX, oldScaleY);
// Store coordinates passed to BitmapFontCache
lastLayoutX = x;
lastLayoutY = y;
// Perform cache layout operation, where the magic happens
GlyphUtils.freeAll(glyphCache);
layoutCache();
}
/** Reallocate glyph clones according to the updated {@link GlyphLayout}. This should only be called when the text or the
* layout changes. */
private void layoutCache () {
BitmapFontCache cache = getBitmapFontCache();
GlyphLayout layout = super.getGlyphLayout();
Array<GlyphRun> runs = layout.runs;
// Store GlyphRun sizes and count how many glyphs we have
int glyphCount = 0;
glyphRunCapacities.setSize(runs.size);
for (int i = 0; i < runs.size; i++) {
Array<Glyph> glyphs = runs.get(i).glyphs;
glyphRunCapacities.set(i, glyphs.size);
glyphCount += glyphs.size;
}
// Make sure our cache array can hold all glyphs
if (glyphCache.size < glyphCount) {
glyphCache.setSize(glyphCount);
offsetCache.setSize(glyphCount * 2);
}
// Clone original glyphs with independent instances
int index = -1;
for (int i = 0; i < runs.size; i++) {
Array<Glyph> glyphs = runs.get(i).glyphs;
for (int j = 0; j < glyphs.size; j++) {
index++;
// Get original glyph
Glyph original = glyphs.get(j);
// Get clone glyph
Glyph clone = null;
if (index < glyphCache.size) {
clone = glyphCache.get(index);
}
if (clone == null) {
clone = GlyphUtils.obtain();
glyphCache.set(index, clone);
}
GlyphUtils.clone(original, clone);
clone.width *= getFontScaleX();
clone.height *= getFontScaleY();
clone.xoffset *= getFontScaleX();
clone.yoffset *= getFontScaleY();
// Store offset data
offsetCache.set(index * 2, clone.xoffset);
offsetCache.set(index * 2 + 1, clone.yoffset);
// Replace glyph in original array
glyphs.set(j, clone);
}
}
// Remove exceeding glyphs from original array
int glyphCountdown = glyphCharIndex;
for (int i = 0; i < runs.size; i++) {
Array<Glyph> glyphs = runs.get(i).glyphs;
if (glyphs.size < glyphCountdown) {
glyphCountdown -= glyphs.size;
continue;
}
for (int j = 0; j < glyphs.size; j++) {
glyphCountdown
if (glyphCountdown < 0) {
glyphs.removeRange(j, glyphs.size - 1);
break;
}
}
}
// Pass new layout with custom glyphs to BitmapFontCache
cache.setText(layout, lastLayoutX, lastLayoutY);
}
/** Adds cached glyphs to the active BitmapFontCache as the char index progresses. */
private void addMissingGlyphs () {
// Add additional glyphs to layout array, if any
int glyphLeft = glyphCharIndex - cachedGlyphCharIndex;
if (glyphLeft < 1) return;
// Get runs
GlyphLayout layout = super.getGlyphLayout();
Array<GlyphRun> runs = layout.runs;
// Iterate through GlyphRuns to find the next glyph spot
int glyphCount = 0;
for (int runIndex = 0; runIndex < glyphRunCapacities.size; runIndex++) {
int runCapacity = glyphRunCapacities.get(runIndex);
if ((glyphCount + runCapacity) < cachedGlyphCharIndex) {
glyphCount += runCapacity;
continue;
}
// Get run and increase glyphCount up to its current size
Array<Glyph> glyphs = runs.get(runIndex).glyphs;
glyphCount += glyphs.size;
// Next glyphs go here
while (glyphLeft > 0) {
// Skip run if this one is full
int runSize = glyphs.size;
if (runCapacity == runSize) {
break;
}
// Put new glyph to this run
cachedGlyphCharIndex++;
glyphCount++;
glyphLeft
glyphs.add(glyphCache.get(cachedGlyphCharIndex));
}
}
}
@Override
public void draw (Batch batch, float parentAlpha) {
super.validate();
addMissingGlyphs();
// Update cache with new glyphs
// Check if we have special effects, otherwise only run this when necessary
getBitmapFontCache().setText(getGlyphLayout(), lastLayoutX, lastLayoutY);
super.draw(batch, parentAlpha);
}
}
|
package com.reason.lang.core.psi.impl;
import com.intellij.extapi.psi.StubBasedPsiElementBase;
import com.intellij.lang.ASTNode;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.reason.icons.Icons;
import com.reason.lang.core.psi.PsiModule;
import com.reason.lang.core.psi.PsiModuleName;
import com.reason.lang.core.psi.PsiLet;
import com.reason.lang.core.psi.PsiScopedExpr;
import com.reason.lang.core.stub.ModuleStub;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Collection;
public class PsiModuleImpl extends StubBasedPsiElementBase<ModuleStub> implements PsiModule {
//region Constructors
public PsiModuleImpl(ASTNode node) {
super(node);
}
public PsiModuleImpl(ModuleStub stub, IStubElementType nodeType) {
super(stub, nodeType);
}
//endregion
//region NamedElement
@Override
public String getName() {
PsiElement nameIdentifier = getNameIdentifier();
return nameIdentifier == null ? "" : nameIdentifier.getText();
}
@Nullable
@Override
public PsiElement getNameIdentifier() {
return findChildByClass(PsiModuleName.class);
}
@Override
public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
return this; // Use PsiModuleReference.handleElementRename()
}
//endregion
@Nullable
public PsiScopedExpr getModuleBody() {
return findChildByClass(PsiScopedExpr.class);
}
public Collection<PsiLet> getLetExpressions() {
return PsiTreeUtil.findChildrenOfType(this, PsiLet.class);
}
public ItemPresentation getPresentation() {
return new ItemPresentation() {
@Nullable
@Override
public String getPresentableText() {
return getName();
}
@Nullable
@Override
public String getLocationString() {
return null;
}
@Nullable
@Override
public Icon getIcon(boolean unused) {
return Icons.MODULE;
}
};
}
@Override
public String toString() {
return "Module(" + getName() + ")";
}
}
|
package com.rox.emu.processor.mos6502.util;
import com.rox.emu.UnknownOpCodeException;
import com.rox.emu.processor.mos6502.Mos6502;
import com.rox.emu.processor.mos6502.op.AddressingMode;
import com.rox.emu.processor.mos6502.op.OpCode;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A compiler for a {@link Mos6502} for taking a textual program and converting it into an executable byte stream, e.g.<br/>
* <br/>
* <code>
* LDA {@value IMMEDIATE_VALUE_PREFIX}52 <br/>
* LDX {@value IMMEDIATE_VALUE_PREFIX}10<br/>
* STA {@value VALUE_PREFIX}F1{@value X_INDEXED_POSTFIX}<br/>
* </code> <br/>
* → <code> [0xA9, 0x52, 0xA2, 0x10, 0x95, 0xF1] </code>
*
* <table>
* <tr>
* <th>Format</th>
* <th>Addressing Mode</th>
* </tr>
*
* <tr>
* <td><code>{@value IMMEDIATE_VALUE_PREFIX}V</code></td>
* <td>Immediate</td>
* </tr>
*
* <tr>
* <td><code>{@value ACCUMULATOR_PREFIX}VV</code></td>
* <td>Accumulator</td>
* </tr>
*
* <tr>
* <td><code>{@value VALUE_PREFIX}V</code> / <code>{@value VALUE_PREFIX}VV</code></td>
* <td>Zero Page</td>
* </tr>
*
* <tr>
* <td><code>{@value VALUE_PREFIX}V{@value X_INDEXED_POSTFIX}</code> / <code>{@value VALUE_PREFIX}VV{@value X_INDEXED_POSTFIX}</code></td>
* <td>Zero Page[X]</td>
* </tr>
*
* <tr>
* <td><code>{@value VALUE_PREFIX}V{@value Y_INDEXED_POSTFIX}</code> / <code>{@value VALUE_PREFIX}VV{@value Y_INDEXED_POSTFIX}</code></td>
* <td>Zero Page[Y]</td>
* </tr>
*
* <tr>
* <td><code>{@value VALUE_PREFIX}VVV</code> / <code>{@value VALUE_PREFIX}VVVV</code></td>
* <td>Absolute</td>
* </tr>
*
* <tr>
* <td><code>{@value VALUE_PREFIX}VVV{@value X_INDEXED_POSTFIX}</code> / <code>{@value VALUE_PREFIX}VVVV{@value X_INDEXED_POSTFIX}</code></td>
* <td>Absolute[X]</td>
* </tr>
*
* <tr>
* <td><code>{@value VALUE_PREFIX}VVV{@value Y_INDEXED_POSTFIX}</code> / <code>{@value VALUE_PREFIX}VVVV{@value Y_INDEXED_POSTFIX}</code></td>
* <td>Absolute[Y]</td>
* </tr>
*
* <tr>
* <td><code>{@value INDIRECT_PREFIX}V{@value INDIRECT_X_POSTFIX}</code> / <code>{@value INDIRECT_PREFIX}VV{@value INDIRECT_X_POSTFIX}</code></td>
* <td>Indirect, X</td>
* </tr>
*
* <tr>
* <td><code>{@value INDIRECT_PREFIX}V{@value INDIRECT_Y_POSTFIX}</code> / <code>{@value INDIRECT_PREFIX}VV{@value INDIRECT_Y_POSTFIX}</code></td>
* <td>Indirect, Y</td>
* </tr>
*
* </Table>
*
* TODO accept tokens as arguments.
*
* @author Ross Drew
*/
public class Compiler {
/** Regex used to extract an argument prefix */
public static final Pattern ARG_PREFIX_REGEX = Pattern.compile("^[^0-9a-fA-F]{1,4}");
/** Regex used to extract an argument value */
public static final Pattern ARG_VALUE_REGEX = Pattern.compile("[0-9a-fA-F]+");
/** Regex used to extract an argument postfix */
public static final Pattern ARG_POSTFIX_REGEX = Pattern.compile("(?<=\\w)(,[XY]|,X\\)|\\),Y)$");
/** Regex used to extract a program label reference as an opcode argument */
public static final Pattern LABEL_REF_REGEX = Pattern.compile("\\w+");
/** Regex used to extract a program label */
public static final Pattern LABEL_REGEX = Pattern.compile(LABEL_REF_REGEX + ":");
/** The prefix expected for an accumulator addressed argument */
public static final String ACCUMULATOR_PREFIX = "
/** The prefix expected for a value argument */
public static final String VALUE_PREFIX = "$";
/** The prefix expected for an immediate value argument */
public static final String IMMEDIATE_VALUE_PREFIX = ACCUMULATOR_PREFIX + VALUE_PREFIX;
/** The prefix expected for an indirect value. Value must also be postfixed with INDIRECT_X_POSTFIX( "<code>{@value INDIRECT_X_POSTFIX}</code>" ) or INDIRECT_Y_POSTFIX( "<code>{@value INDIRECT_Y_POSTFIX}</code>" ) */
public static final String INDIRECT_PREFIX = "(" + VALUE_PREFIX;
/** The postfix expected for an X indexed argument value */
public static final String X_INDEXED_POSTFIX = ",X";
/** The postfix expected for an Y indexed argument value */
public static final String Y_INDEXED_POSTFIX = ",Y";
/** The postfix expected for an indexed indirect addressed argument value. Must also be prefixed with INDIRECT_PREFIX ( "<code>{@value INDIRECT_PREFIX}</code>" ) */
public static final String INDIRECT_X_POSTFIX = X_INDEXED_POSTFIX + ")";
/** The postfix expected for an indirect indexed addressed argument value. Must also be prefixed with INDIRECT_PREFIX ( "<code>{@value INDIRECT_PREFIX}</code>" ) */
public static final String INDIRECT_Y_POSTFIX = ")" + Y_INDEXED_POSTFIX;
private final String programText;
/**
* Create a compiler object around a textual program, ready for compilation
*
* @param programText The MOS6502 program as {@link String} ready for compilation
*/
public Compiler(String programText){
this.programText = programText;
}
/**
* Extract a compiled {@link Program} from this compiler.
* This will use the program text contained in this object and attempt to compile it
*
* @return A compiled {@link Program} object
* @throws UnknownOpCodeException if during the course of compilation, we encounter an unknown where we expect an op-code to be
*/
public Program compileProgram() throws UnknownOpCodeException{
Program workingProgram = new Program();
final StringTokenizer tokenizer = new StringTokenizer(programText);
while (tokenizer.hasMoreTokens()){
final String opCodeToken = tokenizer.nextToken();
switch(opCodeToken){
//These need to work with hard coded values as well
case "BPL": case "BMI": case "BVC": case "BVS": case "BCC": case "BCS": case "BNE": case "BEQ":
// final String argToken = tokenizer.nextToken().trim();
// //XXX Check for label.
// // -> on compilation, check for markets and do (label.index - label.reference)
// final String labelReference = extractFirstOccurrence(LABEL_REF_REGEX, argToken).trim();
// if (labelReference != null && !labelReference.isEmpty()){
// System.out.println("FOUND LABEL '" + labelReference + "'");
case "TAX": case "TAY":
case "TYA": case "TXA": case "TXS": case "TXY": case "TSX":
case "PHA": case "PLA":
case "PHP": case "PLP":
case "INY": case "DEY":
case "INX": case "DEX":
case "RTS": case "RTI":
case "JSR":
case "SEC": case "CLC":
case "SEI": case "SED":
case "CLD": case "CLI": case "CLV":
case "BRK":
case "NOP":
workingProgram = workingProgram.with(OpCode.from(opCodeToken).getByteValue());
break;
case "ADC": case "SBC":
case "LDA": case "LDY": case "LDX":
case "AND": case "ORA": case "EOR":
case "ASL": case "ROL": case "LSR":
case "STY": case "STX": case "STA":
case "CMP": case "CPX": case "CPY":
case "INC": case "DEC":
case "BIT":
case "JMP": //Absolute only
case "ROR": //Accumulator only
final String valueToken = tokenizer.nextToken().trim();
final String prefix = extractFirstOccurrence(ARG_PREFIX_REGEX, valueToken).trim();
final String value = extractFirstOccurrence(ARG_VALUE_REGEX, valueToken).trim();
final String postfix = extractFirstOccurrence(ARG_POSTFIX_REGEX, valueToken).trim();
final AddressingMode addressingMode = getAddressingModeFrom(prefix, value, postfix);
workingProgram = workingProgram.with(OpCode.from(opCodeToken, addressingMode).getByteValue());
workingProgram = extractArgumentValue(workingProgram, value);
break;
default:
workingProgram = workingProgram.with(parseLabel(opCodeToken));
break;
}
}
return workingProgram;
}
private Program extractArgumentValue(Program workingProgram, String value) {
//high byte
if (value.length() == 4 ) {
workingProgram = workingProgram.with(Integer.decode("0x" + value.substring(value.length() - 4, 2)));
}else if (value.length() == 3 ) {
workingProgram = workingProgram.with(Integer.decode("0x" + value.substring(value.length() - 3 , 1)));
}
//low byte
if (value.length() == 1)
workingProgram = workingProgram.with(Integer.decode("0x" + value.substring(value.length()-1)));
else if (value.length() > 1)
workingProgram = workingProgram.with(Integer.decode("0x" + value.substring(value.length()-2)));
return workingProgram;
}
/**
* Extract the first occurrence of the given pattern from the given token {@link String}
*
* @param pattern The compiled regex {@link Pattern} for the desired search
* @param token The {@link String} to search by applying the <code>pattern</code>
* @return The first found occurrence or an empty {@link String}
*/
public static String extractFirstOccurrence(Pattern pattern, String token){
final Matcher prefixMatcher = pattern.matcher(token);
prefixMatcher.find();
try {
return prefixMatcher.group(0);
}catch(IllegalStateException | ArrayIndexOutOfBoundsException e){
return "";
}
}
private String parseLabel(final String opCodeToken) throws UnknownOpCodeException{
final String label = extractFirstOccurrence(LABEL_REGEX, opCodeToken);
if (label.isEmpty())
throw new UnknownOpCodeException("Unknown op-code (\"" + opCodeToken + "\") while parsing program", opCodeToken);
return label;
}
private AddressingMode getAddressingModeFrom(String prefix, String value, String postfix){
if (prefix.equalsIgnoreCase(IMMEDIATE_VALUE_PREFIX)) {
return AddressingMode.IMMEDIATE;
}else if (prefix.equalsIgnoreCase(ACCUMULATOR_PREFIX)){
return AddressingMode.ACCUMULATOR;
}else if (prefix.equalsIgnoreCase(VALUE_PREFIX)){
return getIndexedAddressingMode(prefix, value, postfix);
}else if (prefix.equalsIgnoreCase(INDIRECT_PREFIX)){
return getIndirectIndexMode(prefix, value, postfix);
}
throw new UnknownOpCodeException("Invalid or unimplemented argument: '" + prefix + value + postfix + "'", prefix+value);
}
private AddressingMode getIndirectIndexMode(String prefix, String value, String postfix){
if (postfix.equalsIgnoreCase(INDIRECT_X_POSTFIX)){
return AddressingMode.INDIRECT_X;
}else if (postfix.equalsIgnoreCase(INDIRECT_Y_POSTFIX)){
return AddressingMode.INDIRECT_Y;
}
throw new UnknownOpCodeException("Invalid or unimplemented argument: '" + prefix + value + postfix + "'", prefix+value);
}
private AddressingMode getIndexedAddressingMode(String prefix, String value, String postfix){
if (value.length() <= 2) {
return decorateWithIndexingMode(AddressingMode.ZERO_PAGE, postfix);
}else if (value.length() <= 4){
return decorateWithIndexingMode(AddressingMode.ABSOLUTE, postfix);
}
throw new UnknownOpCodeException("Invalid or unimplemented argument: '" + prefix + value + postfix + "'", prefix+value);
}
private AddressingMode decorateWithIndexingMode(AddressingMode addressingMode, String postfix){
if (postfix.equalsIgnoreCase(X_INDEXED_POSTFIX)){
return addressingMode.xIndexed();
}else if (postfix.equalsIgnoreCase(Y_INDEXED_POSTFIX)){
return addressingMode.yIndexed();
}
return addressingMode;
}
}
|
package com.sixtyfour.cbmnative.mos6502;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sixtyfour.Logger;
import com.sixtyfour.cbmnative.Optimizer;
import com.sixtyfour.cbmnative.Pattern;
import com.sixtyfour.cbmnative.PlatformProvider;
/**
* @author EgonOlsen
*
*/
public class Optimizer64 implements Optimizer {
private List<Pattern> patterns = new ArrayList<Pattern>() {
private static final long serialVersionUID = 1L;
{
this.add(new Pattern("Simplified setting to 0", new String[] { "LDA #0", "STA {MEM0}" }, "LDA #<{#0.0}", "LDY #>{#0.0}", "JSR REALFAC", "LDX #<{MEM0}", "LDY #>{MEM0}",
"JSR FACMEM"));
this.add(new Pattern(false, "Faster logic OR", new String[] { "JSR FASTOR" }, "JSR FACOR"));
this.add(new Pattern(false, "Faster logic AND", new String[] { "JSR FASTAND" }, "JSR ARGAND"));
this.add(new Pattern(false, "Simple POKE", new String[] { "{LINE0}", "{LINE2}" }, "LDY {MEM0}", "LDA #0", "STY {*}"));
this.add(new Pattern("REALOUT + LINEBRK", new String[] { "JSR REALOUTBRK" }, "JSR REALOUT", "JSR LINEBREAK"));
this.add(new Pattern("STROUT + LINEBRK", new String[] { "JSR STROUTBRK" }, "JSR STROUT", "JSR LINEBREAK"));
this.add(new Pattern("INTOUT + LINEBRK", new String[] { "JSR INTOUTBRK" }, "JSR INTOUT", "JSR LINEBREAK"));
this.add(new Pattern("POP, REG0, VAR0", new String[] { "{LINE0}", "{LINE1}", "{LINE2}", "{LINE3}" }, "JSR POPREAL", "LDX #<{REG0}", "LDY #>{REG0}", "JSR FACMEM",
"LDA #<{REG0}", "LDY #>{REG0}", "JSR REALFAC"));
this.add(new Pattern(false, "Array index is integer (store)", new String[] { "{LINE10}", "{LINE11}", "{LINE12}", "{LINE13}", "{LINE18}", "{LINE19}", "{LINE20}",
"{LINE21}", "{LINE0}", "{LINE1}", "{LINE22}_INT" }, "LDY {MEM0}", "LDA {MEM0}", "JSR INTFAC", "LDX #<{REG0}", "LDY #>{REG0}", "JSR FACMEM", "LDA #<{REG0}",
"LDY #>{REG0}", "JSR REALFAC", "JSR PUSHREAL", "LDA {*}", "LDY {*}", "STA {REG1}", "STY {REG1}", "JSR POPREAL", "LDX #<{REG2}", "LDY #>{REG2}", "JSR FACMEM",
"LDA #<{MEM2}", "LDY #>{MEM2}", "STA G_REG", "STY G_REG+1", "JSR ARRAYSTORE{*}"));
this.add(new Pattern(false, "Array index is integer (load)", new String[] { "{LINE6}", "{LINE7}", "{LINE8}", "{LINE9}", "{LINE0}", "{LINE1}", "{LINE10}_INT" },
"LDY {MEM0}", "LDA {MEM0}", "JSR INTFAC", "LDX #<{REG0}", "LDY #>{REG0}", "JSR FACMEM", "LDA #<{MEM1}", "LDY #>{MEM1}", "STA G_REG", "STY G_REG+1",
"JSR ARRAYACCESS{*}"));
this.add(new Pattern("Quick copy into REG", new String[] { "{LINE0}", "{LINE1}", "STA TMP3_ZP", "STY TMP3_ZP+1", "{LINE3}", "{LINE4}", "JSR COPY2_XY" },
"LDA #<{MEM0}", "LDY #>{MEM0}", "JSR REALFAC", "LDX #<{REG0}", "LDY #>{REG0}", "JSR FACMEM"));
this.add(new Pattern(false, "Simplified CMP with 0", new String[] { "{LINE0}", "LDA $61" }, "JSR REALFAC", "LDX #<{REG0}", "LDY #>{REG0}", "JSR FACMEM",
"LDA #<{#0.0}", "LDY #>{#0.0}", "JSR REALFAC", "LDA #<{REG0}", "LDY #>{REG0}", "JSR CMPFAC"));
this.add(new Pattern("REG0->REG1, REG1->REG0", new String[] { "{LINE0}", "{LINE1}", "{LINE2}" }, "LDX #<{MEM0}", "LDY #>{MEM0}", "JSR FACMEM", "LDA #<{REG0}",
"LDY #>{REG0}", "JSR REALFAC", "LDX #<{REG1}", "LDY #>{REG1}", "JSR FACMEM", "LDA #<{REG1}", "LDY #>{REG1}", "JSR REALFAC", "LDX #<{REG0}", "LDY #>{REG0}",
"JSR FACMEM", "LDA #<{REG0}", "LDY #>{REG0}", "JSR REALFAC"));
this.add(new Pattern("REG0->VAR, REG0->REG1", new String[] { "{LINE6}", "{LINE7}", "{LINE8}" }, "LDX #<{REG0}", "LDY #>{REG0}", "JSR FACMEM", "LDA #<{REG0}",
"LDY #>{REG0}", "JSR REALFAC", "LDX #<{MEM0}", "LDY #>{MEM0}", "JSR FACMEM", "LDA #<{REG0}", "LDY #>{REG0}", "JSR REALFAC", "LDX #<{REG1}", "LDY #>{REG1}",
"JSR FACMEM", "LDA #<{REG1}", "LDY #>{REG1}", "JSR REALFAC"));
// todo: This still removes too much in some cases...fix this!
this.add(new Pattern("FAC into REG?, REG? into FAC", null, "LDX #<{REG0}", "LDY #>{REG0}", "JSR FACMEM", "LDA #<{REG0}", "LDY #>{REG0}", "JSR REALFAC"));
this.add(new Pattern("INT to FAC, FAC to INT", new String[] { "{LINE0}", "{LINE1}" }, "LDY {*}", "LDA {*}", "JSR INTFAC", "JSR FACINT"));
this.add(new Pattern("STY A...LDY A...STY B", new String[] { "{LINE0}", "{LINE3}" }, "STY {MEM0}", "LDY {MEM0}", "LDA #0", "STY {*}"));
this.add(new Pattern("FAC to INT, INT to FAC", null, "JSR INTFAC", "JSR FACINT"));
this.add(new Pattern("VAR into FAC, FAC into VAR", null, "LDA #<{MEM0}", "LDY #>{MEM0}", "JSR REALFAC", "LDX #<{MEM0}", "LDY #>{MEM0}", "JSR FACMEM"));
this.add(new Pattern(false, "CHR with integer constant", new String[] { "LDA {MEM0}", "JSR CHRINT" }, "LDY {MEM0}", "LDA {MEM0}", "JSR INTFAC", "LDX #<{REG0}",
"LDY #>{REG0}", "JSR FACMEM", "JSR CHR"));
this.add(new Pattern(false, "NEXT check simplified", new String[] { "JSR NEXT", "LDA A_REG", "{LINE8}", "JMP (JUMP_TARGET)" }, "JSR NEXT", "LDY {MEM0}", "LDA {MEM0}",
"CPY A_REG", "BNE {*}", "CMP A_REG+1", "BNE {*}", "{LABEL}", "BNE {*}", "JMP (JUMP_TARGET)"));
this.add(new Pattern(false, "Multiple loads of the same value(1)", new String[] { "{LINE0}", "{LINE1}", "{LINE2}", "{LINE3}", "{LINE4}", "{LINE5}", "{LINE9}",
"{LINE10}", "{LINE11}" }, "LDA #<{MEM0}", "LDY #>{MEM0}", "JSR REALFAC", "LDX #<{REG0}", "LDY #>{REG0}", "JSR FACMEM", "LDA #<{MEM0}", "LDY #>{MEM0}",
"JSR REALFAC", "LDX #<{REG1}", "LDY #>{REG1}", "JSR FACMEM"));
this.add(new Pattern(false, "Multiple loads of the same value(2)", new String[] { "{LINE0}", "{LINE1}", "{LINE2}", "{LINE3}", "{LINE4}", "{LINE5}", "{LINE6}",
"{LINE11}", "{LINE12}", "{LINE13}" }, "LDA #<{MEM0}", "LDY #>{MEM0}", "STA TMP3_ZP", "STY TMP3_ZP+1", "LDX #<{REG0}", "LDY #>{REG0}", "JSR COPY2_XY",
"LDA #<{MEM0}", "LDY #>{MEM0}", "STA TMP3_ZP", "STY TMP3_ZP+1", "LDX #<{REG1}", "LDY #>{REG1}", "JSR COPY2_XY"));
this.add(new Pattern("Value already in X", new String[] { "{LINE0}", "{LINE1}", "{LINE2}", "TXA", "{LINE4}" }, "LDX #<{REG0}", "LDY #>{REG0}", "JSR COPY2_XY",
"LDA #<{REG0}", "LDY #>{REG0}"));
this.add(new Pattern(false, "Variable used twice in calculation", new String[] { "{LINE3}", "{LINE4}", "{LINE5}", "TXA", "{LINE10}", "{LINE8}", "{LINE9}", "{LINE10}",
"{LINE11}", "{LINE12}" }, "LDX #<{REG0}", "LDY #>{REG0}", "JSR COPY2_XY", "LDX #<{REG1}", "LDY #>{REG1}", "JSR COPY2_XY", "LDA #<{REG0}", "LDY #>{REG0}",
"JSR REALFAC", "LDA #<{REG1}", "LDY #>{REG1}", "JSR MEMARG", "JSR {*}"));
this.add(new Pattern("Avoid INTEGER->REAL conversion", true, new String[] { "LDA #<{CONST0}R", "LDY #>{CONST0}R", "JSR REALFAC" }, "LDY {CONST0}", "LDA {CONST0}",
"JSR INTFAC"));
this.add(new Pattern(false, "Array value used twice in calculation", new String[] { "{LINE0}", "{LINE1}", "{LINE2}", "{LINE3}", "{LINE4}", "{LINE5}", "{LINE6}",
"{LINE7}", "{LINE8}", "{LINE9}", "{LINE10}", "{LINE11}", "{LINE12}", "{LINE13}", "{LINE14}", "{LINE12}", "{LINE13}", "JSR MEMARG" }, "LDA #<{MEM0}",
"LDY #>{MEM0}", "STA TMP3_ZP", "STY TMP3_ZP+1", "LDX #<{REG0}", "LDY #>{REG0}", "JSR COPY2_XY", "LDA #<{MEM1}", "LDY #>{MEM1}", "STA {REG1}", "STY {REG1}",
"JSR {*}", "LDA #<{REG0}", "LDY #>{REG0}", "JSR REALFAC", "JSR PUSHREAL", "LDA #<{MEM0}", "LDY #>{MEM0}", "STA TMP3_ZP", "STY TMP3_ZP+1", "LDX #<{REG0}",
"LDY #>{REG0}", "JSR COPY2_XY", "LDA #<{MEM1}", "LDY #>{MEM1}", "STA {REG1}", "STY {REG1}", "JSR {*}", "JSR POPREAL", "LDA #<{REG0}", "LDY #>{REG0}",
"JSR MEMARG"));
this.add(new Pattern("Constant directly into FAC", new String[] { "LDA #0", "STA $61", "{LINE2}", "{LINE3}",
"LDA #0", "STA $63", "STA $64", "STA $65", "LDY #128", "STY $62", "INY", "STY $61", "LDY #$FF", "STY $66", "{LINE6}", "{LINE8}" }, "LDA #<REAL_CONST_ZERO",
"LDY #>REAL_CONST_ZERO", "JMP {*}", "{LABEL}", "LDA #<REAL_CONST_MINUS_ONE", "LDY #>REAL_CONST_MINUS_ONE", "{LABEL}", "JSR REALFAC", "LDA $61"));
this.add(new Pattern(false, "Highly simplified loading for CMP", new String[] { "{LINE0}", "{LINE1}", "JSR REALFAC", "{LINE7}", "{LINE8}", "{LINE19}" },
"LDA #<{MEM0}", "LDY #>{MEM0}", "STA TMP3_ZP", "STY TMP3_ZP+1", "LDX #<{REG0}", "LDY #>{REG0}", "JSR COPY2_XY", "LDA #<{MEM1}", "LDY #>{MEM1}", "STA TMP3_ZP",
"STY TMP3_ZP+1", "LDX #<{REG1}", "LDY #>{REG1}", "JSR COPY2_XY", "LDA #<{REG0}", "LDY #>{REG0}", "JSR REALFAC", "LDA #<{REG1}", "LDY #>{REG1}", "JSR CMPFAC"));
this.add(new Pattern(false, "Highly simplified loading for calculations", new String[] { "{LINE0}", "{LINE1}", "JSR REALFAC", "{LINE7}", "{LINE8}", "{LINE19}",
"{LINE20}" }, "LDA #<{MEM0}", "LDY #>{MEM0}", "STA TMP3_ZP", "STY TMP3_ZP+1", "LDX #<{REG0}", "LDY #>{REG0}", "JSR COPY2_XY", "LDA #<{MEM1}", "LDY #>{MEM1}",
"STA TMP3_ZP", "STY TMP3_ZP+1", "LDX #<{REG1}", "LDY #>{REG1}", "JSR COPY2_XY", "LDA #<{REG0}", "LDY #>{REG0}", "JSR REALFAC", "LDA #<{REG1}", "LDY #>{REG1}",
"JSR MEMARG", "JSR {*}"));
this.add(new Pattern(false, "NEXT with no variable name simplified", new String[] { "LDA #0", "STA A_REG", "STA A_REG+1", "JSR NEXT" }, "LDY {CONST0}", "LDA {CONST0}",
"STY A_REG", "STA A_REG+1", "JSR NEXT"));
this.add(new Pattern("Improved copy from REG0 to REG1", new String[] { "{LINE0}", "{LINE1}", "STA TMP3_ZP", "STY TMP3_ZP+1", "{LINE3}", "{LINE4}", "JSR COPY2_XY" },
"LDA #<{REG0}", "LDY #>{REG0}", "JSR REALFAC", "LDX #<{REG1}", "LDY #>{REG1}", "JSR FACMEM"));
this.add(new Pattern(false, "Fast SQRT", new String[] { "JSR SQRT" }, "JSR FACSQR"));
this.add(new Pattern(false, "Fast address push", new String[] { "{LINE4}", "{LINE5}", "{LINE6}" }, "STA {REG0}", "STY {REG0}", "LDA {REG0}", "LDY {REG0}",
"STA TMP_ZP", "STY TMP_ZP+1", "JSR PUSHINT"));
this.add(new Pattern(false, "Simplified loading of Strings", new String[] { "{LINE4}", "{LINE5}", "{LINE6}", "{LINE7}", "{LINE8}" }, "STA {REG0}", "STY {REG0}",
"LDA {REG0}", "LDY {REG0}", "STA TMP_ZP", "STY TMP_ZP+1", "LDA #<{MEM0}", "LDY #>{MEM0}", "JSR COPYSTRING"));
this.add(new Pattern("MEM->REG, REG->TMP_ZP", new String[] { "{LINE0}", "{LINE1}", "{LINE6}", "{LINE7}" }, "LDA #<{MEM0}", "LDY #>{MEM0}", "STA {REG0}", "STY {REG0}",
"LDA {REG0}", "LDY {REG0}", "STA TMP_ZP", "STY TMP_ZP+1"));
this.add(new Pattern("Direct loading of values into FAC", new String[] { "{LINE0}", "{LINE1}", "{LINE9}" }, "LDA #<{MEM0}", "LDY #>{MEM0}", "STA TMP3_ZP",
"STY TMP3_ZP+1", "LDX #<Y_REG", "LDY #>Y_REG", "JSR COPY2_XY", "TXA", "LDY #>Y_REG", "JSR REALFAC"));
this.add(new Pattern(false, "POP, REG0, VAR0 -> direct calc", new String[] { "{LINE0}", "{LINE4}", "{LINE5}", "{LINE6}", "{LINE7}" }, "JSR POPREAL", "LDX #<{REG0}",
"LDY #>{REG0}", "JSR FACMEM", "LDA #<{REG1}", "LDY #>{REG1}", "JSR MEMARG", "JSR {*}"));
this.add(new Pattern(false, "POP, REG0, VAR0 -> to WORD", new String[] { "{LINE0}", "{LINE4}" }, "JSR POPREAL", "LDX #<{REG0}", "LDY #>{REG0}", "JSR FACMEM",
"JSR FACWORD"));
this.add(new Pattern(false, "Load and PUSH combined", new String[] { "JSR REALFACPUSH" }, "JSR REALFAC", "JSR PUSHREAL"));
this.add(new Pattern(false, "Memory saving copy", new String[] { "{LINE1}", "{LINE2}", "{LINE3}", "JSR COPY2_XYA" }, "STA TMP3_ZP", "STY TMP3_ZP+1", "LDX #<{REG0}",
"LDY #>{REG0}", "JSR COPY2_XY"));
this.add(new Pattern(false, "Memory saving array access (real)", new String[] { "{LINE0}", "{LINE1}", "JSR ARRAYACCESS_REAL_S" }, "LDA #<{MEM0}", "LDY #>{MEM0}",
"STA G_REG", "STY G_REG+1", "JSR ARRAYACCESS_REAL"));
this.add(new Pattern(false, "Memory saving array access (integer)", new String[] { "{LINE0}", "{LINE1}", "JSR ARRAYACCESS_INTEGER_S" }, "LDA #<{MEM0}", "LDY #>{MEM0}",
"STA G_REG", "STY G_REG+1", "JSR ARRAYACCESS_INTEGER"));
this.add(new Pattern(false, "POPREAL and load X", new String[] { "JSR POPREAL2X" }, "JSR POPREAL", "LDA #<X_REG", "LDY #>X_REG", "JSR MEMARG"));
this.add(new Pattern(false, "Simplified CMP redux", new String[]{"{LINE0}","{LINE2}","{LINE3}","LDA #$1","{LINE14}","{LINE16}","{LINE17}",},"LDA #0","STA $61","JMP {*}", "{LABEL}","LDA #0","STA $63","STA $64","STA $65",
"LDY #128","STY $62","INY","STY $61","LDY #$FF","STY $66","{LABEL}","LDA $61","{LABEL}","BNE {*}"));
this.add(new Pattern(false, "CMP (REG) = 0", new String[] { "LDA {REG0}", "{LINE6}", "{LINE7}" }, "LDA #<{#0.0}", "LDY #>{#0.0}", "JSR REALFAC", "LDA #<{REG0}",
"LDY #>{REG0}", "JSR CMPFAC", "BEQ {*}", "LDA #0"));
this.add(new Pattern(false, "CMP (REG) != 0", new String[] { "LDA {REG0}", "{LINE6}", "{LINE7}" }, "LDA #<{#0.0}", "LDY #>{#0.0}", "JSR REALFAC", "LDA #<{REG0}",
"LDY #>{REG0}", "JSR CMPFAC", "BNE {*}", "LDA #0"));
this.add(new Pattern(false, "CMP (MEM) = 0", new String[] { "LDA {MEM0}", "{LINE6}", "{LINE7}" }, "LDA #<{#0.0}", "LDY #>{#0.0}", "JSR REALFAC", "LDA #<{MEM0}",
"LDY #>{MEM0}", "JSR CMPFAC", "BEQ {*}", "LDA #0"));
this.add(new Pattern(false, "CMP (MEM) != 0", new String[] { "LDA {MEM0}", "{LINE6}", "{LINE7}" }, "LDA #<{#0.0}", "LDY #>{#0.0}", "JSR REALFAC", "LDA #<{MEM0}",
"LDY #>{MEM0}", "JSR CMPFAC", "BNE {*}", "LDA #0"));
this.add(new Pattern(false, "CMP (REG) = 0(2)", new String[] { "LDA {REG0}", "{LINE6}", "{LINE7}" }, "LDA #<{#0.0}", "LDY #>{#0.0}", "JSR REALFAC", "LDA #<{REG0}",
"LDY #>{REG0}", "JSR CMPFAC", "{LABEL}", "BEQ {*}"));
this.add(new Pattern(false, "CMP (REG) != 0(2)", new String[] { "LDA {REG0}", "{LINE6}", "{LINE7}" }, "LDA #<{#0.0}", "LDY #>{#0.0}", "JSR REALFAC", "LDA #<{REG0}",
"LDY #>{REG0}", "JSR CMPFAC", "{LABEL}", "BNE {*}"));
this.add(new Pattern(false, "CMP (MEM) = 0(2)", new String[] { "LDA {MEM0}", "{LINE6}", "{LINE7}" }, "LDA #<{#0.0}", "LDY #>{#0.0}", "JSR REALFAC", "LDA #<{MEM0}",
"LDY #>{MEM0}", "JSR CMPFAC", "{LABEL}", "BEQ {*}"));
this.add(new Pattern(false, "CMP (MEM) != 0(2)", new String[] { "LDA {MEM0}", "{LINE6}", "{LINE7}" }, "LDA #<{#0.0}", "LDY #>{#0.0}", "JSR REALFAC", "LDA #<{MEM0}",
"LDY #>{MEM0}", "JSR CMPFAC", "{LABEL}", "BNE {*}"));
this.add(new Pattern(false, "Direct loading of 0", new String[]{"LDA #$0", "STA $61"},"LDA #<{#0.0}","LDY #>{#0.0}","JSR REALFAC"));
this.add(new Pattern(false, "FAC into REG?, REG? into FAC (2)", new String[]{"{LINE0}","{LINE1}","{LINE2}"}, "LDY #>{REG0}", "LDX #<{REG0}", "JSR FACMEM", "LDA #<{REG0}", "LDY #>{REG0}", "JSR REALFAC"));
}
};
@Override
public List<String> optimize(PlatformProvider platform, List<String> input) {
// if (true) return input;
long s = System.currentTimeMillis();
Map<String, Integer> type2count = new HashMap<>();
Map<String, Number> const2Value = extractConstants(input);
trimLines(input);
input=trackAndModifyRegisterUsage(input);
Set<Pattern> used = new HashSet<Pattern>();
boolean optimized = false;
do {
optimized = false;
for (Pattern pattern : patterns) {
if (pattern.isLooseTypes() && !platform.useLooseTypes()) {
continue;
}
if (used.contains(pattern)) {
continue;
}
for (int i = 0; i < input.size(); i++) {
String line = input.get(i);
if (line.startsWith("; *** SUBROUTINES ***")) {
break;
}
int sp = pattern.getPos();
boolean matches = pattern.matches(line, i, const2Value);
if (matches) {
String name = pattern.getName();
Integer cnt = type2count.get(name);
if (cnt == null) {
type2count.put(name, 1);
} else {
type2count.put(name, cnt + 1);
}
input = pattern.apply(input);
optimized = true;
break;
}
if (pattern.getPos() == 0 && sp > 1) {
i
}
}
if (optimized) {
break;
} else {
if (!pattern.isSimple()) {
used.add(pattern);
}
}
}
} while (optimized);
for (Map.Entry<String, Integer> cnts : type2count.entrySet()) {
Logger.log("Optimization " + cnts.getKey() + " applied " + cnts.getValue() + " times!");
}
input = applySpecialRules(input);
input = removeNops(input);
Logger.log("Assembly code optimized in " + (System.currentTimeMillis() - s) + "ms");
return input;
}
private void trimLines(List<String> input) {
for (int i = 0; i < input.size(); i++) {
String line = input.get(i).trim();
if (line.startsWith("; *** SUBROUTINES ***")) {
break;
}
input.set(i, line);
}
}
private Map<String, Number> extractConstants(List<String> input) {
Map<String, Number> const2Value = new HashMap<>();
for (String line : input) {
line = line.replace("\t", " ");
if (line.startsWith("CONST_")) {
int pos = line.indexOf(" ");
if (pos != -1) {
String name = line.substring(0, pos).trim();
String right = line.substring(pos + 1).trim();
pos = right.indexOf(" ");
if (pos != -1) {
String type = right.substring(0, pos).trim();
String number = right.substring(pos + 1).trim();
if (type.equals(".REAL") || type.equals(".WORD")) {
try {
Float num = Float.valueOf(number);
if (type.equals(".REAL")) {
const2Value.put(name, num);
} else {
const2Value.put(name, num.intValue());
}
} catch (Exception e) {
Logger.log("Failed to parse " + number + " as a number!");
}
}
}
}
}
}
return const2Value;
}
private List<String> removeNops(List<String> input) {
for (Iterator<String> itty = input.iterator(); itty.hasNext();) {
if (itty.next().equals("NOP")) {
itty.remove();
}
}
return input;
}
private List<String> applySpecialRules(List<String> input) {
input = simplifyBranches(input);
return aggregateLoads(input);
}
private List<String> aggregateLoads(List<String> input) {
boolean loadMode = false;
for (Iterator<String> itty = input.iterator(); itty.hasNext();) {
String line = itty.next().trim();
if (line.startsWith(";") || line.isEmpty() || line.equals("NOP")) {
continue;
}
if (!loadMode && (line.equals("LDA #0") || line.equals("LDA #$0"))) {
loadMode = true;
} else {
if (loadMode) {
if (line.equals("LDA #0") || line.equals("LDA #$0")) {
itty.remove();
} else if (!line.startsWith("STA")) {
loadMode = false;
}
}
}
}
return input;
}
private List<String> trackAndModifyRegisterUsage(List<String> code)
{
Map<String, Integer[]> regState = new HashMap<>();
String lastReg = "";
for (int i = 0; i < code.size(); i++)
{
String line = code.get(i);
if (line.startsWith(";"))
{
continue;
}
if (line.startsWith("JMP") || line.startsWith("B") || line.startsWith("RTS"))
{
regState.clear();
lastReg = "";
}
if (line.startsWith("L") && line.endsWith("_REG"))
{
String reg = line.substring(line.indexOf(" ")).trim();
lastReg = reg;
Integer[] state = regState.get(reg);
if (state == null)
{
regState.put(reg, new Integer[] { 0, i }); // Unknown stage...yet
}
else
{
if (code.get(i + 2).startsWith("JSR FACMEM"))
{
regState.put(reg, new Integer[] { 1, i }); // Already written into memory? Update the location to the latest
// one!
}
}
}
else
{
Integer[] state = regState.get(lastReg);
if (state != null)
{
if (line.startsWith("JSR FACMEM"))
{
regState.put(lastReg, new Integer[] { 1, state[1] }); // Mark as: Value stored in reg!
}
else
{
if (line.startsWith("JSR REALFAC") || line.startsWith("JSR MEMARG"))
{
if (state[0] < 2)
{
regState.put(lastReg, new Integer[] { 2, state[1] }); // Mark as: Value read back into FAC!
}
else
{
// The value from the register is read without being written before again...don't optimize the initial
// setter away...
// ...so we swap the order of that setter to prevent this.
String l1 = code.get(state[1]);
String l0 = code.get(state[1] - 1);
code.set(state[1] - 1, l1);
code.set(state[1], l0);
Logger.log("Swapped: " + l0 + "/" + l1 + "@" + state[1]);
}
}
else
{
lastReg = "";
}
}
}
else
{
lastReg = "";
}
}
}
return code;
}
private List<String> simplifyBranches(List<String> input) {
List<String> ret = new ArrayList<String>();
for (int i = 0; i < input.size() - 2; i++) {
String line = trimLine(input, i);
String line2 = trimLine(input, i+1);
String line3 = trimLine(input, i+2);
if (line.startsWith("; *** SUBROUTINES ***")) {
ret.addAll(input.subList(i, input.size()));
break;
}
boolean skip = false;
int add=1;
if(line2.startsWith(";")) {
line2=line3;
add=2;
}
if (line.contains("BNE LINE_NSKIP") && line2.contains("JMP LINE_SKIP")) {
for (int p = i + 1; p < Math.min(input.size(), i + 30); p++) {
String subLine = input.get(p);
if (subLine.startsWith("LINE_SKIP")) {
ret.add(line2.replace("JMP LINE_SKIP", "BEQ LINE_SKIP"));
ret.add("; Simplified conditional branch");
skip = true;
i+=add;
break;
}
}
}
if (skip) {
continue;
}
ret.add(line);
}
return ret;
}
private String trimLine(List<String> input, int i) {
String line3 = input.get(i);
line3 = line3.replace("\t", " ").trim();
return line3;
}
}
|
package com.timgroup.statsd;
import jnr.unixsocket.UnixSocketAddress;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
* A simple StatsD client implementation facilitating metrics recording.
*
* <p>Upon instantiation, this client will establish a socket connection to a StatsD instance
* running on the specified host and port. Metrics are then sent over this connection as they are
* received by the client.
* </p>
*
* <p>Three key methods are provided for the submission of data-points for the application under
* scrutiny:
* <ul>
* <li>{@link #incrementCounter} - adds one to the value of the specified named counter</li>
* <li>{@link #recordGaugeValue} - records the latest fixed value for the specified named gauge</li>
* <li>{@link #recordExecutionTime} - records an execution time in milliseconds for the specified named operation</li>
* <li>{@link #recordHistogramValue} - records a value, to be tracked with average, maximum, and percentiles</li>
* <li>{@link #recordEvent} - records an event</li>
* <li>{@link #recordSetValue} - records a value in a set</li>
* </ul>
* From the perspective of the application, these methods are non-blocking, with the resulting
* IO operations being carried out in a separate thread. Furthermore, these methods are guaranteed
* not to throw an exception which may disrupt application execution.
*
* <p>As part of a clean system shutdown, the {@link #stop()} method should be invoked
* on any StatsD clients.</p>
*
* @author Tom Denley
*
*/
public class NonBlockingStatsDClient implements StatsDClient {
public static final String DD_DOGSTATSD_PORT_ENV_VAR = "DD_DOGSTATSD_PORT";
public static final String DD_AGENT_HOST_ENV_VAR = "DD_AGENT_HOST";
public static final String DD_NAMED_PIPE_ENV_VAR = "DD_DOGSTATSD_PIPE_NAME";
public static final String DD_ENTITY_ID_ENV_VAR = "DD_ENTITY_ID";
private static final String ENTITY_ID_TAG_NAME = "dd.internal.entity_id" ;
enum Literal {
SERVICE,
ENV,
VERSION
;
private static final String PREFIX = "dd";
String envName() {
return (PREFIX + "_" + toString()).toUpperCase();
}
String envVal() {
return System.getenv(envName());
}
String tag() {
return toString().toLowerCase();
}
}
public static final int DEFAULT_UDP_MAX_PACKET_SIZE_BYTES = 1432;
public static final int DEFAULT_UDS_MAX_PACKET_SIZE_BYTES = 8192;
public static final int DEFAULT_QUEUE_SIZE = 4096;
public static final int DEFAULT_POOL_SIZE = 512;
public static final int DEFAULT_PROCESSOR_WORKERS = 1;
public static final int DEFAULT_SENDER_WORKERS = 1;
public static final int DEFAULT_DOGSTATSD_PORT = 8125;
public static final int SOCKET_TIMEOUT_MS = 100;
public static final int SOCKET_BUFFER_BYTES = -1;
public static final boolean DEFAULT_BLOCKING = false;
public static final boolean DEFAULT_ENABLE_TELEMETRY = true;
public static final boolean DEFAULT_ENABLE_AGGREGATION = true;
public static final String CLIENT_TAG = "client:java";
public static final String CLIENT_VERSION_TAG = "client_version:";
public static final String CLIENT_TRANSPORT_TAG = "client_transport:";
/**
* UTF-8 is the expected encoding for data sent to the agent.
*/
public static final Charset UTF_8 = StandardCharsets.UTF_8;
private static final StatsDClientErrorHandler NO_OP_HANDLER = new StatsDClientErrorHandler() {
@Override public void handle(final Exception ex) { /* No-op */ }
};
/**
* The NumberFormat instances are not threadsafe and thus defined as ThreadLocal
* for safety.
*/
protected static final ThreadLocal<NumberFormat> NUMBER_FORMATTER = new ThreadLocal<NumberFormat>() {
@Override
protected NumberFormat initialValue() {
return newFormatter(false);
}
};
protected static final ThreadLocal<NumberFormat> SAMPLE_RATE_FORMATTER = new ThreadLocal<NumberFormat>() {
@Override
protected NumberFormat initialValue() {
return newFormatter(true);
}
};
static {
}
private static NumberFormat newFormatter(boolean sampler) {
// Always create the formatter for the US locale in order to avoid this bug:
NumberFormat numberFormatter = NumberFormat.getInstance(Locale.US);
numberFormatter.setGroupingUsed(false);
// we need to specify a value for Double.NaN that is recognized by dogStatsD
if (numberFormatter instanceof DecimalFormat) { // better safe than a runtime error
final DecimalFormat decimalFormat = (DecimalFormat) numberFormatter;
final DecimalFormatSymbols symbols = decimalFormat.getDecimalFormatSymbols();
symbols.setNaN("NaN");
decimalFormat.setDecimalFormatSymbols(symbols);
}
if (sampler) {
numberFormatter.setMinimumFractionDigits(6);
} else {
numberFormatter.setMaximumFractionDigits(6);
}
return numberFormatter;
}
protected static String format(ThreadLocal<NumberFormat> formatter, Number value) {
return formatter.get().format(value);
}
private final String prefix;
private final ClientChannel clientChannel;
private final ClientChannel telemetryClientChannel;
private final StatsDClientErrorHandler handler;
private final String constantTagsRendered;
// Typically the telemetry and regular processors will be the same,
// but a separate destination for telemetry is supported.
protected final StatsDProcessor statsDProcessor;
protected StatsDProcessor telemetryStatsDProcessor;
protected final StatsDSender statsDSender;
protected StatsDSender telemetryStatsDSender;
protected final Telemetry telemetry;
private final boolean blocking;
/**
* Create a new StatsD client communicating with a StatsD instance on the
* specified host and port. All messages send via this client will have
* their keys prefixed with the specified string. The new client will
* attempt to open a connection to the StatsD server immediately upon
* instantiation, and may throw an exception if that a connection cannot
* be established. Once a client has been instantiated in this way, all
* exceptions thrown during subsequent usage are passed to the specified
* handler and then consumed, guaranteeing that failures in metrics will
* not affect normal code execution.
*
* @param prefix
* the prefix to apply to keys sent via this client
* @param constantTags
* tags to be added to all content sent
* @param errorHandler
* handler to use when an exception occurs during usage, may be null to indicate noop
* @param addressLookup
* yields the IP address and socket of the StatsD server
* @param telemetryAddressLookup
* yields the IP address and socket of the StatsD telemetry server destination
* @param queueSize
* the maximum amount of unprocessed messages in the Queue.
* @param timeout
* the timeout in milliseconds for blocking operations. Applies to unix sockets only.
* @param bufferSize
* the socket buffer size in bytes. Applies to unix sockets only.
* @param maxPacketSizeBytes
* the maximum number of bytes for a message that can be sent
* @param entityID
* the entity id value used with an internal tag for tracking client entity.
* If "entityID=null" the client default the value with the environment variable "DD_ENTITY_ID".
* If the environment variable is not defined, the internal tag is not added.
* @param poolSize
* The size for the network buffer pool.
* @param processorWorkers
* The number of processor worker threads assembling buffers for submission.
* @param senderWorkers
* The number of sender worker threads submitting buffers to the socket.
* @param blocking
* Blocking or non-blocking implementation for statsd message queue.
* @param enableTelemetry
* Boolean to enable client telemetry.
* @param telemetryFlushInterval
* Telemetry flush interval integer, in milliseconds.
* @param aggregationFlushInterval
* Aggregation flush interval integer, in milliseconds. 0 disables aggregation.
* @param aggregationShards
* Aggregation flush interval integer, in milliseconds. 0 disables aggregation.
* @throws StatsDClientException
* if the client could not be started
*/
private NonBlockingStatsDClient(final String prefix, final int queueSize, final String[] constantTags,
final StatsDClientErrorHandler errorHandler, final Callable<SocketAddress> addressLookup,
final Callable<SocketAddress> telemetryAddressLookup, final int timeout, final int bufferSize,
final int maxPacketSizeBytes, String entityID, final int poolSize, final int processorWorkers,
final int senderWorkers, boolean blocking, final boolean enableTelemetry, final int telemetryFlushInterval,
final int aggregationFlushInterval, final int aggregationShards, final ThreadFactory customThreadFactory)
throws StatsDClientException {
if ((prefix != null) && (!prefix.isEmpty())) {
this.prefix = prefix + ".";
} else {
this.prefix = "";
}
if (errorHandler == null) {
handler = NO_OP_HANDLER;
} else {
handler = errorHandler;
}
this.blocking = blocking;
{
List<String> costantPreTags = new ArrayList<>();
if (constantTags != null) {
for (final String constantTag : constantTags) {
costantPreTags.add(constantTag);
}
}
// Support "dd.internal.entity_id" internal tag.
updateTagsWithEntityID(costantPreTags, entityID);
for (final Literal literal : Literal.values()) {
final String envVal = literal.envVal();
if (envVal != null && !envVal.trim().isEmpty()) {
costantPreTags.add(literal.tag() + ":" + envVal);
}
}
if (costantPreTags.isEmpty()) {
constantTagsRendered = null;
} else {
constantTagsRendered = tagString(
costantPreTags.toArray(new String[costantPreTags.size()]), null, new StringBuilder()).toString();
}
costantPreTags = null;
}
try {
clientChannel = createByteChannel(addressLookup, timeout, bufferSize);
ThreadFactory threadFactory = customThreadFactory != null ? customThreadFactory : new StatsDThreadFactory();
statsDProcessor = createProcessor(queueSize, handler, maxPacketSizeBytes, poolSize,
processorWorkers, blocking, aggregationFlushInterval, aggregationShards, threadFactory);
Properties properties = new Properties();
properties.load(getClass().getClassLoader().getResourceAsStream(
"dogstatsd/version.properties"));
String telemetryTags = tagString(new String[]{CLIENT_TRANSPORT_TAG + clientChannel.getTransportType(),
CLIENT_VERSION_TAG + properties.getProperty("dogstatsd_client_version"),
CLIENT_TAG}, new StringBuilder()).toString();
if (addressLookup == telemetryAddressLookup) {
telemetryClientChannel = clientChannel;
telemetryStatsDProcessor = statsDProcessor;
} else {
telemetryClientChannel = createByteChannel(telemetryAddressLookup, timeout, bufferSize);
// similar settings, but a single worker and non-blocking.
telemetryStatsDProcessor = createProcessor(queueSize, handler, maxPacketSizeBytes,
poolSize, 1, false, 0, aggregationShards, threadFactory);
}
this.telemetry = new Telemetry.Builder()
.tags(telemetryTags)
.processor(telemetryStatsDProcessor)
.build();
statsDSender = createSender(handler, clientChannel, statsDProcessor.getBufferPool(),
statsDProcessor.getOutboundQueue(), senderWorkers, threadFactory);
telemetryStatsDSender = statsDSender;
if (telemetryStatsDProcessor != statsDProcessor) {
// TODO: figure out why the hell telemetryClientChannel does not work here!
telemetryStatsDSender = createSender(handler, telemetryClientChannel,
telemetryStatsDProcessor.getBufferPool(), telemetryStatsDProcessor.getOutboundQueue(),
1, threadFactory);
}
// set telemetry
statsDProcessor.setTelemetry(this.telemetry);
statsDSender.setTelemetry(this.telemetry);
} catch (final Exception e) {
throw new StatsDClientException("Failed to start StatsD client", e);
}
statsDProcessor.startWorkers("StatsD-Processor-");
statsDSender.startWorkers("StatsD-Sender-");
if (enableTelemetry) {
if (telemetryStatsDProcessor != statsDProcessor) {
telemetryStatsDProcessor.startWorkers("StatsD-TelemetryProcessor-");
telemetryStatsDSender.startWorkers("StatsD-TelemetrySender-");
}
this.telemetry.start(telemetryFlushInterval);
}
}
/**
* Create a new StatsD client communicating with a StatsD instance on the
* host and port specified by the given builder.
* The builder must be resolved before calling this internal constructor.
*
* @param builder
* the resolved configuration builder
*
* @see NonBlockingStatsDClientBuilder#resolve()
*/
public NonBlockingStatsDClient(final NonBlockingStatsDClientBuilder builder) throws StatsDClientException {
this(builder.prefix, builder.queueSize, builder.constantTags, builder.errorHandler,
builder.addressLookup, builder.telemetryAddressLookup, builder.timeout,
builder.socketBufferSize, builder.maxPacketSizeBytes, builder.entityID,
builder.bufferPoolSize, builder.processorWorkers, builder.senderWorkers,
builder.blocking, builder.enableTelemetry, builder.telemetryFlushInterval,
(builder.enableAggregation ? builder.aggregationFlushInterval : 0),
builder.aggregationShards, builder.threadFactory);
}
protected StatsDProcessor createProcessor(final int queueSize, final StatsDClientErrorHandler handler,
final int maxPacketSizeBytes, final int bufferPoolSize, final int workers, final boolean blocking,
final int aggregationFlushInterval, final int aggregationShards, final ThreadFactory threadFactory)
throws Exception {
if (blocking) {
return new StatsDBlockingProcessor(queueSize, handler, maxPacketSizeBytes, bufferPoolSize,
workers, aggregationFlushInterval, aggregationShards, threadFactory);
} else {
return new StatsDNonBlockingProcessor(queueSize, handler, maxPacketSizeBytes, bufferPoolSize,
workers, aggregationFlushInterval, aggregationShards, threadFactory);
}
}
protected StatsDSender createSender(final StatsDClientErrorHandler handler,
final WritableByteChannel clientChannel, BufferPool pool, BlockingQueue<ByteBuffer> buffers, final int senderWorkers,
final ThreadFactory threadFactory) throws Exception {
return new StatsDSender(clientChannel, handler, pool, buffers, senderWorkers, threadFactory);
}
/**
* Cleanly shut down this StatsD client. This method may throw an exception if
* the socket cannot be closed.
*
* <p>In blocking mode, this will block until all messages are sent to the server.
*/
@Override
public void stop() {
try {
this.telemetry.stop();
statsDProcessor.shutdown(blocking);
statsDSender.shutdown(blocking);
// shut down telemetry workers if need be
if (telemetryStatsDProcessor != statsDProcessor) {
telemetryStatsDProcessor.shutdown(false);
telemetryStatsDSender.shutdown(false);
}
} catch (final Exception e) {
handler.handle(e);
} finally {
if (clientChannel != null) {
try {
clientChannel.close();
} catch (final IOException e) {
handler.handle(e);
}
}
if (telemetryClientChannel != null && telemetryClientChannel != clientChannel) {
try {
telemetryClientChannel.close();
} catch (final IOException e) {
handler.handle(e);
}
}
}
}
@Override
public void close() {
stop();
}
/**
* Return tag list as a tag string.
* Generate a suffix conveying the given tag list to the client
*/
static StringBuilder tagString(final String[] tags, final String tagPrefix, final StringBuilder sb) {
if (tagPrefix != null) {
sb.append(tagPrefix);
if ((tags == null) || (tags.length == 0)) {
return sb;
}
sb.append(',');
} else {
if ((tags == null) || (tags.length == 0)) {
return sb;
}
sb.append("|
}
for (int n = tags.length - 1; n >= 0; n
sb.append(tags[n]);
if (n > 0) {
sb.append(',');
}
}
return sb;
}
/**
* Generate a suffix conveying the given tag list to the client.
*/
StringBuilder tagString(final String[] tags, StringBuilder builder) {
return tagString(tags, constantTagsRendered, builder);
}
ClientChannel createByteChannel(Callable<SocketAddress> addressLookup, int timeout, int bufferSize) throws Exception {
final SocketAddress address = addressLookup.call();
if (address instanceof NamedPipeSocketAddress) {
return new NamedPipeClientChannel((NamedPipeSocketAddress) address);
} else if (address instanceof UnixSocketAddress) {
return new UnixDatagramClientChannel(address, timeout, bufferSize);
} else {
return new DatagramClientChannel(address);
}
}
abstract class StatsDMessage<T extends Number> extends NumericMessage<T> {
final double sampleRate; // NaN for none
protected StatsDMessage(String aspect, Message.Type type, T value, double sampleRate, String[] tags) {
super(aspect, type, value, tags);
this.sampleRate = sampleRate;
}
@Override
public final void writeTo(StringBuilder builder) {
builder.append(prefix).append(aspect).append(':');
writeValue(builder);
builder.append('|').append(type);
if (!Double.isNaN(sampleRate)) {
builder.append('|').append('@').append(format(SAMPLE_RATE_FORMATTER, sampleRate));
}
tagString(this.tags, builder);
builder.append('\n');
}
protected abstract void writeValue(StringBuilder builder);
}
private boolean sendMetric(final Message message) {
return send(message);
}
private boolean send(final Message message) {
boolean success = statsDProcessor.send(message);
if (success) {
this.telemetry.incrMetricsSent(1, message.getType());
} else {
this.telemetry.incrPacketDroppedQueue(1);
}
return success;
}
// send double with sample rate
private void send(String aspect, final double value, Message.Type type, double sampleRate, String[] tags) {
if (statsDProcessor.getAggregator().getFlushInterval() != 0 && !Double.isNaN(sampleRate)) {
switch (type) {
case COUNT:
sampleRate = Double.NaN;
break;
default:
break;
}
}
if (Double.isNaN(sampleRate) || !isInvalidSample(sampleRate)) {
sendMetric(new StatsDMessage<Double>(aspect, type, Double.valueOf(value), sampleRate, tags) {
@Override protected void writeValue(StringBuilder builder) {
builder.append(format(NUMBER_FORMATTER, this.value));
}
});
}
}
// send double without sample rate
private void send(String aspect, final double value, Message.Type type, String[] tags) {
send(aspect, value, type, Double.NaN, tags);
}
// send long with sample rate
private void send(String aspect, final long value, Message.Type type, double sampleRate, String[] tags) {
if (statsDProcessor.getAggregator().getFlushInterval() != 0 && !Double.isNaN(sampleRate)) {
switch (type) {
case COUNT:
sampleRate = Double.NaN;
break;
default:
break;
}
}
if (Double.isNaN(sampleRate) || !isInvalidSample(sampleRate)) {
sendMetric(new StatsDMessage<Long>(aspect, type, value, sampleRate, tags) {
@Override protected void writeValue(StringBuilder builder) {
builder.append(this.value);
}
});
}
}
// send long without sample rate
private void send(String aspect, final long value, Message.Type type, String[] tags) {
send(aspect, value, type, Double.NaN, tags);
}
/**
* Adjusts the specified counter by a given delta.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the counter to adjust
* @param delta
* the amount to adjust the counter by
* @param tags
* array of tags to be added to the data
*/
@Override
public void count(final String aspect, final long delta, final String... tags) {
send(aspect, delta, Message.Type.COUNT, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void count(final String aspect, final long delta, final double sampleRate, final String...tags) {
send(aspect, delta, Message.Type.COUNT, sampleRate, tags);
}
/**
* Adjusts the specified counter by a given delta.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the counter to adjust
* @param delta
* the amount to adjust the counter by
* @param tags
* array of tags to be added to the data
*/
@Override
public void count(final String aspect, final double delta, final String... tags) {
send(aspect, delta, Message.Type.COUNT, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void count(final String aspect, final double delta, final double sampleRate, final String...tags) {
send(aspect, delta, Message.Type.COUNT, sampleRate, tags);
}
/**
* Increments the specified counter by one.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the counter to increment
* @param tags
* array of tags to be added to the data
*/
@Override
public void incrementCounter(final String aspect, final String... tags) {
count(aspect, 1, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void incrementCounter(final String aspect, final double sampleRate, final String... tags) {
count(aspect, 1, sampleRate, tags);
}
/**
* Convenience method equivalent to {@link #incrementCounter(String, String[])}.
*/
@Override
public void increment(final String aspect, final String... tags) {
incrementCounter(aspect, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(final String aspect, final double sampleRate, final String...tags ) {
incrementCounter(aspect, sampleRate, tags);
}
/**
* Decrements the specified counter by one.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the counter to decrement
* @param tags
* array of tags to be added to the data
*/
@Override
public void decrementCounter(final String aspect, final String... tags) {
count(aspect, -1, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void decrementCounter(String aspect, final double sampleRate, final String... tags) {
count(aspect, -1, sampleRate, tags);
}
/**
* Convenience method equivalent to {@link #decrementCounter(String, String[])}.
*/
@Override
public void decrement(final String aspect, final String... tags) {
decrementCounter(aspect, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void decrement(final String aspect, final double sampleRate, final String... tags) {
decrementCounter(aspect, sampleRate, tags);
}
/**
* Records the latest fixed value for the specified named gauge.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the gauge
* @param value
* the new reading of the gauge
* @param tags
* array of tags to be added to the data
*/
@Override
public void recordGaugeValue(final String aspect, final double value, final String... tags) {
send(aspect, value, Message.Type.GAUGE, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void recordGaugeValue(final String aspect, final double value, final double sampleRate, final String... tags) {
send(aspect, value, Message.Type.GAUGE, sampleRate, tags);
}
/**
* Records the latest fixed value for the specified named gauge.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the gauge
* @param value
* the new reading of the gauge
* @param tags
* array of tags to be added to the data
*/
@Override
public void recordGaugeValue(final String aspect, final long value, final String... tags) {
send(aspect, value, Message.Type.GAUGE, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void recordGaugeValue(final String aspect, final long value, final double sampleRate, final String... tags) {
send(aspect, value, Message.Type.GAUGE, sampleRate, tags);
}
/**
* Convenience method equivalent to {@link #recordGaugeValue(String, double, String[])}.
*/
@Override
public void gauge(final String aspect, final double value, final String... tags) {
recordGaugeValue(aspect, value, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void gauge(final String aspect, final double value, final double sampleRate, final String... tags) {
recordGaugeValue(aspect, value, sampleRate, tags);
}
/**
* Convenience method equivalent to {@link #recordGaugeValue(String, long, String[])}.
*/
@Override
public void gauge(final String aspect, final long value, final String... tags) {
recordGaugeValue(aspect, value, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void gauge(final String aspect, final long value, final double sampleRate, final String... tags) {
recordGaugeValue(aspect, value, sampleRate, tags);
}
/**
* Records an execution time in milliseconds for the specified named operation.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the timed operation
* @param timeInMs
* the time in milliseconds
* @param tags
* array of tags to be added to the data
*/
@Override
public void recordExecutionTime(final String aspect, final long timeInMs, final String... tags) {
send(aspect, timeInMs, Message.Type.TIME, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void recordExecutionTime(final String aspect, final long timeInMs, final double sampleRate, final String... tags) {
send(aspect, timeInMs, Message.Type.TIME, sampleRate, tags);
}
/**
* Convenience method equivalent to {@link #recordExecutionTime(String, long, String[])}.
*/
@Override
public void time(final String aspect, final long value, final String... tags) {
recordExecutionTime(aspect, value, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void time(final String aspect, final long value, final double sampleRate, final String... tags) {
recordExecutionTime(aspect, value, sampleRate, tags);
}
/**
* Records a value for the specified named histogram.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the histogram
* @param value
* the value to be incorporated in the histogram
* @param tags
* array of tags to be added to the data
*/
@Override
public void recordHistogramValue(final String aspect, final double value, final String... tags) {
send(aspect, value, Message.Type.HISTOGRAM, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void recordHistogramValue(final String aspect, final double value, final double sampleRate, final String... tags) {
send(aspect, value, Message.Type.HISTOGRAM, sampleRate, tags);
}
/**
* Records a value for the specified named histogram.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the histogram
* @param value
* the value to be incorporated in the histogram
* @param tags
* array of tags to be added to the data
*/
@Override
public void recordHistogramValue(final String aspect, final long value, final String... tags) {
send(aspect, value, Message.Type.HISTOGRAM, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void recordHistogramValue(final String aspect, final long value, final double sampleRate, final String... tags) {
send(aspect, value, Message.Type.HISTOGRAM, sampleRate, tags);
}
/**
* Convenience method equivalent to {@link #recordHistogramValue(String, double, String[])}.
*/
@Override
public void histogram(final String aspect, final double value, final String... tags) {
recordHistogramValue(aspect, value, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void histogram(final String aspect, final double value, final double sampleRate, final String... tags) {
recordHistogramValue(aspect, value, sampleRate, tags);
}
/**
* Convenience method equivalent to {@link #recordHistogramValue(String, long, String[])}.
*/
@Override
public void histogram(final String aspect, final long value, final String... tags) {
recordHistogramValue(aspect, value, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void histogram(final String aspect, final long value, final double sampleRate, final String... tags) {
recordHistogramValue(aspect, value, sampleRate, tags);
}
/**
* Records a value for the specified named distribution.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the distribution
* @param value
* the value to be incorporated in the distribution
* @param tags
* array of tags to be added to the data
*/
@Override
public void recordDistributionValue(final String aspect, final double value, final String... tags) {
send(aspect, value, Message.Type.DISTRIBUTION, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void recordDistributionValue(final String aspect, final double value, final double sampleRate, final String... tags) {
send(aspect, value, Message.Type.DISTRIBUTION, sampleRate, tags);
}
/**
* Records a value for the specified named distribution.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the distribution
* @param value
* the value to be incorporated in the distribution
* @param tags
* array of tags to be added to the data
*/
@Override
public void recordDistributionValue(final String aspect, final long value, final String... tags) {
send(aspect, value, Message.Type.DISTRIBUTION, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void recordDistributionValue(final String aspect, final long value, final double sampleRate, final String... tags) {
send(aspect, value, Message.Type.DISTRIBUTION, sampleRate, tags);
}
/**
* Convenience method equivalent to {@link #recordDistributionValue(String, double, String[])}.
*/
@Override
public void distribution(final String aspect, final double value, final String... tags) {
recordDistributionValue(aspect, value, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void distribution(final String aspect, final double value, final double sampleRate, final String... tags) {
recordDistributionValue(aspect, value, sampleRate, tags);
}
/**
* Convenience method equivalent to {@link #recordDistributionValue(String, long, String[])}.
*/
@Override
public void distribution(final String aspect, final long value, final String... tags) {
recordDistributionValue(aspect, value, tags);
}
/**
* {@inheritDoc}
*/
@Override
public void distribution(final String aspect, final long value, final double sampleRate, final String... tags) {
recordDistributionValue(aspect, value, sampleRate, tags);
}
private StringBuilder eventMap(final Event event, StringBuilder res) {
final long millisSinceEpoch = event.getMillisSinceEpoch();
if (millisSinceEpoch != -1) {
res.append("|d:").append(millisSinceEpoch / 1000);
}
final String hostname = event.getHostname();
if (hostname != null) {
res.append("|h:").append(hostname);
}
final String aggregationKey = event.getAggregationKey();
if (aggregationKey != null) {
res.append("|k:").append(aggregationKey);
}
final String priority = event.getPriority();
if (priority != null) {
res.append("|p:").append(priority);
}
final String alertType = event.getAlertType();
if (alertType != null) {
res.append("|t:").append(alertType);
}
final String sourceTypeName = event.getSourceTypeName();
if (sourceTypeName != null) {
res.append("|s:").append(sourceTypeName);
}
return res;
}
@Override
public void recordEvent(final Event event, final String... eventTags) {
statsDProcessor.send(new AlphaNumericMessage(Message.Type.EVENT, "") {
@Override public void writeTo(StringBuilder builder) {
final String title = escapeEventString(prefix + event.getTitle());
final String text = escapeEventString(event.getText());
builder.append(Message.Type.EVENT.toString())
.append("{")
.append(getUtf8Length(title))
.append(",")
.append(getUtf8Length(text))
.append("}:")
.append(title)
.append("|");
if (text != null) {
builder.append(text);
}
eventMap(event, builder);
tagString(eventTags, builder);
builder.append('\n');
}
});
this.telemetry.incrEventsSent(1);
}
private static String escapeEventString(final String title) {
if (title == null) {
return null;
}
return title.replace("\n", "\\n");
}
private int getUtf8Length(final String text) {
if (text == null) {
return 0;
}
return text.getBytes(UTF_8).length;
}
/**
* Records a run status for the specified named service check.
*
* <p>This method is a DataDog extension, and may not work with other servers.</p>
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param sc
* the service check object
*/
@Override
public void recordServiceCheckRun(final ServiceCheck sc) {
statsDProcessor.send(new AlphaNumericMessage(Message.Type.SERVICE_CHECK, "") {
@Override public void writeTo(StringBuilder sb) {
// see http://docs.datadoghq.com/guides/dogstatsd/#service-checks
sb.append(Message.Type.SERVICE_CHECK.toString())
.append("|")
.append(sc.getName())
.append("|")
.append(sc.getStatus());
if (sc.getTimestamp() > 0) {
sb.append("|d:").append(sc.getTimestamp());
}
if (sc.getHostname() != null) {
sb.append("|h:").append(sc.getHostname());
}
tagString(sc.getTags(), sb);
if (sc.getMessage() != null) {
sb.append("|m:").append(sc.getEscapedMessage());
}
sb.append('\n');
}
});
this.telemetry.incrServiceChecksSent(1);
}
/**
* Updates and returns tags completed with the entityID tag if needed.
*
* @param tags the current constant tags list
*
* @param entityID the entityID string provided by argument
*
* @return true if tags was modified
*/
private static boolean updateTagsWithEntityID(final List<String> tags, String entityID) {
// Support "dd.internal.entity_id" internal tag.
if (entityID == null || entityID.trim().isEmpty()) {
// if the entityID parameter is null, default to the environment variable
entityID = System.getenv(DD_ENTITY_ID_ENV_VAR);
}
if (entityID != null && !entityID.trim().isEmpty()) {
final String entityTag = ENTITY_ID_TAG_NAME + ":" + entityID;
return tags.add(entityTag);
}
return false;
}
/**
* Convenience method equivalent to {@link #recordServiceCheckRun(ServiceCheck sc)}.
*/
@Override
public void serviceCheck(final ServiceCheck sc) {
recordServiceCheckRun(sc);
}
@Override
public void recordSetValue(final String aspect, final String val, final String... tags) {
// documentation is light, but looking at dogstatsd source, we can send string values
// here instead of numbers
statsDProcessor.send(new AlphaNumericMessage(aspect, Message.Type.SET, val, tags) {
protected void writeValue(StringBuilder builder) {
builder.append(getValue());
}
@Override protected final void writeTo(StringBuilder builder) {
builder.append(prefix).append(aspect).append(':');
writeValue(builder);
builder.append('|').append(type);
tagString(this.tags, builder);
builder.append('\n');
}
});
}
protected boolean isInvalidSample(double sampleRate) {
return sampleRate != 1 && ThreadLocalRandom.current().nextDouble() > sampleRate;
}
}
|
package com.witchworks.common.block.tile;
import com.witchworks.api.KettleRegistry;
import com.witchworks.api.recipe.ItemValidator;
import com.witchworks.api.recipe.KettleItemRecipe;
import com.witchworks.api.ritual.RitualHolder;
import com.witchworks.client.fx.ParticleF;
import com.witchworks.common.WitchWorks;
import com.witchworks.common.core.net.PacketHandler;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.potion.PotionUtils;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;
import javax.annotation.Nullable;
import java.awt.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static net.minecraftforge.fluids.Fluid.BUCKET_VOLUME;
@SuppressWarnings("WeakerAccess")
public class TileKettle extends TileFluidInventory implements ITickable {
private final String TAG_HEAT = "heat";
private final String TAG_RGB = "rgb";
private final String TAG_MODE = "mode";
private final String TAG_INGREDIENTS = "ingredients";
private final String TAG_CONTAINER = "container";
private final KettleFluid inv = tank();
private int rgb = -14532558;
private RitualHolder ritual;
private Mode mode = Mode.NORMAL;
private ItemStack[] ingredients = new ItemStack[64];
private ItemStack container;
private int heat;
private int ticks;
@SuppressWarnings("ConstantConditions")
public void collideItem(EntityItem entityItem) {
final ItemStack dropped = entityItem.getEntityItem();
if (dropped == null || entityItem.isDead)
return;
if (inv.hasFluid()) {
if (!inv.hasFluid(FluidRegistry.LAVA)) {
boolean splash = false;
if (isBoiling()) {
splash = recipeDropLogic(dropped);
}
if (splash)
play(SoundEvents.ENTITY_GENERIC_SPLASH, 0.5F, 0.5F);
} else {
play(SoundEvents.BLOCK_LAVA_EXTINGUISH, 1F, 1F);
entityItem.setDead();
return;
}
dropped.setCount(0);
entityItem.setDead();
}
}
public boolean recipeDropLogic(ItemStack dropped) {
switch (mode) {
case NORMAL:
return processingLogic(dropped)
|| (inv.hasFluid(FluidRegistry.WATER) && acceptIngredient(dropped));
case POTION:
return false;
case CUSTOM:
return false;
default:
}
return false;
}
public boolean useKettle(EntityPlayer player, EnumHand hand, @Nullable ItemStack heldItem) {
if (!world.isRemote) {
if (heldItem == null) {
if (getContainer() != null && mode != Mode.RITUAL) {
giveItem(player, hand, null, getContainer());
setContainer(null);
} else if (inv.isFull() && hasIngredients() && mode != Mode.RITUAL) {
itemRitualLogic();
}
return true;
}
//Held Item is not null
if (heldItem.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null)) {
handleLiquid(heldItem.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null));
} else if (heldItem.getItem() == Items.POTIONITEM && PotionUtils.getEffectsFromStack(heldItem).isEmpty()) {
int level = inv.getFluidAmount();
if (level < BUCKET_VOLUME && (inv.getFluid() == null || inv.hasFluid(FluidRegistry.WATER))) {
play(SoundEvents.ITEM_BUCKET_FILL, 1F, 1F);
giveItem(player, hand, heldItem, new ItemStack(Items.GLASS_BOTTLE));
FluidStack fluidStack = new FluidStack(FluidRegistry.WATER, 250);
inv.fill(fluidStack, true);
}
} else if (heldItem.getItem() == Items.GLASS_BOTTLE) {
//TODO: Add Potion Logic here
} else if (getContainer() == null) {
ItemStack copy = heldItem.copy();
copy.setCount(1);
setContainer(copy);
giveItem(player, hand, heldItem, null);
}
}
return true;
}
private void handleLiquid(IFluidHandler handler) {
if (inv.isEmpty()) {
FluidStack drain = handler.drain(BUCKET_VOLUME, false);
if (drain != null && drain.amount <= BUCKET_VOLUME) {
handler.drain(drain.amount, true);
inv.setFluid(drain);
onLiquidChange();
play(drain.getFluid().getEmptySound(), 1F, 1F);
}
} else {
if (inv.isFull()) {
FluidStack fill = inv.drain(BUCKET_VOLUME, false);
FluidStack compare = handler.drain(BUCKET_VOLUME, false);
int filled = handler.fill(fill, false);
if (fill != null && (compare == null || fill.isFluidEqual(compare)) && filled <= BUCKET_VOLUME) {
handler.fill(fill, true);
inv.drain(filled, true);
play(fill.getFluid().getEmptySound(), 1F, 1F);
}
} else {
FluidStack drain = handler.drain(BUCKET_VOLUME, false);
if (drain != null && drain.isFluidEqual(inv.getFluid()) && drain.amount <= BUCKET_VOLUME) {
handler.drain(drain.amount, true);
inv.fill(drain, true);
play(drain.getFluid().getFillSound(), 1F, 1F);
}
}
}
}
//FIXME To work on later. Fucking screwed up sleep. There is probably an error here I bet.
private void giveItem(EntityPlayer player, EnumHand hand, @Nullable ItemStack heldItem, @Nullable ItemStack toGive) {
if (heldItem == null) heldItem.shrink(0);
{
player.setHeldItem(hand, toGive);
} (!player.inventory.addItemStackToInventory(toGive)) {
player.dropItem(toGive, false);
} (player instanceof EntityPlayerMP) {
((EntityPlayerMP) player).sendContainerToPlayer(player.inventoryContainer);
}
}
@Override
public void update() {
if (!world.isRemote && ticks % 2 == 0) {
double x = getPos().getX();
double y = getPos().getY();
double z = getPos().getZ();
AxisAlignedBB box = new AxisAlignedBB(x, y, z, x + 1, y + 0.7D, z + 1);
final List<EntityItem> entityItemList = world.getEntitiesWithinAABB(EntityItem.class, box);
entityItemList.forEach(this::collideItem);
}
if (inv.hasFluid()) {
if (!inv.hasFluid(FluidRegistry.LAVA)) {
if (isBoiling()) {
handleParticles();
if (ticks % 5 == 0 && world.rand.nextInt(15) == 0) {
play(SoundEvents.BLOCK_LAVA_AMBIENT, 0.1F, 1F);
}
}
} else if (ticks % 5 == 0 && world.rand.nextInt(20) == 0) {
play(SoundEvents.BLOCK_LAVA_AMBIENT, 1F, 1F);
}
}
if (ticks % 20 == 0) {
handleHeat();
}
if (!world.isRemote && mode == Mode.RITUAL && ritual != null) {
handleRitual();
}
++ticks;
}
private void handleParticles() {
if (world.rand.nextInt(10) == 0) {
float x = getPos().getX();
float z = getPos().getZ();
for (int i = 0; i < 4; i++) {
final float posX = x + MathHelper.clamp(world.rand.nextFloat(), 0.2F, 0.9F);
final float posY = getParticleLevel();
final float posZ = z + MathHelper.clamp(world.rand.nextFloat(), 0.2F, 0.9F);
WitchWorks.proxy.spawnParticle(ParticleF.CAULDRON_BUBBLE, posX, posY, posZ, 0.0D, 0.01D, 0.0D, rgb);
}
}
if (hasIngredients() && ticks % 2 == 0) {
final float x = getPos().getX() + MathHelper.clamp(world.rand.nextFloat(), 0.2F, 0.9F);
float y = getParticleLevel();
final float z = getPos().getZ() + MathHelper.clamp(world.rand.nextFloat(), 0.2F, 0.9F);
WitchWorks.proxy.spawnParticle(ParticleF.SPARK, x, y, z, 0.0D, 0.1D, 0.0D);
}
}
private void handleHeat() {
boolean aboveFire = world.getBlockState(getPos().down()).getMaterial() == Material.FIRE;
if (aboveFire && inv.getFluidAmount() > 0 && heat < 10) {
++heat;
} else if ((!aboveFire || !(inv.getFluidAmount() > 0)) && heat > 0) {
--heat;
}
}
@SuppressWarnings("unchecked")
private void handleRitual() {
if (!ritual.isFail()) {
ritual.update(this);
} else {
failHorribly();
}
}
@Override
void writeDataNBT(NBTTagCompound cmp) {
saveItems(cmp);
cmp.setInteger(TAG_HEAT, heat);
cmp.setInteger(TAG_RGB, rgb);
cmp.setString(TAG_MODE, mode.name());
if (ritual != null) {
ritual.writeNBT(cmp);
}
}
private void saveItems(NBTTagCompound cmp) {
NBTTagList nbttaglist = new NBTTagList();
for (int i = 0; i < ingredients.length; ++i) {
if (ingredients[i] != null) {
NBTTagCompound tag = new NBTTagCompound();
tag.setByte("slot", (byte) i);
ingredients[i].writeToNBT(tag);
nbttaglist.appendTag(tag);
}
}
cmp.setTag(TAG_INGREDIENTS, nbttaglist);
if (container != null) {
NBTTagCompound tag = new NBTTagCompound();
container.writeToNBT(tag);
cmp.setTag(TAG_CONTAINER, tag);
}
}
@Override
void readDataNBT(NBTTagCompound cmp) {
loadItems(cmp);
heat = cmp.getInteger(TAG_HEAT);
setColorRGB(cmp.getInteger(TAG_RGB));
setMode(Mode.valueOf(cmp.getString(TAG_MODE)));
if (cmp.hasKey("ritual_data")) {
ritual = RitualHolder.newInstance();
ritual.readNBT(cmp);
}
}
private void loadItems(NBTTagCompound cmp) {
NBTTagList nbttaglist = cmp.getTagList(TAG_INGREDIENTS, 10);
ingredients = new ItemStack[64];
for (int i = 0; i < nbttaglist.tagCount(); ++i) {
NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i);
int j = nbttagcompound.getByte("slot");
if (j >= 0 && j < ingredients.length) {
this.ingredients[j] = ItemStack.loadItemStackFromNBT(nbttagcompound);
}
}
if (cmp.hasKey(TAG_CONTAINER)) {
NBTTagCompound tag = cmp.getCompoundTag(TAG_CONTAINER);
container = ItemStack.loadItemStackFromNBT(tag);
} else {
container = null;
}
}
@SuppressWarnings("ConstantConditions")
@Override
public void onLiquidChange() {
ingredients = new ItemStack[64];
mode = Mode.NORMAL;
ritual = null;
Fluid fluid = inv.getInnerFluid();
if (fluid == FluidRegistry.WATER) {
setColorRGB(-14532558);
} else if (fluid != null) {
setColorRGB(fluid.getBlock().getMapColor(null).colorValue);
}
if (!world.isRemote)
PacketHandler.updateToNearbyPlayers(world, pos);
}
public boolean acceptIngredient(ItemStack stack) {
if (ingredients[ingredients.length - 1] == null) {
addIngredient(stack);
final float hue = world.rand.nextFloat();
final float saturation = (world.rand.nextInt(2000) + 1000) / 7000f;
final float luminance = 0.25f;
setColorRGB(Color.getHSBColor(hue, saturation, luminance).getRGB());
PacketHandler.updateToNearbyPlayers(world, pos);
return true;
}
return false;
}
public void addIngredient(ItemStack stack) {
for (int i = 0; i < ingredients.length; i++) {
if (ingredients[i] == null) {
ingredients[i] = stack.copy();
stack.shrink(0);
break;
}
}
}
public boolean isBoiling() {
return heat == 10;
}
public boolean hasIngredients() {
return ingredients[0] != null;
}
public int getColorRGB() {
return rgb;
}
public void setColorRGB(int rgbIn) {
this.rgb = rgbIn;
}
public float getParticleLevel() {
float level = (float) inv.getFluidAmount() / (Fluid.BUCKET_VOLUME * 2F);
return getPos().getY() + 0.1F + level;
}
@Nullable
public ItemStack getContainer() {
return container;
}
public void setContainer(@Nullable ItemStack container) {
this.container = container;
world.updateComparatorOutputLevel(pos, world.getBlockState(pos).getBlock());
PacketHandler.updateToNearbyPlayers(world, pos);
}
public void setMode(Mode mode) {
this.mode = mode;
markDirty();
}
public void setRitual(RitualHolder ritual) {
this.ritual = ritual;
markDirty();
}
@SuppressWarnings("ConstantConditions")
public boolean processingLogic(ItemStack stack) {
if (!isBoiling() || hasIngredients() || stack.getCount() > 64) return false;
Map<Item, ItemValidator<ItemStack>> processing = KettleRegistry.getKettleProcessing(inv.getInnerFluid());
if (processing != null && processing.containsKey(stack.getItem())) {
ItemValidator<ItemStack> validator = processing.get(stack.getItem());
Optional<ItemStack> optional = validator.getMatchFor(stack);
if (optional.isPresent()) {
ItemStack out = optional.get().copy();
if (stack.isItemDamaged() && out.isItemStackDamageable())
out.setItemDamage(stack.getItemDamage());
out.shrink(0);
int fluid = inv.getFluidAmount();
int taken = 0;
if (stack.stackSize <= 16) {
taken = 250;
out.stackSize = stack.stackSize;
stack.stackSize = 0;
} else {
while (stack.stackSize > 0 && taken <= fluid) {
--stack.stackSize;
++out.stackSize;
if (out.stackSize % 16 == 0)
taken += 250;
}
}
if (out.stackSize > 0) {
final double x = getPos().getX();
final double y = getPos().getY() + 1D;
final double z = getPos().getZ();
final EntityItem item = new EntityItem(world, x + 0.5D, y, z + 0.5D, out);
item.motionX = world.rand.nextDouble() * 2 - 1;
item.motionZ = world.rand.nextDouble() * 2 - 1;
item.motionY = 0.1D;
item.setPickupDelay(0);
world.spawnEntity(item);
play(SoundEvents.BLOCK_FIRE_EXTINGUISH, 1F, 1F);
for (int i = 0; i < 4; i++) {
PacketHandler.spawnParticle(ParticleF.STEAM, world, x + world.rand.nextFloat(), getParticleLevel(), z + world.rand.nextFloat(), 5, 0, 0, 0);
}
inv.drain(taken, true);
return true;
}
}
}
return false;
}
@SuppressWarnings("unchecked")
public void itemRitualLogic() {
Optional<KettleItemRecipe> optional = KettleRegistry.getKettleItemRituals().stream().filter(
i -> i.matches(ingredients)
).findAny();
if (optional.isPresent()) {
KettleItemRecipe recipe = optional.get();
setRitual(new RitualHolder<>(recipe.getRitual()));
if (ritual.canPerform(this, world, getPos())) {
setMode(Mode.RITUAL);
markDirty();
} else {
failHorribly();
}
}
}
public void failHorribly() {
play(SoundEvents.ENTITY_GENERIC_EXPLODE, 1F, 1F);
particleServerSide(EnumParticleTypes.EXPLOSION_HUGE, 0.5, 0.5, 0.5, 0, 0, 0, 5);
inv.setFluid(null);
onLiquidChange();
world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(getPos()).expandXyz(2))
.forEach(entity -> entity.attackEntityFrom(DamageSource.MAGIC, ingredients.length / 2));
}
public enum Mode {
NORMAL,
RITUAL,
POTION,
CUSTOM
}
}
|
package com.zaliczenie.projekt;
import javafx.application.Platform;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.fxml.Initializable;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
public class MainWindowController implements Initializable{
// @FXML
// private Button chooseImageFile;
// @FXML
// private Button chooseImageFolder;
// @FXML
// private Button searchImagesCopies;
// @FXML
// private MenuItem removeFileOption;
@FXML
private TextField imagePathField;
@FXML
private TextField imageFolderPathField;
@FXML
private ListView<String> imageCopiesList;
DuplicatesModel model = new DuplicatesModel();
@Override
public void initialize(URL location, ResourceBundle resources) {
imageCopiesList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
imageCopiesList.itemsProperty().bind(model.getListProperty());
}
@FXML
public void chooseImageFileOnClick(ActionEvent actionEvent) {
try {
final FileChooser chooser = ChooserComponentFactory.CreateFileChooser("Choose your directory", ExtensionFilterFactory.GetFiltersForImages());
final File imageFile = chooser.showOpenDialog(null);
if(imageFile != null)
imagePathField.setText(imageFile.getAbsolutePath());
}
catch (Exception e) {
System.out.println(e.toString());
}
}
@FXML
public void chooseImageFolderOnClick(ActionEvent actionEvent) {
try {
final DirectoryChooser chooser = ChooserComponentFactory.CreateDirectoryChooser("Choose your directory");
final File imageFolder = chooser.showDialog(null);
if (imageFolder != null)
imageFolderPathField.setText(imageFolder.getAbsolutePath());
}
catch (Exception e) {
System.out.println(e.toString());
}
}
@FXML
public void searchImagesCopiesOnClick(ActionEvent actionEvent) {
try {
final File patternFile = new File(imagePathField.getText());
final File imageDirectory = new File(imageFolderPathField.getText());
ImageDuplicateFinder finder = new ImageDuplicateFinder(new ImageDuplicateChecker());
List<File> listFile = finder.findDuplicates(patternFile, imageDirectory);
model.updateDuplicateList(listFile);
}
catch (Exception e) {
System.out.println(e.toString());
}
}
@FXML
public void removeFileOptionOnClick(ActionEvent actionEvent) {
model.deleteDuplicates(imageCopiesList.getSelectionModel().getSelectedIndices());
}
@FXML
public void closeApplication(ActionEvent actionEvent) {
Platform.exit();
System.exit(0);
}
@FXML
public void showAboutInfo(ActionEvent actionEvent) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("O programie");
alert.setHeaderText(null);
alert.setContentText("To jest proggram będący projektem zaliczeniowym.\nAutor: Maria Kępa");
alert.showAndWait();
}
}
|
package com.zx.sms.session.cmpp;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import java.nio.channels.ClosedChannelException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zx.sms.codec.cmpp.msg.CmppActiveTestRequestMessage;
import com.zx.sms.codec.cmpp.msg.Message;
import com.zx.sms.connect.manager.CMPPEndpointManager;
import com.zx.sms.connect.manager.EndpointConnector;
import com.zx.sms.connect.manager.EventLoopGroupFactory;
import com.zx.sms.connect.manager.cmpp.CMPPEndpointEntity;
/**
* @author Lihuanghe(18852780@qq.com)
*/
public class SessionStateManager extends ChannelHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(SessionStateManager.class);
private final Logger errlogger;
/**
* @param entity
* Session
* @param storeMap
* resp
* @param preSend
*
*/
public SessionStateManager(CMPPEndpointEntity entity, Map<Long, Message> storeMap, Map<Long, Message> preSend) {
this.entity = entity;
windowSize = entity.getWindows();
if (windowSize == 0) {
windows = null;
} else {
windows = new Semaphore(windowSize);
}
errlogger = LoggerFactory.getLogger(entity.getId());
this.storeMap = storeMap;
this.preSend = preSend;
}
private long msgReadCount = 0;
private long msgWriteCount = 0;
private CMPPEndpointEntity entity;
private final int windowSize;
private Semaphore windows;
private final ConcurrentHashMap<Long, Entry> msgRetryMap = new ConcurrentHashMap<Long, Entry>();
/**
* respMap.
*/
private final Map<Long, Message> storeMap;
private Map<Long, Message> preSend;
private ConcurrentLinkedQueue<Runnable> waitWindowQueue = new ConcurrentLinkedQueue<Runnable>();
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
logger.warn("Connection closed. channel:{}", ctx.channel());
for (Map.Entry<Long, Entry> entry : msgRetryMap.entrySet()) {
final Long key = entry.getKey();
Entry en = cancelRetry(key, ctx.channel());
EndpointConnector conn = CMPPEndpointManager.INS.getEndpointConnector(entity);
if (conn == null)
break;
Channel ch = conn.fetch();
if (ch != null) {
ch.write(en.request);
logger.debug("current channel {} is closed.send requestMsg from other channel {} which is active.", ctx.channel(), ch);
}
}
if (windowSize != 0) {
int avab = windows.availablePermits();
if (avab < windowSize) {
try {
windows.release(windowSize - avab);
} catch (Exception ex) {
logger.warn("window release failed .", ex);
}
}
}
ctx.fireChannelInactive();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
msgReadCount++;
if (msg instanceof Message) {
final Message message = (Message) msg;
message.setLifeTime(entity.getLiftTime());
// resp
if (!isRequestMsg(message)) {
storeMap.remove(message.getHeader().getSequenceId());
cancelRetry(message.getHeader().getSequenceId(), ctx.channel());
}
}
ctx.fireChannelRead(msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof Message) {
if (((Message) msg).isTerminationLife()) {
errlogger.error("Msg Life over .{}", msg);
promise.setFailure(new RuntimeException("Msg Life over"));
return;
}
if (isRequestMsg((Message) msg)) {
// Response60,
writeWithWindow(ctx, (Message) msg, promise);
} else {
// Response
ctx.write(msg, promise);
}
} else {
// Message
ctx.write(msg, promise);
}
}
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt == SessionState.Connect) {
preSendMsg(ctx);
}
ctx.fireUserEventTriggered(evt);
}
private boolean writeWithWindow(final ChannelHandlerContext ctx, final Message message, final ChannelPromise promise) {
boolean acquired = false;
try {
acquired = (windows == null ? true : windows.tryAcquire(0, TimeUnit.SECONDS));
if (acquired) {
safewrite(ctx, message, promise);
} else {
waitWindowQueue.offer(new Runnable() {
@Override
public void run() {
safewrite(ctx, message, promise);
}
});
}
} catch (InterruptedException e) {
logger.error("windows acquire interrupted: ", e.getCause() != null ? e.getCause() : e);
}
return acquired;
}
private void scheduleRetryMsg(final ChannelHandlerContext ctx, final Message message, final ChannelPromise promise) {
long seq = message.getHeader().getSequenceId();
Entry entry = msgRetryMap.get(seq);
if (entry != null && entity.getMaxRetryCnt() > 1) {
Future<?> future = EventLoopGroupFactory.INS.getMsgResend().scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
int times = message.incrementAndGetRequests();
logger.debug("retry Send Msg : {}", message);
if (times > entity.getMaxRetryCnt()) {
cancelRetry(message.getHeader().getSequenceId(), ctx.channel());
storeMap.remove(message.getHeader().getSequenceId());
// TODO 3
logger.error("retry send msg {} timescancel retry task", times);
errlogger.error("RetryFailed: {}", message);
if (message instanceof CmppActiveTestRequestMessage) {
ctx.close();
logger.error("retry send CmppActiveTestRequestMessage 3 times,the connection may die.close it");
}
} else {
msgWriteCount++;
ctx.writeAndFlush(message, ctx.newPromise());
}
} catch (Throwable e) {
logger.error("retry send Msg Error.", e);
}
}
}, entity.getRetryWaitTimeSec(), entity.getRetryWaitTimeSec(), TimeUnit.SECONDS);
entry.future = future;
// resp,respmsgRetryMapentry remove
if (msgRetryMap.get(seq) == null) {
future.cancel(true);
}
} else if (entry == null) {
// respentry
logger.warn("receive seq {} not exists in msgRetryMap,maybe response received before create retrytask .", seq);
}
}
private Entry cancelRetry(Long seq, Channel channel) {
Entry entry = msgRetryMap.remove(seq);
if (entry != null && entry.future != null) {
entry.future.cancel(true);
}
if (windows != null) {
if (channel != null && channel.isActive() && !waitWindowQueue.isEmpty()) {
Runnable task = waitWindowQueue.poll();
if (task != null) {
EventLoopGroupFactory.INS.getWaitWindow().submit(task);
}
} else {
windows.release();
}
}
return entry;
}
private boolean isRequestMsg(Message msg) {
long commandId = msg.getHeader().getCommandId();
return (commandId & 0x80000000L) == 0L;
}
private void preSendMsg(ChannelHandlerContext ctx) {
if (preSend != null && preSend.size() > 0) {
for (Map.Entry<Long, Message> entry : preSend.entrySet()) {
Long key = entry.getKey();
Message msg = entry.getValue();
if (msg.isTerminationLife()) {
errlogger.error("Msg Life is Over. {}", msg);
continue;
}
if (msg != null) {
if (entity.isReSendFailMsg()) {
logger.debug("Send last failed msg . {}", msg);
storeMap.remove(key);
writeWithWindow(ctx, msg, ctx.newPromise());
} else {
storeMap.remove(key);
errlogger.warn("msg send may not success. {}", msg);
}
}
}
preSend.clear();
preSend = null;
}
}
/**
* msg,
*/
private void safewrite(ChannelHandlerContext ctx, final Message message, ChannelPromise promise) {
if (ctx.channel().isActive()) {
final Long seq = message.getHeader().getSequenceId();
message.incrementAndGetRequests();
msgWriteCount++;
// ,msgmapretryTaskresp
msgRetryMap.put(seq, new Entry(message));
storeMap.put(seq, message);
ctx.write(message, promise);
scheduleRetryMsg(ctx, message, promise);
ctx.flush();
} else {
if (promise != null && (!promise.isDone()))
promise.setFailure(new ClosedChannelException());
}
}
private class Entry {
// future
volatile Future future;
Message request;
Entry(Message request) {
this.request = request;
}
}
}
|
package de.cosmocode.palava.security;
/**
* Static constant holder class for config key names.
*
* @author Tobias Sarnowski
*/
public final class SecurityConfig {
public static final String PREFIX = "security.";
public static final String PASSPHRASE_LENGTH = PREFIX + "passphrase.length";
private SecurityConfig() {
}
}
|
package de.dynamobeuth.multiscreen;
abstract public class ScreenController {
private ScreenManager screenManager;
// private Application application;
// public void setApplication(Application application) {
// this.application = application;
// public Application getApplication() {
// return application;
public void setScreenManager(ScreenManager manager) {
this.screenManager = manager;
}
protected ScreenManager getScreenManager() {
return screenManager;
}
/**
* Will be called once after initialize() and after application and screenManager were injected
*/
protected void prepare() {
}
/**
* Will be called once when the screen is shown for the first time
* and just before the screen is added to its root and before possible screen transition animations
*/
protected void onBeforeFirstShow() {
}
/**
* Will be called every time the screen is to be shown
* and just before the screen is added to its root and before possible screen transition animations
*/
protected void onBeforeShow() {
}
/**
* Will be called once when the screen is shown for the first time
* and when possible screen transition animations are just finished
*/
protected void onFirstShow() {
}
/**
* Will be called every time the screen is shown
* and when possible screen transition animations are just finished
*/
protected void onShow() {
}
// TODO: integration should be possible; wait for use-case before implementation
// public void beforeHide() {
// System.out.println("show game view");
// public void hide() {
// System.out.println("hide game view");
}
|
package de.retest.recheck.auth;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.keycloak.OAuth2Constants;
import com.auth0.jwk.JwkException;
import com.auth0.jwk.UrlJwkProvider;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
import kong.unirest.json.JSONObject;
import lombok.Cleanup;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class RetestAuthentication {
private static final String REALM = "customer";
private static final String URL = "https://sso.prod.cloud.retest.org/auth";
private static final String BASE_URL = URL + "/realms/" + REALM + "/protocol/openid-connect";
private static final String AUTH_URL = BASE_URL + "/auth";
private static final String TOKEN_URL = BASE_URL + "/token";
private static final String CERTS_URL = BASE_URL + "/certs";
private static final String LOGOUT_URL = BASE_URL + "/logout";
private static final String KID = "cXdlj_AlGVf-TbXyauXYM2XairgNUahzgOXHAuAxAmQ";
private DecodedJWT accessToken;
private final AuthenticationHandler handler;
private final String client;
private final JWTVerifier verifier;
public RetestAuthentication( final AuthenticationHandler handler, final String client ) {
this.handler = handler;
this.client = client;
verifier = getJwtVerifier();
}
private JWTVerifier getJwtVerifier() {
try {
final UrlJwkProvider provider = new UrlJwkProvider( URI.create( CERTS_URL ).toURL() );
final PublicKey publicKey = provider.get( KID ).getPublicKey();
return JWT.require( Algorithm.RSA256( (RSAPublicKey) publicKey, null ) ).build();
} catch ( final JwkException | MalformedURLException e ) {
throw new RuntimeException( "Error accessing keycloak JWK information", e );
}
}
public void authenticate() {
if ( handler.getOfflineToken() != null ) {
refreshTokens();
} else {
log.info( "No active token found, initiating authentication" );
login();
}
}
private void login() {
try {
final CallbackListener callback = new CallbackListener();
callback.start();
final String redirectUri = "http://localhost:" + callback.server.getLocalPort();
final String state = UUID.randomUUID().toString();
final URIBuilder builder = new URIBuilder( AUTH_URL );
builder.addParameter( "response_type", "code" );
builder.addParameter( "client_id", client );
builder.addParameter( "redirect_uri", redirectUri );
builder.addParameter( "state", state );
builder.addParameter( "scope", "offline_access" );
final URI loginUri = URI.create( builder.build().toString() );
handler.showWebLoginUri( loginUri );
callback.join();
if ( !state.equals( callback.result.getState() ) ) {
handler.loginFailed( new RuntimeException() );
}
if ( callback.result.getError() != null ) {
handler.loginFailed( new RuntimeException() );
}
if ( callback.result.getErrorException() != null ) {
handler.loginFailed( callback.result.getErrorException() );
}
final TokenBundle bundle = accessCodeToToken( callback.result.getCode(), redirectUri );
accessToken = verifier.verify( bundle.accessToken );
handler.loginPerformed( bundle.refreshToken );
} catch ( final InterruptedException | IOException | URISyntaxException e ) {
log.error( "Error during authentication", e );
Thread.currentThread().interrupt();
}
}
private TokenBundle accessCodeToToken( final String code, final String redirectUri ) {
final TokenBundle bundle = new TokenBundle();
final HttpResponse<JsonNode> response = Unirest.post( TOKEN_URL )
.field( "grant_type", "authorization_code" )
.field( "code", code )
.field( "client_id", client )
.field( "redirect_uri", redirectUri )
.asJson();
if ( response.isSuccess() ) {
final JSONObject object = response.getBody().getObject();
bundle.setAccessToken( object.getString( "access_token" ) );
bundle.setRefreshToken( object.getString( "refresh_token" ) );
}
return bundle;
}
@Data
private static class TokenBundle {
private String accessToken;
private String refreshToken;
}
public void logout() {
final String offlineToken = handler.getOfflineToken();
if ( offlineToken != null ) {
final HttpResponse<JsonNode> response = Unirest.post( LOGOUT_URL )
.field( "refresh_token", handler.getOfflineToken() )
.field( "client_id", client )
.asJson();
if ( response.isSuccess() ) {
handler.logoutPerformed();
} else {
handler.logoutFailed( new RuntimeException( response.getStatusText() ) );
}
} else {
log.error( "No offline token provided" );
}
}
private void refreshTokens() {
final Optional<DecodedJWT> refreshedToken = refreshAccessToken();
if ( refreshedToken.isPresent() ) {
accessToken = refreshedToken.get();
} else {
login();
}
}
public DecodedJWT getAccessToken() {
if ( !isAccessTokenValid() ) {
refreshTokens();
}
return accessToken;
}
private Optional<DecodedJWT> refreshAccessToken() {
final HttpResponse<JsonNode> response = Unirest.post( TOKEN_URL )
.field( "grant_type", "refresh_token" )
.field( "refresh_token", handler.getOfflineToken() )
.field( "client_id", client )
.asJson();
if ( response.isSuccess() ) {
final JSONObject object = response.getBody().getObject();
return Optional.of( verifier.verify( object.getString( "access_token" ) ) );
} else {
log.error( "Error retrieving access token: {}", response.getStatusText() );
return Optional.empty();
}
}
private boolean isAccessTokenValid() {
try {
final DecodedJWT verify = verifier.verify( accessToken );
return accessToken != null && verify != null;
} catch ( final JWTVerificationException exception ) {
log.info( "Current token is invalid, requesting new one" );
}
return false;
}
static KeycloakResult getRequestParameters( final String request ) {
final String url = "http://localhost/" + request.split( " " )[1];
final Map<String, String> parameters = URLEncodedUtils.parse( URI.create( url ), StandardCharsets.UTF_8 )
.stream()
.collect( Collectors.toMap( NameValuePair::getName, NameValuePair::getValue ) );
return KeycloakResult.builder()
.code( parameters.get( OAuth2Constants.CODE ) )
.error( parameters.get( OAuth2Constants.ERROR ) )
.errorDescription( parameters.get( "error-description" ) )
.state( parameters.get( OAuth2Constants.STATE ) )
.build();
}
private class CallbackListener extends Thread {
private final ServerSocket server;
private KeycloakResult result;
public CallbackListener() throws IOException {
server = new ServerSocket( 0 );
}
@Override
public void run() {
try ( Socket socket = server.accept() ) {
@Cleanup
final BufferedReader br = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
final String request = br.readLine();
result = getRequestParameters( request );
@Cleanup
final OutputStreamWriter out = new OutputStreamWriter( socket.getOutputStream() );
@Cleanup
final PrintWriter writer = new PrintWriter( out );
if ( result.getError() == null ) {
writer.println( "HTTP/1.1 302 Found" );
writer.println( "Location: " + TOKEN_URL.replace( "/token", "/delegated" ) );
} else {
writer.println( "HTTP/1.1 302 Found" );
writer.println( "Location: " + TOKEN_URL.replace( "/token", "/delegated?error=true" ) );
}
} catch ( final IOException e ) {
log.error( "Error during communication with sso.cloud.retest.org", e );
}
}
}
}
|
package edu.harvard.iq.dataverse;
import edu.harvard.iq.dataverse.authorization.Permission;
import edu.harvard.iq.dataverse.authorization.users.GuestUser;
import edu.harvard.iq.dataverse.authorization.users.User;
import javax.ejb.EJB;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
/**
*
* @author gdurand
*/
@ViewScoped
@Named
public class PermissionsWrapper {
@EJB
PermissionServiceBean permissionService;
@Inject
DataverseSession session;
public boolean canManagePermissions(DvObject dvo) {
User u = session.getUser() != null ? session.getUser() : GuestUser.get();
return dvo instanceof Dataverse ?
canManageDataversePermissions(u, (Dataverse) dvo) :
canManageDatasetPermissions(u, (Dataset) dvo);
}
public boolean canManageDatasetPermissions(User u, Dataset ds) {
return permissionService.userOn(u, ds).has(Permission.ManageDatasetPermissions);
}
public boolean canManageDataversePermissions(User u, Dataverse dv) {
return permissionService.userOn(u, dv).has(Permission.ManageDataversePermissions);
}
}
|
package fi.csc.microarray.analyser;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import fi.csc.microarray.messaging.message.ModuleDescriptionMessage;
import fi.csc.microarray.messaging.message.ModuleDescriptionMessage.Category;
import fi.csc.microarray.util.XmlUtil;
/**
* <p>One module in repository, corresponds to one (modulename)-module.xml file.</p>
*
* <p>Access is strictly synchronised, because all operations
* may lead to module or script updates if files on the disk have changed. To avoid
* deadlocking, dependencies must be kept one way: RepositoryModule never calls ToolRepository and
* ToolDescription never calls RepositoryModule.</p>
*
* @author Taavi Hupponen, Aleksi Kallio
*/
public class RepositoryModule {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(RepositoryModule.class);
private LinkedList<Category> categories = new LinkedList<Category>();
private LinkedHashSet<ToolDescription> descriptions = new LinkedHashSet<ToolDescription>();
private LinkedHashSet<String> supportedDescriptions = new LinkedHashSet<String>();
private LinkedHashSet<String> visibleDescriptions = new LinkedHashSet<String>();
private File moduleDir;
private File moduleFile;
private long moduleFileTimestamp;
private HashMap<String, ToolRuntime> runtimes;
private String summary = null;
private String moduleName = null;
public RepositoryModule(File moduleDir, File moduleFile, HashMap<String, ToolRuntime> runtimes) throws ParserConfigurationException, FileNotFoundException, SAXException, IOException {
this.moduleFile = moduleFile;
this.moduleDir = moduleDir;
this.runtimes = runtimes;
load();
}
public synchronized ModuleDescriptionMessage getModuleDescriptionMessage() {
// Check if up-to-date
reloadModuleIfNeeded();
// Construct description message using the current state
ModuleDescriptionMessage msg = new ModuleDescriptionMessage(moduleName);
for (Category category : categories) {
msg.addCategory(category);
}
return msg;
}
public synchronized ToolDescription getDescription(String id) {
// Check if up-to-date
reloadModuleIfNeeded();
// Find description
ToolDescription desc = findDescription(id);
// Return null if nothing is found
if (desc == null) {
return null;
}
// Check if description needs to be updated
if (desc != null && !desc.isUptodate()) {
updateDescription(desc);
logger.info("updated tool: " + desc.getID());
}
// Return the possibly updated description
return findDescription(id);
}
private ToolDescription findDescription(String id) {
// Always iterate over descriptions, because they can change their ID on the fly
for (ToolDescription description : descriptions) {
if (id.equals(description.getID())) {
return description;
}
}
// Matching description was not found
return null;
}
public synchronized boolean isSupportedDescription(String id) {
// Check if up-to-date
reloadModuleIfNeeded();
return supportedDescriptions.contains(id);
}
public synchronized File getModuleDir() {
return moduleDir;
}
public synchronized String getSummary() throws FileNotFoundException, SAXException, IOException, ParserConfigurationException {
// Check if up-to-date
reloadModuleIfNeeded();
return summary;
}
private synchronized void updateDescription(ToolDescription desc) {
// FIXME params should not be empty
HashMap<String, String> params = new HashMap<String, String>();
ToolDescription newDescription;
try {
newDescription = desc.getHandler().handle(moduleDir, desc.getToolFile().getName(), params);
} catch (AnalysisException e) {
// update failed, continue using the old one
return;
}
if (newDescription != null) {
newDescription.setUpdatedSinceStartup();
// name (id) of the tool has not changed
if (desc.getID().equals(newDescription.getID())) {
// replace the old description with the same name
descriptions.add(newDescription);
if (supportedDescriptions.contains(desc.getID())) {
supportedDescriptions.add(newDescription.getID());
}
if (visibleDescriptions.contains(desc.getID())) {
visibleDescriptions.add(newDescription.getID());
}
}
// name (id) of the tool has changed
else {
logger.warn("ID of the tool has changed, registering it with old and new name");
if (findDescription(newDescription.getID()) != null){
logger.warn("descriptions already contain a tool with the new name, ignoring the new tool");
return;
}
// add the tool with the new name
descriptions.add(newDescription);
if (supportedDescriptions.contains(desc.getID())) {
supportedDescriptions.add(newDescription.getID());
}
if (visibleDescriptions.contains(desc.getID())) {
visibleDescriptions.add(newDescription.getID());
}
}
}
}
/**
* Parses a module file and loads all tools listed in it.
*
* Disabled tools are not available in this analyser instance,
* but are available in some other instances running, so the
* client still has to be informed about them.
*
* @param moduleDir directory where module specification file and runtime specific tool directories are located in
* @param moduleFile module specification file
* @return summary of tool counts
*
* @throws FileNotFoundException
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
*/
private synchronized void load() throws FileNotFoundException, SAXException, IOException, ParserConfigurationException {
// Update timestamp, so that even if loading fails, we do not try to load again before the file has been changed (hopefully fixed)
moduleFileTimestamp = moduleFile.lastModified();
// Load module description file
Document document = XmlUtil.parseReader(new FileReader(moduleFile));
Element moduleElement = (Element)document.getElementsByTagName("module").item(0);
// Load and check module name
this.moduleName = moduleElement.getAttribute("name");
if (moduleName.isEmpty()) {
this.summary = "not loading a module without a name";
logger.warn(summary);
return;
}
// Initialise stats
int totalCount = 0;
int successfullyLoadedCount = 0;
int hiddenCount = 0;
int disabledCount = 0;
// Load categories and tools in them
for (Element categoryElement: XmlUtil.getChildElements(moduleElement, "category")) {
// Category name
String categoryName = categoryElement.getAttribute("name");
if (categoryName.isEmpty()) {
logger.warn("not loading a category without a name");
continue;
}
// Enabled or disabled status
boolean categoryDisabled = categoryElement.getAttribute("disabled").equals("true");
if (categoryDisabled) {
logger.info("not loading category " + categoryName + ": disabled");
continue;
}
// GUI color
String categoryColor = categoryElement.getAttribute("color");
if (categoryColor.isEmpty()) {
logger.warn("not loading category " + categoryName + ": no color");
continue;
}
// Category visibility
boolean categoryHidden = Boolean.valueOf(categoryElement.getAttribute("hidden"));
// Create and register the category
Category category = new Category(categoryName, categoryColor, categoryHidden);
categories.add(category);
// Load tools and add them to category
for (Element toolElement: XmlUtil.getChildElements(categoryElement, "tool")) {
totalCount++;
// Resource (script file name, Java class name, ...)
Element resourceElement = XmlUtil.getChildElement(toolElement, "resource");
if (resourceElement == null) {
logger.warn("not loading a tool without resource element");
continue;
}
String resource = resourceElement.getTextContent().trim();
if (resource == null || resource.isEmpty()) {
logger.warn("not loading a tool with empty resource element");
continue;
}
// Tool visibility
boolean toolDisabled = toolElement.getAttribute("disabled").equals("true");
boolean toolHidden = categoryHidden; // currently tools can be hidden only if their category is hidden
// Tool runtime
String runtimeName = toolElement.getAttribute("runtime");
ToolRuntime runtime = runtimes.get(runtimeName); // FIXME depends on repository!!!
if (runtime == null) {
logger.warn("not loading " + resource + ": runtime " + runtimeName + " not found");
continue;
}
// Tool parameters
boolean parametersOk = true;
HashMap<String, String> parameters = new HashMap<String, String>();
for (Element parameterElement : XmlUtil.getChildElements(toolElement, "parameter")) {
String parameterName = XmlUtil.getChildElement(parameterElement, "name").getTextContent().trim();
if (parameterName == null || parameterName.isEmpty()) {
logger.warn("parameter without a name");
parametersOk = false;
break;
}
String parameterValue = XmlUtil.getChildElement(parameterElement, "value").getTextContent().trim();
if (parameterValue == null) {
logger.warn("parameter without a value");
parametersOk = false;
break;
}
// This parameter is ok
parameters.put(parameterName, parameterValue);
}
if (!parametersOk) {
logger.warn("not loading " + resource + ": parameters not ok");
continue;
}
// Create the analysis description
ToolDescription description;
try {
description = runtime.getHandler().handle(moduleDir, resource, parameters);
// check for duplicates in this module
ToolDescription previousDescription = getDescription(description.getID());
if (previousDescription != null) {
logger.warn("not loading " + resource + ": tool with the same ID already exists in this module");
continue;
}
} catch (AnalysisException e) {
logger.warn("loading " + resource + " failed, could not create description", e);
continue;
}
// Register the tool
descriptions.add(description);
successfullyLoadedCount++;
// Set disabled if needed
String disabledStatus = "";
if (!runtime.isDisabled() && !toolDisabled) {
// Not disabled, add to supported descriptions list
supportedDescriptions.add(description.getID());
} else {
disabledStatus = " DISABLED";
disabledCount++;
}
// Add to category, which gets sent to the client
category.addTool(description.getSADL(), description.getHelpURL());
// Set hidden if needed
String hiddenStatus = "";
if (toolHidden) {
hiddenStatus = " HIDDEN";
hiddenCount++;
}
logger.info("loaded " + description.getID() + " " + description.getDisplayName() + " " +
description.getToolFile() + disabledStatus + hiddenStatus);
}
}
// Update summary
this.summary = "loaded " + moduleName + " " + successfullyLoadedCount + "/" + totalCount +
" tools, " + disabledCount + " disabled, " + hiddenCount + " hidden";
logger.info(summary);
}
private synchronized void reloadModuleIfNeeded() {
if (moduleFile.lastModified() > moduleFileTimestamp) {
// Clean everything
this.categories.clear();
this.descriptions.clear();
this.moduleName = null;
this.summary = null;
this.supportedDescriptions.clear();
this.visibleDescriptions.clear();
// Reload
try {
load();
} catch (Exception e) {
logger.error("reloading module " + moduleName + " failed", e);
}
}
}
}
|
package fr.wseduc.rbs.controllers;
import static fr.wseduc.rbs.BookingStatus.*;
import static fr.wseduc.rbs.Rbs.*;
import static org.entcore.common.http.response.DefaultResponseHandler.arrayResponseHandler;
import static org.entcore.common.http.response.DefaultResponseHandler.defaultResponseHandler;
import static org.entcore.common.http.response.DefaultResponseHandler.notEmptyResponseHandler;
import static org.entcore.common.sql.SqlResult.validResultHandler;
import static org.entcore.common.sql.SqlResult.validRowsResultHandler;
import static org.entcore.common.sql.SqlResult.validUniqueResultHandler;
import java.util.ArrayList;
import java.util.List;
import org.entcore.common.controller.ControllerHelper;
import org.entcore.common.service.VisibilityFilter;
import org.entcore.common.sql.Sql;
import org.entcore.common.sql.SqlConf;
import org.entcore.common.sql.SqlConfs;
import org.entcore.common.user.UserInfos;
import org.entcore.common.user.UserUtils;
import org.vertx.java.core.Handler;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import fr.wseduc.rbs.filters.TypeAndResourceAppendPolicy;
import fr.wseduc.rs.ApiDoc;
import fr.wseduc.rs.Delete;
import fr.wseduc.rs.Get;
import fr.wseduc.rs.Post;
import fr.wseduc.rs.Put;
import fr.wseduc.security.ActionType;
import fr.wseduc.security.ResourceFilter;
import fr.wseduc.security.SecuredAction;
import fr.wseduc.webutils.Either;
import fr.wseduc.webutils.http.Renders;
import fr.wseduc.webutils.request.RequestUtils;
public class BookingController extends ControllerHelper {
@Post("/resource/:id/booking")
@ApiDoc("Create booking of a given resource")
@SecuredAction(value = "rbs.contrib", type= ActionType.RESOURCE)
@ResourceFilter(TypeAndResourceAppendPolicy.class)
public void createBooking(final HttpServerRequest request) {
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
if (user != null) {
RequestUtils.bodyToJson(request, pathPrefix + "createBooking", new Handler<JsonObject>() {
@Override
public void handle(JsonObject object) {
final String id = request.params().get("id");
long resourceId = 0;
try {
resourceId = Long.parseLong(id);
} catch (NumberFormatException e) {
log.error("Invalid resourceId", e);
Renders.badRequest(request, "Invalid resourceId");
}
object.putNumber("status", CREATED.status());
SqlConf conf = SqlConfs.getConf(BookingController.class.getName());
/* Query :
* Unix timestamps are converted into postgresql timestamps.
* Check that there does not exist a validated booking that overlaps the new booking.
*/
StringBuilder query = new StringBuilder();
query.append("INSERT INTO ")
.append(conf.getSchema())
.append(conf.getTable())
.append("(resource_id, owner, booking_reason, status, start_date, end_date)")
.append(" SELECT ?, ?, ?, ?, to_timestamp(?), to_timestamp(?)");
query.append(" WHERE NOT EXISTS (")
.append("SELECT id FROM ")
.append(conf.getSchema())
.append(conf.getTable())
.append(" WHERE resource_id = ?")
.append(" AND status = " + VALIDATED.status())
.append(" AND (")
.append("( start_date >= to_timestamp(?) AND start_date < to_timestamp(?) )")
.append(" OR ( end_date > to_timestamp(?) AND end_date <= to_timestamp(?) )")
.append(")) RETURNING id;");
Object startDate = object.getValue("start_date");
Object endDate = object.getValue("end_date");
JsonArray values = new JsonArray();
// Values for the INSERT clause
values.add(resourceId)
.add(object.getValue("owner"))
.add(object.getValue("booking_reason"))
.add(object.getValue("status"))
.add(startDate)
.add(endDate);
// Values for the NOT EXISTS clause
values.add(resourceId)
.add(startDate)
.add(endDate)
.add(startDate)
.add(endDate);
Handler<Either<String, JsonObject>> handler = new Handler<Either<String, JsonObject>>() {
@Override
public void handle(Either<String, JsonObject> event) {
if (event.isRight()) {
if (event.right().getValue() != null && event.right().getValue().size() > 0) {
Renders.renderJson(request, event.right().getValue(), 200);
} else {
JsonObject error = new JsonObject()
.putString("error", "A validated booking overlaps the booking you tried to create.");
Renders.renderError(request, error);
}
} else {
JsonObject error = new JsonObject()
.putString("error", event.left().getValue());
Renders.renderJson(request, error, 400);
}
}
};
// Send query to eventbus
Sql.getInstance()
.prepared(
query.toString(),
values,
validUniqueResultHandler(handler));
}
});
} else {
log.debug("User not found in session.");
Renders.unauthorized(request);
}
}
});
}
// @Post("/resource/:id/booking/periodic")
// @ApiDoc("Create periodic booking of a given resource")
// @SecuredAction(value = "rbs.contrib", type= ActionType.RESOURCE)
// @ResourceFilter(TypeAndResourceAppendPolicy.class)
// public void createPeriodicBooking() {
private void addFieldToUpdate(StringBuilder sb, String fieldname, JsonObject object, JsonArray values){
if("start_date".equals(fieldname) || "end_date".equals(fieldname)){
sb.append(fieldname).append("= to_timestamp(?), ");
}
else {
sb.append(fieldname).append("= ?, ");
}
values.add(object.getValue(fieldname));
}
@Put("/resource/:id/booking/:bookingId")
@ApiDoc("Update booking")
@SecuredAction(value = "rbs.contrib", type= ActionType.RESOURCE)
@ResourceFilter(TypeAndResourceAppendPolicy.class)
public void updateBooking(final HttpServerRequest request){
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
if (user != null) {
RequestUtils.bodyToJson(request, pathPrefix + "updateBooking", new Handler<JsonObject>() {
@Override
public void handle(JsonObject object) {
String bookingId = request.params().get("bookingId");
SqlConf conf = SqlConfs.getConf(BookingController.class.getName());
// Query
JsonArray values = new JsonArray();
StringBuilder sb = new StringBuilder();
for (String fieldname : object.getFieldNames()) {
addFieldToUpdate(sb, fieldname, object, values);
}
StringBuilder query = new StringBuilder();
query.append("UPDATE ")
.append(conf.getSchema())
.append(conf.getTable())
.append(" SET " + sb.toString() + "modified = NOW()")
.append(" WHERE id = ?;");
values.add(bookingId);
// Send query to eventbus
Sql.getInstance()
.prepared(
query.toString(),
values,
validRowsResultHandler(notEmptyResponseHandler(request)));
}
});
} else {
log.debug("User not found in session.");
Renders.unauthorized(request);
}
}
});
}
@Put("/resource/:id/booking/:bookingId/process")
@ApiDoc("Validate or refuse booking")
@SecuredAction(value = "rbs.publish", type= ActionType.RESOURCE)
@ResourceFilter(TypeAndResourceAppendPolicy.class)
public void processBooking(final HttpServerRequest request){
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
if (user != null) {
RequestUtils.bodyToJson(request, pathPrefix + "processBooking", new Handler<JsonObject>() {
@Override
public void handle(JsonObject object) {
String bookingId = request.params().get("bookingId");
int newStatus = 0;
try {
newStatus = (int) object.getValue("status");
} catch (Exception e) {
log.error(e.getMessage());
Renders.renderError(request);
}
if (newStatus != VALIDATED.status()
&& newStatus != REFUSED.status()) {
Renders.badRequest(request, "Invalid status");
}
object.putString("moderator_id", user.getUserId());
// TODO : interdire la validation, s'il existe deja une demande validee
crudService.update(bookingId, object, user, notEmptyResponseHandler(request));
}
});
} else {
log.debug("User not found in session.");
Renders.unauthorized(request);
}
}
});
}
@Delete("/resource/:id/booking/:bookingId")
@ApiDoc("Delete booking")
@SecuredAction(value = "rbs.manager", type= ActionType.RESOURCE)
@ResourceFilter(TypeAndResourceAppendPolicy.class)
public void deleteBooking(final HttpServerRequest request){
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
if (user != null) {
String bookingId = request.params().get("bookingId");
crudService.delete(bookingId, user, defaultResponseHandler(request, 204));
} else {
log.debug("User not found in session.");
Renders.unauthorized(request);
}
}
});
}
@Get("/bookings")
@ApiDoc("List all bookings created by current user")
@SecuredAction("rbs.booking.list")
public void listUserBookings(final HttpServerRequest request) {
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
crudService.list(VisibilityFilter.OWNER, user, arrayResponseHandler(request));
}
});
}
@Get("/bookings/unprocessed")
@ApiDoc("List all bookings waiting to be processed by current user")
@SecuredAction("rbs.booking.list.unprocessed")
public void listUnprocessedBookings(final HttpServerRequest request){
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
@Override
public void handle(final UserInfos user) {
if (user != null) {
SqlConf conf = SqlConfs.getConf(BookingController.class.getName());
final List<String> groupsAndUserIds = new ArrayList<>();
groupsAndUserIds.add(user.getUserId());
if (user.getProfilGroupsIds() != null) {
groupsAndUserIds.addAll(user.getProfilGroupsIds());
}
// Query
StringBuilder query = new StringBuilder();
JsonArray values = new JsonArray();
query.append("SELECT b.* FROM ")
.append(conf.getSchema())
.append(conf.getTable() + " AS b")
.append(" INNER JOIN " + conf.getSchema() + RESOURCE_TABLE + " AS r")
.append(" ON b.resource_id = r.id")
.append(" INNER JOIN " + conf.getSchema() + RESOURCE_TYPE_TABLE + " AS t")
.append(" ON t.id = r.type_id")
.append(" LEFT JOIN " + conf.getSchema() + RESOURCE_TYPE_SHARE_TABLE + " AS ts")
.append(" ON t.id = ts.resource_id")
.append(" LEFT JOIN " + conf.getSchema() + RESOURCE_SHARE_TABLE + " AS rs")
.append(" ON r.id = rs.resource_id")
.append(" WHERE b.status = " + CREATED.status());
query.append(" AND (ts.member_id IN " + Sql.listPrepared(groupsAndUserIds.toArray()) + "");
for (String groupOruser : groupsAndUserIds) {
values.add(groupOruser);
}
query.append(" OR rs.member_id IN "+ Sql.listPrepared(groupsAndUserIds.toArray()));
for (String groupOruser : groupsAndUserIds) {
values.add(groupOruser);
}
query.append(" OR t.owner = ?");
values.add(user.getUserId());
query.append(" OR r.owner = ?");
values.add(user.getUserId());
query.append(");");
// Send query to event bus
Sql.getInstance().prepared(query.toString(), values,
validResultHandler(arrayResponseHandler(request)));
}
else {
log.debug("User not found in session.");
Renders.unauthorized(request);
}
}
});
}
// Pour afficher l'historique des reservations
// @Get("/bookings/all")
// @ApiDoc("List all bookings")
// @SecuredAction(value = "rbs.manage", type = ActionType.RESOURCE)
}
|
package frogcraftrebirth.common.lib.tile;
import ic2.api.energy.event.EnergyTileLoadEvent;
import ic2.api.energy.event.EnergyTileUnloadEvent;
import ic2.api.energy.tile.IEnergyTile;
import net.minecraftforge.common.MinecraftForge;
public abstract class TileEnergy extends TileFrog implements IEnergyTile {
private static transient boolean processingEnergyTileLoading = false;
private boolean isInEnergyNet;
@Override
public void invalidate() {
if (!getWorld().isRemote && isInEnergyNet) {
isInEnergyNet = false;
MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this));
}
super.invalidate();
}
@Override
public void validate() {
while (processingEnergyTileLoading) {
// This will ensure that chunk loading won't stuck
// I could not think about another way to prevent this happening
// This will definitely slow down chunk loading somehow,
// hope it won't slow it down too much
return;
}
if (!getWorld().isRemote && !isInEnergyNet) {
processingEnergyTileLoading = true;
MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this));
processingEnergyTileLoading = false;
isInEnergyNet = true;
}
}
public boolean hasBeenInEnergyNet() {
return this.isInEnergyNet;
}
}
|
package hudson.plugins.analysis.views;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.google.common.collect.Maps;
import hudson.model.Item;
import hudson.model.AbstractBuild;
import hudson.plugins.analysis.Messages;
import hudson.plugins.analysis.core.BuildResult;
import hudson.plugins.analysis.core.ResultAction;
import hudson.plugins.analysis.util.model.AnnotationContainer;
import hudson.plugins.analysis.util.model.DefaultAnnotationContainer;
import hudson.plugins.analysis.util.model.FileAnnotation;
/**
* Creates detail objects for the selected element of a annotation container.
*
* @author Ulli Hafner
*/
public class DetailFactory {
/** Default detail builder class. */
private static final DetailFactory DEFAULT_DETAIL_BUILDER = new DetailFactory();
/** Maps plug-ins to detail builders. */
private static Map<Class<? extends ResultAction<? extends BuildResult>>, DetailFactory> factories = Maps.newHashMap();
/**
* Creates a new detail builder.
*
* @param actionType
* the type of the action (i.e., the plug-in) to get the detail
* builder for
* @return the detail builder
*/
public static DetailFactory create(final Class<? extends ResultAction<? extends BuildResult>> actionType) {
if (factories.containsKey(actionType)) {
return factories.get(actionType);
}
return DEFAULT_DETAIL_BUILDER;
}
/**
* Sets the detail builder class to the specified value.
*
* @param actionType
* the type of the action (i.e., the plug-in) to set the detail
* builder for
* @param detailBuilder
* the value to set
*/
public static void addDetailBuilder(final Class<? extends ResultAction<? extends BuildResult>> actionType,
final DetailFactory detailBuilder) {
synchronized (factories) {
factories.put(actionType, detailBuilder);
}
}
/**
* Returns a detail object for the selected element of the specified
* annotation container. The details will include the new and fixed warnings
* trends as well as the errors report.
*
* @param link
* the link to identify the sub page to show
* @param owner
* the build as owner of the detail page
* @param container
* the annotation container to get the details for
* @param fixedAnnotations
* the annotations fixed in this build
* @param newAnnotations
* the annotations new in this build
* @param errors
* the errors in this build
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
* @param displayName
* the name of the selected object
* @return the dynamic result of this module detail view
*/
// CHECKSTYLE:OFF
public Object createTrendDetails(final String link, final AbstractBuild<?, ?> owner,
final AnnotationContainer container, final Collection<FileAnnotation> fixedAnnotations,
final Collection<FileAnnotation> newAnnotations, final Collection<String> errors,
final String defaultEncoding, final String displayName) {
// CHECKSTYLE:ON
if ("fixed".equals(link)) {
return createFixedWarningsDetail(owner, fixedAnnotations, defaultEncoding, displayName);
}
else if ("new".equals(link)) {
return new NewWarningsDetail(owner, this, newAnnotations, defaultEncoding, displayName);
}
else if ("error".equals(link)) {
return new ErrorDetail(owner, errors);
}
else if (link.startsWith("tab.new")) {
return createTabDetail(owner, newAnnotations, createGenericTabUrl(link), defaultEncoding);
}
else if (link.startsWith("tab.fixed")) {
return createTabDetail(owner, fixedAnnotations, createGenericTabUrl(link), defaultEncoding);
}
else {
return createDetails(link, owner, container, defaultEncoding, displayName);
}
}
/**
* Returns a detail object for the selected element of the specified
* annotation container.
*
* @param link
* the link to identify the sub page to show
* @param owner
* the build as owner of the detail page
* @param container
* the annotation container to get the details for
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
* @param displayName
* the name of the selected object
* @return the dynamic result of this module detail view
*/
public Object createDetails(final String link, final AbstractBuild<?, ?> owner, final AnnotationContainer container,
final String defaultEncoding, final String displayName) {
PriorityDetailFactory factory = new PriorityDetailFactory(this);
if (factory.isPriority(link)) {
return factory.create(link, owner, container, defaultEncoding, displayName);
}
else if (link.startsWith("module.")) {
return new ModuleDetail(owner, this, container.getModule(createHashCode(link, "module.")), defaultEncoding, displayName);
}
else if (link.startsWith("package.")) {
return new PackageDetail(owner, this, container.getPackage(createHashCode(link, "package.")), defaultEncoding, displayName);
}
else if (link.startsWith("file.")) {
return new FileDetail(owner, this, container.getFile(createHashCode(link, "file.")), defaultEncoding, displayName);
}
else if (link.startsWith("tab.")) {
return createTabDetail(owner, container.getAnnotations(), createGenericTabUrl(link), defaultEncoding);
}
else if (link.startsWith("source.")) {
owner.checkPermission(Item.WORKSPACE);
return new SourceDetail(owner, container.getAnnotation(StringUtils.substringAfter(link, "source.")), defaultEncoding);
}
else if (link.startsWith("category.")) {
DefaultAnnotationContainer category = container.getCategory(createHashCode(link, "category."));
return createAttributeDetail(owner, category, displayName, Messages.CategoryDetail_header(), defaultEncoding);
}
else if (link.startsWith("type.")) {
DefaultAnnotationContainer type = container.getType(createHashCode(link, "type."));
return createAttributeDetail(owner, type, displayName, Messages.TypeDetail_header(), defaultEncoding);
}
return null;
}
/**
* Creates a generic detail tab with the specified link.
*
* @param owner
* the build as owner of the detail page
* @param annotations
* the annotations to display
* @param displayName
* the name of the view
* @param header
* the bread crumb name
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
* @return the detail view
*/
protected AttributeDetail createAttributeDetail(final AbstractBuild<?, ?> owner, final DefaultAnnotationContainer annotations,
final String displayName, final String header, final String defaultEncoding) {
return new AttributeDetail(owner, this, annotations.getAnnotations(), defaultEncoding, displayName, header + " " + annotations.getName());
}
/**
* Creates a generic detail tab with the specified link.
*
* @param owner
* the build as owner of the detail page
* @param annotations
* the annotations to display
* @param url
* the URL for the details view
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
* @return the detail view
*/
protected TabDetail createTabDetail(final AbstractBuild<?, ?> owner, final Collection<FileAnnotation> annotations,
final String url, final String defaultEncoding) {
return new TabDetail(owner, this, annotations, url, defaultEncoding);
}
/**
* Creates a generic fixed warnings detail tab with the specified link.
*
* @param owner
* the build as owner of the detail page
* @param fixedAnnotations
* the annotations to display
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
* @param displayName
* the name of the view
* @return the detail view
*/
protected FixedWarningsDetail createFixedWarningsDetail(final AbstractBuild<?, ?> owner,
final Collection<FileAnnotation> fixedAnnotations, final String defaultEncoding,
final String displayName) {
return new FixedWarningsDetail(owner, this, fixedAnnotations, defaultEncoding, displayName);
}
/**
* Creates the actual URL from the synthetic link.
*
* @param link
* the link
* @return the actual URL
*/
private String createGenericTabUrl(final String link) {
return StringUtils.substringAfter(link, "tab.") + ".jelly";
}
/**
* Extracts the hash code from the given link stripping of the given prefix.
*
* @param link the whole link
* @param prefix the prefix to remove
*
* @return the hash code
*/
private int createHashCode(final String link, final String prefix) {
return Integer.parseInt(StringUtils.substringAfter(link, prefix));
}
}
|
package it.tylframework.vaadin.addon;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.util.BeanItem;
import it.tylframework.vaadin.addon.utils.Page;
import org.bson.types.ObjectId;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.beans.*;
import java.lang.reflect.Field;
import java.util.*;
import java.util.logging.Logger;
import static org.springframework.data.mongodb.core.query.Criteria.where;
public class MongoContainer<Bean>
//extends AbstractContainer
implements Container, Container.Ordered, Container.Indexed {
public static class Builder {
private final static int DEFAULT_PAGE_SIZE = 100;
private final MongoOperations mongoOps;
private Criteria mongoCriteria = new Criteria();
private Class<?> beanClass;
private boolean buffered = false;
private int pageSize = DEFAULT_PAGE_SIZE;
private Map<Object,Class<?>> ids = new HashMap<Object, Class<?>>();
public static MongoContainer.Builder with(final MongoOperations mongoOps) {
return new MongoContainer.Builder(mongoOps);
}
private Builder(final MongoOperations mongoOps) {
this.mongoOps = mongoOps;
}
public Builder forCriteria(final Criteria mongoCriteria) {
this.mongoCriteria = mongoCriteria;
return this;
}
public Builder withBeanClass(final Class<?> beanClass) {
this.beanClass = beanClass;
return this;
}
public Builder withPageSize(final int pageSize) {
this.pageSize = pageSize;
return this;
}
public Builder withProperty(Object id, Class<?> type) {
ids.put(id, type);
return this;
}
public Builder buffered() {
this.buffered = true;
return this;
}
public <Bean> MongoContainer<Bean> build() {
MongoContainer<Bean> mc;
if (buffered) {
mc = new BufferedMongoContainer<Bean>(mongoCriteria, mongoOps, (Class<Bean>) beanClass, pageSize);
} else {
mc = new MongoContainer<Bean>(mongoCriteria, mongoOps, (Class<Bean>) beanClass, pageSize);
}
for (Object id: ids.keySet()) {
mc.addContainerProperty(id, ids.get(id), null);
}
return mc;
}
}
protected static final String ID = "_id";
protected static final Logger log = Logger.getLogger("MongoContainer");
@Nonnull private Page<ObjectId> page;
protected final int pageSize;
protected final Criteria criteria;
protected final Query query;
protected final MongoOperations mongoOps;
protected final Class<Bean> beanClass;
protected final BeanDescriptor beanDescriptor;
protected final LinkedHashMap<String, PropertyDescriptor> propertyDescriptorMap;
MongoContainer(final Criteria criteria,
final MongoOperations mongoOps,
final Class<Bean> beanClass,
final int pageSize) {
this.criteria = criteria;
this.query = Query.query(criteria);
this.mongoOps = mongoOps;
this.beanClass = beanClass;
this.beanDescriptor = getBeanDescriptor(beanClass);
this.propertyDescriptorMap = getBeanPropertyDescriptor(beanClass);
this.pageSize = pageSize;
fetchPage(0, pageSize);
}
private DBCursor cursor() {
DBObject criteriaObject = criteria.getCriteriaObject();
DBObject projectionObject = new BasicDBObject(ID, true);
String collectionName = mongoOps.getCollectionName(beanClass);
DBCollection dbCollection = mongoOps.getCollection(collectionName);
// TODO: keep cursor around to possibly reuse
DBCursor cursor = dbCollection.find(criteriaObject, projectionObject);
return cursor;
}
private DBCursor cursorInRange(int skip, int limit) {
return cursor().skip(skip).limit(limit);
}
private void fetchPage(int offset, int pageSize) {
// TODO: keep cursor around to possibly reuse
DBCursor cursor = cursorInRange(offset, pageSize);
Page<ObjectId> newPage = new Page<ObjectId>(pageSize, offset, this.size());
for (int i = offset; cursor.hasNext(); i++)
newPage.set(i, (ObjectId) cursor.next().get(ID));
this.page = newPage;
}
static class BeanId { @Id public ObjectId _id; }
BeanDescriptor beanIdDescriptor = getBeanDescriptor(BeanId.class);
public BeanItem<Bean> getItem(Object o) {
assertIdValid(o);
final Bean document = mongoOps.findById(o, beanClass);
return new BeanItem<Bean>(document);
}
@Override
public Collection<?> getContainerPropertyIds() {
try {
return getVaadinPropertyIds(beanClass);
} catch (Exception e) { throw new Error(e); }
}
@Override
@Deprecated
public List<ObjectId> getItemIds() {
throw new UnsupportedOperationException("this expensive operation is unsupported");
// Query q = Query.query(criteria).fields().include(ID);
// List<BeanId> beans = mongoOps.find(q, beanClass);
// return new PropertyList<Id,Bean>(beans, beanDescriptor, "id");
}
@Override
public Property<?> getContainerProperty(Object itemId, Object propertyId) {
return getItem(itemId).getItemProperty(propertyId);
}
// return the data type of the given property id
@Override
public Class<?> getType(Object propertyId) {
PropertyDescriptor pd = propertyDescriptorMap.get(propertyId);
return pd == null? null: pd.getPropertyType();
}
@Override
public int size() {
return (int) mongoOps.count(query, beanClass);
}
@Override
public boolean containsId(Object itemId) {
return mongoOps.exists(Query.query(where(ID).is(itemId)), beanClass);
}
@Override
public BeanItem<Bean> addItem(Object itemId) throws UnsupportedOperationException {
throw new UnsupportedOperationException(
"cannot addItem(); insert() into mongo or build a buffered container");
}
@Override
public ObjectId addItem() throws UnsupportedOperationException {
throw new UnsupportedOperationException(
"cannot addItem(); insert() into mongo or build a buffered container");
}
public ObjectId addEntity(Bean target) {
mongoOps.insert(target);
try {
return (ObjectId) getIdField(target).get(target);
} catch (IllegalAccessException ex) {
throw new UnsupportedOperationException(ex);
}
}
@Override
public boolean removeItem(Object itemId) throws UnsupportedOperationException {
mongoOps.findAndRemove(Query.query(where(ID).is(itemId)), beanClass);
page.setInvalid();
return true;
}
@Override
public boolean addContainerProperty(Object o, Class<?> aClass, Object o2) throws UnsupportedOperationException {
throw new UnsupportedOperationException("cannot add container property dynamically; use Builder");
}
@Override
public boolean removeContainerProperty(Object o) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAllItems() throws UnsupportedOperationException {
mongoOps.remove(Query.query(criteria), beanClass);
return true;
}
@Override
public int indexOfId(Object itemId) {
ObjectId oid = assertIdValid(itemId);
// for the principle of locality,
// let us optimistically first check within the page
int index = page.indexOf(oid);
if (index > -1) return index;
// otherwise, linearly scan the entire collection using a cursor
// and only fetch the ids
DBCursor cur = cursor();
for (int i = 0; cur.hasNext(); i++) {
// skip the check for those already in the page
if (i >= page.offset && i < page.maxIndex) continue;
if (cur.next().get(ID).equals(itemId)) return i;
}
return -1;
}
@Override
@Nullable
public ObjectId getIdByIndex(int index) {
if (size() == 0) return null;
DBCursor cur = cursorInRange(index, 1);
return cur.hasNext()?
(ObjectId)cur.next().get(ID)
: null;
}
@Override
public List<ObjectId> getItemIds(int startIndex, int numberOfItems) {
//List<BeanId> beans = mongoOps.find(Query.query(criteria).skip(startIndex).limit(numberOfItems), BeanId.class);
//List<ObjectId> ids = new PropertyList<ObjectId,BeanId>(beans, beanIdDescriptor, "_id");
if (page.isValid() && page.isWithinRange(startIndex, numberOfItems)) {
List<ObjectId> idList = this.page.toImmutableList(); // indexed from 0, as required by the interface contract
return idList.subList(startIndex-page.offset, numberOfItems); // return the requested range
}
fetchPage(startIndex, numberOfItems);
return this.page.toImmutableList();
}
@Override
public Object addItemAt(int index) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public Item addItemAt(int index, Object newItemId) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public ObjectId nextItemId(Object itemId) {
int index = indexOfId(itemId);
return getIdByIndex(index+1);
}
@Override
public ObjectId prevItemId(Object itemId) {
int index = indexOfId(itemId);
return getIdByIndex(index - 1);
}
@Override
public ObjectId firstItemId() {
return getIdByIndex(0);
}
@Override
public ObjectId lastItemId() {
return size() > 0 ?
getIdByIndex(size()-1)
: null;
}
@Override
public boolean isFirstId(Object itemId) {
assertIdValid(itemId);
return itemId.equals(firstItemId());
}
@Override
public boolean isLastId(Object itemId) {
assertIdValid(itemId);
return itemId.equals(lastItemId());
}
@Override
public Object addItemAfter(Object previousItemId) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public Item addItemAfter(Object previousItemId, Object newItemId) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
private ObjectId assertIdValid(Object o) {
if ( o == null )
throw new NullPointerException("Id cannot be null");
if ( ! ( o instanceof ObjectId ) )
throw new IllegalArgumentException("Id is not instance of ObjectId: "+o);
return (ObjectId) o;
}
private static <T> BeanDescriptor getBeanDescriptor(Class<T> beanClass) {
try {
return Introspector.getBeanInfo(beanClass).getBeanDescriptor();
} catch (Exception ex) { throw new Error(ex); }
}
private static LinkedHashMap<String, PropertyDescriptor> getBeanPropertyDescriptor(
final Class<?> beanClass) {
try {
LinkedHashMap<String, PropertyDescriptor> propertyDescriptorMap =
new LinkedHashMap<String, PropertyDescriptor>();
if (beanClass.isInterface()) {
for (Class<?> cls : beanClass.getInterfaces()) {
propertyDescriptorMap.putAll(getBeanPropertyDescriptor(cls));
}
BeanInfo info = Introspector.getBeanInfo(beanClass);
for (PropertyDescriptor pd: info.getPropertyDescriptors()) {
propertyDescriptorMap.put(pd.getName(), pd);
}
} else {
BeanInfo info = Introspector.getBeanInfo(beanClass);
for (PropertyDescriptor pd: info.getPropertyDescriptors()) {
propertyDescriptorMap.put(pd.getName(), pd);
}
}
return propertyDescriptorMap;
} catch (Exception ex) { throw new Error(ex); }
}
private static Set<?> getVaadinPropertyIds(final Class<?> beanClass) throws IntrospectionException {
LinkedHashMap<String,PropertyDescriptor> propDescrs = getBeanPropertyDescriptor(beanClass);
return Collections.unmodifiableSet(propDescrs.keySet());
}
protected Field getIdField(Bean target) {
for (Field f : beanClass.getDeclaredFields()) {
System.out.println(f);
if (f.isAnnotationPresent(org.springframework.data.annotation.Id.class)) {
f.setAccessible(true);
return f;
}
}
throw new UnsupportedOperationException("no id field was found");
}
}
|
package it.unimib.disco.bimib.cyTRON.view;
import it.unimib.disco.bimib.cyTRON.R.RConnectionManager;
import it.unimib.disco.bimib.cyTRON.controller.DatasetController;
import it.unimib.disco.bimib.cyTRON.cytoscape.CommandExecutor;
import it.unimib.disco.bimib.cyTRON.model.Dataset;
import it.unimib.disco.bimib.cyTRON.model.Gene;
import it.unimib.disco.bimib.cyTRON.model.Sample;
import java.awt.Window;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class MainFrame extends javax.swing.JFrame {
private static final long serialVersionUID = 6101131522201523082L;
private final CommandExecutor commandExecutor;
private final DatasetController datasetController;
public MainFrame(CommandExecutor commandExecutor, boolean instantiateRConnection) {
try {
if (instantiateRConnection) {
// instantiate the connection with R and load TRONCO
RConnectionManager.instantiateConnection();
RConnectionManager.loadTronco();
}
} catch (RuntimeException e) {
JOptionPane.showConfirmDialog(this, e.getMessage(), RConnectionManager.ERROR, JOptionPane.PLAIN_MESSAGE);
}
// get the command executor
this.commandExecutor = commandExecutor;
// instantiate the dataset controller
datasetController = new DatasetController();
// draws the interface
initComponents();
initCustomComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
tabbedPane = new javax.swing.JTabbedPane();
editPanel = new javax.swing.JPanel();
currentDatasetPanel = new javax.swing.JPanel();
genesPanelList = new javax.swing.JPanel();
renameGeneButton = new javax.swing.JButton();
deleteGeneButton = new javax.swing.JButton();
genesScrollPane = new javax.swing.JScrollPane();
genesList = new javax.swing.JList<>();
filterGenesTextField = new javax.swing.JTextField();
filterGenesLabel = new javax.swing.JLabel();
typesPanelList = new javax.swing.JPanel();
renameTypeButton = new javax.swing.JButton();
deleteTypeButton = new javax.swing.JButton();
joinTypesButton = new javax.swing.JButton();
typesScrollPane = new javax.swing.JScrollPane();
typesList = new javax.swing.JList<>();
samplesPanelList = new javax.swing.JPanel();
samplesScrollPane = new javax.swing.JScrollPane();
samplesList = new javax.swing.JList<>();
deteleSampleButton = new javax.swing.JButton();
samplesSelectionButton = new javax.swing.JButton();
selectMultipleSamplesButton = new javax.swing.JButton();
deleteMultipleSamplesButton = new javax.swing.JButton();
shortenBarcodesButton = new javax.swing.JButton();
filterSamplesLabel = new javax.swing.JLabel();
filterSamplesTextField = new javax.swing.JTextField();
eventsPanelList = new javax.swing.JPanel();
eventsScrollPane = new javax.swing.JScrollPane();
eventsList = new javax.swing.JList<>();
deleteEventButton = new javax.swing.JButton();
joinEventsButton = new javax.swing.JButton();
eventsSelectionButton = new javax.swing.JButton();
trimButton = new javax.swing.JButton();
infoPanel = new javax.swing.JPanel();
typesLabel = new javax.swing.JLabel();
genesLabel = new javax.swing.JLabel();
eventsLabel = new javax.swing.JLabel();
samplesLabel = new javax.swing.JLabel();
typesNumberLabel = new javax.swing.JLabel();
genesNumberLabel = new javax.swing.JLabel();
eventsNumberLabel = new javax.swing.JLabel();
samplesNumberLabel = new javax.swing.JLabel();
datasetsPanelList = new javax.swing.JPanel();
datasetsListScrollPane = new javax.swing.JScrollPane();
datasetsList = new javax.swing.JList<>();
importDatasetButton = new javax.swing.JButton();
deleteDatasetButton = new javax.swing.JButton();
bindEventsButton = new javax.swing.JButton();
bindSamplesButton = new javax.swing.JButton();
intersectButton = new javax.swing.JButton();
saveDatasetButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("cyTRON");
setMaximumSize(new java.awt.Dimension(1280, 720));
setMinimumSize(new java.awt.Dimension(1280, 720));
currentDatasetPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
genesPanelList.setBorder(javax.swing.BorderFactory.createTitledBorder("Genes"));
genesPanelList.setToolTipText("");
genesPanelList.setPreferredSize(new java.awt.Dimension(300, 320));
renameGeneButton.setText("Rename...");
renameGeneButton.setToolTipText("");
renameGeneButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
renameGeneButtonActionPerformed(evt);
}
});
deleteGeneButton.setText("Delete");
deleteGeneButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteGeneButtonActionPerformed(evt);
}
});
genesList.setModel(datasetController.getGenesListModel());
genesScrollPane.setViewportView(genesList);
filterGenesTextField.setToolTipText("");
filterGenesLabel.setText("Filter:");
javax.swing.GroupLayout genesPanelListLayout = new javax.swing.GroupLayout(genesPanelList);
genesPanelList.setLayout(genesPanelListLayout);
genesPanelListLayout.setHorizontalGroup(
genesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(genesPanelListLayout.createSequentialGroup()
.addContainerGap()
.addGroup(genesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(genesScrollPane)
.addGroup(genesPanelListLayout.createSequentialGroup()
.addComponent(renameGeneButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(deleteGeneButton))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, genesPanelListLayout.createSequentialGroup()
.addComponent(filterGenesLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(filterGenesTextField)))
.addContainerGap())
);
genesPanelListLayout.setVerticalGroup(
genesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, genesPanelListLayout.createSequentialGroup()
.addContainerGap()
.addComponent(genesScrollPane)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(genesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(filterGenesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(filterGenesLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(genesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(renameGeneButton)
.addComponent(deleteGeneButton))
.addContainerGap())
);
typesPanelList.setBorder(javax.swing.BorderFactory.createTitledBorder("Types"));
renameTypeButton.setText("Rename...");
renameTypeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
renameTypeButtonActionPerformed(evt);
}
});
deleteTypeButton.setText("Delete");
deleteTypeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteTypeButtonActionPerformed(evt);
}
});
joinTypesButton.setText("Join...");
joinTypesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
joinTypesButtonActionPerformed(evt);
}
});
typesList.setModel(datasetController.getTypesListModel());
typesScrollPane.setViewportView(typesList);
javax.swing.GroupLayout typesPanelListLayout = new javax.swing.GroupLayout(typesPanelList);
typesPanelList.setLayout(typesPanelListLayout);
typesPanelListLayout.setHorizontalGroup(
typesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(typesPanelListLayout.createSequentialGroup()
.addContainerGap()
.addGroup(typesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(typesScrollPane)
.addGroup(typesPanelListLayout.createSequentialGroup()
.addComponent(renameTypeButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(deleteTypeButton))
.addGroup(typesPanelListLayout.createSequentialGroup()
.addComponent(joinTypesButton)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
typesPanelListLayout.setVerticalGroup(
typesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, typesPanelListLayout.createSequentialGroup()
.addContainerGap()
.addComponent(typesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(joinTypesButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(typesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(renameTypeButton)
.addComponent(deleteTypeButton))
.addContainerGap())
);
samplesPanelList.setBorder(javax.swing.BorderFactory.createTitledBorder("Samples"));
samplesList.setModel(datasetController.getSamplesListModel());
samplesScrollPane.setViewportView(samplesList);
deteleSampleButton.setText("Delete");
deteleSampleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deteleSampleButtonActionPerformed(evt);
}
});
samplesSelectionButton.setText("Selection...");
samplesSelectionButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
samplesSelectionButtonActionPerformed(evt);
}
});
selectMultipleSamplesButton.setText("Select multiple");
selectMultipleSamplesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectMultipleSamplesButtonActionPerformed(evt);
}
});
deleteMultipleSamplesButton.setText("Delete multiple");
deleteMultipleSamplesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteMultipleSamplesButtonActionPerformed(evt);
}
});
shortenBarcodesButton.setText("Shorten barcodes");
shortenBarcodesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
shortenBarcodesButtonActionPerformed(evt);
}
});
filterSamplesLabel.setText("Filter:");
filterSamplesTextField.setToolTipText("");
javax.swing.GroupLayout samplesPanelListLayout = new javax.swing.GroupLayout(samplesPanelList);
samplesPanelList.setLayout(samplesPanelListLayout);
samplesPanelListLayout.setHorizontalGroup(
samplesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(samplesPanelListLayout.createSequentialGroup()
.addContainerGap()
.addGroup(samplesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(samplesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(samplesPanelListLayout.createSequentialGroup()
.addComponent(filterSamplesLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(filterSamplesTextField)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(samplesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(samplesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(samplesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(samplesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(shortenBarcodesButton)
.addComponent(deteleSampleButton, javax.swing.GroupLayout.Alignment.TRAILING))
.addComponent(samplesSelectionButton, javax.swing.GroupLayout.Alignment.TRAILING))
.addComponent(deleteMultipleSamplesButton, javax.swing.GroupLayout.Alignment.TRAILING))
.addComponent(selectMultipleSamplesButton, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
samplesPanelListLayout.setVerticalGroup(
samplesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(samplesPanelListLayout.createSequentialGroup()
.addContainerGap()
.addGroup(samplesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(samplesPanelListLayout.createSequentialGroup()
.addComponent(selectMultipleSamplesButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(deleteMultipleSamplesButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(shortenBarcodesButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(samplesSelectionButton))
.addComponent(samplesScrollPane))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(samplesPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(deteleSampleButton)
.addComponent(filterSamplesLabel)
.addComponent(filterSamplesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
eventsPanelList.setBorder(javax.swing.BorderFactory.createTitledBorder("Events"));
eventsList.setModel(datasetController.getEventsListModel());
eventsScrollPane.setViewportView(eventsList);
deleteEventButton.setText("Delete");
deleteEventButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteEventButtonActionPerformed(evt);
}
});
joinEventsButton.setText("Join...");
joinEventsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
joinEventsButtonActionPerformed(evt);
}
});
eventsSelectionButton.setText("Selection...");
eventsSelectionButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
eventsSelectionButtonActionPerformed(evt);
}
});
trimButton.setText("Trim");
trimButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
trimButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout eventsPanelListLayout = new javax.swing.GroupLayout(eventsPanelList);
eventsPanelList.setLayout(eventsPanelListLayout);
eventsPanelListLayout.setHorizontalGroup(
eventsPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(eventsPanelListLayout.createSequentialGroup()
.addContainerGap()
.addGroup(eventsPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(eventsScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 418, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, eventsPanelListLayout.createSequentialGroup()
.addComponent(joinEventsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(deleteEventButton))
.addGroup(eventsPanelListLayout.createSequentialGroup()
.addComponent(eventsSelectionButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(trimButton)))
.addContainerGap())
);
eventsPanelListLayout.setVerticalGroup(
eventsPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(eventsPanelListLayout.createSequentialGroup()
.addContainerGap()
.addComponent(eventsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(eventsPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(eventsSelectionButton)
.addComponent(trimButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(eventsPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(deleteEventButton)
.addComponent(joinEventsButton))
.addContainerGap())
);
infoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Info"));
infoPanel.setToolTipText("");
typesLabel.setText("Types:");
genesLabel.setText("Genes:");
eventsLabel.setText("Events:");
samplesLabel.setText("Samples:");
javax.swing.GroupLayout infoPanelLayout = new javax.swing.GroupLayout(infoPanel);
infoPanel.setLayout(infoPanelLayout);
infoPanelLayout.setHorizontalGroup(
infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(infoPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(typesLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(typesNumberLabel)
.addGap(99, 99, 99)
.addComponent(genesLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(genesNumberLabel)
.addGap(99, 99, 99)
.addComponent(eventsLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(eventsNumberLabel)
.addGap(99, 99, 99)
.addComponent(samplesLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(samplesNumberLabel)
.addContainerGap())
);
infoPanelLayout.setVerticalGroup(
infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(infoPanelLayout.createSequentialGroup()
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(typesLabel)
.addComponent(genesLabel)
.addComponent(eventsLabel)
.addComponent(typesNumberLabel)
.addComponent(genesNumberLabel)
.addComponent(eventsNumberLabel))
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(samplesLabel)
.addComponent(samplesNumberLabel)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout currentDatasetPanelLayout = new javax.swing.GroupLayout(currentDatasetPanel);
currentDatasetPanel.setLayout(currentDatasetPanelLayout);
currentDatasetPanelLayout.setHorizontalGroup(
currentDatasetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(currentDatasetPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(currentDatasetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(infoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(currentDatasetPanelLayout.createSequentialGroup()
.addGroup(currentDatasetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(eventsPanelList, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(typesPanelList, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(currentDatasetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(samplesPanelList, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(genesPanelList, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE))))
.addContainerGap())
);
currentDatasetPanelLayout.setVerticalGroup(
currentDatasetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, currentDatasetPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(infoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(currentDatasetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(typesPanelList, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(genesPanelList, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(currentDatasetPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(eventsPanelList, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(samplesPanelList, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
javax.swing.GroupLayout editPanelLayout = new javax.swing.GroupLayout(editPanel);
editPanel.setLayout(editPanelLayout);
editPanelLayout.setHorizontalGroup(
editPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, editPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(currentDatasetPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
editPanelLayout.setVerticalGroup(
editPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, editPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(currentDatasetPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
tabbedPane.addTab("Edit", editPanel);
datasetsPanelList.setBorder(javax.swing.BorderFactory.createTitledBorder("Datasets"));
datasetsList.setModel(datasetController.getDatasetsListModel());
datasetsList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
datasetsList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
datasetsListValueChanged(evt);
}
});
datasetsListScrollPane.setViewportView(datasetsList);
importDatasetButton.setText("Import...");
importDatasetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
importDatasetButtonActionPerformed(evt);
}
});
deleteDatasetButton.setText("Delete");
deleteDatasetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteDatasetButtonActionPerformed(evt);
}
});
bindEventsButton.setText("Bind events...");
bindEventsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bindEventsButtonActionPerformed(evt);
}
});
bindSamplesButton.setText("Bind samples...");
bindSamplesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bindSamplesButtonActionPerformed(evt);
}
});
intersectButton.setText("Intersect...");
intersectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
intersectButtonActionPerformed(evt);
}
});
saveDatasetButton.setText("Save...");
saveDatasetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveDatasetButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout datasetsPanelListLayout = new javax.swing.GroupLayout(datasetsPanelList);
datasetsPanelList.setLayout(datasetsPanelListLayout);
datasetsPanelListLayout.setHorizontalGroup(
datasetsPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(datasetsPanelListLayout.createSequentialGroup()
.addContainerGap()
.addGroup(datasetsPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(datasetsListScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
.addGroup(datasetsPanelListLayout.createSequentialGroup()
.addComponent(bindEventsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(bindSamplesButton))
.addGroup(datasetsPanelListLayout.createSequentialGroup()
.addGroup(datasetsPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(importDatasetButton)
.addComponent(intersectButton))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(datasetsPanelListLayout.createSequentialGroup()
.addComponent(deleteDatasetButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(saveDatasetButton)))
.addContainerGap())
);
datasetsPanelListLayout.setVerticalGroup(
datasetsPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(datasetsPanelListLayout.createSequentialGroup()
.addContainerGap()
.addComponent(importDatasetButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(datasetsPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(deleteDatasetButton)
.addComponent(saveDatasetButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(datasetsListScrollPane)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(intersectButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(datasetsPanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bindEventsButton)
.addComponent(bindSamplesButton))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(datasetsPanelList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tabbedPane)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(datasetsPanelList, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(tabbedPane))
.addContainerGap())
);
tabbedPane.getAccessibleContext().setAccessibleName("");
pack();
}// </editor-fold>//GEN-END:initComponents
private void initCustomComponents() {
hypothesesPanel = new HypothesesPanel(datasetController, this);
externalToolsPanel = new ExternalToolsPanel(datasetController, this);
visualizationPanel = new VisualizationPanel(this, commandExecutor);
statisticsPanel = new StatisticsPanel(this, visualizationPanel);
inferencePanel = new InferencePanel(this, statisticsPanel, visualizationPanel);
tabbedPane.addTab("Hypotheses", hypothesesPanel);
tabbedPane.addTab("External Tools", externalToolsPanel);
tabbedPane.addTab("Inference", inferencePanel);
tabbedPane.addTab("Statistics", statisticsPanel);
tabbedPane.addTab("Visualization", visualizationPanel);
filterGenesTextField.getDocument().addDocumentListener(new DocumentListener(){
@Override
public void insertUpdate(DocumentEvent e) {
filterGenes();
}
@Override
public void removeUpdate(DocumentEvent e) {
filterGenes();
}
@Override
public void changedUpdate(DocumentEvent e) {}
});
filterSamplesTextField.getDocument().addDocumentListener(new DocumentListener(){
@Override
public void insertUpdate(DocumentEvent e) {
filterSamples();
}
@Override
public void removeUpdate(DocumentEvent e) {
filterSamples();
}
@Override
public void changedUpdate(DocumentEvent e) {}
});
}
private void importDatasetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importDatasetButtonActionPerformed
ImportDatasetFrame importDatasetFrame = new ImportDatasetFrame(datasetController);
importDatasetFrame.setLocationRelativeTo(null);
importDatasetFrame.setVisible(true);
}//GEN-LAST:event_importDatasetButtonActionPerformed
private void deleteDatasetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteDatasetButtonActionPerformed
// if there is no selection
if (datasetsList.getSelectedIndex() == -1) {
// return
return;
}
// get the confirmation
int confirmation = JOptionPane.showConfirmDialog(this, "The dataset will be deleted.\nAre you sure?", "", JOptionPane.OK_CANCEL_OPTION);
// if confirmed
if (confirmation == JOptionPane.OK_OPTION) {
// execute the action
datasetController.deleteDataset(datasetsList.getSelectedIndex());
// if the last console message is regular
if (RConnectionManager.getTextConsole().isLastMessageRegular()) {
// clear the number labels
clearNumberLabels();
} else {
JOptionPane.showConfirmDialog(this, RConnectionManager.getTextConsole().getLastConsoleMessage(), RConnectionManager.ERROR, JOptionPane.PLAIN_MESSAGE);
}
}
}//GEN-LAST:event_deleteDatasetButtonActionPerformed
private void deteleSampleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deteleSampleButtonActionPerformed
// if there is no selection
if (samplesList.getSelectedIndex() == -1) {
// return
return;
}
// get the confirmation
int confirmation = JOptionPane.showConfirmDialog(this, "The sample will be deleted.\nAre you sure?", "", JOptionPane.OK_CANCEL_OPTION);
// if confirmed
if (confirmation == JOptionPane.OK_OPTION) {
// excute the action
datasetController.deleteSample(samplesList.getSelectedIndex(), datasetsList.getSelectedIndex());
// if the last console message is regular
if (RConnectionManager.getTextConsole().isLastMessageRegular()) {
// update the number labels
updateNumberLabels();
} else {
JOptionPane.showConfirmDialog(this, RConnectionManager.getTextConsole().getLastConsoleMessage(), RConnectionManager.ERROR, JOptionPane.PLAIN_MESSAGE);
}
}
}//GEN-LAST:event_deteleSampleButtonActionPerformed
private void filterSamples() {
// get the filter and the dataset index
String filter = filterSamplesTextField.getText().toLowerCase();
int datasetIndex = datasetsList.getSelectedIndex();
// return if no dataset is selected
if (datasetIndex == -1) {
return;
}
// filter the genes
datasetController.filterSamples(datasetIndex, filter);
}
private void renameGeneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renameGeneButtonActionPerformed
// if there is no selection
if (genesList.getSelectedIndex() == -1) {
// return
return;
}
RenameGeneFrame renameGeneFrame = new RenameGeneFrame(datasetController, genesList.getSelectedIndex(), datasetsList.getSelectedIndex());
renameGeneFrame.setLocationRelativeTo(null);
renameGeneFrame.setVisible(true);
}//GEN-LAST:event_renameGeneButtonActionPerformed
private void deleteGeneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteGeneButtonActionPerformed
// if there is no selection
if (genesList.getSelectedIndex() == -1) {
// return
return;
}
// get the confirmation
int confirmation = JOptionPane.showConfirmDialog(this, "The gene will be deleted.\nAre you sure?", "", JOptionPane.OK_CANCEL_OPTION);
// if confirmed
if (confirmation == JOptionPane.OK_OPTION) {
// execute the actioin
datasetController.deleteGene(genesList.getSelectedIndex(), datasetsList.getSelectedIndex());
// if the last console message is regular
if (RConnectionManager.getTextConsole().isLastMessageRegular()) {
// update the number labels
updateNumberLabels();
} else {
JOptionPane.showConfirmDialog(this, RConnectionManager.getTextConsole().getLastConsoleMessage(), RConnectionManager.ERROR, JOptionPane.PLAIN_MESSAGE);
}
}
}//GEN-LAST:event_deleteGeneButtonActionPerformed
private void filterGenes() {
// get the filter and the dataset index
String filter = filterGenesTextField.getText().toLowerCase();
int datasetIndex = datasetsList.getSelectedIndex();
// return if no dataset is selected
if (datasetIndex == -1) {
return;
}
// filter the genes
datasetController.filterGenes(datasetIndex, filter);
}
private void deleteTypeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteTypeButtonActionPerformed
// if there is no selection
if (typesList.getSelectedIndex() == -1) {
// return
return;
}
// get the confirmation
int confirmation = JOptionPane.showConfirmDialog(this, "The type will be deleted.\nAre you sure?", "", JOptionPane.OK_CANCEL_OPTION);
// if confirmed
if (confirmation == JOptionPane.OK_OPTION) {
// execute the action
datasetController.deleteType(typesList.getSelectedIndex(), datasetsList.getSelectedIndex());
// if the last console message is regular
if (RConnectionManager.getTextConsole().isLastMessageRegular()) {
// update the number labels
updateNumberLabels();
} else {
JOptionPane.showConfirmDialog(this, RConnectionManager.getTextConsole().getLastConsoleMessage(), RConnectionManager.ERROR, JOptionPane.PLAIN_MESSAGE);
}
}
}//GEN-LAST:event_deleteTypeButtonActionPerformed
private void renameTypeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renameTypeButtonActionPerformed
// if there is no selection
if (typesList.getSelectedIndex() == -1) {
// return
return;
}
RenameTypeFrame renameTypeFrame = new RenameTypeFrame(datasetController, typesList.getSelectedIndex(), datasetsList.getSelectedIndex());
renameTypeFrame.setLocationRelativeTo(null);
renameTypeFrame.setVisible(true);
}//GEN-LAST:event_renameTypeButtonActionPerformed
private void joinTypesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_joinTypesButtonActionPerformed
// if there is no selection
if (typesList.getSelectedIndex() == -1 || datasetController.getTypesListModel().size() < 2) {
// return
return;
}
JoinTypesFrame joinTypesFrame = new JoinTypesFrame(this, datasetController, typesList.getSelectedIndex(), datasetsList.getSelectedIndex());
joinTypesFrame.setLocationRelativeTo(null);
joinTypesFrame.setVisible(true);
}//GEN-LAST:event_joinTypesButtonActionPerformed
private void deleteEventButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteEventButtonActionPerformed
// if there is no selection
if (eventsList.getSelectedIndex() == -1) {
// return
return;
}
// get the confirmation
int confirmation = JOptionPane.showConfirmDialog(this, "The event will be deleted.\nAre you sure?", "", JOptionPane.OK_CANCEL_OPTION);
// if confirmed
if (confirmation == JOptionPane.OK_OPTION) {
// execute the action
datasetController.deleteEvent(eventsList.getSelectedIndex(), datasetsList.getSelectedIndex());
// if the last console message is regular
if (RConnectionManager.getTextConsole().isLastMessageRegular()) {
// update the number labels
updateNumberLabels();
} else {
JOptionPane.showConfirmDialog(this, RConnectionManager.getTextConsole().getLastConsoleMessage(), RConnectionManager.ERROR, JOptionPane.PLAIN_MESSAGE);
}
}
}//GEN-LAST:event_deleteEventButtonActionPerformed
private void joinEventsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_joinEventsButtonActionPerformed
// if there is no selection
if (eventsList.getSelectedIndex() == -1 || datasetController.getEventsListModel().size() < 2) {
// return
return;
}
JoinEventsFrame joinEventsFrame = new JoinEventsFrame(this, datasetController, eventsList.getSelectedIndex(), datasetsList.getSelectedIndex());
joinEventsFrame.setLocationRelativeTo(null);
joinEventsFrame.setVisible(true);
}//GEN-LAST:event_joinEventsButtonActionPerformed
private void bindEventsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bindEventsButtonActionPerformed
// if there is no selection
if (datasetsList.getSelectedIndex() == -1 || datasetController.getDatasetsListModel().size() < 2) {
// return
return;
}
BindDatasetsFrame bindDatasetsFrame = new BindDatasetsFrame(this, datasetController, datasetsList.getSelectedIndex(), DatasetController.EVENTS);
bindDatasetsFrame.setLocationRelativeTo(null);
bindDatasetsFrame.setVisible(true);
}//GEN-LAST:event_bindEventsButtonActionPerformed
private void bindSamplesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bindSamplesButtonActionPerformed
// if there is no selection
if (datasetsList.getSelectedIndex() == -1 || datasetController.getDatasetsListModel().size() < 2) {
// return
return;
}
BindDatasetsFrame bindDatasetsFrame = new BindDatasetsFrame(this, datasetController, datasetsList.getSelectedIndex(), DatasetController.SAMPLES);
bindDatasetsFrame.setLocationRelativeTo(null);
bindDatasetsFrame.setVisible(true);
}//GEN-LAST:event_bindSamplesButtonActionPerformed
private void intersectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_intersectButtonActionPerformed
// if there is no selection
if (datasetsList.getSelectedIndex() == -1 || datasetController.getDatasetsListModel().size() < 2) {
// return
return;
}
IntersectDatasetsFrame intersectDatasetsFrame = new IntersectDatasetsFrame(this, datasetController, datasetsList.getSelectedIndex());
intersectDatasetsFrame.setLocationRelativeTo(null);
intersectDatasetsFrame.setVisible(true);
}//GEN-LAST:event_intersectButtonActionPerformed
private void datasetsListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_datasetsListValueChanged
if (datasetsList.getSelectedIndex() != -1) {
// update the lists
datasetController.updateLists(datasetsList.getSelectedIndex());
// update the number labels
updateNumberLabels();
// update the other panels
hypothesesPanel.updateSelectedDataset(datasetsList.getSelectedIndex());
externalToolsPanel.updateSelectedDataset();
inferencePanel.updateSelectedDataset();
statisticsPanel.updateSelectedDataset();
visualizationPanel.updateSelectedDataset();
}
}//GEN-LAST:event_datasetsListValueChanged
private void samplesSelectionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_samplesSelectionButtonActionPerformed
// if there is no selection
if (datasetController.getSamplesListModel().size() == 0) {
// return
return;
}
SamplesSelectionFrame samplesSelectionFrame = new SamplesSelectionFrame(this, datasetController, datasetsList.getSelectedIndex());
samplesSelectionFrame.setLocationRelativeTo(null);
samplesSelectionFrame.setVisible(true);
}//GEN-LAST:event_samplesSelectionButtonActionPerformed
private void eventsSelectionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eventsSelectionButtonActionPerformed
// if there is no selection
if (datasetController.getEventsListModel().size() == 0) {
// return
return;
}
EventsSelectionFrame eventsSelectionFrame = new EventsSelectionFrame(this, datasetController, datasetsList.getSelectedIndex());
eventsSelectionFrame.setLocationRelativeTo(null);
eventsSelectionFrame.setVisible(true);
}//GEN-LAST:event_eventsSelectionButtonActionPerformed
private void trimButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_trimButtonActionPerformed
// if there is no selection
if (datasetController.getEventsListModel().size() == 0) {
// return
return;
}
// get the confirmation
int confirmation = JOptionPane.showConfirmDialog(this, "Events will be trimmed.\nAre you sure?", "", JOptionPane.OK_CANCEL_OPTION);
// if confirmed
if (confirmation == JOptionPane.OK_OPTION) {
// trim the events
datasetController.trim(datasetsList.getSelectedIndex());
// if the last console message is regular
if (RConnectionManager.getTextConsole().isLastMessageRegular()) {
updateNumberLabels();
} else {
JOptionPane.showConfirmDialog(this, RConnectionManager.getTextConsole().getLastConsoleMessage(), RConnectionManager.ERROR, JOptionPane.PLAIN_MESSAGE);
}
}
}//GEN-LAST:event_trimButtonActionPerformed
private void selectMultipleSamplesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectMultipleSamplesButtonActionPerformed
// if there is no selection
if (datasetController.getSamplesListModel().size() < 2) {
// return
return;
}
// get the indexes of the multiple samples of the dataset
int[] multipleSamplesIndexes = datasetController.selectMultipleSamples(datasetsList.getSelectedIndex());
// if the last console message is regular
if (RConnectionManager.getTextConsole().isLastMessageRegular()) {
// if there are no multiple samples
if (multipleSamplesIndexes.length == 0) {
// show a message
JOptionPane.showConfirmDialog(this, "No multiple samples.", "", JOptionPane.PLAIN_MESSAGE);
} else {
// select the multiple samples
samplesList.setSelectedIndices(multipleSamplesIndexes);
// scroll to the first multiple sample
samplesList.ensureIndexIsVisible(multipleSamplesIndexes[0]);
}
} else {
JOptionPane.showConfirmDialog(this, RConnectionManager.getTextConsole().getLastConsoleMessage(), RConnectionManager.ERROR, JOptionPane.PLAIN_MESSAGE);
}
}//GEN-LAST:event_selectMultipleSamplesButtonActionPerformed
private void deleteMultipleSamplesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteMultipleSamplesButtonActionPerformed
// if there is no selection
if (datasetController.getSamplesListModel().size() < 2) {
// return
return;
}
// get the confirmation
int confirmation = JOptionPane.showConfirmDialog(this, "Multiple samples will be deleted.\nAre you sure?", "", JOptionPane.OK_CANCEL_OPTION);
// if confirmed
if (confirmation == JOptionPane.OK_OPTION) {
// remove multiple samples from the dataset
datasetController.removeMultipleSamples(datasetsList.getSelectedIndex());
// if the last console message is regular
if (RConnectionManager.getTextConsole().isLastMessageRegular()) {
// update the number labels
updateNumberLabels();
} else {
JOptionPane.showConfirmDialog(this, RConnectionManager.getTextConsole().getLastConsoleMessage(), RConnectionManager.ERROR, JOptionPane.PLAIN_MESSAGE);
}
}
}//GEN-LAST:event_deleteMultipleSamplesButtonActionPerformed
private void shortenBarcodesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_shortenBarcodesButtonActionPerformed
// if there is no selection
if (datasetController.getSamplesListModel().size() == 0) {
// return
return;
}
// get the confirmation
int confirmation = JOptionPane.showConfirmDialog(this, "Samples' names will be shortened.\nAre you sure?", "", JOptionPane.OK_CANCEL_OPTION);
// if confirmed
if (confirmation == JOptionPane.OK_OPTION) {
// remove multiple samples from the dataset
datasetController.shortenBarcodes(datasetsList.getSelectedIndex());
// if the last console message is regular
if (RConnectionManager.getTextConsole().isLastMessageRegular()) {
// update the number labels
updateNumberLabels();
} else {
JOptionPane.showConfirmDialog(this, RConnectionManager.getTextConsole().getLastConsoleMessage(), RConnectionManager.ERROR, JOptionPane.PLAIN_MESSAGE);
}
}
}//GEN-LAST:event_shortenBarcodesButtonActionPerformed
private void saveDatasetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveDatasetButtonActionPerformed
// if there is no selection
if (datasetsList.getSelectedIndex() == -1) {
// return
return;
}
SaveDatasetFrame saveDatasetFrame = new SaveDatasetFrame(datasetController, this);
saveDatasetFrame.setLocationRelativeTo(null);
saveDatasetFrame.setVisible(true);
}//GEN-LAST:event_saveDatasetButtonActionPerformed
public void updateNumberLabels() {
typesNumberLabel.setText(String.valueOf(datasetController.getTypesListModel().size()));
genesNumberLabel.setText(String.valueOf(datasetController.getGenesListModel().size()));
eventsNumberLabel.setText(String.valueOf(datasetController.getEventsListModel().size()));
samplesNumberLabel.setText(String.valueOf(datasetController.getSamplesListModel().size()));
}
private void clearNumberLabels() {
typesNumberLabel.setText("");
genesNumberLabel.setText("");
eventsNumberLabel.setText("");
samplesNumberLabel.setText("");
}
public Dataset getSelectedDataset() {
int datasetIndex = datasetsList.getSelectedIndex();
if (datasetIndex == -1) {
return null;
}
return (Dataset) datasetController.getDatasetsListModel().get(datasetIndex);
}
// dispose all option panes
public static void disposeJOptionPanes() {
Window[] windows = Window.getWindows();
for (Window window : windows) {
if (window instanceof JDialog) {
JDialog dialog = (JDialog) window;
if (dialog.getContentPane().getComponentCount() == 1 && dialog.getContentPane().getComponent(0) instanceof JOptionPane){
dialog.dispose();
}
}
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bindEventsButton;
private javax.swing.JButton bindSamplesButton;
private javax.swing.JPanel currentDatasetPanel;
private javax.swing.JList<String> datasetsList;
private javax.swing.JScrollPane datasetsListScrollPane;
private javax.swing.JPanel datasetsPanelList;
private javax.swing.JButton deleteDatasetButton;
private javax.swing.JButton deleteEventButton;
private javax.swing.JButton deleteGeneButton;
private javax.swing.JButton deleteMultipleSamplesButton;
private javax.swing.JButton deleteTypeButton;
private javax.swing.JButton deteleSampleButton;
private javax.swing.JPanel editPanel;
private javax.swing.JLabel eventsLabel;
private javax.swing.JList<String> eventsList;
private javax.swing.JLabel eventsNumberLabel;
private javax.swing.JPanel eventsPanelList;
private javax.swing.JScrollPane eventsScrollPane;
private javax.swing.JButton eventsSelectionButton;
private javax.swing.JLabel filterGenesLabel;
private javax.swing.JTextField filterGenesTextField;
private javax.swing.JLabel filterSamplesLabel;
private javax.swing.JTextField filterSamplesTextField;
private javax.swing.JLabel genesLabel;
private javax.swing.JList<Gene> genesList;
private javax.swing.JLabel genesNumberLabel;
private javax.swing.JPanel genesPanelList;
private javax.swing.JScrollPane genesScrollPane;
private javax.swing.JButton importDatasetButton;
private javax.swing.JPanel infoPanel;
private javax.swing.JButton intersectButton;
private javax.swing.JButton joinEventsButton;
private javax.swing.JButton joinTypesButton;
private javax.swing.JButton renameGeneButton;
private javax.swing.JButton renameTypeButton;
private javax.swing.JLabel samplesLabel;
private javax.swing.JList<Sample> samplesList;
private javax.swing.JLabel samplesNumberLabel;
private javax.swing.JPanel samplesPanelList;
private javax.swing.JScrollPane samplesScrollPane;
private javax.swing.JButton samplesSelectionButton;
private javax.swing.JButton saveDatasetButton;
private javax.swing.JButton selectMultipleSamplesButton;
private javax.swing.JButton shortenBarcodesButton;
private javax.swing.JTabbedPane tabbedPane;
private javax.swing.JButton trimButton;
private javax.swing.JLabel typesLabel;
private javax.swing.JList<it.unimib.disco.bimib.cyTRON.model.Type> typesList;
private javax.swing.JLabel typesNumberLabel;
private javax.swing.JPanel typesPanelList;
private javax.swing.JScrollPane typesScrollPane;
// End of variables declaration//GEN-END:variables
private HypothesesPanel hypothesesPanel;
private ExternalToolsPanel externalToolsPanel;
private InferencePanel inferencePanel;
private StatisticsPanel statisticsPanel;
private VisualizationPanel visualizationPanel;
}
|
package jenkins.advancedqueue;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.matrix.MatrixConfiguration;
import hudson.matrix.MatrixProject;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Job;
import hudson.model.Queue;
import hudson.model.RootAction;
import hudson.model.TopLevelItem;
import hudson.model.View;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.servlet.ServletException;
import jenkins.advancedqueue.priority.PriorityStrategy;
import jenkins.advancedqueue.sorter.ItemInfo;
import jenkins.advancedqueue.sorter.QueueItemCache;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
/**
* @author Magnus Sandberg
* @since 2.0
*/
@Extension
public class PriorityConfiguration extends Descriptor<PriorityConfiguration> implements RootAction,
Describable<PriorityConfiguration> {
private final static Logger LOGGER = Logger.getLogger(PriorityConfiguration.class.getName());
transient private Map<Integer, JobGroup> id2jobGroup;
private List<JobGroup> jobGroups;
public PriorityConfiguration() {
super(PriorityConfiguration.class);
jobGroups = new LinkedList<JobGroup>();
load();
Collections.sort(jobGroups, new Comparator<JobGroup>() {
public int compare(JobGroup o1, JobGroup o2) {
return o1.getId() - o2.getId();
}
});
id2jobGroup = new HashMap<Integer, JobGroup>();
for (JobGroup jobGroup : jobGroups) {
id2jobGroup.put(jobGroup.getId(), jobGroup);
Collections.sort(jobGroup.getPriorityStrategies(), new Comparator<JobGroup.PriorityStrategyHolder>() {
public int compare(JobGroup.PriorityStrategyHolder o1, JobGroup.PriorityStrategyHolder o2) {
return o1.getId() - o2.getId();
}
});
}
}
public String getIconFileName() {
if (PrioritySorterConfiguration.get().getLegacyMode()) {
return null;
}
return "/plugin/PrioritySorter/advqueue.png";
}
@Override
public String getDisplayName() {
return Messages.PriorityConfiguration_displayName();
}
public String getUrlName() {
if (PrioritySorterConfiguration.get().getLegacyMode()) {
return null;
}
return "advanced-build-queue";
}
public List<JobGroup> getJobGroups() {
return jobGroups;
}
public ListBoxModel getListViewItems() {
ListBoxModel items = new ListBoxModel();
Collection<View> views = Jenkins.getInstance().getViews();
for (View view : views) {
items.add(view.getDisplayName(), view.getViewName());
}
return items;
}
public JobGroup getJobGroup(int id) {
return id2jobGroup.get(id);
}
public ExtensionList<Descriptor<PriorityStrategy>> getPriorityStrategyDescriptors() {
return PriorityStrategy.all();
}
public ListBoxModel getPriorities() {
ListBoxModel items = PrioritySorterConfiguration.get().doGetPriorityItems();
return items;
}
public void doPriorityConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
jobGroups = new LinkedList<JobGroup>();
id2jobGroup = new HashMap<Integer, JobGroup>();
String parameter = req.getParameter("json");
JSONObject jobGroupsObject = JSONObject.fromObject(parameter);
JSONArray jsonArray = JSONArray.fromObject(jobGroupsObject.get("jobGroup"));
int id = 0;
for (Object object : jsonArray) {
JSONObject jobGroupObject = JSONObject.fromObject(object);
if (jobGroupObject.isEmpty()) {
break;
}
JobGroup jobGroup = JobGroup.newInstance(req, jobGroupObject, id++);
jobGroups.add(jobGroup);
id2jobGroup.put(jobGroup.getId(), jobGroup);
}
save();
rsp.sendRedirect(Jenkins.getInstance().getRootUrl());
}
public Descriptor<PriorityConfiguration> getDescriptor() {
return this;
}
public FormValidation doCheckJobPattern(@QueryParameter String value) throws IOException, ServletException {
if (value.length() > 0) {
try {
Pattern.compile(value);
} catch (PatternSyntaxException e) {
return FormValidation.warning("The expression is not valid, please enter a valid expression.");
}
}
return FormValidation.ok();
}
public PriorityConfigurationCallback getPriority(Queue.Item item, PriorityConfigurationCallback priorityCallback) {
Job<?, ?> job = (Job<?, ?>) item.task;
// [JENKINS-8597]
// For MatrixConfiguration use the latest assigned Priority from the MatrixProject
if (job instanceof MatrixConfiguration) {
priorityCallback.addDecisionLog("Job is MatrixConfiguration ...");
MatrixProject matrixProject = ((MatrixConfiguration) job).getParent();
ItemInfo itemInfo = QueueItemCache.get().getItem(matrixProject.getName());
// Can be null (for example) at startup when the MatrixBuild got lost (was running at
// restart)
if (itemInfo != null) {
priorityCallback.addDecisionLog("MatrixProject found in cache, using priority from queue-item ["
+ itemInfo.getItemId() + "]");
return priorityCallback.setPrioritySelection(itemInfo.getPriority(), itemInfo.getJobGroupId(),
itemInfo.getPriorityStrategy());
}
priorityCallback.addDecisionLog("MatrixProject not found in cache, assigning global default priority");
return priorityCallback.setPrioritySelection(PrioritySorterConfiguration.get().getStrategy()
.getDefaultPriority());
}
if (PrioritySorterConfiguration.get().getAllowPriorityOnJobs()) {
AdvancedQueueSorterJobProperty priorityProperty = job.getProperty(AdvancedQueueSorterJobProperty.class);
if (priorityProperty != null && priorityProperty.getUseJobPriority()) {
int priority = priorityProperty.priority;
if (priority == PriorityCalculationsUtil.getUseDefaultPriorityPriority()) {
priority = PrioritySorterConfiguration.get().getStrategy().getDefaultPriority();
}
priorityCallback.addDecisionLog("Using priority taken directly from the Job");
return priorityCallback.setPrioritySelection(priority);
}
}
JobGroup jobGroup = getJobGroup(priorityCallback, job.getName());
if (jobGroup != null) {
return getPriorityForJobGroup(priorityCallback, jobGroup, item);
}
return priorityCallback.setPrioritySelection(PrioritySorterConfiguration.get().getStrategy()
.getDefaultPriority());
}
public JobGroup getJobGroup(PriorityConfigurationCallback priorityCallback, String jobName) {
for (JobGroup jobGroup : jobGroups) {
priorityCallback.addDecisionLog("Evaluating JobGroup [" + jobGroup.getId() + "] ...");
Collection<View> views = Jenkins.getInstance().getViews();
nextView: for (View view : views) {
priorityCallback.addDecisionLog(" Evaluating View [" + view.getViewName() + "] ...");
if (view.getViewName().equals(jobGroup.getView())) {
// getItem() always returns the item
TopLevelItem jobItem = view.getItem(jobName);
// Now check if the item is actually in the view
if (view.contains(jobItem)) {
// If filtering is not used use the priority
// If filtering is used but the pattern is empty regard
// it as a match all
if (!jobGroup.isUseJobFilter() || jobGroup.getJobPattern().trim().isEmpty()) {
priorityCallback.addDecisionLog(" Not using filter ...");
return jobGroup;
} else {
priorityCallback.addDecisionLog(" Using filter ...");
// So filtering is on - use the priority if there's
// a match
try {
if (jobName.matches(jobGroup.getJobPattern())) {
priorityCallback.addDecisionLog(" Job is matching the filter ...");
return jobGroup;
} else {
priorityCallback.addDecisionLog(" Job is not matching the filter ...");
continue nextView;
}
} catch (PatternSyntaxException e) {
// If the pattern is broken treat this a non
// match
priorityCallback.addDecisionLog(" Filter has syntax error");
continue nextView;
}
}
}
}
}
}
return null;
}
private PriorityConfigurationCallback getPriorityForJobGroup(PriorityConfigurationCallback priorityCallback,
JobGroup jobGroup, Queue.Item item) {
int priority = jobGroup.getPriority();
PriorityStrategy reason = null;
if (jobGroup.isUsePriorityStrategies()) {
priorityCallback.addDecisionLog(" Evaluating strategies ...");
List<JobGroup.PriorityStrategyHolder> priorityStrategies = jobGroup.getPriorityStrategies();
for (JobGroup.PriorityStrategyHolder priorityStrategy : priorityStrategies) {
PriorityStrategy strategy = priorityStrategy.getPriorityStrategy();
priorityCallback.addDecisionLog(" Evaluating strategy ["
+ strategy.getDescriptor().getDisplayName() + "] ...");
if (strategy.isApplicable(item)) {
priorityCallback.addDecisionLog(" Strategy is applicable");
int foundPriority = strategy.getPriority(item);
if (foundPriority > 0
&& foundPriority <= PrioritySorterConfiguration.get().getStrategy().getNumberOfPriorities()) {
priority = foundPriority;
reason = strategy;
break;
}
}
}
}
if (reason == null) {
priorityCallback.addDecisionLog(" Using JobGroup default");
}
if (priority == PriorityCalculationsUtil.getUseDefaultPriorityPriority()) {
priority = PrioritySorterConfiguration.get().getStrategy().getDefaultPriority();
}
return priorityCallback.setPrioritySelection(priority, jobGroup.getId(), reason);
}
static public PriorityConfiguration get() {
return (PriorityConfiguration) Jenkins.getInstance().getDescriptor(PriorityConfiguration.class);
}
}
|
package jfdi.parser.commandparsers;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jfdi.logic.commands.AddCommandStub;
import jfdi.logic.commands.AddCommandStub.Builder;
import jfdi.parser.Constants;
import jfdi.parser.DateTimeParser;
public class AddCommandParser extends CommandParser {
public static AddCommandParser instance;
public static AddCommandParser getInstance() {
if (instance == null) {
return instance = new AddCommandParser();
}
return instance;
}
@Override
/**
* All user inputs for adding tasks adhere to the following format:
* "<add identifier>(optional) <task description> <date time identifier)(optional) <tags>(optional)
* To build the add command, we traverse from the back, retrieving the tags
* first, then the date time identifiers if present, then the task.
*
* @param input
* the user input String
* @return the AddCommand.
*/
public AddCommandStub build(String input) {
Builder addCommandBuilder = new Builder();
input = setAndRemoveTags(input, addCommandBuilder);
input = setAndRemoveDateTime(input, addCommandBuilder);
setDescription(input, addCommandBuilder);
AddCommandStub addCommand = addCommandBuilder.build();
return addCommand;
}
/**
* Finds instances that match the tag Regex specified in
* parser.Constants.java, removes them from the input string, then adds the
* list of tags found into the Builder object.
*
* @param input
* the user input String
* @param builder
* the builder object for AddCommand
* @return the input, trimmed and without tags.
*/
private String setAndRemoveTags(String input, Builder builder) {
ArrayList<String> tags = new ArrayList<String>();
Pattern tagPattern = Pattern.compile(Constants.REGEX_TAGS);
Matcher matcher = tagPattern.matcher(input);
while (matcher.find()) {
// All tags are prepended with an identifier specified in
// parser.Constants.java. We need to remove this identifier.
String tag = removeFirstChar(getTrimmedSubstringInRange(input,
matcher.start(), matcher.end()));
input = getTrimmedSubstringInRange(input, 0, matcher.start());
tags.add(tag);
matcher.reset(input);
}
builder.addTags(tags);
return input;
}
/**
* Sets the date time identifier field in the builder, if it can be found in
* the string input. If the user input has many instances of substrings that
* match the Regex for date time identifiers (see parser.Constants.java),
* then only the one closest to the tail of the string is taken as the date
* time identifier. This is to allow for the user to both specify date times
* for his task, while still allowing him the flexibility of typing in dates
* and times in his task description.
*
* @param input
* the input string
* @param builder
* the builder object for AddCommand
* @return the input, trimmed and without date time identifiers.
*/
private String setAndRemoveDateTime(String input, Builder builder) {
Pattern dateTimePattern = Pattern
.compile(Constants.REGEX_DATE_TIME_IDENTIFIER);
Matcher matcher = dateTimePattern.matcher(input);
String dateTimeIdentifier = null;
if (matcher.find()) {
dateTimeIdentifier = getTrimmedSubstringInRange(input,
matcher.start(), matcher.end());
input = getTrimmedSubstringInRange(input, 0, matcher.start());
}
if (dateTimeIdentifier != null) {
DateTimeParser dateTimeParser = DateTimeParser.getInstance();
List<LocalDateTime> dateTimeList = dateTimeParser
.parseDateTime(dateTimeIdentifier);
ArrayList<LocalDateTime> dateTimeArrayList = new ArrayList<LocalDateTime>();
dateTimeArrayList.addAll(dateTimeList);
builder.addDateTimes(dateTimeArrayList);
}
return input;
}
/**
* Sets the description field of the builder object. Sets it to null if the
* input String is empty, or just an add identifier without any task
* descriptions.
*
* @param input
* is the input string from which the description is extracted.
* @param builder
* the builder object for AddCommand
*/
private void setDescription(String input, Builder builder) {
if (!input.isEmpty()) {
String firstWord = getFirstWord(input);
String taskDescription = null;
if (firstWord.matches(Constants.REGEX_ADD)) {
taskDescription = removeFirstWord(input);
} else {
taskDescription = input;
}
builder.addDescription(taskDescription);
} else {
builder.addDescription(null);
}
}
private String removeFirstChar(String string) {
return string.substring(1, string.length());
}
/**
* Get the substring of an input String from startindex inclusive to
* endindex exclusive, trimming it at the same time.
*
* @param input
* a string to get substring of
* @param startIndex
* index of the start of the substring (inclusive)
* @param endIndex
* index of the end of the substring (exclusive)
* @return the trimmed substring
*/
private String getTrimmedSubstringInRange(String input, int startIndex,
int endIndex) {
return input.substring(startIndex, endIndex).trim();
}
private String getFirstWord(String input) {
return input.split(Constants.REGEX_WHITESPACE)[0];
}
/**
* Removes the first word in the input string, and returns the rest of the
* input.
*
* @param input
* the string from which the first word is to be removed
* @return the input string without the first word and the whitespace
* separating the first word from the rest of the string. If the
* string only consists of one word, return null.
*/
private String removeFirstWord(String input) {
String[] splitInput = input.split(Constants.REGEX_WHITESPACE, 2);
if (splitInput.length == 1) {
return null;
} else {
return splitInput[1];
}
}
}
|
package main.java.com.bag.server;
import bftsmart.reconfiguration.util.RSAKeyLoader;
import bftsmart.tom.MessageContext;
import bftsmart.tom.ServiceProxy;
import bftsmart.tom.core.messages.TOMMessageType;
import bftsmart.tom.util.TOMUtil;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.pool.KryoPool;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import main.java.com.bag.operations.IOperation;
import main.java.com.bag.util.Constants;
import main.java.com.bag.util.Log;
import main.java.com.bag.util.storage.NodeStorage;
import main.java.com.bag.util.storage.RelationshipStorage;
import main.java.com.bag.util.storage.SignatureStorage;
import org.jetbrains.annotations.NotNull;
import java.security.PublicKey;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Class handling server communication in the global cluster.
*/
public class GlobalClusterSlave extends AbstractRecoverable
{
/**
* Name of the location of the global config.
*/
private static final String GLOBAL_CONFIG_LOCATION = "global/config";
/**
* The wrapper class instance. Used to access the global cluster if possible.
*/
private final ServerWrapper wrapper;
/**
* The id of the local cluster.
*/
private final int id;
/**
* The id of the internal client used in this server
*/
private final int idClient;
/**
* Cache which holds the signatureStorages for the consistency.
*/
private final Cache<Long, SignatureStorage> signatureStorageCache = Caffeine.newBuilder().build();
/**
* The last sent commit, do not put anything under this number in the signature cache.
*/
private long lastSent = 0;
/**
* The serviceProxy to establish communication with the other replicas.
*/
private final ServiceProxy proxy;
/**
* SignatureStorageCache lock to be sure that we compare correctly.
*/
private static final Object lock = new Object();
/**
* Thread pool for message sending.
*/
private final ExecutorService service = Executors.newSingleThreadExecutor();
GlobalClusterSlave(final int id, @NotNull final ServerWrapper wrapper, final ServerInstrumentation instrumentation)
{
super(id, GLOBAL_CONFIG_LOCATION, wrapper, instrumentation);
this.id = id;
this.idClient = id + 1000;
this.wrapper = wrapper;
Log.getLogger().info("Turning on client proxy with id:" + idClient);
this.proxy = new ServiceProxy(this.idClient, GLOBAL_CONFIG_LOCATION);
Log.getLogger().info("Turned on global cluster with id:" + id);
}
/**
* Every byte array is one request.
*
* @param bytes the requests.
* @param messageContexts the contexts.
* @return the answers of all requests in this batch.
*/
@Override
public byte[][] appExecuteBatch(final byte[][] bytes, final MessageContext[] messageContexts)
{
byte[][] allResults = new byte[bytes.length][];
for (int i = 0; i < bytes.length; ++i)
{
if (messageContexts != null && messageContexts[i] != null)
{
KryoPool pool = new KryoPool.Builder(super.getFactory()).softReferences().build();
Kryo kryo = pool.borrow();
Input input = new Input(bytes[i]);
String type = kryo.readObject(input, String.class);
if (Constants.COMMIT_MESSAGE.equals(type))
{
final Long timeStamp = kryo.readObject(input, Long.class);
byte[] result = executeCommit(kryo, input, timeStamp);
pool.release(kryo);
allResults[i] = result;
}
else
{
Log.getLogger().error("Return empty bytes for message type: " + type);
allResults[i] = makeEmptyAbortResult();
updateCounts(0, 0, 0, 1);
}
}
else
{
Log.getLogger().error("Received message with empty context!");
allResults[i] = makeEmptyAbortResult();
updateCounts(0, 0, 0, 1);
}
}
return allResults;
}
@Override
void readSpecificData(final Input input, final Kryo kryo)
{
final int length = kryo.readObject(input, Integer.class);
for (int i = 0; i < length; i++)
{
try
{
signatureStorageCache.put(kryo.readObject(input, Long.class), kryo.readObject(input, SignatureStorage.class));
}
catch (ClassCastException ex)
{
Log.getLogger().warn("Unable to restore signatureStoreMap entry: " + i + " at server: " + id, ex);
}
}
}
@Override
public Output writeSpecificData(final Output output, final Kryo kryo)
{
if (signatureStorageCache == null)
{
return output;
}
Log.getLogger().warn("Size at global: " + signatureStorageCache.estimatedSize());
final Map<Long, SignatureStorage> copy = signatureStorageCache.asMap();
kryo.writeObject(output, copy.size());
for (final Map.Entry<Long, SignatureStorage> entrySet : copy.entrySet())
{
kryo.writeObject(output, entrySet.getKey());
kryo.writeObject(output, entrySet.getValue());
}
return output;
}
/**
* Check for conflicts and unpack things for conflict handle check.
*
* @param kryo the kryo instance.
* @param input the input.
* @return the response.
*/
private synchronized byte[] executeCommit(final Kryo kryo, final Input input, final long timeStamp)
{
Log.getLogger().info("Execute commit");
//Read the inputStream.
final List readsSetNodeX = kryo.readObject(input, ArrayList.class);
final List readsSetRelationshipX = kryo.readObject(input, ArrayList.class);
final List writeSetX = kryo.readObject(input, ArrayList.class);
//Create placeHolders.
ArrayList<NodeStorage> readSetNode;
ArrayList<RelationshipStorage> readsSetRelationship;
ArrayList<IOperation> localWriteSet;
input.close();
Output output = new Output(128);
kryo.writeObject(output, Constants.COMMIT_RESPONSE);
try
{
readSetNode = (ArrayList<NodeStorage>) readsSetNodeX;
readsSetRelationship = (ArrayList<RelationshipStorage>) readsSetRelationshipX;
localWriteSet = (ArrayList<IOperation>) writeSetX;
}
catch (Exception e)
{
Log.getLogger().warn("Couldn't convert received data to sets. Returning abort", e);
kryo.writeObject(output, Constants.ABORT);
kryo.writeObject(output, getGlobalSnapshotId());
//Send abort to client and abort
byte[] returnBytes = output.getBuffer();
output.close();
return returnBytes;
}
if (!ConflictHandler.checkForConflict(super.getGlobalWriteSet(),
super.getLatestWritesSet(),
new ArrayList<>(localWriteSet),
readSetNode,
readsSetRelationship,
timeStamp,
wrapper.getDataBaseAccess()))
{
updateCounts(0, 0, 0, 1);
Log.getLogger()
.info("Found conflict, returning abort with timestamp: " + timeStamp + " globalSnapshot at: " + getGlobalSnapshotId() + " and writes: "
+ localWriteSet.size()
+ " and reads: " + readSetNode.size() + " + " + readsSetRelationship.size());
kryo.writeObject(output, Constants.ABORT);
kryo.writeObject(output, getGlobalSnapshotId());
if (!localWriteSet.isEmpty())
{
Log.getLogger().info("Aborting of: " + getGlobalSnapshotId() + " localId: " + timeStamp);
//Log.getLogger().info("Global: " + super.getGlobalWriteSet().size() + " id: " + super.getId());
//Log.getLogger().info("Latest: " + super.getLatestWritesSet().size() + " id: " + super.getId());
}
//Send abort to client and abort
byte[] returnBytes = output.getBuffer();
output.close();
return returnBytes;
}
if (!localWriteSet.isEmpty())
{
Log.getLogger().info("Comitting: " + getGlobalSnapshotId() + " localId: " + timeStamp);
//Log.getLogger().info("Global: " + super.getGlobalWriteSet().size() + " id: " + super.getId());
//Log.getLogger().info("Latest: " + super.getLatestWritesSet().size() + " id: " + super.getId());
final RSAKeyLoader rsaLoader = new RSAKeyLoader(idClient, GLOBAL_CONFIG_LOCATION, false);
super.executeCommit(localWriteSet, rsaLoader, idClient);
if (wrapper.getLocalCLuster() != null)
{
signCommitWithDecisionAndDistribute(localWriteSet, Constants.COMMIT, getGlobalSnapshotId(), kryo, idClient);
}
}
else
{
updateCounts(0, 0, 1, 0);
}
kryo.writeObject(output, Constants.COMMIT);
kryo.writeObject(output, getGlobalSnapshotId());
byte[] returnBytes = output.getBuffer();
output.close();
Log.getLogger().info("No conflict found, returning commit with snapShot id: " + getGlobalSnapshotId() + " size: " + returnBytes.length);
return returnBytes;
}
/**
* Check for conflicts and unpack things for conflict handle check.
*
* @param kryo the kryo instance.
* @param input the input.
* @return the response.
*/
private byte[] executeReadOnlyCommit(final Kryo kryo, final Input input, final long timeStamp)
{
//Read the inputStream.
final List readsSetNodeX = kryo.readObject(input, ArrayList.class);
final List readsSetRelationshipX = kryo.readObject(input, ArrayList.class);
final List writeSetX = kryo.readObject(input, ArrayList.class);
//Create placeHolders.
ArrayList<NodeStorage> readSetNode;
ArrayList<RelationshipStorage> readsSetRelationship;
ArrayList<IOperation> localWriteSet;
input.close();
Output output = new Output(128);
kryo.writeObject(output, Constants.COMMIT_RESPONSE);
try
{
readSetNode = (ArrayList<NodeStorage>) readsSetNodeX;
readsSetRelationship = (ArrayList<RelationshipStorage>) readsSetRelationshipX;
localWriteSet = (ArrayList<IOperation>) writeSetX;
}
catch (Exception e)
{
Log.getLogger().warn("Couldn't convert received data to sets. Returning abort", e);
kryo.writeObject(output, Constants.ABORT);
kryo.writeObject(output, getGlobalSnapshotId());
//Send abort to client and abort
byte[] returnBytes = output.getBuffer();
output.close();
return returnBytes;
}
if (!ConflictHandler.checkForConflict(super.getGlobalWriteSet(),
super.getLatestWritesSet(),
localWriteSet,
readSetNode,
readsSetRelationship,
timeStamp,
wrapper.getDataBaseAccess()))
{
updateCounts(0, 0, 0, 1);
Log.getLogger()
.info("Found conflict, returning abort with timestamp: " + timeStamp + " globalSnapshot at: " + getGlobalSnapshotId() + " and writes: "
+ localWriteSet.size()
+ " and reads: " + readSetNode.size() + " + " + readsSetRelationship.size());
kryo.writeObject(output, Constants.ABORT);
kryo.writeObject(output, getGlobalSnapshotId());
//Send abort to client and abort
byte[] returnBytes = output.getBuffer();
output.close();
return returnBytes;
}
updateCounts(0, 0, 1, 0);
kryo.writeObject(output, Constants.COMMIT);
kryo.writeObject(output, getGlobalSnapshotId());
byte[] returnBytes = output.getBuffer();
output.close();
Log.getLogger().info("No conflict found, returning commit with snapShot id: " + getGlobalSnapshotId() + " size: " + returnBytes.length);
return returnBytes;
}
private void signCommitWithDecisionAndDistribute(
final List<IOperation> localWriteSet, final String decision, final long snapShotId, final Kryo kryo, final int idClient)
{
Log.getLogger().info("Sending signed commit to the other global replicas");
final RSAKeyLoader rsaLoader = new RSAKeyLoader(idClient, GLOBAL_CONFIG_LOCATION, false);
//Todo probably will need a bigger buffer in the future. size depending on the set size?
final Output output = new Output(0, 100240);
kryo.writeObject(output, Constants.SIGNATURE_MESSAGE);
kryo.writeObject(output, decision);
kryo.writeObject(output, snapShotId);
kryo.writeObject(output, localWriteSet);
final byte[] message = output.toBytes();
final byte[] signature;
try
{
signature = TOMUtil.signMessage(rsaLoader.loadPrivateKey(), message);
}
catch (Exception e)
{
Log.getLogger().warn("Unable to sign message at server " + getId(), e);
return;
}
SignatureStorage signatureStorage = signatureStorageCache.getIfPresent(snapShotId);
if (signatureStorage != null)
{
if (signatureStorage.getMessage().length != output.toBytes().length)
{
Log.getLogger()
.info("Message in signatureStorage: " + signatureStorage.getMessage().length + " message of committing server: " + message.length + "id: "
+ snapShotId);
//signatureStorage.setProcessed();
}
}
else
{
Log.getLogger().info("Size of message stored is: " + message.length);
signatureStorage = new SignatureStorage(getReplica().getReplicaContext().getStaticConfiguration().getF() + 1, message, decision);
signatureStorageCache.put(snapShotId, signatureStorage);
}
signatureStorage.setProcessed();
Log.getLogger().info("Set processed by global cluster: " + snapShotId + " by: " + idClient);
signatureStorage.addSignatures(idClient, signature);
if (signatureStorage.hasEnough())
{
Log.getLogger().info("Sending update to slave signed by all members: " + snapShotId);
final Output messageOutput = new Output(100096);
kryo.writeObject(messageOutput, Constants.UPDATE_SLAVE);
kryo.writeObject(messageOutput, decision);
kryo.writeObject(messageOutput, snapShotId);
kryo.writeObject(messageOutput, signatureStorage);
final MessageThread runnable = new MessageThread(messageOutput.getBuffer());
//updateSlave(slaveUpdateOutput.getBuffer());
//updateNextSlave(slaveUpdateOutput.getBuffer());
service.submit(runnable);
messageOutput.close();
signatureStorage.setDistributed();
signatureStorageCache.put(snapShotId, signatureStorage);
signatureStorageCache.invalidate(snapShotId);
lastSent = snapShotId;
}
else
{
signatureStorageCache.put(snapShotId, signatureStorage);
}
kryo.writeObject(output, message.length);
kryo.writeObject(output, signature.length);
output.writeBytes(signature);
proxy.sendMessageToTargets(output.getBuffer(), 0, proxy.getViewManager().getCurrentViewProcesses(), TOMMessageType.UNORDERED_REQUEST);
output.close();
}
private static class SenderThread extends Thread
{
private final byte[] bytes;
private final ServiceProxy proxy;
public SenderThread(final byte[] bytes, @NotNull final ServiceProxy proxy)
{
this.bytes = bytes;
this.proxy = proxy;
}
@Override
public void run()
{
byte[] respondBytes = null;
while(respondBytes == null)
{
respondBytes = proxy.invokeUnordered(bytes);
}
}
}
/**
* Handle a signature message.
*
* @param input the message.
* @param messageContext the context.
* @param kryo the kryo object.
*/
private void handleSignatureMessage(final Input input, final MessageContext messageContext, final Kryo kryo)
{
//Our own message.
if (idClient == messageContext.getSender())
{
return;
}
final byte[] buffer = input.getBuffer();
final String decision = kryo.readObject(input, String.class);
final Long snapShotId = kryo.readObject(input, Long.class);
final List writeSet = kryo.readObject(input, ArrayList.class);
final ArrayList<IOperation> localWriteSet;
if(lastSent > snapShotId)
{
final SignatureStorage tempStorage = signatureStorageCache.getIfPresent(snapShotId);
if(tempStorage == null || tempStorage.isDistributed())
{
signatureStorageCache.invalidate(snapShotId);
return;
}
}
try
{
localWriteSet = (ArrayList<IOperation>) writeSet;
}
catch (final ClassCastException e)
{
Log.getLogger().warn("Couldn't convert received signature message.", e);
return;
}
Log.getLogger().info("Server: " + id + " Received message to sign with snapShotId: "
+ snapShotId + " of Server "
+ messageContext.getSender()
+ " and decision: " + decision
+ " and a writeSet of the length of: " + localWriteSet.size());
final int messageLength = kryo.readObject(input, Integer.class);
final int signatureLength = kryo.readObject(input, Integer.class);
final byte[] signature = input.readBytes(signatureLength);
//Not required anymore.
input.close();
final RSAKeyLoader rsaLoader = new RSAKeyLoader(messageContext.getSender(), GLOBAL_CONFIG_LOCATION, false);
final PublicKey key;
try
{
key = rsaLoader.loadPublicKey();
}
catch (Exception e)
{
Log.getLogger().warn("Unable to load public key on server " + id + " sent by server " + messageContext.getSender(), e);
return;
}
final byte[] message = new byte[messageLength];
System.arraycopy(buffer, 0, message, 0, messageLength);
boolean signatureMatches = TOMUtil.verifySignature(key, message, signature);
//if (signatureMatches)
{
storeSignedMessage(snapShotId, signature, messageContext, decision, message, writeSet);
return;
}
//Log.getLogger().warn("Signature doesn't match of message, throwing message away.");
}
@Override
public byte[] appExecuteUnordered(final byte[] bytes, final MessageContext messageContext)
{
Log.getLogger().info("Received unordered message at global replica");
final KryoPool pool = new KryoPool.Builder(getFactory()).softReferences().build();
final Kryo kryo = pool.borrow();
final Input input = new Input(bytes);
final String messageType = kryo.readObject(input, String.class);
Output output = new Output(1, 804800);
switch (messageType)
{
case Constants.READ_MESSAGE:
Log.getLogger().info("Received Node read message");
try
{
kryo.writeObject(output, Constants.READ_MESSAGE);
output = handleNodeRead(input, kryo, output);
}
catch (Exception t)
{
Log.getLogger().error("Error on " + Constants.READ_MESSAGE + ", returning empty read", t);
output.close();
output = makeEmptyReadResponse(Constants.READ_MESSAGE, kryo);
}
break;
case Constants.RELATIONSHIP_READ_MESSAGE:
Log.getLogger().info("Received Relationship read message");
try
{
kryo.writeObject(output, Constants.READ_MESSAGE);
output = handleRelationshipRead(input, kryo, output);
}
catch (Exception t)
{
Log.getLogger().error("Error on " + Constants.RELATIONSHIP_READ_MESSAGE + ", returning empty read", t);
output = makeEmptyReadResponse(Constants.RELATIONSHIP_READ_MESSAGE, kryo);
}
break;
case Constants.SIGNATURE_MESSAGE:
if (wrapper.getLocalCLuster() != null)
{
handleSignatureMessage(input, messageContext, kryo);
}
break;
case Constants.REGISTER_GLOBALLY_MESSAGE:
Log.getLogger().info("Received register globally message");
output.close();
input.close();
pool.release(kryo);
return handleRegisteringSlave(input, kryo);
case Constants.REGISTER_GLOBALLY_CHECK:
Log.getLogger().info("Received globally check message");
output.close();
input.close();
pool.release(kryo);
return handleGlobalRegistryCheck(input, kryo);
case Constants.COMMIT:
Log.getLogger().info("Received commit message");
output.close();
byte[] result = handleReadOnlyCommit(input, kryo);
input.close();
pool.release(kryo);
Log.getLogger().info("Return it to client, size: " + result.length);
return result;
default:
Log.getLogger().warn("Incorrect operation sent unordered to the server");
break;
}
byte[] returnValue = output.getBuffer();
Log.getLogger().info("Return it to client, size: " + returnValue.length);
input.close();
output.close();
pool.release(kryo);
return returnValue;
}
private byte[] handleReadOnlyCommit(final Input input, final Kryo kryo)
{
final Long timeStamp = kryo.readObject(input, Long.class);
return executeReadOnlyCommit(kryo, input, timeStamp);
}
/**
* Handle the check for the global registering of a slave.
*
* @param input the incoming message.
* @param kryo the kryo instance.
* @return the reply
*/
private byte[] handleGlobalRegistryCheck(final Input input, final Kryo kryo)
{
final Output output = new Output(512);
kryo.writeObject(output, Constants.REGISTER_GLOBALLY_CHECK);
boolean decision = false;
if (!wrapper.getLocalCLuster().isPrimary() || wrapper.getLocalCLuster().askIfIsPrimary(kryo.readObject(input, Integer.class), kryo.readObject(input, Integer.class), kryo))
{
decision = true;
}
kryo.writeObject(output, decision);
final byte[] result = output.getBuffer();
output.close();
input.close();
return result;
}
/**
* This message comes from the local cluster.
* Will respond true if it can register.
* Message which handles slaves registering at the global cluster.
*
* @param kryo the kryo instance.
* @param input the message.
* @return the message in bytes.
*/
@SuppressWarnings("squid:S2095")
private byte[] handleRegisteringSlave(final Input input, final Kryo kryo)
{
final int localClusterID = kryo.readObject(input, Integer.class);
final int newPrimary = kryo.readObject(input, Integer.class);
final int oldPrimary = kryo.readObject(input, Integer.class);
final ServiceProxy localProxy = new ServiceProxy(1000 + oldPrimary, "local" + localClusterID);
final Output output = new Output(512);
kryo.writeObject(output, Constants.REGISTER_GLOBALLY_CHECK);
kryo.writeObject(output, newPrimary);
byte[] result = localProxy.invokeUnordered(output.getBuffer());
final Output nextOutput = new Output(512);
kryo.writeObject(output, Constants.REGISTER_GLOBALLY_REPLY);
final Input answer = new Input(result);
if (Constants.REGISTER_GLOBALLY_REPLY.equals(answer.readString()))
{
kryo.writeObject(nextOutput, answer.readBoolean());
}
final byte[] returnBuffer = nextOutput.getBuffer();
nextOutput.close();
answer.close();
localProxy.close();
output.close();
return returnBuffer;
//remove currentView and edit system.config
//If alright send the result to all remaining global clusters so that they update themselves.
}
/**
* Store the signed message on the server.
* If n-f messages arrived send it to client.
*
* @param snapShotId the snapShotId as key.
* @param signature the signature
* @param context the message context.
* @param decision the decision.
* @param message the message.
*/
private void storeSignedMessage(
final Long snapShotId,
final byte[] signature,
@NotNull final MessageContext context,
final String decision,
final byte[] message,
final List<IOperation> writeSet)
{
final SignatureStorage signatureStorage;
synchronized (lock)
{
final SignatureStorage tempStorage = signatureStorageCache.getIfPresent(snapShotId);
signatureStorageCache.invalidate(snapShotId);
if (tempStorage == null)
{
signatureStorage = new SignatureStorage(super.getReplica().getReplicaContext().getStaticConfiguration().getF() + 1, message, decision);
Log.getLogger().info("Replica: " + id + " did not have the transaction prepared. Might be slow or corrupted, message size stored: " + message.length);
}
else
{
signatureStorage = tempStorage;
}
if (signatureStorage.getMessage().length != message.length)
{
Log.getLogger().info("Message in signatureStorage: " + signatureStorage.getMessage().length + " message of writing server "
+ message.length + " ws: " + writeSet.size() + " id: " + snapShotId);
}
if (!decision.equals(signatureStorage.getDecision()))
{
Log.getLogger().warn("Replica: " + id + " did receive a different decision of replica: " + context.getSender() + ". Might be corrupted.");
return;
}
signatureStorage.addSignatures(context.getSender(), signature);
Log.getLogger().info("Adding signature to signatureStorage, has: " + signatureStorage.getSignatures().size() + " is: " + signatureStorage.isProcessed()
+ " by: " + context.getSender());
if (signatureStorage.hasEnough())
{
Log.getLogger().info("Sending update to slave signed by all members: " + snapShotId);
if (signatureStorage.isProcessed())
{
final Output messageOutput = new Output(100096);
KryoPool pool = new KryoPool.Builder(super.getFactory()).softReferences().build();
Kryo kryo = pool.borrow();
kryo.writeObject(messageOutput, Constants.UPDATE_SLAVE);
kryo.writeObject(messageOutput, decision);
kryo.writeObject(messageOutput, snapShotId);
kryo.writeObject(messageOutput, signatureStorage);
final MessageThread runnable = new MessageThread(messageOutput.getBuffer());
//updateSlave(slaveUpdateOutput.getBuffer());
//updateNextSlave(slaveUpdateOutput.getBuffer());
service.submit(runnable);
messageOutput.close();
pool.release(kryo);
lastSent = snapShotId;
signatureStorage.setDistributed();
}
}
if(!signatureStorage.isDistributed())
{
signatureStorageCache.put(snapShotId, signatureStorage);
}
}
}
private void updateSlave(final byte[] message)
{
if (wrapper.getLocalCLuster() != null)
{
Log.getLogger().info("Notifying local cluster!");
wrapper.getLocalCLuster().propagateUpdate(message);
}
}
@Override
public void putIntoWriteSet(final long currentSnapshot, final List<IOperation> localWriteSet)
{
super.putIntoWriteSet(currentSnapshot, localWriteSet);
if (wrapper.getLocalCLuster() != null)
{
wrapper.getLocalCLuster().putIntoWriteSet(currentSnapshot, localWriteSet);
}
}
/**
* Invoke a message to the global cluster.
*
* @param input the input object.
* @return the response.
*/
Output invokeGlobally(final Input input)
{
return new Output(proxy.invokeOrdered(input.getBuffer()));
}
/**
* Closes the global cluster and his code.
*/
public void close()
{
super.terminate();
proxy.close();
}
private class MessageThread implements Runnable
{
private final byte[] message;
MessageThread(byte[] message)
{
this.message = message;
}
@Override
public void run()
{
updateSlave(message);
}
/**
* Update the slave with a transaction.
*
* @param message the message to propagate.
*/
private void updateSlave(final byte[] message)
{
if (wrapper.getLocalCLuster() != null)
{
Log.getLogger().info("Notifying local cluster!");
wrapper.getLocalCLuster().propagateUpdate(message);
}
}
}
}
|
package me.chaopeng.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* OrderedThreadPoolExecutornetty3OrderedMemoryAwareThreadPoolExecutor<b>MemoryAware</b>
* <p/>
* <ul>
* <li>keyRunableexecute</li>
* <li>keyRunable</li>
* <li>keyRunableexecute</li>
* <li>keyRunablekey</li>
* <li>taskhash</li>
* </ul>
*
* @author chao
* @see OrderedRunable
*/
public final class OrderedThreadPoolExecutor extends ForkJoinPool {
private static Logger logger = LoggerFactory.getLogger(OrderedThreadPoolExecutor.class);
private final static int DEFAULT_NUM_EXECUTOR = 1024;
private final static int DEFAULT_BATCH_LIMIT = 5;
/**
* executors
*/
private final ChildExecutor[] childExecutors;
/**
* the limit of batch process tasks
*/
private final int batchLimit;
/**
* Executors.newFiexedThreadPool()
*
* @param corePoolSize
* @return OrderedThreadPoolExecutor
*/
public static OrderedThreadPoolExecutor newFixesOrderedThreadPool(int corePoolSize) {
return newFixesOrderedThreadPool(corePoolSize, DEFAULT_NUM_EXECUTOR, DEFAULT_BATCH_LIMIT);
}
/**
* Executors.newFiexedThreadPool()
*
* @param corePoolSize
* @param numOfExecutor executor
* @param batchLimit executor
* @return OrderedThreadPoolExecutor
*/
public static OrderedThreadPoolExecutor newFixesOrderedThreadPool(int corePoolSize, int numOfExecutor, int batchLimit) {
logger.info("!!! init " + corePoolSize + " core OrderedThreadPoolExecutor");
return new OrderedThreadPoolExecutor(
corePoolSize, numOfExecutor, batchLimit
);
}
/**
* Creates a new instance.
*
* @param numOfExecutor the number of executor
* @param batchLimit the limit of batch process tasks
*/
private OrderedThreadPoolExecutor(int corePoolSize, int numOfExecutor, int batchLimit) {
super(corePoolSize, ForkJoinPool.defaultForkJoinWorkerThreadFactory, new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
logger.error(e.getMessage(), e);
}
}, true);
this.childExecutors = new ChildExecutor[numOfExecutor];
for (int i = 0; i < this.childExecutors.length; ++i) {
this.childExecutors[i] = new ChildExecutor(i);
}
this.batchLimit = batchLimit;
}
@Override
public void execute(Runnable task) {
if (task instanceof OrderedRunable) {
doExecute((OrderedRunable) task);
} else {
throw new RejectedExecutionException("task must be enclosed an OrderedRunable.");
}
}
private void doExecute(OrderedRunable task) {
getChildExecutor(task.key).execute(task);
}
private void doUnorderedExecute(ChildExecutor runnable) {
super.execute(runnable);
}
private ChildExecutor getChildExecutor(Long key) {
return childExecutors[(int) (key % childExecutors.length)];
}
/**
* Runable Task for OrderedThreadPoolExecutor
*
* @see OrderedThreadPoolExecutor
*/
public abstract static class OrderedRunable implements Runnable {
protected Long key;
public OrderedRunable(Long key) {
this.key = key;
}
@Override
public String toString() {
return "OrderedRunable{" +
"key=" + key +
'}';
}
}
protected final class ChildExecutor implements Executor, Runnable {
private final Queue<Runnable> tasks = new ConcurrentLinkedQueue<>();
private final AtomicBoolean isRunning = new AtomicBoolean();
private final int executorId;
public ChildExecutor(int executorId) {
this.executorId = executorId;
}
public void execute(Runnable command) {
// TODO: What todo if the add return false ?
tasks.add(command);
// logger.debug("add cmd " + command + " to ChildExecutor-" + executorId);
// add to schedule if executor is not waiting to process
if (isRunning.compareAndSet(false, true)) {
doUnorderedExecute(this);
}
}
public void run() {
for (int i = 0; i < batchLimit; ++i) {
final Runnable task = tasks.poll();
// if the task is null we should exit the loop
if (task == null) {
break;
}
// logger.debug("execute cmd " + task + " in ChildExecutor-" + executorId);
boolean ran = false;
try {
task.run();
ran = true;
} catch (RuntimeException e) {
if (!ran) {
logger.error("execute cmd " + task + " error:" + e.getMessage(), e);
}
// throw e;
}
}
// logger.debug("ChildExecutor-" + executorId + " exit");
// re-add to thread pool if tasks is not empty
isRunning.set(false);
if (!tasks.isEmpty()) {
if (isRunning.compareAndSet(false, true)) {
doUnorderedExecute(this);
isRunning.set(true);
}
}
}
}
}
|
package mil.dds.anet.resources;
import java.util.List;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException;
import com.codahale.metrics.annotation.Timed;
import com.microsoft.sqlserver.jdbc.SQLServerException;
import io.dropwizard.auth.Auth;
import mil.dds.anet.AnetObjectEngine;
import mil.dds.anet.beans.ApprovalStep;
import mil.dds.anet.beans.Organization;
import mil.dds.anet.beans.Organization.OrganizationType;
import mil.dds.anet.beans.Person;
import mil.dds.anet.beans.Poam;
import mil.dds.anet.beans.lists.AbstractAnetBeanList.OrganizationList;
import mil.dds.anet.beans.lists.AbstractAnetBeanList.PoamList;
import mil.dds.anet.beans.search.OrganizationSearchQuery;
import mil.dds.anet.database.OrganizationDao;
import mil.dds.anet.graphql.GraphQLFetcher;
import mil.dds.anet.graphql.GraphQLParam;
import mil.dds.anet.graphql.IGraphQLResource;
import mil.dds.anet.utils.AnetAuditLogger;
import mil.dds.anet.utils.AuthUtils;
import mil.dds.anet.utils.DaoUtils;
import mil.dds.anet.utils.ResponseUtils;
import mil.dds.anet.utils.Utils;
@Path("/api/organizations")
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
public class OrganizationResource implements IGraphQLResource {
private OrganizationDao dao;
private AnetObjectEngine engine;
public OrganizationResource(AnetObjectEngine engine) {
this.dao = engine.getOrganizationDao();
this.engine = engine;
}
@Override
public Class<Organization> getBeanClass() {
return Organization.class;
}
public Class<OrganizationList> getBeanListClass() {
return OrganizationList.class;
}
@Override
public String getDescription() {
return "Organizations";
}
@GET
@Timed
@GraphQLFetcher
@Path("/")
public OrganizationList getAll(@DefaultValue("0") @QueryParam("pageNum") Integer pageNum,
@DefaultValue("100") @QueryParam("pageSize") Integer pageSize) {
return dao.getAll(pageNum, pageSize);
}
@GET
@Timed
@GraphQLFetcher
@Path("/topLevel")
public OrganizationList getTopLevelOrgs(@QueryParam("type") OrganizationType type) {
return new OrganizationList(dao.getTopLevelOrgs(type));
}
@POST
@Timed
@Path("/new")
@RolesAllowed("ADMINISTRATOR")
public Organization createNewOrganization(Organization org, @Auth Person user) {
AuthUtils.assertAdministrator(user);
final Organization created;
try {
created = dao.insert(org);
} catch (UnableToExecuteStatementException e) {
throw handleSqlException(e);
}
if (org.getPoams() != null) {
//Assign all of these poams to this organization.
for (Poam p : org.getPoams()) {
engine.getPoamDao().setResponsibleOrgForPoam(p, created);
}
}
if (org.getApprovalSteps() != null) {
//Create the approval steps
for (ApprovalStep step : org.getApprovalSteps()) {
validateApprovalStep(step);
step.setAdvisorOrganizationId(created.getId());
engine.getApprovalStepDao().insertAtEnd(step);
}
}
AnetAuditLogger.log("Organization {} created by {}", org, user);
return created;
}
@GET
@Timed
@GraphQLFetcher
@Path("/{id}")
public Organization getById(@PathParam("id") int id) {
Organization org = dao.getById(id);
if (org == null) { throw new WebApplicationException(Status.NOT_FOUND); }
return org;
}
/**
* Primary endpoint to update all aspects of an Organization.
* - Organization (shortName, longName, identificationCode)
* - Poams
* - Approvers
*/
@POST
@Timed
@Path("/update")
@RolesAllowed("SUPER_USER")
public Response updateOrganization(Organization org, @Auth Person user) {
//Verify correct Organization
AuthUtils.assertSuperUserForOrg(user, org);
final int numRows;
try {
numRows = dao.update(org);
} catch (UnableToExecuteStatementException e) {
throw handleSqlException(e);
}
if (org.getPoams() != null || org.getApprovalSteps() != null) {
//Load the existing org, so we can check for differences.
Organization existing = dao.getById(org.getId());
if (org.getPoams() != null) {
Utils.addRemoveElementsById(existing.loadPoams(), org.getPoams(),
newPoam -> engine.getPoamDao().setResponsibleOrgForPoam(newPoam, existing),
oldPoamId -> engine.getPoamDao().setResponsibleOrgForPoam(Poam.createWithId(oldPoamId), null));
}
if (org.getApprovalSteps() != null) {
for (ApprovalStep step : org.getApprovalSteps()) {
validateApprovalStep(step);
step.setAdvisorOrganizationId(org.getId());
}
List<ApprovalStep> existingSteps = existing.loadApprovalSteps();
Utils.addRemoveElementsById(existingSteps, org.getApprovalSteps(),
newStep -> engine.getApprovalStepDao().insert(newStep),
oldStepId -> engine.getApprovalStepDao().deleteStep(oldStepId));
for (int i = 0;i < org.getApprovalSteps().size();i++) {
ApprovalStep curr = org.getApprovalSteps().get(i);
ApprovalStep next = (i == (org.getApprovalSteps().size() - 1)) ? null : org.getApprovalSteps().get(i + 1);
curr.setNextStepId(DaoUtils.getId(next));
ApprovalStep existingStep = Utils.getById(existingSteps, curr.getId());
//If this step didn't exist before, we still need to set the nextStepId on it, but don't need to do a deep update.
if (existingStep == null) {
engine.getApprovalStepDao().update(curr);
} else {
//Check for updates to name, nextStepId and approvers.
ApprovalStepResource.updateStep(curr, existingStep);
}
}
}
}
AnetAuditLogger.log("Organization {} edited by {}", org, user);
return (numRows == 1) ? Response.ok().build() : Response.status(Status.NOT_FOUND).build();
}
@POST
@Timed
@GraphQLFetcher
@Path("/search")
public OrganizationList search(@GraphQLParam("query") OrganizationSearchQuery query) {
return dao.search(query);
}
@GET
@Timed
@Path("/search")
public OrganizationList search(@Context HttpServletRequest request) {
try {
return search(ResponseUtils.convertParamsToBean(request, OrganizationSearchQuery.class));
} catch (IllegalArgumentException e) {
throw new WebApplicationException(e.getMessage(), e.getCause(), Status.BAD_REQUEST);
}
}
@GET
@Timed
@Path("/{id}/poams")
public PoamList getPoams(@PathParam("id") Integer orgId) {
return new PoamList(AnetObjectEngine.getInstance().getPoamDao().getPoamsByOrganizationId(orgId));
}
private WebApplicationException handleSqlException(UnableToExecuteStatementException e) {
// FIXME: Ugly way to handle the unique index on identificationCode
final Throwable cause = e.getCause();
if (cause != null && cause instanceof SQLServerException) {
final String message = cause.getMessage();
if (message != null && message.contains(" duplicate ")) {
return new WebApplicationException("Duplicate identification code", Status.CONFLICT);
}
}
return new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
}
private void validateApprovalStep(ApprovalStep step) {
if (Utils.isEmptyOrNull(step.getName())) {
throw new WebApplicationException("A name is required for every approval step");
}
if (Utils.isEmptyOrNull(step.loadApprovers())) {
throw new WebApplicationException("An approver is required for every approval step");
}
}
}
|
package mpicbg.spim.data.sequence;
import java.text.ParseException;
import java.util.HashMap;
public class TimePointsPattern extends TimePoints
{
private String pattern;
public TimePointsPattern( final String pattern ) throws ParseException
{
setPattern( pattern );
}
public String getPattern()
{
return pattern;
}
protected void setPattern( final String pattern ) throws ParseException
{
this.pattern = pattern;
final HashMap< Integer, TimePoint > map = new HashMap< Integer, TimePoint >();
if ( pattern == null || "".equals( pattern ) )
{
// set an empty list
setTimePoints( map );
return;
}
for ( final int t : IntegerPattern.parseIntegerString( pattern ) )
map.put( t, new TimePoint( t ) );
// set a full list (this copies the list)
setTimePoints( map );
}
protected TimePointsPattern()
{}
}
|
package net.cyanwool.api.entity.component;
import net.cyanwool.api.entity.Entity;
public interface Component {
public void initialization();
public boolean isNeedUpdate();
public void update();
public boolean autoUpdate();
public Entity getEntity();
public String getID();
}
|
package net.darkhax.bookshelf.inventory;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.tags.ITag;
import net.minecraft.util.IItemProvider;
import net.minecraftforge.items.ItemStackHandler;
/**
* An implementation of ItemStackHandler that combines lambdas with a build-esq pattern.
*
* @param <T> The handler's own type. This is used to spare devs from having to cast their
* after using a builder method.
*/
public class ItemHandler<T extends ItemHandler<T>> extends ItemStackHandler {
/**
* Function used to derive the max stack size of a slot. This is a stand in for
* {@link #getSlotLimit(int)}.
*/
private IntFunction<Integer> maxSize = super::getSlotLimit;
/**
* Predicate used to check if an item can be inserted into a slot. This is a stand in for
* {@link #isItemValid(int, ItemStack)}.
*/
private BiPredicate<Integer, ItemStack> validItems = super::isItemValid;
/**
* Listeners which detect changes to the internal inventory.
*/
private final List<Consumer<Integer>> changeListener = new ArrayList<>();
/**
* Creates a new item handler with only one slot.
*/
public ItemHandler() {
this(1);
}
/**
* Creates a new item handler with any number of slots.
*
* @param invSize The amount of slots to track.
*/
public ItemHandler(int invSize) {
super(invSize);
}
/**
* Sets the max stack size of all slots to a single value.
*
* @param maxSize The max stack size for every slot.
* @return The same item handler.
*/
public T withMaxSize (int maxSize) {
return this.withMaxSize(slot -> maxSize);
}
/**
* Sets the max stack size for all slots using an int array. If a slot ID is not within the
* bounds of the array a max size of 0 will be used. See {@link #withMaxSize(int[], int)}
* for custom default values.
*
* @param maxSizes An array of max stack sizes based on the slot index.
* @return The same item handler.
*/
public T withMaxSize (int[] maxSizes) {
return this.withMaxSize(maxSizes, 0);
}
/**
* Sets the max stack size for all slots using an int array. If a slot ID is not within the
* bounds of the array the default size will be used.
*
* @param maxSizes An array of max stack sizes based on the slot index.
* @param defaultSize The default max stack size used when the slot index is out of bounds.
* @return The same item handler.
*/
public T withMaxSize (int[] maxSizes, int defaultSize) {
return this.withMaxSize(slot -> slot >= 0 && slot < maxSizes.length ? maxSizes[slot] : defaultSize);
}
/**
* Sets a function that is used to determine the maximum stack size of a given slot.
*
* @param maxSizeFunc The function that determines stack size for a given slot index.
* @return The same item handler.
*/
public T withMaxSize (IntFunction<Integer> maxSizeFunc) {
this.maxSize = maxSizeFunc;
return this.self();
}
/**
* Sets the inventory to blanket allow/deny any item for every slot in the inventory.
*
* @param isValid Whether or not every item is valid/invalid for insertion.
* @return The same item handler.
*/
public T withItemValidator (boolean isValid) {
return this.withItemValidator( (slot, stack) -> isValid);
}
/**
* Sets the inventory to only accept item stacks from a given set of items.
*
* @param items The items to accept.
* @return The same item handler.
*/
public T withItemValidator (IItemProvider... items) {
return this.withItemValidator(Ingredient.fromItems(items));
}
/**
* Sets the inventory to only accept item stacks from a given item tag.
*
* @param tag The tag to check.
* @return The same item handler.
*/
public T withItemValidator (ITag<Item> tag) {
return this.withItemValidator(Ingredient.fromTag(tag));
}
/**
* Sets a function to test the insertion validity of each individual item stack.
*
* @param validator The validation predicate.
* @return The same item handler.
*/
public T withItemValidator (Predicate<ItemStack> validator) {
return this.withItemValidator( (slot, stack) -> validator.test(stack));
}
/**
* Sets a function to test the insertion validity of an item stack into a given slot.
*
* @param validator A predicate which accepts the slot index and the stack being inserted
* and returns the results of an insertion validity check.
* @return The same item handler.
*/
public T withItemValidator (BiPredicate<Integer, ItemStack> validator) {
this.validItems = validator;
return this.self();
}
/**
* Adds a listener function that will be invoked every time the inventory is changed.
*
* @param listener The listener function.
* @return The same item handler.
*/
public T withChangeListener (Runnable listener) {
return this.withChangeListener(i -> listener.run());
}
/**
* Adds a listener that will be invoked every time the inventory is changed.
*
* @param listener A biconsumer that accepts the slot index and the stack that is now in
* the slot.
* @return The same item handler.
*/
public T withChangeListener (BiConsumer<Integer, ItemStack> listener) {
return this.withChangeListener(slot -> listener.accept(slot, this.getStackInSlot(slot)));
}
/**
* Adds a listener that will be invoked every time the inventory is changed.
*
* @param listener A consumer that accepts the slot index that was modified.
* @return The same item handler.
*/
public T withChangeListener (Consumer<Integer> listener) {
this.changeListener.add(listener);
return this.self();
}
@Override
public int getSlotLimit (int slot) {
return this.maxSize.apply(slot);
}
@Override
public boolean isItemValid (int slot, ItemStack stack) {
return this.validItems.test(slot, stack);
}
@Override
public void onContentsChanged (int slot) {
super.onContentsChanged(slot);
this.changeListener.forEach(listener -> listener.accept(slot));
}
@SuppressWarnings("unchecked")
public T self () {
return (T) this;
}
}
|
package net.elprespufferfish.rssreader;
import static android.widget.Toast.LENGTH_LONG;
import static android.widget.Toast.LENGTH_SHORT;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final Logger LOGGER = LoggerFactory.getLogger(MainActivity.class);
private BroadcastReceiver refreshCompletionReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
refreshDialog.dismiss();
boolean didRefreshComplete = intent.getBooleanExtra(RefreshService.DID_REFRESH_COMPLETE, Boolean.FALSE);
if (!didRefreshComplete) {
Toast.makeText(
MainActivity.this,
MainActivity.this.getString(R.string.refresh_failed),
LENGTH_LONG)
.show();
return;
}
boolean wasRefreshStarted = intent.getBooleanExtra(RefreshService.WAS_REFRESH_STARTED, Boolean.FALSE);
if (!wasRefreshStarted) {
Toast.makeText(
MainActivity.this,
MainActivity.this.getString(R.string.refresh_already_started),
LENGTH_SHORT)
.show();
} else {
Toast.makeText(
MainActivity.this,
MainActivity.this.getString(R.string.refresh_complete),
LENGTH_SHORT)
.show();
MainActivity.this.reloadPager(nullFeed);
}
}
};
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private ViewPager viewPager;
private ArticlePagerAdapter articlePagerAdapter;
private ProgressDialog refreshDialog;
private ShareActionProvider shareActionProvider;
private Feed nullFeed; // sentinel Feed to select 'all' feeds
private Feed currentFeed;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// set up left drawer
ListView drawerList = (ListView) findViewById(R.id.left_drawer);
drawerList.setAdapter(new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.drawer_items)));
drawerList.setOnItemClickListener(new DrawerClickListener());
// tie drawer to action bar
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.string.drawer_open,
R.string.drawer_close);
drawerLayout.setDrawerListener(drawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
this.refreshDialog = new ProgressDialog(this);
refreshDialog.setMessage(getString(R.string.loading_articles));
refreshDialog.setIndeterminate(true);
refreshDialog.setCancelable(false);
Intent intent = getIntent();
if (Intent.ACTION_SEND.equals(intent.getAction())) {
if ("text/plain".equals(intent.getType())) {
String address = intent.getStringExtra(Intent.EXTRA_TEXT);
new AddFeedTask(this).execute(address);
}
}
this.shareActionProvider = new ShareActionProvider(this);
nullFeed = Feed.nullFeed(this);
reloadPager(nullFeed);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.layout.action_bar_menu, menu);
MenuItem shareItem = menu.findItem(R.id.action_share);
MenuItemCompat.setActionProvider(shareItem, shareActionProvider);
if (articlePagerAdapter.getCount() != 0) {
ArticleFragment articleFragment = (ArticleFragment) articlePagerAdapter.getItem(viewPager.getCurrentItem());
updateShareAction(articleFragment);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
// handled by action bar icon
return true;
}
// NOTE: share action is handled by the ShareActionProvider
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
// prevent interactions if a refresh is in progress
// or reload if one just finished
Intent refreshIntent = new Intent(MainActivity.this, RefreshService.class);
ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
RefreshService.RefreshServiceBinder binder = (RefreshService.RefreshServiceBinder) service;
if (binder.isRefreshInProgress()) {
MainActivity.this.refreshDialog.show();
} else if (MainActivity.this.refreshDialog.isShowing()) {
// refresh completed while UI was in the background
MainActivity.this.refreshDialog.dismiss();
reloadPager(nullFeed);
}
MainActivity.this.unbindService(this);
}
@Override
public void onServiceDisconnected(ComponentName name) {
// no-op
}
};
bindService(refreshIntent, serviceConnection, Context.BIND_AUTO_CREATE);
LocalBroadcastManager.getInstance(this).registerReceiver(refreshCompletionReceiver, new IntentFilter(RefreshService.COMPLETION_NOTIFICATION));
}
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(refreshCompletionReceiver);
}
/**
* Don't finish() when we hit back
*/
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
@Override
protected void onDestroy() {
super.onDestroy();
this.articlePagerAdapter.close();
}
private void reloadPager(Feed feed) {
currentFeed = feed;
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.clearOnPageChangeListeners();
if (articlePagerAdapter != null) articlePagerAdapter.close();
articlePagerAdapter = new ArticlePagerAdapter(getSupportFragmentManager(), MainActivity.this, feed.getUrl());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// no-op
}
@Override
public void onPageSelected(int position) {
ArticleFragment articleFragment = (ArticleFragment) articlePagerAdapter.getItem(position);
setTitle(articleFragment);
updateShareAction(articleFragment);
}
@Override
public void onPageScrollStateChanged(int state) {
// no-op
}
});
viewPager.addOnPageChangeListener(new ArticleReadListener(articlePagerAdapter));
viewPager.setAdapter(articlePagerAdapter);
if (articlePagerAdapter.getCount() != 0) {
ArticleFragment articleFragment = (ArticleFragment) articlePagerAdapter.getItem(0);
setTitle(articleFragment);
updateShareAction(articleFragment);
}
}
private void setTitle(ArticleFragment articleFragment) {
Article article = articleFragment.getArguments().getParcelable(ArticleFragment.ARTICLE_KEY);
MainActivity.this.getSupportActionBar().setTitle(article.getFeed());
}
private void updateShareAction(ArticleFragment articleFragment) {
Bundle arguments = articleFragment.getArguments();
Article article = arguments.getParcelable(ArticleFragment.ARTICLE_KEY);
String textToShare = article.getTitle() + "\n\n" + article.getLink();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_SUBJECT, article.getTitle());
intent.putExtra(Intent.EXTRA_TEXT, textToShare);
intent.setType("text/plain");
shareActionProvider.setShareIntent(intent);
}
private class DrawerClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0: { // TODO
// Refresh
refreshDialog.show();
Intent refreshIntent = new Intent(MainActivity.this, RefreshService.class);
refreshIntent.putExtra(RefreshService.FORCE_REFRESH, Boolean.TRUE);
MainActivity.this.startService(refreshIntent);
drawerLayout.closeDrawers();
break;
}
case 1: {
// Add Feed
final View addFeedDialogView = getLayoutInflater().inflate(R.layout.add_feed_dialog, null);
AlertDialog addFeedDialog = new AlertDialog.Builder(MainActivity.this)
.setView(addFeedDialogView)
.setTitle(R.string.add_feed_title)
.setPositiveButton(R.string.add_feed_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();;
EditText feedUrlInput = (EditText) addFeedDialogView.findViewById(R.id.feed_url);
String feedUrl = feedUrlInput.getText().toString();
new AddFeedTask(MainActivity.this).execute(feedUrl);
}
})
.setNegativeButton(R.string.add_feed_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.create();
addFeedDialog.show();
break;
}
case 2: {
// View Feed
Map<Feed, Integer> feeds = Feeds.getInstance().getFeedsWithContent();
final Map<Feed, Integer> allFeeds = new LinkedHashMap<>();
int totalUnread = 0;
for (Integer numUnread : feeds.values()) {
totalUnread += numUnread;
}
allFeeds.put(nullFeed, totalUnread);
allFeeds.putAll(feeds);
int currentFeedIndex = 0;
int i = 0;
List<String> feedNames = new ArrayList<>(allFeeds.size());
for (Map.Entry<Feed, Integer> entry : allFeeds.entrySet()) {
Feed feed = entry.getKey();
feedNames.add(feed.getName() + " (" + entry.getValue() + ")");
if (feed.equals(currentFeed)) {
currentFeedIndex = i;
}
i++;
}
AlertDialog viewFeedDialog = new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.view_feed_title)
.setSingleChoiceItems(feedNames.toArray(new String[0]), currentFeedIndex, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
int selectedPosition = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
Feed selectedFeed = null;
int i = 0;
for (Feed feed : allFeeds.keySet()) {
if (i++ == selectedPosition) {
selectedFeed = feed;
break;
}
}
if (selectedFeed == null) throw new AssertionError("Could not determine selected feed at position " + selectedPosition + " from " + allFeeds);
drawerLayout.closeDrawers();
reloadPager(selectedFeed);
}
})
.create();
viewFeedDialog.show();
break;
}
case 3: {
// Remove Feed
final List<Feed> feeds = Feeds.getInstance().getFeeds();
List<String> feedNames = new ArrayList<>(feeds.size());
for (Feed feed : feeds) feedNames.add(feed.getName());
AlertDialog viewFeedDialog = new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.remove_feed_title)
.setSingleChoiceItems(feedNames.toArray(new String[0]), -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// no-op
}
})
.setPositiveButton(R.string.remove_feed_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
int selectedPosition = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
Feed feedToRemove = feeds.get(selectedPosition);
Feeds.getInstance().removeFeed(feedToRemove);
Toast.makeText(
MainActivity.this,
MainActivity.this.getString(R.string.remove_feed_complete, feedToRemove.getName()),
Toast.LENGTH_LONG)
.show();
drawerLayout.closeDrawers();
if (currentFeed.equals(feedToRemove)) {
reloadPager(nullFeed);
} else {
reloadPager(currentFeed);
}
}
})
.setNegativeButton(R.string.remove_feed_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.create();
viewFeedDialog.show();
break;
}
default:
throw new IllegalArgumentException("Unexpected menu item at position " + position);
}
}
}
}
|
package net.fortuna.ical4j.vcard.property;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.List;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.util.Strings;
import net.fortuna.ical4j.vcard.Group;
import net.fortuna.ical4j.vcard.Parameter;
import net.fortuna.ical4j.vcard.Property;
import net.fortuna.ical4j.vcard.PropertyFactory;
import net.fortuna.ical4j.vcard.parameter.Type;
import net.fortuna.ical4j.vcard.parameter.Value;
import org.apache.commons.lang.StringUtils;
public final class Telephone extends Property {
private static final long serialVersionUID = -7747040131815077325L;
private static final String TEL_SCHEME = "tel";
public static final PropertyFactory<Telephone> FACTORY = new Factory();
private URI uri;
private String value;
/**
* @param uri specifies the URI of a telephone definition
* @param types optional parameter types
*/
public Telephone(URI uri, Type...types) {
this(null, uri, types);
}
/**
* @param group a property group
* @param uri specifies the URI of a telephone definition
* @param types optional parameter types
*/
public Telephone(Group group, URI uri, Type...types) {
super(group, Id.TEL);
this.uri = normalise(uri);
getParameters().add(Value.URI);
for (Type type : types) {
getParameters().add(type);
}
}
/**
* Provide backwards-compatibility for vCard 3.0.
* @param value a non-URI value
* @param types optional parameter types
*/
public Telephone(String value, Type...types) {
super(null, Id.TEL);
this.value = value;
for (Type type : types) {
getParameters().add(type);
}
}
/**
* Factory constructor.
* @param params property parameters
* @param value string representation of a property value
* @throws URISyntaxException where the specified value is not a valid URI
*/
public Telephone(List<Parameter> params, String value) throws URISyntaxException {
this(null, params, value);
}
/**
* Factory constructor.
* @param group a property group
* @param params property parameters
* @param value string representation of a property value
* @throws URISyntaxException where the specified value is not a valid URI
*/
public Telephone(Group group, List<Parameter> params, String value) throws URISyntaxException {
super(group, Id.TEL, params);
if (Value.URI.equals(getParameter(Parameter.Id.VALUE))) {
this.uri = normalise(new URI(value.trim().replaceAll("\\s+", "-")));
}
else {
this.value = value;
}
}
private URI normalise(URI uri) {
URI retVal = null;
if (uri.getScheme() == null && StringUtils.isNotEmpty(uri.getSchemeSpecificPart())) {
try {
retVal = new URI(TEL_SCHEME, uri.getSchemeSpecificPart(), uri.getFragment());
}
catch (URISyntaxException e) {
retVal = uri;
}
}
else {
retVal = uri;
}
return retVal;
}
/**
* @return the uri
*/
public URI getUri() {
return uri;
}
/**
* {@inheritDoc}
*/
@Override
public String getValue() {
if (uri != null) {
return Strings.valueOf(uri);
}
else {
return value;
}
}
/**
* {@inheritDoc}
*/
@Override
public void validate() throws ValidationException {
for (Parameter param : getParameters()) {
Parameter.Id id = param.getId();
if (!Parameter.Id.PID.equals(id) &&
!Parameter.Id.PREF.equals(id) &&
!Parameter.Id.TYPE.equals(id)) {
throw new ValidationException(MessageFormat.format(ILLEGAL_PARAMETER_MESSAGE, id));
}
}
}
private static class Factory implements PropertyFactory<Telephone> {
/**
* {@inheritDoc}
*/
public Telephone createProperty(final List<Parameter> params, final String value)
throws URISyntaxException {
return new Telephone(params, value);
}
/**
* {@inheritDoc}
*/
public Telephone createProperty(final Group group, final List<Parameter> params, final String value)
throws URISyntaxException, ParseException {
return new Telephone(group, params, value);
}
}
}
|
package net.morematerials.commands;
import gnu.trove.map.hash.TLongObjectHashMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import net.morematerials.MoreMaterials;
import net.morematerials.wgen.Decorator;
import net.morematerials.wgen.ore.CustomOreDecorator;
import net.morematerials.wgen.thread.MaffThread;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class DecorateExecutor implements CommandExecutor {
private static final Random RANDOM = new Random();
private MoreMaterials plugin;
private String par1, par2, par3, par4, par5;
private boolean canPlace = false;
private int rand1, rand2, offsetX, offsetZ;
private Map<UUID, TLongObjectHashMap<List<String>>> alreadyDecorated = new HashMap<>();
public DecorateExecutor(MoreMaterials plugin) {
this.plugin = plugin;
}
@SuppressWarnings("unused")
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
// Command Structure
final World world = ((Player)sender).getWorld();
// /mmpopulate intRadius CustomOreName OverPopulate
if (!(sender instanceof Player)) {
plugin.getLogger().severe("This command is only available to logged in players!");
return true;
}
// Setup command arguments
try {
par1 = args[0]; //Command or Radius
par2 = args[1]; //Ore Type or "All" or chunkCoord X
par3 = args[2]; //Decorate existing chunks or ChunkCoord Z
} catch (Exception e) {
if (plugin.showDebug) {
System.out.println(e);
System.out.println("Par1: " + par1 + " Par2: " + par2 + " Par3: " + par3);
}
}
if (par1 == null) { // par1 cannot be null and continue.
sender.sendMessage("Invalid command syntax.");
return false;
}
// Handler triggering of debug mode.
if (par1.equalsIgnoreCase("debug")) {
if (!plugin.showDebug) {
sender.sendMessage("[MoreMaterials] - Decorator Debug On");
plugin.showDebug = true;
} else {
plugin.showDebug = false;
sender.sendMessage("[MoreMaterials] - Decorator Debug Off");
}
return true; // End Command.
}
if (par1.equalsIgnoreCase("pause")) {
if (!plugin.getPlacer().paused) {
plugin.getPlacer().pause();
sender.sendMessage("[MoreMaterials] - Block Placer Paused, queue remaining: " + plugin.getPlacer().queue.size());
} else {
sender.sendMessage("[MoreMaterials] - Block Placer already Paused");
}
return true; // End Command.
}
if (par1.equalsIgnoreCase("resume")) {
if (plugin.getPlacer().paused) {
plugin.getPlacer().resume();
sender.sendMessage("[MoreMaterials] - Block Placer Resumed");
} else {
if (plugin.getPlacer().queue.size() > 0) {
sender.sendMessage("[MoreMaterials] - Block Placer is already running.");
} else {
sender.sendMessage("[MoreMaterials] - Block Placer is already running but queue is empty.");
}
}
return true; // End Command.
}
if (par1.equalsIgnoreCase("save")) {
plugin.save();
sender.sendMessage("[MoreMaterials] - Saved Processed queue to file system.");
return true; // End Command.
}
if (par1.equalsIgnoreCase("status")) {
if (plugin.getPlacer() != null && plugin.getPlacer().queue != null) {
sender.sendMessage("[MoreMaterials] - Block Placer queue remaining: [" + ChatColor.AQUA + plugin.getPlacer().queue.size() + ChatColor.RESET + "].");
//sender.sendMessage("[MoreMaterials] - Chunk.dat entires: " + plugin.fileSize());
return true; // End Command.
}
}
if (par1.equalsIgnoreCase("check")) {
final int checkX;
final int checkZ;
if (par2.equalsIgnoreCase("this") || par2 == null) {
checkX = ((Player)sender).getLocation().getChunk().getX();
checkZ = ((Player)sender).getLocation().getChunk().getZ();
} else {
checkX = Integer.parseInt(par2);
checkZ = Integer.parseInt(par3);
}
if (plugin.containsAny(((Player)sender).getWorld(), checkX, checkZ)) {
sender.sendMessage("[MoreMaterials] - Chunk already decorated.");
} else {
sender.sendMessage("[MoreMaterials] - Chunk has not been decorated.");
}
return true; // End Command.
}
if (par1.equalsIgnoreCase("displayores")) {
for (Decorator myOre : plugin.getDecoratorRegistry().getAll()) {
sender.sendMessage("[MoreMaterials] - Ore: [" + ChatColor.DARK_AQUA + myOre.getIdentifier() + ChatColor.RESET + "].");
}
return true; //End Command.
}
// Setup current location, chunk and radius values.
final Location myLocation = ((Player) sender).getLocation();
final int chunkX = myLocation.getChunk().getX();
final int chunkZ = myLocation.getChunk().getZ();
final int radius = Integer.parseInt(par1);
// Determine already decorated into our own map.
final Map<UUID, TLongObjectHashMap<List<String>>> alreadyDecorated = plugin.getWorldsDecorated();
System.out.println("Size: " + alreadyDecorated.get(world.getUID()).size());
// Startup Maff thread.
MaffThread thread = plugin.getThreadRegistry().get(myLocation.getWorld());
if (thread == null) {
thread = plugin.getThreadRegistry().start(50000, myLocation.getWorld());
}
//Filter invalid command syntax.
if (par2 == null || par3 == null) {
sender.sendMessage("Invalid command syntax.");
return false;
}
// Single Chunk Generation using all ores in objects.yml (ores)
if (par2.equalsIgnoreCase("all") && radius == 0) {
for (Decorator myOre : plugin.getDecoratorRegistry().getAll()) {
if (myOre instanceof CustomOreDecorator) {
// Tracking
((CustomOreDecorator) myOre).toDecorateCount = 0;
// Set replacement ore type.
((CustomOreDecorator) myOre).replace(Material.STONE, Material.DIRT, Material.GRAVEL);
// Calculate chance of decorate for this specific chunk and specific ore type.
rand1 = RANDOM.nextInt(((CustomOreDecorator) myOre).getDecorateChance()) + 1;
rand2 = ((CustomOreDecorator) myOre).getDecorateChance();
if (rand1 == rand2) {
if (par3.equalsIgnoreCase("true")) {
canPlace = !plugin.contains(((Player) sender).getWorld(), chunkX, chunkZ, myOre.getIdentifier());
} else {
canPlace = !this.hasOres(world, chunkX, chunkZ);
}
if (canPlace) {
thread.offer(myLocation.getWorld(), chunkX, chunkZ, myOre);
plugin.put(((Player) sender).getWorld(), chunkX, chunkZ, myOre.getIdentifier());
((CustomOreDecorator) myOre).toDecorateCount++;
} else {
if (plugin.showDebug) {
plugin.getLogger().info("Offer to Queue: " + myOre.getIdentifier() + " at: " + chunkX + " / " + chunkZ + " is already decorated.");
}
}
} else {
if (plugin.showDebug) {
//plugin.getLogger().info("Offer to Queue: [" + myOre.getIdentifier() + "] failed chance calculation for manual decorate. Chance: " + rand1 + "/" + rand2);
}
}
if (((CustomOreDecorator) myOre).toDecorateCount > 0) {
if (plugin.showDebug) {
plugin.getLogger().info("Queue Generation: " + ((CustomOreDecorator) myOre).toDecorateCount + " of: " + myOre.getIdentifier());
}
sender.sendMessage("[MoreMaterials] - Queued Generation of: [" + ChatColor.AQUA + ((CustomOreDecorator) myOre).toDecorateCount + ChatColor.RESET + "] chunk(s) of: [" + ChatColor.DARK_AQUA + myOre.getIdentifier() + ChatColor.RESET + "].");
}
}
}
}
// Single Chunk Generation specified by arg[1]
if (!par2.equalsIgnoreCase("all") && radius == 0) {
System.out.println("Zero Radius Detected");
Decorator myOre = this.plugin.getDecoratorRegistry().get(par2);
if (myOre instanceof CustomOreDecorator) {
// Tracking
((CustomOreDecorator) myOre).toDecorateCount = 0;
// Set replacement ore type.
((CustomOreDecorator) myOre).replace(Material.STONE, Material.DIRT, Material.GRAVEL);
// Calculate chance of decorate for this specific chunk and specific ore type.
rand1 = RANDOM.nextInt(((CustomOreDecorator) myOre).getDecorateChance()) + 1;
rand2 = ((CustomOreDecorator) myOre).getDecorateChance();
if (rand1 == rand2) {
if (par3.equalsIgnoreCase("true")) {
canPlace = !plugin.contains(((Player) sender).getWorld(), chunkX, chunkZ, myOre.getIdentifier());
} else {
canPlace = !this.hasOres(world, chunkX, chunkZ);
}
if (canPlace) {
thread.offer(myLocation.getWorld(), chunkX, chunkZ, myOre);
plugin.put(((Player) sender).getWorld(), chunkX, chunkZ, myOre.getIdentifier());
((CustomOreDecorator) myOre).toDecorateCount++;
} else {
if (plugin.showDebug) {
//plugin.getLogger().info("Offer to Queue: " + myOre.getIdentifier() + " at: " + chunkX + " / " + chunkZ + " is already decorated.");
}
}
} else {
if (plugin.showDebug) {
//plugin.getLogger().info("Offer to Queue: " + myOre.getIdentifier() + " failed chance calculation for manual decorate. Chance: " + rand1 + "/" + rand2);
}
}
if (((CustomOreDecorator) myOre).toDecorateCount > 0) {
if (plugin.showDebug) {
plugin.getLogger().info("Queue Generation: " + ((CustomOreDecorator) myOre).toDecorateCount + " of: " + myOre.getIdentifier());
}
sender.sendMessage("[MoreMaterials] - Queued Generation of: [" + ChatColor.AQUA + ((CustomOreDecorator) myOre).toDecorateCount + ChatColor.RESET + "] chunk(s) of: [" + ChatColor.DARK_AQUA + myOre.getIdentifier() + ChatColor.RESET + "].");
}
}
}
// Multi-Chunk Generation using all ores within objects.yml (ores)
if (par2.equalsIgnoreCase("all") && radius >= 1) {
for (Decorator myOre : plugin.getDecoratorRegistry().getAll()) {
if (myOre instanceof CustomOreDecorator) {
// Tracking
((CustomOreDecorator) myOre).toDecorateCount = 0;
// Set replacement ore type.
((CustomOreDecorator) myOre).replace(Material.STONE, Material.DIRT, Material.GRAVEL);
// Calculate circular decorate based on current location.
for (int x = -radius; x < radius; x++) {
for (int j = -radius; j < radius; j++) {
offsetX = chunkX + x;
offsetZ = chunkZ + j;
// Calculate chance of decorate for this specific chunk and specific ore type.
rand1 = RANDOM.nextInt(((CustomOreDecorator) myOre).getDecorateChance()) + 1;
rand2 = ((CustomOreDecorator) myOre).getDecorateChance();
if (rand1 == rand2) {
if (par3.equalsIgnoreCase("true")) {
canPlace = !plugin.contains(((Player) sender).getWorld(), offsetX, offsetZ, myOre.getIdentifier());
} else {
canPlace = !this.hasOres(world, offsetX, offsetZ);
}
if (canPlace) {
thread.offer(myLocation.getWorld(), offsetX, offsetZ, myOre);
plugin.put(((Player) sender).getWorld(), offsetX, offsetZ, myOre.getIdentifier());
((CustomOreDecorator) myOre).toDecorateCount++;
} else {
if (plugin.showDebug) {
//plugin.getLogger().info("Offer to Queue: " + myOre.getIdentifier() + " at: " + offsetX + " / " + offsetZ + " is already decorated.");
}
}
} else {
if (plugin.showDebug) {
//plugin.getLogger().info("Offer to Queue: " + myOre.getIdentifier() + " failed chance calculation for manual populate. Chance: " + rand1 + "/" + rand2);
}
}
}
}
if (((CustomOreDecorator) myOre).toDecorateCount > 0) {
if (plugin.showDebug) {
plugin.getLogger().info("Queue Generation: " + ((CustomOreDecorator) myOre).toDecorateCount + " of: " + myOre.getIdentifier());
}
sender.sendMessage("[MoreMaterials] - Queued Generation of: [" + ChatColor.AQUA + ((CustomOreDecorator) myOre).toDecorateCount + ChatColor.RESET + "] chunk(s) of: [" + ChatColor.DARK_AQUA + myOre.getIdentifier() + ChatColor.RESET + "].");
}
}
}
}
// Multi-Chunk Generation using specified args[1] ore.
if (!par2.equalsIgnoreCase("all") && radius >= 1) {
Decorator myOre = this.plugin.getDecoratorRegistry().get(par2);
if (myOre instanceof CustomOreDecorator) {
// Tracking
((CustomOreDecorator) myOre).toDecorateCount = 0;
// Set replacement ore type.
((CustomOreDecorator) myOre).replace(Material.STONE, Material.DIRT, Material.GRAVEL);
// Should replace the ore in the chunk you are standing in.
for (int x = -radius; x < radius; x++) {
for (int j = -radius; j < radius; j++) {
offsetX = chunkX + x;
offsetZ = chunkZ + j;
rand1 = RANDOM.nextInt(((CustomOreDecorator) myOre).getDecorateChance()) + 1;
rand2 = ((CustomOreDecorator) myOre).getDecorateChance();
if (rand1 == rand2) {
if (par3.equalsIgnoreCase("true")) {
canPlace = !plugin.contains(((Player) sender).getWorld(), offsetX, offsetZ, myOre.getIdentifier());
} else {
canPlace = !this.hasOres(world, offsetX, offsetZ);
}
if (canPlace) {
thread.offer(myLocation.getWorld(), offsetX, offsetZ, myOre);
plugin.put(((Player) sender).getWorld(), offsetX, offsetZ, myOre.getIdentifier());
((CustomOreDecorator) myOre).toDecorateCount++;
} else {
if (plugin.showDebug) {
//plugin.getLogger().info("Offer to Queue: " + myOre.getIdentifier() + " at: " + offsetX + " / " + offsetZ + " is already decorated.");
}
}
} else {
if (plugin.showDebug) {
//plugin.getLogger().info("Offer to Queue: " + myOre.getIdentifier() + " failed chance calculation for manual decorate. Chance: " + rand1 + "/" + rand2);
}
}
}
}
if (((CustomOreDecorator) myOre).toDecorateCount > 0) {
if (plugin.showDebug) {
plugin.getLogger().info("Queue Generation: " + ((CustomOreDecorator) myOre).toDecorateCount + " of: " + myOre.getIdentifier());
}
sender.sendMessage("[MoreMaterials] - Queued Generation of: [" + ChatColor.AQUA + ((CustomOreDecorator) myOre).toDecorateCount + ChatColor.RESET + "] chunk(s) of: [" + ChatColor.DARK_AQUA + myOre.getIdentifier() + ChatColor.RESET + "].");
}
}
}
sender.sendMessage("[MoreMaterials] - command completed sucessfully.");
if (plugin.getPlacer() != null) {
plugin.getPlacer().player = Bukkit.getPlayer(sender.getName());
}
return true;
}
public boolean hasOres(World world, int cx, int cz) {
TLongObjectHashMap<List<String>> chunksDecorated = alreadyDecorated.get(world.getUID());
if (chunksDecorated != null) {
final long key = (((long) cx) << 32) | (((long) cz) & 0xFFFFFFFFL);
final List<String> decorationsInChunk = chunksDecorated.get(key);
return decorationsInChunk != null && !decorationsInChunk.isEmpty();
} else {
System.out.println("ChunksDecorated = false");
}
System.out.println("hasOres returned false");
return false;
}
}
|
package net.openhft.chronicle.queue;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.WriteBytesMarshallable;
import net.openhft.chronicle.wire.DocumentContext;
import net.openhft.chronicle.wire.WriteMarshallable;
import org.jetbrains.annotations.NotNull;
/**
* The component that facilitates sequentially writing data to a {@link ChronicleQueue}.
*
* @author peter.lawrey
*/
public interface ExcerptAppender extends ExcerptCommon {
DocumentContext writingDocument();
/**
* @param writer to write to excerpt.
*/
void writeDocument(@NotNull WriteMarshallable writer);
/**
* @param marshallable to write to excerpt.
*/
void writeBytes(@NotNull WriteBytesMarshallable marshallable);
/**
* @param bytes to write to excerpt.
*/
void writeBytes(@NotNull Bytes<?> bytes);
long lastIndexAppended();
/**
* @return the cycle this tailer is on, usually with chronicle-queue each cycle will have its
* own unique data file to store the excerpt
*/
long cycle();
}
|
package net.sf.jabref.gui.maintable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import net.sf.jabref.gui.*;
import net.sf.jabref.model.entry.AuthorList;
import net.sf.jabref.model.entry.BibtexEntry;
import net.sf.jabref.Globals;
import net.sf.jabref.JabRefPreferences;
import net.sf.jabref.model.entry.EntryUtil;
import net.sf.jabref.specialfields.Priority;
import net.sf.jabref.specialfields.Rank;
import net.sf.jabref.specialfields.ReadStatus;
import net.sf.jabref.specialfields.SpecialFieldValue;
import net.sf.jabref.specialfields.SpecialFieldsUtils;
import ca.odell.glazedlists.gui.TableFormat;
import javax.swing.JLabel;
/**
* Class defining the contents and column headers of the main table.
*/
public class MainTableFormat implements TableFormat<BibtexEntry> {
// Character separating field names that are to be used in sequence as
// fallbacks for a single column (e.g. "author/editor" to use editor where
// author is not set):
public static final String COL_DEFINITION_FIELD_SEPARATOR = "/";
// Values to gather iconImages for those columns
// These values are also used to put a heading into the table; see getColumnName(int)
private static final String[] PDF = {"pdf", "ps"};
private static final String[] URL_FIRST = {"url", "doi"};
private static final String[] DOI_FIRST = {"doi", "url"};
private static final String[] ARXIV = {"eprint"};
public static final String[] FILE = {Globals.FILE_FIELD};
private List<MainTableColumn> tableColumns = new ArrayList<>();
private boolean namesAsIs;
private boolean abbr_names;
private boolean namesNatbib;
private boolean namesFf;
private boolean namesLf;
private boolean namesLastOnly;
@Override
public int getColumnCount() {
return tableColumns.size();
}
/**
* @return the string that should be put in the column header
*/
@Override
public String getColumnName(int col) {
return tableColumns.get(col).getDisplayName();
}
public List<MainTableColumn> getTableColumns() {
return tableColumns;
}
/**
* This method returns a string array indicating the types of icons to be displayed in the given column.
* It returns null if the column is not an icon column, and thereby also serves to identify icon
* columns.
*/
//TODO to be removed?
public String[] getIconTypeForColumn(int col) {
return null;
// Object o = iconCols.get(Integer.valueOf(col));
// if (o != null) {
// return (String[]) o;
// } else {
// return null;
}
/**
* Finds the column index for the given column name.
*
* @param colName The column name
* @return The column index if any, or -1 if no column has that name.
*/
public int getColumnIndex(String colName) {
for (MainTableColumn tableColumn : tableColumns) {
if (tableColumn.getColumnName().equalsIgnoreCase(colName)) {
return tableColumns.lastIndexOf(tableColumn);
}
}
return -1;
}
@Override
public Object getColumnValue(BibtexEntry be, int col) {
return tableColumns.get(col).getColumnValue(be);
}
/**
* Format a name field for the table, according to user preferences.
*
* @param nameToFormat The contents of the name field.
* @return The formatted name field.
*/
// TODO move to some Util class?
public String formatName(String nameToFormat) {
if (nameToFormat == null) {
return null;
} else if (namesAsIs) {
return nameToFormat;
} else if (namesNatbib) {
nameToFormat = AuthorList.fixAuthor_Natbib(nameToFormat);
} else if (namesLastOnly) {
nameToFormat = AuthorList.fixAuthor_lastNameOnlyCommas(nameToFormat, false);
} else if (namesFf) {
nameToFormat = AuthorList.fixAuthor_firstNameFirstCommas(nameToFormat, abbr_names, false);
} else if (namesLf) {
nameToFormat = AuthorList.fixAuthor_lastNameFirstCommas(nameToFormat, abbr_names, false);
}
return nameToFormat;
}
public void updateTableFormat() {
// clear existing column configuration
tableColumns.clear();
// Add numbering column to tableColumns
tableColumns.add(SpecialMainTableColumns.NUMBER_COL);
// Add 'normal' bibtex fields as configured in the preferences
// Read table columns from prefs:
String[] colSettings = Globals.prefs.getStringArray(JabRefPreferences.COLUMN_NAMES);
for (int i = 0; i < colSettings.length; i++) {
// stored column name will be used as columnName
String columnName = colSettings[i];
// There might be more than one field to display, e.g., "author/editor" or "date/year" - so split
// at MainTableFormat.COL_DEFINITION_FIELD_SEPARATOR
String[] fields = colSettings[i].split(MainTableFormat.COL_DEFINITION_FIELD_SEPARATOR);
tableColumns.add(new MainTableColumn(columnName, fields));
}
// Add the "special" icon columns (e.g., ranking, file, ...) that are enabled in preferences.
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED)) {
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING)) {
tableColumns.add(SpecialMainTableColumns.RANKING_COLUMN);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE)) {
tableColumns.add(SpecialMainTableColumns.RELEVANCE_COLUMN);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY)) {
tableColumns.add(SpecialMainTableColumns.QUALITY_COLUMN);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY)) {
tableColumns.add(SpecialMainTableColumns.PRIORITY_COLUMN);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED)) {
tableColumns.add(SpecialMainTableColumns.PRINTED_COLUMN);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_READ)) {
tableColumns.add(SpecialMainTableColumns.READ_STATUS_COLUMN);
}
}
if (Globals.prefs.getBoolean(JabRefPreferences.FILE_COLUMN)) {
tableColumns.add(SpecialMainTableColumns.FILE_COLUMN);
}
if (Globals.prefs.getBoolean(JabRefPreferences.PDF_COLUMN)) {
tableColumns.add(SpecialMainTableColumns.createIconColumn(JabRefPreferences.PDF_COLUMN, MainTableFormat.PDF));
}
if (Globals.prefs.getBoolean(JabRefPreferences.URL_COLUMN)) {
if (Globals.prefs.getBoolean(JabRefPreferences.PREFER_URL_DOI)) {
tableColumns.add(SpecialMainTableColumns.createIconColumn(JabRefPreferences.URL_COLUMN, MainTableFormat.DOI_FIRST));
} else {
tableColumns.add(SpecialMainTableColumns.createIconColumn(JabRefPreferences.URL_COLUMN, MainTableFormat.URL_FIRST));
}
}
if (Globals.prefs.getBoolean(JabRefPreferences.ARXIV_COLUMN)) {
tableColumns.add(SpecialMainTableColumns.createIconColumn(JabRefPreferences.ARXIV_COLUMN, MainTableFormat.ARXIV));
}
if (Globals.prefs.getBoolean(JabRefPreferences.EXTRA_FILE_COLUMNS)) {
String[] desiredColumns = Globals.prefs.getStringArray(JabRefPreferences.LIST_OF_FILE_COLUMNS);
for (String desiredColumn : desiredColumns) {
tableColumns.add(SpecialMainTableColumns.createFileIconColumn(desiredColumn));
}
}
// Read name format options:
namesNatbib = Globals.prefs.getBoolean(JabRefPreferences.NAMES_NATBIB);
namesLastOnly = Globals.prefs.getBoolean(JabRefPreferences.NAMES_LAST_ONLY);
namesAsIs = Globals.prefs.getBoolean(JabRefPreferences.NAMES_AS_IS);
abbr_names = Globals.prefs.getBoolean(JabRefPreferences.ABBR_AUTHOR_NAMES);
namesFf = Globals.prefs.getBoolean(JabRefPreferences.NAMES_FIRST_LAST);
namesLf = !(namesAsIs || namesFf || namesNatbib || namesLastOnly); // None of the above.
}
}
|
package net.weverwijk.address.cleaner;
import au.com.bytecode.opencsv.CSVReader;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
import org.apache.lucene.analysis.nl.DutchAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queries.BooleanFilter;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.similarities.DefaultSimilarity;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
public class PostcodeCheck {
private static final Version version = Version.LUCENE_4_10_2;
private final Directory index;
private final PerFieldAnalyzerWrapper analyzer;
public PostcodeCheck() {
index = new RAMDirectory();
analyzer = new PerFieldAnalyzerWrapper(new KeywordAnalyzer(), Collections.<String, Analyzer>singletonMap("complete", new DutchAnalyzer()));
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
index.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void loadAddresses(String fileName) throws IOException {
CSVReader csvReader = new CSVReader(new FileReader(fileName), ';', '\"');
HashMap<String, Integer> header = convertToColumnLookup(csvReader.readNext());
IndexWriterConfig config = new IndexWriterConfig(version, analyzer)
.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
IndexWriter writer = new IndexWriter(index, config);
String[] nextLine;
while ((nextLine = csvReader.readNext()) != null) {
Document doc = new Document();
String postcode = nextLine[header.get("postcode")];
String city = nextLine[header.get("city")];
String street = nextLine[header.get("street")];
doc.add(new TextField("postcode", postcode, Field.Store.YES));
doc.add(new TextField("street", street, Field.Store.YES));
doc.add(new TextField("city", city, Field.Store.YES));
doc.add(new TextField("numbertype", nextLine[header.get("numbertype")], Field.Store.YES));
doc.add(new IntField("minnumber", Integer.parseInt(nextLine[header.get("minnumber")]), Field.Store.YES));
doc.add(new IntField("maxnumber", Integer.parseInt(nextLine[header.get("maxnumber")]), Field.Store.YES));
doc.add(new TextField("complete", String.format("%s %s %s", postcode, street, city), Field.Store.YES));
writer.addDocument(doc);
}
writer.commit();
writer.close();
}
public Address getAddress(Address address) throws IOException, ParseException {
return this.getAddress(address, false);
}
public Address getAddress(Address address, boolean debug) throws IOException, ParseException {
int limit = 20;
Address result;
try (IndexReader reader = DirectoryReader.open(index)) {
BooleanQuery booleanQuery = new BooleanQuery();
if (address.getPostcode() != null) {
Query postcode = new TermQuery(new Term("postcode", address.getPostcode()));
postcode.setBoost(20F);
booleanQuery.add(postcode, BooleanClause.Occur.SHOULD);
}
if (address.getStreet() != null) {
TermQuery streetTerm = new TermQuery(new Term("street", address.getStreet()));
streetTerm.setBoost(30F);
booleanQuery.add(streetTerm, BooleanClause.Occur.SHOULD);
booleanQuery.add(new FuzzyQuery(new Term("street", address.getStreet())), BooleanClause.Occur.SHOULD);
}
if (address.getCity() != null) {
booleanQuery.add(new FuzzyQuery(new Term("city", address.getCity())), BooleanClause.Occur.SHOULD);
TermQuery cityTerm = new TermQuery(new Term("city", address.getCity()));
cityTerm.setBoost(30F);
booleanQuery.add(cityTerm, BooleanClause.Occur.SHOULD);
}
BooleanFilter filterClauses = null;
try {
if (address.getHouseNumber() != null) {
// filterClauses = new BooleanFilter();
int houseNumber = Integer.parseInt(address.getHouseNumber());
BooleanQuery oddEvenQuery = new BooleanQuery();
oddEvenQuery.add(new TermQuery(new Term("numbertype", "mixed")), BooleanClause.Occur.SHOULD);
if (houseNumber % 2 == 0) {
oddEvenQuery.add(new TermQuery(new Term("numbertype", "even")), BooleanClause.Occur.SHOULD);
} else {
oddEvenQuery.add(new TermQuery(new Term("numbertype", "odd")), BooleanClause.Occur.SHOULD);
}
booleanQuery.add(oddEvenQuery, BooleanClause.Occur.MUST);
booleanQuery.add(NumericRangeQuery.newIntRange("minnumber", 0, houseNumber, true, true), BooleanClause.Occur.SHOULD);
booleanQuery.add(NumericRangeQuery.newIntRange("maxnumber", houseNumber, 9999, true, true), BooleanClause.Occur.SHOULD);
}
} catch (NumberFormatException e) {
// nothing to see, walk through...
}
if (booleanQuery.getClauses().length == 0 && address.getDescription() != null) {
QueryParser qp = new QueryParser("complete", new DutchAnalyzer());
booleanQuery.add(qp.parse(QueryParser.escape(address.getDescription())), BooleanClause.Occur.SHOULD);
}
result = searchAddress(limit, booleanQuery, filterClauses, reader, debug, address);
}
if (result != null) {
addHouseNumber(address, result);
}
return result;
}
private void addHouseNumber(Address address, Address result) {
result.setHouseNumber(address.getHouseNumber());
result.setHouseNumberAffix(address.getHouseNumberAffix());
result.setDescription(address.getDescription());
if (StringUtils.isEmpty(result.getHouseNumber())) {
result.fillHouseNumberFromDescription();
// if we don't know the houseNumber we cannot know the postcode
result.setPostcode(null);
}
}
public HashMap<String, Integer> convertToColumnLookup(String[] headers) {
HashMap<String, Integer> result = new HashMap<String, Integer>();
for (int i = 0; i < headers.length; i++) {
result.put(headers[i], i);
}
return result;
}
private Address searchAddress(final int limit, final Query query,
BooleanFilter filterClauses, final IndexReader reader, boolean debug, Address originalAddress) throws IOException {
Address result = null;
Float lastScore = null;
IndexSearcher searcher = new IndexSearcher(reader);
// resetIDF(searcher);
TopDocs docs = searcher.search(query, filterClauses, limit);
if (debug) {
printDebug(query, searcher, docs);
}
for (final ScoreDoc scoreDoc : docs.scoreDocs) {
if (lastScore == null) {
lastScore = scoreDoc.score;
} else if ((lastScore / 2) > scoreDoc.score) {
break;
}
Address nextAddress = new Address(reader.document(scoreDoc.doc));
if (result == null) {
result = nextAddress;
continue;
}
if (nextAddress.getLevenshteinDistance(originalAddress) < result.getLevenshteinDistance(originalAddress)) {
result = nextAddress;
}
}
return result;
}
private void resetIDF(IndexSearcher searcher) {
searcher.setSimilarity(new DefaultSimilarity() {
@Override
public float tf(float freq) {
return 1.0f;
}
@Override
public float idf(long docFreq, long numDocs) {
return 1.0f;
}
});
}
private void printDebug(Query query, IndexSearcher searcher, TopDocs docs) throws IOException {
System.out.println(docs.totalHits + " found for query: " + query);
for (final ScoreDoc scoreDoc : docs.scoreDocs) {
System.out.println(searcher.doc(scoreDoc.doc));
System.out.println(searcher.explain(query, scoreDoc.doc));
}
}
}
|
package nl.topicus.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import nl.topicus.jdbc.metadata.AbstractCloudSpannerWrapper;
public abstract class AbstractCloudSpannerFetcher extends AbstractCloudSpannerWrapper {
private int fetchSize = 0;
private int direction = ResultSet.FETCH_FORWARD;
/**
*
* @param direction The fetch direction to use. Only {@link ResultSet#FETCH_FORWARD} is supported.
* @throws SQLException Thrown if any other fetch direction than {@link ResultSet#FETCH_FORWARD}
* is supplied
*/
public void setFetchDirection(int direction) throws SQLException {
if (direction != ResultSet.FETCH_FORWARD)
throw new SQLFeatureNotSupportedException("Only FETCH_FORWARD is supported");
this.direction = direction;
}
/**
*
* @return Always returns {@link ResultSet#FETCH_FORWARD}
* @throws SQLException Cannot be thrown by this method, but is added to the method signature in
* order to comply with the interfaces that will be implemented by this abstract class'
* concrete subclasses
*/
public int getFetchDirection() throws SQLException {
if (this.direction != ResultSet.FETCH_FORWARD)
throw new SQLFeatureNotSupportedException("Only FETCH_FORWARD is supported");
return this.direction;
}
/**
*
* @param rows The number of rows to fetch
* @throws SQLException Cannot be thrown by this method, but is added to the method signature in
* order to comply with the interfaces that will be implemented by this abstract class'
* concrete subclasses
*/
public void setFetchSize(int rows) throws SQLException {
this.fetchSize = rows;
}
/**
*
* @return The number of rows to fetch
* @throws SQLException Cannot be thrown by this method, but is added to the method signature in
* order to comply with the interfaces that will be implemented by this abstract class'
* concrete subclasses
*/
public int getFetchSize() throws SQLException {
return fetchSize;
}
}
|
package org.barebonesdigest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class DigestChallengeResponse {
/**
* The name of the HTTP request header ({@value #HTTP_HEADER_AUTHORIZATION}).
*/
public static final String HTTP_HEADER_AUTHORIZATION = "Authorization";
private static final int CLIENT_NONCE_BYTE_COUNT = 8;
private static final SecureRandom RANDOM = new SecureRandom();
private static byte[] clientNonceByteBuffer = new byte[CLIENT_NONCE_BYTE_COUNT];
private final MessageDigest md5;
private String algorithm;
private String username;
private String password;
private String clientNonce;
private String nonce;
private int nonceCount;
private String quotedOpaque;
private String uri;
private String realm;
private String requestMethod;
public DigestChallengeResponse() {
try {
this.md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// TODO find out if this can happen
throw new RuntimeException(e);
}
this.nonceCount(1);
}
/**
* Creates a digest challenge response, setting the ealm` and the values values of the `nonce`,
* `opaque`, and `algorithm` directives based on a challenge.
*
* @param challenge the challenge
* @return a response to the challenge.
*/
public static DigestChallengeResponse responseTo(DigestChallenge challenge) {
return new DigestChallengeResponse().challenge(challenge);
}
public DigestChallengeResponse algorithm(String algorithm) {
if (!"MD5".equals(algorithm)) {
throw new IllegalArgumentException("Unsupported algorithm: " + algorithm);
}
this.algorithm = algorithm;
return this;
}
public DigestChallengeResponse username(String username) {
this.username = username;
return this;
}
/**
* Sets the password to use for authentication.
*
* @param password the password
* @return this object so that setting directives can be easily chained
*/
public DigestChallengeResponse password(String password) {
this.password = password;
return this;
}
public DigestChallengeResponse clientNonce(String clientNonce) {
this.clientNonce = clientNonce;
return this;
}
public DigestChallengeResponse nonce(String nonce) {
this.nonce = nonce;
resetNonceCount();
return this;
}
public DigestChallengeResponse nonceCount(int nonceCount) {
this.nonceCount = nonceCount;
return this;
}
public DigestChallengeResponse quotedOpaque(String quotedOpaque) {
this.quotedOpaque = quotedOpaque;
return this;
}
public DigestChallengeResponse uri(String uri) {
this.uri = uri;
return this;
}
public DigestChallengeResponse realm(String realm) {
this.realm = realm;
return this;
}
public DigestChallengeResponse requestMethod(String requestMethod) {
this.requestMethod = requestMethod;
return this;
}
public DigestChallengeResponse challenge(DigestChallenge challenge) {
return nonce(challenge.getNonce()).quotedOpaque(challenge.getOpaqueQuoted())
.realm(challenge.getRealm())
.algorithm(challenge.getAlgorithm());
}
public String getAlgorithm() {
return algorithm;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getClientNonce() {
if (clientNonce == null) {
synchronized (this) {
if (clientNonce == null) {
clientNonce = generateRandomNonce();
}
}
}
return clientNonce;
}
public String getNonce() {
return nonce;
}
public int getNonceCount() {
return nonceCount;
}
public void resetNonceCount() {
nonceCount(1);
}
public void incrementNonceCount() {
nonceCount(nonceCount + 1);
}
public String getQuotedOpaque() {
return quotedOpaque;
}
public String getUri() {
return uri;
}
public String getRealm() {
return realm;
}
public String getRequestMethod() {
return requestMethod;
}
public String getHeaderValue() {
// TODO: verify that all values are set
String response = calculateResponse();
StringBuilder result = new StringBuilder();
result.append("Digest ");
// Username is defined in Section 3.2.2 of RFC 2617
// username = "username" "=" username-value
// username-value = quoted-string
result.append("username=");
result.append(Rfc2616AbnfParser.quote(username));
result.append(",");
// Realm is defined in RFC 2617, Section 1.2
// realm = "realm" "=" realm-value
// realm-value = quoted-string
// TODO: Unnecessary to quote and then unquote string value
result.append("realm=");
result.append(Rfc2616AbnfParser.quote(realm));
result.append(",");
// nonce = "nonce" "=" nonce-value
// nonce-value = quoted-string
// TODO: Unnecessary to quote and then unquote string value
result.append("nonce=");
result.append(Rfc2616AbnfParser.quote(nonce));
result.append(",");
// digest-uri = "uri" "=" digest-uri-value
// digest-uri-value = request-uri ; As specified by HTTP/1.1
result.append("uri=");
result.append(Rfc2616AbnfParser.quote(uri));
result.append(",");
// Response is defined in RFC 2617, Section 3.2.2 and 3.2.2.1
// response = "response" "=" request-digest
result.append("response=");
result.append(response);
result.append(",");
// Cnonce is defined in RFC 2617, Section 3.2.2
// cnonce = "cnonce" "=" cnonce-value
// cnonce-value = nonce-value
// Must be present if qop is specified, must not if qop is unspecified
// TODO: don't include if qop is unspecified
result.append("cnonce=");
result.append(Rfc2616AbnfParser.quote(getClientNonce()));
result.append(",");
// Opaque and algorithm are explained in Section 3.2.2 of RFC 2617:
// "The values of the opaque and algorithm fields must be those supplied
// in the WWW-Authenticate response header for the entity being
// requested."
if (quotedOpaque != null) {
result.append("opaque=");
result.append(quotedOpaque);
result.append(",");
}
if (algorithm != null) {
result.append("algorithm=");
result.append(algorithm);
result.append(",");
}
// TODO Verify that server supports auth
// TODO Also support auth-int
result.append("qop=auth");
result.append(",");
// Nonce count is defined in RFC 2617, Section 3.2.2
// nonce-count = "nc" "=" nc-value
// nc-value = 8LHEX (lower case hex)
// Must be present if qop is specified, must not if qop is unspecified
result.append("nc=");
result.append(String.format("%08x", nonceCount));
return result.toString();
}
private String calculateResponse() {
// TODO: Below calculation is for the case where qop is present, if not qop is calculated
// differently
String a1 = calculateA1();
String a2 = calculateA2();
String secret = calculateMd5(a1);
String data = joinWithColon(nonce,
String.format("%08x", nonceCount),
getClientNonce(),
"auth",
calculateMd5(a2));
return "\"" + calculateMd5(secret + ":" + data) + "\"";
}
private String calculateA1() {
// TODO: Below calculation is for if algorithm is MD5 or unspecified
// TODO: Support MD5-sess algorithm
return joinWithColon(username, realm, password);
}
private String calculateA2() {
// TODO: Below calculation if if qop is auth or unspecified
// TODO: Support auth-int qop
return joinWithColon(requestMethod, uri);
}
private String joinWithColon(String... parts) {
StringBuilder result = new StringBuilder();
for (String part : parts) {
if (result.length() > 0) {
result.append(":");
}
result.append(part);
}
return result.toString();
}
private String calculateMd5(String string) {
md5.reset();
// TODO find out which encoding to use
md5.update(string.getBytes());
return encodeHexString(md5.digest());
}
private static String encodeHexString(byte[] bytes) {
StringBuilder result = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
result.append(Integer.toHexString((bytes[i] & 0xf0) >> 4));
result.append(Integer.toHexString((bytes[i] & 0x0f)));
}
return result.toString();
}
private static synchronized String generateRandomNonce() {
RANDOM.nextBytes(clientNonceByteBuffer);
return encodeHexString(clientNonceByteBuffer);
}
}
|
package org.cobbzilla.util.string;
import org.cobbzilla.util.collection.MapBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.cobbzilla.util.string.StringUtil.chop;
public class ValidationRegexes {
public static final Pattern LOGIN_PATTERN = pattern("^[\\w\\-]+$");
public static final Pattern EMAIL_PATTERN = pattern("^[A-Z0-9][A-Z0-9._%+-]*@[A-Z0-9.-]+\\.[A-Z]{2,6}$");
public static final Pattern EMAIL_NAME_PATTERN = pattern("^[A-Z0-9][A-Z0-9._%+-]*$");
public static final Pattern[] LOCALE_PATTERNS = {
pattern("^[a-zA-Z]{2,3}([-_][a-zA-z]{2}(@[\\w]+)?)?"), // ubuntu style: en_US or just en
pattern("^[a-zA-Z]{2,3}([-_][\\w]+)?"), // some apps use style: ca-valencia
};
public static final String UUID_REGEX = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
public static final Pattern UUID_PATTERN = pattern(UUID_REGEX);
public static final String NUMERIC_REGEX = "\\d+";
public static final Pattern NUMERIC_PATTERN = pattern(NUMERIC_REGEX);
public static final int IP4_MAXLEN = 15;
public static final int IP6_MAXLEN = 45;
public static final Pattern IPv4_PATTERN = pattern("^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$");
public static final Pattern IPv6_PATTERN = pattern("^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$");
public static final String HOST = "([A-Z0-9]{1,63}|[A-Z0-9][A-Z0-9\\-]{0,61}[A-Z0-9])(\\.([A-Z0-9]{1,63}|[A-Z0-9][A-Z0-9\\-]{0,61}[A-Z0-9]))*";
public static final String HOST_REGEX = "^" + HOST + "$";
public static final Pattern HOST_PATTERN = pattern(HOST_REGEX);
public static final String HOST_PART = "([A-Z0-9]|[A-Z0-9][A-Z0-9\\-]{0,61}[A-Z0-9])";
public static final String HOST_PART_REGEX = "^"+HOST_PART+"$";
public static final Pattern HOST_PART_PATTERN = pattern(HOST_PART_REGEX);
public static final Pattern PORT_PATTERN = pattern("^[\\d]{1,5}$");
public static final String DOMAIN_REGEX = "^([A-Z0-9]{1,63}|[A-Z0-9][A-Z0-9\\-]{0,61}[A-Z0-9])(\\.([A-Z0-9]{1,63}|[A-Z0-9][A-Z0-9\\-]{0,61}[A-Z0-9]))+$";
public static final Pattern DOMAIN_PATTERN = pattern(DOMAIN_REGEX);
public static final String URL_REGEX = "(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
public static final String URL_REGEX_ONLY = "^" + URL_REGEX + "$";
public static final Pattern URL_PATTERN = pattern(URL_REGEX_ONLY);
public static final Pattern HTTP_PATTERN = pattern("^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]$");
public static final Pattern HTTPS_PATTERN = pattern("^https://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]$");
public static final String VARNAME_REGEX = "^[A-Za-z][_A-Za-z0-9]+$";
public static final Pattern VARNAME_PATTERN = pattern(VARNAME_REGEX);
public static final Pattern FILENAME_PATTERN = pattern("^[_A-Z0-9\\-\\.]+$");
public static final Pattern INTEGER_PATTERN = pattern("^[0-9]+$");
public static final Pattern DECIMAL_PATTERN = pattern("^[0-9]+(\\.[0-9]+)?$");
public static final Pattern HEXADECIMAL_PATTERN = pattern("^[0-9a-f]+$");
public static final Map<String, Pattern> PHONE_PATTERNS = MapBuilder.build(new Object[][]{
{"US", pattern("^\\d{10}$")}
});
public static final Pattern DEFAULT_PHONE_PATTERN = pattern("^\\d+([-\\.\\s]?\\d+?){8,}[\\d]+$");
public static final String YYYYMMDD_REGEX = "^(19|20|21)[0-9]{2}-[01][0-9]-(0[1-9]|[1-2][0-9]|3[0-1])$";
public static final Pattern YYYYMMDD_PATTERN = pattern(YYYYMMDD_REGEX);
public static final String ZIPCODE_REGEX = "^\\d{5}(-\\d{4})?$";
public static final Pattern ZIPCODE_PATTERN = pattern(ZIPCODE_REGEX);
public static Pattern pattern(String regex) { return Pattern.compile(regex, Pattern.CASE_INSENSITIVE); }
public static List<String> findAllRegexMatches(String text, String regex) {
if (regex.startsWith("^")) regex = regex.substring(1);
if (regex.endsWith("$")) regex = chop(regex, "$");
regex = "(.*(?<match>"+ regex +")+.*)+";
final List<String> found = new ArrayList<>();
final Matcher matcher = Pattern.compile(regex, Pattern.MULTILINE).matcher(text);
while (matcher.find()) {
found.add(matcher.group("match"));
}
return found;
}
public static boolean validateRegexMatches(Pattern pattern, String s) {
return s != null && pattern.matcher(s).matches();
}
}
|
package org.encog.ml.prg.generator;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.encog.mathutil.randomize.RangeRandomizer;
import org.encog.ml.CalculateScore;
import org.encog.ml.ea.species.Species;
import org.encog.ml.fitness.ZeroEvalScoreFunction;
import org.encog.ml.prg.EncogProgram;
import org.encog.ml.prg.EncogProgramContext;
import org.encog.ml.prg.ProgramNode;
import org.encog.ml.prg.extension.ProgramExtensionTemplate;
import org.encog.ml.prg.train.PrgPopulation;
public class PrgGrowGenerator {
private EncogProgramContext context;
private int maxDepth;
private List<ProgramExtensionTemplate> leaves = new ArrayList<ProgramExtensionTemplate>();
public PrgGrowGenerator(EncogProgramContext theContext, int theMaxDepth) {
this.context = theContext;
this.maxDepth = theMaxDepth;
for(ProgramExtensionTemplate temp : this.context.getFunctions().getOpCodes() ) {
if( temp.getChildNodeCount()==0 ) {
this.leaves.add(temp);
}
}
}
public EncogProgram generate(Random rnd) {
EncogProgram program = new EncogProgram(context);
program.setRootNode(createNode(rnd, program,0));
return program;
}
/**
* Generate a new random branch that can be used with the specified program.
* Does not actually attach the new branch anywhere.
* @param rnd Random number generator.
* @param program The program to generate a branch for.
* @return The new branch.
*/
public ProgramNode generate(Random rnd, EncogProgram program) {
return createNode(rnd, program,0);
}
private ProgramNode createLeafNode(Random rnd, EncogProgram program) {
int opCode = rnd.nextInt(this.leaves.size());
ProgramExtensionTemplate temp = this.leaves.get(opCode);
ProgramNode result = new ProgramNode(program, temp, new ProgramNode[] {});
result.randomize(program, 1.0);
return result;
}
private ProgramNode createNode(Random rnd, EncogProgram program, int depth) {
int maxOpCode = context.getFunctions().size();
if( depth>=this.maxDepth ) {
return createLeafNode(rnd, program);
}
int opCode = RangeRandomizer.randomInt(0, maxOpCode-1);
ProgramExtensionTemplate temp = context.getFunctions().getOpCode(opCode);
int childNodeCount = temp.getChildNodeCount();
ProgramNode[] children = new ProgramNode[childNodeCount];
for(int i=0;i<children.length;i++) {
children[i] = createNode(rnd, program, depth+1);
}
ProgramNode result = new ProgramNode(program, temp, children);
result.randomize(program, 1.0);
return result;
}
private EncogProgram attemptCreateGenome(Random rnd, CalculateScore score, Set<String> contents) {
boolean done = false;
EncogProgram result = null;
int tries = 0;
while(!done) {
result = generate(rnd);
double s = score.calculateScore(result);
if( tries>100 ) {
done = true;
} else if( !Double.isNaN(s) && !Double.isInfinite(s) && !contents.contains(result.dumpAsCommonExpression()) ) {
done = true;
}
}
return result;
}
public void generate(Random rnd, PrgPopulation pop, CalculateScore score) {
Set<String> contents = new HashSet<String>();
pop.getSpecies().clear();
final Species defaultSpecies = pop.createSpecies();
for (int i = 0; i < pop.getPopulationSize(); i++) {
final EncogProgram prg = attemptCreateGenome(rnd,score,contents);
defaultSpecies.add(prg);
contents.add(prg.dumpAsCommonExpression());
}
}
}
|
package org.grouplens.grapht.solver;
import org.grouplens.grapht.spi.Desire;
import javax.annotation.Nullable;
public interface BindingFunction {
/**
* Find the applicable binding, if any, for a desire in a particular context.
*
* @param context The context.
* @param desire The desire.
* @return The result of binding {@code desire}, or {@code null} if there is no binding.
* @throws SolverException If there is an error (such as ambiguous bindings).
*/
@Nullable
BindingResult bind(InjectionContext context, Desire desire) throws SolverException;
}
|
package org.irmacard.mno.common;
import net.sf.scuba.util.Hex;
import org.jmrtd.Util;
import org.jmrtd.lds.*;
import java.io.InputStream;
import java.security.*;
import java.security.cert.*;
import java.security.cert.Certificate;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECParameterSpec;
import java.util.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class PassportDataMessage extends BasicClientMessage {
private String imsi;
SODFile sodFile;
DG1File dg1File;
DG14File dg14File;
DG15File dg15File;
byte [] response;
public PassportDataMessage() {
}
public PassportDataMessage(String sessionToken, String imsi) {
super(sessionToken);
this.imsi = imsi;
}
public PassportVerificationResult verify(byte[] challenge) {
System.out.println("challenge:" + Hex.bytesToHexString(challenge));
System.out.println(this.toString());
if (!verifyHashes()) {
return PassportVerificationResult.HASHES_INVALID;
}
if (!verifySignature()) {
return PassportVerificationResult.SIGNATURE_INVALID;
}
if (!verifyAA(challenge)) {
return PassportVerificationResult.AA_FAILED;
}
return PassportVerificationResult.SUCCESS;
}
/**
* Method to verify the hashes of datagroups 1 and 15 against those present in the SOD File
* @return
*/
private boolean verifyHashes(){
String digestAlg = sodFile.getDigestAlgorithm();
Map<Integer, byte[]> hashes = sodFile.getDataGroupHashes();
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance(digestAlg);
} catch (Exception e) {
//TODO: Error!
e.printStackTrace();
}
digest.update(dg1File.getEncoded());
byte[] hash_dg1 = digest.digest();
digest.update(dg15File.getEncoded());
byte[] hash_dg15 = digest.digest();
if (!Arrays.equals(hash_dg1, hashes.get(Integer.valueOf(1)))) {
return false;
}
if (!Arrays.equals(hash_dg15, hashes.get(Integer.valueOf(15)))) {
return false;
}
return true;
}
private boolean verifySignature() {
try {
//retrieve the Certificate used for signing the document.
X509Certificate passportCert = sodFile.getDocSigningCertificate();
//verify the signature over the SOD file
if (!sodFile.checkDocSignature(passportCert)) {
return false;
}
InputStream ins;
CertificateFactory factory = CertificateFactory.getInstance("X.509");
Certificate nlcert;
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
// Load certificates from the jar and put them in the keystore
for (int i = 1; i <= 4; i++) {
ins = this.getClass().getClassLoader().getResourceAsStream("nl" + i + ".cer");
nlcert = factory.generateCertificate(ins);
keyStore.setCertificateEntry("nl" + i, nlcert);
ins.close();
}
// really have _no_ clue why this works while the previous code (which was roughly along the lines of
// The API is vastly unclear, the documentation doesn't help, and neither does the internet. We might even
// want to consider doing the verification entirely manually. At least then we can be sure what's really
// going on.
// TODO revocation checking
CertificateFactory cf = CertificateFactory.getInstance("X.509");
List<X509Certificate> mylist = new ArrayList<X509Certificate>();
mylist.add((X509Certificate) passportCert);
CertPath cp = cf.generateCertPath(mylist);
PKIXParameters params = new PKIXParameters(keyStore);
params.setRevocationEnabled(false);
CertPathValidator cpv = CertPathValidator.getInstance(CertPathValidator.getDefaultType());
PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Verify whether the response matches the AA computation of the challenge and the private key belonging to the public key stored in DG15.
*
* @param challenge The challenge
* @return true if valid, false otherwise
*/
private boolean verifyAA(byte[] challenge) {
PublicKey publickey = dg15File.getPublicKey();
Signature aaSignature = null;
MessageDigest aaDigest = null;
Cipher aaCipher = null;
boolean answer = false;
try {
if (publickey.getAlgorithm().equals("RSA")) {
// Instantiate signature scheme, digest and cipher
aaSignature = Signature.getInstance("SHA1WithRSA/ISO9796-2");
aaDigest = MessageDigest.getInstance("SHA1");
aaCipher = Cipher.getInstance("RSA/NONE/NoPadding");
aaCipher.init(Cipher.DECRYPT_MODE, publickey);
aaSignature.initVerify(publickey);
int digestLength = aaDigest.getDigestLength(); /* should always be 20 */
assert (digestLength == 20);
byte[] plaintext = new byte[0];
plaintext = aaCipher.doFinal(response);
System.out.println("plaintext:" + Hex.bytesToPrettyString(plaintext));
byte[] m1 = recoverMessage(digestLength, plaintext);
aaSignature.update(m1);
aaSignature.update(challenge);
answer = aaSignature.verify(response);
} else if (publickey.getAlgorithm().equals("EC")) {
// Retrieve the signature scheme from DG14
List<ActiveAuthenticationInfo> aaInfos = getDg14File().getActiveAuthenticationInfos();
assert (aaInfos.size() == 1);
ActiveAuthenticationInfo aaInfo = aaInfos.get(0);
String oid = aaInfo.getSignatureAlgorithmOID();
String mnenomic = ActiveAuthenticationInfo.lookupMnemonicByOID(oid);
mnenomic = rewriteECDSAMnenomic(mnenomic);
aaSignature = Signature.getInstance(mnenomic);
assert (aaSignature != null);
ECPublicKey ecPublicKey = (ECPublicKey) publickey;
ECParameterSpec ecParams = ecPublicKey.getParams();
aaSignature.initVerify(publickey);
aaSignature.update(challenge);
answer = aaSignature.verify(response);
}
} catch (ClassCastException // Casting of publickey to an EC public key failed
| NoSuchAlgorithmException // Error initialising AA cipher suite
| NoSuchPaddingException // same
| InvalidKeyException // publickey is invalid
| IllegalBlockSizeException // Error in aaCipher.doFinal()
| BadPaddingException // same
| NumberFormatException // Error in computing or verifying signature
| SignatureException e) { // same
e.printStackTrace();
answer = false;
}
return answer;
}
public static String rewriteECDSAMnenomic (String mnenomic) {
if (mnenomic.equals("SHA1withECDSA")) { return "SHA1/CVC-ECDSA"; }
if (mnenomic.equals("SHA224withECDSA")) { return "SHA224/CVC-ECDSA"; }
if (mnenomic.equals("SHA256withECDSA")) { return "SHA256/CVC-ECDSA"; }
if (mnenomic.equals("SHA384withECDSA")) { return "SHA348/CVC-ECDSA"; }
if (mnenomic.equals("SHA512withECDSA")) { return "SHA512/CVC-ECDSA"; }
if (mnenomic.equals("RIPEMD160withECDSA")) { return "RIPEMD160/CVC-ECDSA"; }
return mnenomic;
}
/**
* Recovers the M1 part of the message sent back by the AA protocol
* (INTERNAL AUTHENTICATE command). The algorithm is described in
* ISO 9796-2:2002 9.3.
*
* Based on code by Ronny (ronny@cs.ru.nl) who presumably ripped this
* from Bouncy Castle.
*
* @param digestLength should be 20
* @param plaintext response from card, already 'decrypted' (using the
* AA public key)
*
* @return the m1 part of the message
*/
public static byte[] recoverMessage(int digestLength, byte[] plaintext) {
if (plaintext == null || plaintext.length < 1) {
throw new IllegalArgumentException("Plaintext too short to recover message");
}
if (((plaintext[0] & 0xC0) ^ 0x40) != 0) {
// 0xC0 = 1100 0000, 0x40 = 0100 0000
throw new NumberFormatException("Could not get M1-0");
}
if (((plaintext[plaintext.length - 1] & 0xF) ^ 0xC) != 0) {
// 0xF = 0000 1111, 0xC = 0000 1100
throw new NumberFormatException("Could not get M1-1");
}
int delta = 0;
if (((plaintext[plaintext.length - 1] & 0xFF) ^ 0xBC) == 0) {
delta = 1;
} else {
// 0xBC = 1011 1100
throw new NumberFormatException("Could not get M1-2");
}
/* find out how much padding we've got */
int paddingLength = 0;
for (; paddingLength < plaintext.length; paddingLength++) {
// 0x0A = 0000 1010
if (((plaintext[paddingLength] & 0x0F) ^ 0x0A) == 0) {
break;
}
}
int messageOffset = paddingLength + 1;
int paddedMessageLength = plaintext.length - delta - digestLength;
int messageLength = paddedMessageLength - messageOffset;
/* there must be at least one byte of message string */
if (messageLength <= 0) {
throw new NumberFormatException("Could not get M1-3");
}
/* TODO: if we contain the whole message as well, check the hash of that. */
if ((plaintext[0] & 0x20) == 0) {
throw new NumberFormatException("Could not get M1-4");
} else {
byte[] recoveredMessage = new byte[messageLength];
System.arraycopy(plaintext, messageOffset, recoveredMessage, 0, messageLength);
return recoveredMessage;
}
}
public boolean isComplete () {
return imsi != null && sodFile != null && dg1File != null && dg15File != null && response != null;
}
public String getImsi() {
return imsi;
}
public void setImsi(String imsi) {
this.imsi = imsi;
}
public SODFile getSodFile() {
return sodFile;
}
public void setSodFile(SODFile sodFile) {
this.sodFile = sodFile;
}
public DG1File getDg1File() {
return dg1File;
}
public void setDg1File(DG1File dg1File) {
this.dg1File = dg1File;
}
public DG14File getDg14File() {
return dg14File;
}
public void setDg14File(DG14File dg14File) {
this.dg14File = dg14File;
}
public DG15File getDg15File() {
return dg15File;
}
public void setDg15File(DG15File dg15File) {
this.dg15File = dg15File;
}
public byte[] getResponse() {
return response;
}
public void setResponse(byte[] response) {
this.response = response;
}
public String toString() {
return "[IMSI: " + imsi + ", Session: " + getSessionToken() + "\n"
+ "SODFile: " + sodFile.toString() +"\n"
+ "DG1:" + dg1File.toString() + "\n"
+ "DG15" + dg15File.toString() + "\n"
+ "response:" + Hex.bytesToHexString(response) + " ]";
}
}
|
package org.jboss.msc.service;
import java.io.IOException;
import java.io.Writer;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import org.jboss.msc.service.management.ServiceStatus;
import org.jboss.msc.value.Value;
/**
* The service controller implementation.
*
* @param <S> the service type
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author <a href="mailto:flavia.rainone@jboss.com">Flavia Rainone</a>
*/
final class ServiceControllerImpl<S> implements ServiceController<S>, Dependent {
private static final String ILLEGAL_CONTROLLER_STATE = "Illegal controller state";
/**
* The service itself.
*/
private final Value<? extends Service<? extends S>> serviceValue;
/**
* The source location in which this service was defined.
*/
private final Location location;
/**
* The dependencies of this service.
*/
private final Dependency[] dependencies;
/**
* The injections of this service.
*/
private final ValueInjection<?>[] injections;
/**
* The set of registered service listeners.
*/
private final IdentityHashSet<ServiceListener<? super S>> listeners;
/**
* The primary registration of this service.
*/
private final ServiceRegistrationImpl primaryRegistration;
/**
* The alias registrations of this service.
*/
private final ServiceRegistrationImpl[] aliasRegistrations;
/**
* The parent of this service.
*/
private final ServiceControllerImpl<?> parent;
/**
* The children of this service (only valid during {@link State#UP}).
*/
private final IdentityHashSet<ServiceControllerImpl<?>> children;
/**
* The start exception.
*/
private StartException startException;
/**
* The controller mode.
*/
private ServiceController.Mode mode = ServiceController.Mode.NEVER;
/**
* The controller state.
*/
private Substate state = Substate.NEW;
/**
* The number of registrations which place a demand-to-start on this instance. If this value is >0, propagate a demand
* up to all parent dependents. If this value is >0 and mode is ON_DEMAND, put a load of +1 on {@code upperCount}.
*/
private int demandedByCount;
/**
* Semaphore count for bringing this dep up. If the value is <= 0, the service is stopped. Each unstarted
* dependency will put a load of -1 on this value. A mode of AUTOMATIC or IMMEDIATE will put a load of +1 on this
* value. A mode of NEVER will cause this value to be ignored. A mode of ON_DEMAND will put a load of +1 on this
* value <b>if</b> {@link #demandedByCount} is >0.
*/
private int upperCount;
/**
* The number of dependents that are currently running. The deployment will not execute the {@code stop()} method
* (and subsequently leave the {@link org.jboss.msc.service.ServiceController.State#STOPPING} state) until all running dependents (and listeners) are stopped.
*/
private int runningDependents;
/**
* Indicates if this service has failed to start.
*/
private boolean failed;
/**
* Indicates if this service has one or more dependencies that failed.
*/
private boolean dependencyFailed = false;
/**
* Indicates if this service has one or more dependencies that are not installed.
*/
private boolean missingDependency;
/**
* The number of asynchronous tasks that are currently running. This includes listeners, start/stop methods,
* outstanding asynchronous start/stops, and internal tasks.
*/
private int asyncTasks;
/**
* The service target for adding child services (can be {@code null} if none were added).
*/
private volatile ChildServiceTarget childTarget;
/**
* The system nanotime of the moment in which the last lifecycle change was initiated.
*/
private volatile long lifecycleTime;
private static final Dependent[] NO_DEPENDENTS = new Dependent[0];
private static final String[] NO_STRINGS = new String[0];
ServiceControllerImpl(final Value<? extends Service<? extends S>> serviceValue, final Location location, final Dependency[] dependencies, final ValueInjection<?>[] injections, final ServiceRegistrationImpl primaryRegistration, final ServiceRegistrationImpl[] aliasRegistrations, final Set<? extends ServiceListener<? super S>> listeners, final ServiceControllerImpl<?> parent) {
this.serviceValue = serviceValue;
this.location = location;
this.dependencies = dependencies;
this.injections = injections;
this.primaryRegistration = primaryRegistration;
this.aliasRegistrations = aliasRegistrations;
this.listeners = new IdentityHashSet<ServiceListener<? super S>>(listeners);
this.parent = parent;
int depCount = dependencies.length;
upperCount = parent == null ? -depCount : -depCount - 1;
children = new IdentityHashSet<ServiceControllerImpl<?>>();
}
/**
* Determine whether the lock is currently held.
*
* @return {@code true} if the lock is held
*/
boolean lockHeld() {
return Thread.holdsLock(this);
}
Substate getSubstateLocked() {
return state;
}
void addAsyncTask() {
asyncTasks++;
}
void removeAsyncTask() {
asyncTasks
}
/**
* Identify the transition to take. Call under lock.
*
* @return the transition or {@code null} if none is needed at this time
*/
private Transition getTransition() {
assert lockHeld();
if (asyncTasks != 0) {
// no movement possible
return null;
}
switch (state) {
case DOWN: {
if (mode == ServiceController.Mode.REMOVE) {
return Transition.DOWN_to_REMOVING;
} else if (mode != ServiceController.Mode.NEVER) {
if (upperCount > 0) {
return Transition.DOWN_to_START_REQUESTED;
}
}
break;
}
case STOPPING: {
return Transition.STOPPING_to_DOWN;
}
case STOP_REQUESTED: {
if (upperCount > 0) {
return Transition.STOP_REQUESTED_to_UP;
}
if (runningDependents == 0) {
return Transition.STOP_REQUESTED_to_STOPPING;
}
break;
}
case UP: {
if (upperCount <= 0) {
return Transition.UP_to_STOP_REQUESTED;
}
break;
}
case START_FAILED: {
if (upperCount > 0) {
if (startException == null) {
return Transition.START_FAILED_to_STARTING;
}
} else {
return Transition.START_FAILED_to_DOWN;
}
break;
}
case STARTING: {
if (startException == null) {
return Transition.STARTING_to_UP;
} else {
return Transition.STARTING_to_START_FAILED;
}
}
case START_REQUESTED: {
if (upperCount > 0) {
return Transition.START_REQUESTED_to_STARTING;
} else {
return Transition.START_REQUESTED_to_DOWN;
}
}
case REMOVING: {
return Transition.REMOVING_to_REMOVED;
}
case REMOVED: {
// no possible actions
break;
}
}
return null;
}
/**
* Run the locked portion of a transition. Call under lock.
*
* @return the async tasks to start when the lock is not held, {@code null} for none
*/
Runnable[] transition() {
assert lockHeld();
final Transition transition = getTransition();
if (transition == null) {
return null;
}
final Runnable[] tasks;
boolean notifyDependentsOfFailure = false;
switch (transition) {
case STOPPING_to_DOWN: {
tasks = getListenerTasks(transition.getAfter().getState(), new DependentStoppedTask());
break;
}
case START_REQUESTED_to_DOWN: {
tasks = new Runnable[] { new DependentStoppedTask() };
break;
}
case START_REQUESTED_to_STARTING: {
tasks = getListenerTasks(transition.getAfter().getState(), new StartTask(true));
break;
}
case UP_to_STOP_REQUESTED: {
lifecycleTime = System.nanoTime();
tasks = new Runnable[] { new DependencyStoppedTask(getDependents()) };
break;
}
case STARTING_to_UP: {
tasks = getListenerTasks(transition.getAfter().getState(), new DependencyStartedTask(getDependents()));
break;
}
case STARTING_to_START_FAILED: {
notifyDependentsOfFailure = true;
ChildServiceTarget childTarget = this.childTarget;
if (childTarget != null) {
childTarget.valid = false;
this.childTarget = null;
}
if (! children.isEmpty()) {
asyncTasks++;
// todo - this might have to happen outside of the lock.
for (ServiceControllerImpl<?> child : children) {
child.setMode(Mode.REMOVE);
}
}
tasks = getListenerTasks(transition.getAfter().getState()/*, new DependencyFailedTask(getDependents())*/);
break;
}
case START_FAILED_to_STARTING: {
notifyDependentsOfFailure = true;
tasks = getListenerTasks(transition.getAfter().getState()/*, new DependencyRetryingTask(getDependents())*/, new StartTask(false));
break;
}
case START_FAILED_to_DOWN: {
startException = null;
failed = false;
notifyDependentsOfFailure = true;
tasks = getListenerTasks(transition.getAfter().getState()/*, new DependencyRetryingTask(getDependents())*/, new StopTask(true), new DependentStoppedTask());
break;
}
case STOP_REQUESTED_to_UP: {
tasks = new Runnable[] { new DependencyStartedTask(getDependents()) };
break;
}
case STOP_REQUESTED_to_STOPPING: {
ChildServiceTarget childTarget = this.childTarget;
if (childTarget != null) {
childTarget.valid = false;
this.childTarget = null;
}
if (! children.isEmpty()) {
asyncTasks++;
// todo - this might have to happen outside of the lock.
for (ServiceControllerImpl<?> child : children) {
child.setMode(Mode.REMOVE);
}
}
tasks = getListenerTasks(transition.getAfter().getState(), new StopTask(false));
break;
}
case DOWN_to_REMOVING: {
tasks = new Runnable[] { new RemoveTask() };
break;
}
case REMOVING_to_REMOVED: {
tasks = getListenerTasks(transition.getAfter().getState());
listeners.clear();
break;
}
case DOWN_to_START_REQUESTED: {
lifecycleTime = System.nanoTime();
tasks = new Runnable[] { new DependentStartedTask() };
break;
}
default: {
throw new IllegalStateException();
}
}
state = transition.getAfter();
if (notifyDependentsOfFailure) {
primaryRegistration.getContainer().checkFailedDependencies(false);
}
asyncTasks += tasks.length;
return tasks;
}
private Runnable[] getListenerTasks(final ServiceController.State newState, final Runnable extraTask1, final Runnable extraTask2) {
final IdentityHashSet<ServiceListener<? super S>> listeners = this.listeners;
final int size = listeners.size();
final Runnable[] tasks = new Runnable[size + 2];
int i = 0;
for (ServiceListener<? super S> listener : listeners) {
tasks[i++] = new ListenerTask(listener, newState);
}
tasks[i++] = extraTask1;
tasks[i] = extraTask2;
return tasks;
}
private Runnable[] getListenerTasks(final ServiceController.State newState, final Runnable extraTask) {
final IdentityHashSet<ServiceListener<? super S>> listeners = this.listeners;
final int size = listeners.size();
final Runnable[] tasks = new Runnable[size + 1];
int i = 0;
for (ServiceListener<? super S> listener : listeners) {
tasks[i++] = new ListenerTask(listener, newState);
}
tasks[i] = extraTask;
return tasks;
}
private Runnable[] getListenerTasks(final ServiceController.State newState) {
final IdentityHashSet<ServiceListener<? super S>> listeners = this.listeners;
final int size = listeners.size();
final Runnable[] tasks = new Runnable[size];
int i = 0;
for (ServiceListener<? super S> listener : listeners) {
tasks[i++] = new ListenerTask(listener, newState);
}
return tasks;
}
private Runnable[] getListenerTasks(final ListenerNotification notification) {
final IdentityHashSet<ServiceListener<? super S>> listeners = this.listeners;
final int size = listeners.size();
final Runnable[] tasks = new Runnable[size];
int i = 0;
for (ServiceListener<? super S> listener : listeners) {
tasks[i++] = new ListenerTask(listener, notification);
}
return tasks;
}
private Runnable[] getListenerTasks(final ListenerNotification notification, final Runnable extraTask) {
final IdentityHashSet<ServiceListener<? super S>> listeners = this.listeners;
final int size = listeners.size();
final Runnable[] tasks = new Runnable[size + 1];
int i = 0;
for (ServiceListener<? super S> listener : listeners) {
tasks[i++] = new ListenerTask(listener, notification);
}
tasks[i] = extraTask;
return tasks;
}
void doExecute(final Runnable task) {
assert ! lockHeld();
if (task == null) return;
try {
primaryRegistration.getContainer().getExecutor().execute(task);
} catch (RejectedExecutionException e) {
task.run();
}
}
void doExecute(final Runnable... tasks) {
assert ! lockHeld();
if (tasks == null) return;
final Executor executor = primaryRegistration.getContainer().getExecutor();
for (Runnable task : tasks) {
try {
executor.execute(task);
} catch (RejectedExecutionException e) {
task.run();
}
}
}
public void setMode(final ServiceController.Mode newMode) {
internalSetMode(null, newMode);
}
private boolean internalSetMode(final ServiceController.Mode expectedMode, final ServiceController.Mode newMode) {
assert !lockHeld();
if (newMode == null) {
throw new IllegalArgumentException("newMode is null");
}
if (newMode != Mode.REMOVE && primaryRegistration.getContainer().isShutdown()) {
throw new IllegalArgumentException("Container is shutting down");
}
Runnable[] bootTasks = null;
final Runnable[] tasks;
Runnable specialTask = null;
synchronized (this) {
if (expectedMode != null && expectedMode != mode) {
return false;
}
final Substate oldState = state;
if (oldState == Substate.NEW) {
state = Substate.DOWN;
bootTasks = getListenerTasks(ListenerNotification.LISTENER_ADDED, new InstallTask());
asyncTasks += bootTasks.length;
}
final ServiceController.Mode oldMode = mode;
mode = newMode;
switch (oldMode) {
case REMOVE: {
switch (newMode) {
case REMOVE: {
break;
}
default: {
throw new IllegalStateException("Service removed");
}
}
break;
}
case NEVER: {
switch (newMode) {
case ON_DEMAND: {
if (demandedByCount > 0) {
upperCount++;
specialTask = new DemandParentsTask();
asyncTasks++;
}
break;
}
case PASSIVE: {
upperCount++;
if (demandedByCount > 0) {
specialTask = new DemandParentsTask();
asyncTasks++;
}
break;
}
case ACTIVE: {
specialTask = new DemandParentsTask();
asyncTasks++;
upperCount++;
break;
}
}
break;
}
case ON_DEMAND: {
switch (newMode) {
case REMOVE:
case NEVER: {
if (demandedByCount > 0) {
upperCount
specialTask = new UndemandParentsTask();
asyncTasks++;
}
break;
}
case PASSIVE: {
if (demandedByCount == 0) {
upperCount++;
}
break;
}
case ACTIVE: {
specialTask = new DemandParentsTask();
asyncTasks++;
if (demandedByCount == 0) {
upperCount++;
}
break;
}
}
break;
}
case PASSIVE: {
switch (newMode) {
case REMOVE:
case NEVER: {
if (demandedByCount > 0) {
specialTask = new UndemandParentsTask();
asyncTasks++;
}
upperCount
break;
}
case ON_DEMAND: {
if (demandedByCount == 0) {
upperCount
}
break;
}
case ACTIVE: {
specialTask = new DemandParentsTask();
asyncTasks++;
break;
}
}
break;
}
case ACTIVE: {
switch (newMode) {
case REMOVE:
case NEVER: {
specialTask = new UndemandParentsTask();
asyncTasks++;
upperCount
break;
}
case ON_DEMAND: {
if (demandedByCount == 0) {
upperCount
specialTask = new UndemandParentsTask();
asyncTasks++;
}
break;
}
case PASSIVE: {
if (demandedByCount == 0) {
specialTask = new UndemandParentsTask();
asyncTasks++;
}
break;
}
}
break;
}
}
tasks = (oldMode == newMode) ? null : transition();
}
if (bootTasks != null) {
for (Runnable bootTask : bootTasks) {
bootTask.run();
}
}
doExecute(tasks);
doExecute(specialTask);
return true;
}
@Override
public void immediateDependencyInstalled() {
}
@Override
public void immediateDependencyUninstalled() {
}
@Override
public void dependencyInstalled() {
final Runnable[] tasks;
synchronized (this) {
if (!missingDependency) {
return;
}
missingDependency = false;
tasks = getListenerTasks(ListenerNotification.DEPENDENCY_INSTALLED);
asyncTasks += tasks.length;
}
doExecute(tasks);
}
@Override
public void dependencyUninstalled() {
final Runnable[] tasks;
synchronized (this) {
if (missingDependency) {
return;
}
missingDependency = true;
tasks = getListenerTasks(ListenerNotification.MISSING_DEPENDENCY);
asyncTasks += tasks.length;
}
doExecute(tasks);
}
@Override
public void immediateDependencyUp() {
Runnable[] tasks = null;
synchronized (this) {
if (++upperCount != 1) {
return;
}
// we raised it to 1
tasks = transition();
}
doExecute(tasks);
}
@Override
public void immediateDependencyDown() {
Runnable[] tasks = null;
synchronized (this) {
if (--upperCount != 0) {
return;
}
// we dropped it below 0
tasks = transition();
}
doExecute(tasks);
}
@Override
public void dependencyFailed() {
Runnable[] tasks = null;
synchronized (this) {
if (dependencyFailed) {
return;
}
dependencyFailed = true;
// we raised it to 1
tasks = getListenerTasks(ListenerNotification.DEPENDENCY_FAILURE);
asyncTasks += tasks.length;
}
doExecute(tasks);
}
@Override
public void dependencyFailureCleared() {
Runnable[] tasks = null;
synchronized (this) {
if (!dependencyFailed) {
return;
}
dependencyFailed = false;
// we dropped it to 0
tasks = getListenerTasks(ListenerNotification.DEPENDENCY_FAILURE_CLEAR);
asyncTasks += tasks.length;
}
doExecute(tasks);
}
Dependency[] getDependencies() {
return dependencies;
}
void dependentStarted() {
assert ! lockHeld();
synchronized (this) {
runningDependents++;
}
}
void dependentStopped() {
assert ! lockHeld();
final Runnable[] tasks;
synchronized (this) {
if (--runningDependents != 0) {
return;
}
tasks = transition();
}
doExecute(tasks);
}
Runnable[] newDependent(final Dependent dependent) {
assert lockHeld();
final Runnable[] tasks;
if (failed || dependencyFailed) {
primaryRegistration.getContainer().checkFailedDependencies(true);
}
if (state == Substate.UP){
tasks = new Runnable[]{new DependencyStartedTask(new Dependent[][]{{dependent}})};
asyncTasks ++;
} else {
tasks = null;
}
return tasks;
}
private void doDemandParents() {
assert ! lockHeld();
for (Dependency dependency : dependencies) {
dependency.addDemand();
}
final ServiceControllerImpl<?> parent = this.parent;
if (parent != null) parent.addDemand();
}
private void doUndemandParents() {
assert ! lockHeld();
for (Dependency dependency : dependencies) {
dependency.removeDemand();
}
final ServiceControllerImpl<?> parent = this.parent;
if (parent != null) parent.removeDemand();
}
void addDemand() {
addDemands(1);
}
void addDemands(final int demandedByCount) {
assert ! lockHeld();
final Runnable[] tasks;
final boolean propagate;
synchronized (this) {
final int cnt = this.demandedByCount;
this.demandedByCount += demandedByCount;
propagate = cnt == 0 && mode.compareTo(Mode.NEVER) > 0;
if (cnt == 0 && mode == Mode.ON_DEMAND) {
upperCount++;
tasks = transition();
} else {
// no change
tasks = null;
}
if (propagate) asyncTasks++;
}
doExecute(tasks);
if (propagate) doExecute(new DemandParentsTask());
}
void removeDemand() {
assert ! lockHeld();
final Runnable[] tasks;
final boolean propagate;
synchronized (this) {
final int cnt = --demandedByCount;
propagate = cnt == 0 && (mode == Mode.ON_DEMAND || mode == Mode.PASSIVE);
if (cnt == 0 && mode == Mode.ON_DEMAND) {
upperCount
tasks = transition();
} else {
// no change
tasks = null;
}
if (propagate) asyncTasks++;
}
doExecute(tasks);
if (propagate) doExecute(new UndemandParentsTask());
}
void addChild(ServiceControllerImpl<?> child) {
assert ! lockHeld();
synchronized (this) {
switch (state) {
case STARTING:
case UP:
case STOP_REQUESTED: {
children.add(child);
break;
}
default: throw new IllegalStateException("Children cannot be added in state " + state.getState());
}
}
}
void removeChild(ServiceControllerImpl<?> child) {
assert ! lockHeld();
final Runnable[] tasks;
synchronized (this) {
children.remove(child);
if (children.isEmpty()) {
switch (state) {
case START_FAILED:
case STOPPING:
asyncTasks
tasks = transition();
break;
default:
return;
}
} else {
return;
}
}
doExecute(tasks);
}
public ServiceContainerImpl getServiceContainer() {
return primaryRegistration.getContainer();
}
public ServiceController.State getState() {
return state.getState();
}
public S getValue() throws IllegalStateException {
return serviceValue.getValue().getValue();
}
public ServiceName getName() {
return primaryRegistration.getName();
}
private static final ServiceName[] NO_NAMES = new ServiceName[0];
public ServiceName[] getAliases() {
final ServiceRegistrationImpl[] aliasRegistrations = this.aliasRegistrations;
final int len = aliasRegistrations.length;
if (len == 0) {
return NO_NAMES;
}
final ServiceName[] names = new ServiceName[len];
for (int i = 0; i < len; i++) {
names[i] = aliasRegistrations[i].getName();
}
return names;
}
public Location getLocation() {
return location;
}
public void addListener(final ServiceListener<? super S> listener) {
assert !lockHeld();
final Substate state;
synchronized (this) {
state = this.state;
// Always run listener if removed.
if (state != Substate.REMOVED) {
if (! listeners.add(listener)) {
// Duplicates not allowed
throw new IllegalArgumentException("Listener " + listener + " already present on controller for " + primaryRegistration.getName());
}
asyncTasks ++;
} else {
asyncTasks += 2;
}
}
invokeListener(listener, ListenerNotification.LISTENER_ADDED, null);
if (state == Substate.REMOVED) {
invokeListener(listener, ListenerNotification.STATE, State.REMOVED);
}
}
public void removeListener(final ServiceListener<? super S> listener) {
synchronized (this) {
listeners.remove(listener);
}
}
public StartException getStartException() {
synchronized (this) {
return startException;
}
}
public void retry() {
assert !lockHeld();
final Runnable[] tasks;
synchronized (this) {
if (state.getState() != ServiceController.State.START_FAILED) {
return;
}
startException = null;
failed = false;
tasks = transition();
}
doExecute(tasks);
}
public ServiceController.Mode getMode() {
synchronized (this) {
return mode;
}
}
public boolean compareAndSetMode(final Mode expectedMode, final Mode newMode) {
if (expectedMode == null) {
throw new IllegalArgumentException("expectedMode is null");
}
return internalSetMode(expectedMode, newMode);
}
ServiceStatus getStatus() {
synchronized (this) {
final String parentName = parent == null ? null : parent.getName().getCanonicalName();
final String name = primaryRegistration.getName().getCanonicalName();
final ServiceRegistrationImpl[] aliasRegistrations = this.aliasRegistrations;
final int aliasLength = aliasRegistrations.length;
final String[] aliases;
if (aliasLength == 0) {
aliases = NO_STRINGS;
} else {
aliases = new String[aliasLength];
for (int i = 0; i < aliasLength; i++) {
aliases[i] = aliasRegistrations[i].getName().getCanonicalName();
}
}
String serviceClass = "<unknown>";
try {
final Service<? extends S> value = serviceValue.getValue();
if (value != null) {
serviceClass = value.getClass().getName();
}
} catch (RuntimeException ignored) {
}
final Dependency[] dependencies = this.dependencies;
final int dependenciesLength = dependencies.length;
final String[] dependencyNames;
if (dependenciesLength == 0) {
dependencyNames = NO_STRINGS;
} else {
dependencyNames = new String[dependenciesLength];
for (int i = 0; i < dependenciesLength; i++) {
dependencyNames[i] = dependencies[i].getName().getCanonicalName();
}
}
return new ServiceStatus(
parentName,
name,
aliases,
serviceClass,
mode.name(),
state.getState().name(),
state.name(),
dependencyNames,
dependencyFailed,
missingDependency
);
}
}
private static enum ListenerNotification {
/** Notify the listener that is has been added. */
LISTENER_ADDED,
/** Notifications related to the current state. */
STATE,
/** Notify the listener that a dependency failure occurred. */
DEPENDENCY_FAILURE,
/** Notify the listener that all dependency failures are cleared. */
DEPENDENCY_FAILURE_CLEAR,
/** Notify the listener that a dependency is missing (uninstalled). */
MISSING_DEPENDENCY,
/** Notify the listener that all missing dependencies are now installed. */
DEPENDENCY_INSTALLED}
/**
* Invokes the listener, performing the notification specified.
*
* @param listener listener to be invoked
* @param notification specified notification
* @param state the state to be notified, only relevant if {@code notification} is
* {@link ListenerNotification#STATE}
*/
private void invokeListener(final ServiceListener<? super S> listener, final ListenerNotification notification, final State state ) {
assert !lockHeld();
try {
switch (notification) {
case LISTENER_ADDED:
listener.listenerAdded(this);
break;
case STATE:
switch (state) {
case DOWN: {
listener.serviceStopped(this);
break;
}
case STARTING: {
listener.serviceStarting(this);
break;
}
case START_FAILED: {
listener.serviceFailed(this, startException);
break;
}
case UP: {
listener.serviceStarted(this);
break;
}
case STOPPING: {
listener.serviceStopping(this);
break;
}
case REMOVED: {
listener.serviceRemoved(this);
break;
}
}
break;
case DEPENDENCY_FAILURE:
listener.dependencyFailed(this);
break;
case DEPENDENCY_FAILURE_CLEAR:
listener.dependencyFailureCleared(this);
break;
case MISSING_DEPENDENCY:
listener.dependencyUninstalled(this);
break;
case DEPENDENCY_INSTALLED:
listener.dependencyInstalled(this);
break;
}
} catch (Throwable t) {
ServiceLogger.INSTANCE.listenerFailed(t, listener);
} finally {
final Runnable[] tasks;
synchronized (this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
}
}
Substate getSubstate() {
synchronized (this) {
return state;
}
}
ServiceRegistrationImpl getPrimaryRegistration() {
return primaryRegistration;
}
ServiceRegistrationImpl[] getAliasRegistrations() {
return aliasRegistrations;
}
/**
* Returns a compiled array of all dependents of this service instance.
*
* @return an array of dependents
*/
private Dependent[][] getDependents() {
if (aliasRegistrations.length == 0) {
synchronized (primaryRegistration.getDependentsLock()) {
return new Dependent[][] {primaryRegistration.getDependents().toScatteredArray(NO_DEPENDENTS)};
}
}
Dependent[][] dependents = new Dependent[aliasRegistrations.length + 1][];
synchronized (primaryRegistration.getDependentsLock()) {
dependents[0] = primaryRegistration.getDependents().toScatteredArray(NO_DEPENDENTS);
}
for (int i = 0; i < aliasRegistrations.length; i++) {
ServiceRegistrationImpl alias = aliasRegistrations[i];
synchronized (alias.getDependentsLock()) {
dependents[i + 1] = alias.getDependents().toScatteredArray(NO_DEPENDENTS);
}
}
return dependents;
}
enum ContextState {
SYNC,
ASYNC,
COMPLETE,
FAILED,
}
private static <T> void doInject(final ValueInjection<T> injection) {
injection.getTarget().inject(injection.getSource().getValue());
}
@Override
public String toString() {
return String.format("Controller for %s@%x", getName(), Integer.valueOf(hashCode()));
}
private class DemandParentsTask implements Runnable {
public void run() {
try {
doDemandParents();
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class UndemandParentsTask implements Runnable {
public void run() {
try {
doUndemandParents();
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class DependentStoppedTask implements Runnable {
public void run() {
try {
for (Dependency dependency : dependencies) {
dependency.dependentStopped();
}
final ServiceControllerImpl<?> parent = ServiceControllerImpl.this.parent;
if (parent != null) {
parent.dependentStopped();
}
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class DependentStartedTask implements Runnable {
public void run() {
try {
for (Dependency dependency : dependencies) {
dependency.dependentStarted();
}
final ServiceControllerImpl<?> parent = ServiceControllerImpl.this.parent;
if (parent != null) {
parent.dependentStarted();
}
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class StartTask implements Runnable {
private final boolean doInjection;
StartTask(final boolean doInjection) {
this.doInjection = doInjection;
}
public void run() {
assert !lockHeld();
final ServiceName serviceName = primaryRegistration.getName();
final long startNanos = System.nanoTime();
final StartContextImpl context = new StartContextImpl(startNanos);
try {
if (doInjection) {
final ValueInjection<?>[] injections = ServiceControllerImpl.this.injections;
final int injectionsLength = injections.length;
boolean ok = false;
int i = 0;
try {
for (; i < injectionsLength; i++) {
final ValueInjection<?> injection = injections[i];
doInject(injection);
}
ok = true;
} finally {
if (! ok) {
for (; i >= 0; i
injections[i].getTarget().uninject();
}
}
}
}
final Service<? extends S> service = serviceValue.getValue();
if (service == null) {
throw new IllegalArgumentException("Service is null");
}
service.start(context);
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
if (context.state != ContextState.SYNC) {
return;
}
context.state = ContextState.COMPLETE;
asyncTasks
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('S', startNanos, System.nanoTime());
}
tasks = transition();
}
doExecute(tasks);
} catch (StartException e) {
e.setServiceName(serviceName);
ServiceLogger.INSTANCE.startFailed(e, serviceName);
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
final ContextState oldState = context.state;
if (oldState != ContextState.SYNC && oldState != ContextState.ASYNC) {
ServiceLogger.INSTANCE.exceptionAfterComplete(e, serviceName);
return;
}
context.state = ContextState.FAILED;
asyncTasks
startException = e;
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('F', startNanos, System.nanoTime());
}
failed = true;
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
final ContextState oldState = context.state;
if (oldState != ContextState.SYNC && oldState != ContextState.ASYNC) {
ServiceLogger.INSTANCE.exceptionAfterComplete(t, serviceName);
return;
}
context.state = ContextState.FAILED;
asyncTasks
ServiceLogger.INSTANCE.startFailed(startException = new StartException("Failed to start service", t, location, serviceName), serviceName);
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('F', startNanos, System.nanoTime());
}
failed = true;
tasks = transition();
}
doExecute(tasks);
}
}
}
private class StopTask implements Runnable {
private final boolean onlyUninject;
StopTask(final boolean onlyUninject) {
this.onlyUninject = onlyUninject;
}
public void run() {
assert !lockHeld();
final ServiceName serviceName = primaryRegistration.getName();
final long startNanos = System.nanoTime();
final StopContextImpl context = new StopContextImpl(startNanos);
boolean ok = false;
try {
if (! onlyUninject) {
try {
final Service<? extends S> service = serviceValue.getValue();
if (service != null) {
service.stop(context);
ok = true;
} else {
ServiceLogger.INSTANCE.stopServiceMissing(serviceName);
}
} catch (Throwable t) {
ServiceLogger.INSTANCE.stopFailed(t, serviceName);
}
}
} finally {
Runnable[] tasks = null;
synchronized (ServiceControllerImpl.this) {
if (ok && context.state != ContextState.SYNC) {
// We want to discard the exception anyway, if there was one. Which there can't be.
//noinspection ReturnInsideFinallyBlock
return;
}
context.state = ContextState.COMPLETE;
}
for (ValueInjection<?> injection : injections) try {
injection.getTarget().uninject();
} catch (Throwable t) {
ServiceLogger.INSTANCE.uninjectFailed(t, serviceName, injection);
}
synchronized (ServiceControllerImpl.this) {
asyncTasks
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('X', startNanos, System.nanoTime());
}
tasks = transition();
}
doExecute(tasks);
}
}
}
private class ListenerTask implements Runnable {
private final ListenerNotification notification;
private final ServiceListener<? super S> listener;
private final ServiceController.State state;
ListenerTask(final ServiceListener<? super S> listener, final ServiceController.State state) {
this.listener = listener;
this.state = state;
notification = ListenerNotification.STATE;
}
ListenerTask(final ServiceListener<? super S> listener, final ListenerNotification notification) {
this.listener = listener;
state = null;
this.notification = notification;
}
public void run() {
assert !lockHeld();
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
final long start = System.nanoTime();
try {
invokeListener(listener, notification, state);
} finally {
writeProfileInfo('L', start, System.nanoTime());
}
} else {
invokeListener(listener, notification, state);
}
}
}
private class DependencyStartedTask implements Runnable {
private final Dependent[][] dependents;
DependencyStartedTask(final Dependent[][] dependents) {
this.dependents = dependents;
}
public void run() {
try {
for (Dependent[] dependentArray : dependents) {
for (Dependent dependent : dependentArray) {
if (dependent != null) dependent.immediateDependencyUp();
}
}
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class DependencyStoppedTask implements Runnable {
private final Dependent[][] dependents;
DependencyStoppedTask(final Dependent[][] dependents) {
this.dependents = dependents;
}
public void run() {
try {
for (Dependent[] dependentArray : dependents) {
for (Dependent dependent : dependentArray) {
if (dependent != null) dependent.immediateDependencyDown();
}
}
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class InstallTask implements Runnable {
private InstallTask() {
}
public void run() {
try {
for (Dependency dependency : dependencies) {
dependency.addDependent(ServiceControllerImpl.this);
}
final ServiceControllerImpl<?> parent = ServiceControllerImpl.this.parent;
if (parent != null) parent.addChild(ServiceControllerImpl.this);
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class RemoveTask implements Runnable {
RemoveTask() {
}
public void run() {
try {
assert getMode() == ServiceController.Mode.REMOVE;
assert getSubstate() == Substate.REMOVING;
primaryRegistration.clearInstance(ServiceControllerImpl.this);
if (failed || dependencyFailed) {
primaryRegistration.getContainer().checkFailedDependencies(true);
}
for (ServiceRegistrationImpl registration : aliasRegistrations) {
registration.clearInstance(ServiceControllerImpl.this);
}
for (Dependency dependency : dependencies) {
dependency.removeDependent(ServiceControllerImpl.this);
}
final ServiceControllerImpl<?> parent = ServiceControllerImpl.this.parent;
if (parent != null) parent.removeChild(ServiceControllerImpl.this);
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class StartContextImpl implements StartContext {
private ContextState state = ContextState.SYNC;
private final long startNanos;
private StartContextImpl(final long startNanos) {
this.startNanos = startNanos;
}
public void failed(final StartException reason) throws IllegalStateException {
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
if (state != ContextState.ASYNC) {
throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE);
}
state = ContextState.FAILED;
final ServiceName serviceName = getName();
reason.setServiceName(serviceName);
ServiceLogger.INSTANCE.startFailed(reason, serviceName);
startException = reason;
failed = true;
asyncTasks
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('F', startNanos, System.nanoTime());
}
tasks = transition();
}
doExecute(tasks);
}
public ServiceTarget getChildTarget() {
synchronized (ServiceControllerImpl.this) {
if (state == ContextState.COMPLETE || state == ContextState.FAILED) {
throw new IllegalStateException("Lifecycle context is no longer valid");
}
if (childTarget == null) {
childTarget = new ChildServiceTarget(parent == null ? getServiceContainer() : parent.childTarget);
}
return childTarget;
}
}
public void asynchronous() throws IllegalStateException {
synchronized (ServiceControllerImpl.this) {
if (state == ContextState.SYNC) {
state = ContextState.ASYNC;
} else {
throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE);
}
}
}
public void complete() throws IllegalStateException {
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
if (state != ContextState.ASYNC) {
throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE);
} else {
state = ContextState.COMPLETE;
asyncTasks
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('S', startNanos, System.nanoTime());
}
tasks = transition();
}
}
doExecute(tasks);
}
public long getElapsedTime() {
return System.nanoTime() - lifecycleTime;
}
public ServiceController<?> getController() {
return ServiceControllerImpl.this;
}
public void execute(final Runnable command) {
doExecute(command);
}
}
private final class ChildServiceTarget extends ServiceTargetImpl {
private volatile boolean valid = true;
private ChildServiceTarget(final ServiceTargetImpl parentTarget) {
super(parentTarget);
}
<T> ServiceController<T> install(final ServiceBuilderImpl<T> serviceBuilder) throws ServiceRegistryException {
if (! valid) {
throw new IllegalStateException("Service target is no longer valid");
}
return super.install(serviceBuilder);
}
protected <T> ServiceBuilder<T> createServiceBuilder(final ServiceName name, final Value<? extends Service<T>> value, final ServiceControllerImpl<?> parent) throws IllegalArgumentException {
return super.createServiceBuilder(name, value, ServiceControllerImpl.this);
}
}
private void writeProfileInfo(final char statusChar, final long startNanos, final long endNanos) {
final ServiceRegistrationImpl primaryRegistration = this.primaryRegistration;
final ServiceName name = primaryRegistration.getName();
final ServiceContainerImpl container = primaryRegistration.getContainer();
final Writer profileOutput = container.getProfileOutput();
if (profileOutput != null) {
synchronized (profileOutput) {
try {
final long startOffset = startNanos - container.getStart();
final long duration = endNanos - startNanos;
profileOutput.write(String.format("%s\t%s\t%d\t%d\n", name.getCanonicalName(), Character.valueOf(statusChar), Long.valueOf(startOffset), Long.valueOf(duration)));
} catch (IOException e) {
// ignore
}
}
}
}
private class StopContextImpl implements StopContext {
private ContextState state = ContextState.SYNC;
private final long startNanos;
private StopContextImpl(final long startNanos) {
this.startNanos = startNanos;
}
public void asynchronous() throws IllegalStateException {
synchronized (ServiceControllerImpl.this) {
if (state == ContextState.SYNC) {
state = ContextState.ASYNC;
} else {
throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE);
}
}
}
public void complete() throws IllegalStateException {
synchronized (ServiceControllerImpl.this) {
if (state != ContextState.ASYNC) {
throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE);
}
state = ContextState.COMPLETE;
}
for (ValueInjection<?> injection : injections) {
injection.getTarget().uninject();
}
final Runnable[] tasks;
synchronized (ServiceControllerImpl.this) {
asyncTasks
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('X', startNanos, System.nanoTime());
}
tasks = transition();
}
doExecute(tasks);
}
public ServiceController<?> getController() {
return ServiceControllerImpl.this;
}
public void execute(final Runnable command) {
doExecute(command);
}
public long getElapsedTime() {
return System.nanoTime() - lifecycleTime;
}
}
enum Substate {
NEW(State.DOWN),
DOWN(State.DOWN),
START_REQUESTED(State.DOWN),
STARTING(State.STARTING),
START_FAILED(State.START_FAILED),
UP(State.UP),
STOP_REQUESTED(State.UP),
STOPPING(State.STOPPING),
REMOVING(State.DOWN),
REMOVED(State.REMOVED),
;
private final ServiceController.State state;
Substate(final ServiceController.State state) {
this.state = state;
}
public ServiceController.State getState() {
return state;
}
}
enum Transition {
START_REQUESTED_to_DOWN(Substate.START_REQUESTED, Substate.DOWN),
START_REQUESTED_to_STARTING(Substate.START_REQUESTED, Substate.STARTING),
STARTING_to_UP(Substate.STARTING, Substate.UP),
STARTING_to_START_FAILED(Substate.STARTING, Substate.START_FAILED),
START_FAILED_to_STARTING(Substate.START_FAILED, Substate.STARTING),
START_FAILED_to_DOWN(Substate.START_FAILED, Substate.DOWN),
UP_to_STOP_REQUESTED(Substate.UP, Substate.STOP_REQUESTED),
STOP_REQUESTED_to_UP(Substate.STOP_REQUESTED, Substate.UP),
STOP_REQUESTED_to_STOPPING(Substate.STOP_REQUESTED, Substate.STOPPING),
STOPPING_to_DOWN(Substate.STOPPING, Substate.DOWN),
REMOVING_to_REMOVED(Substate.REMOVING, Substate.REMOVED),
DOWN_to_REMOVING(Substate.DOWN, Substate.REMOVING),
DOWN_to_START_REQUESTED(Substate.DOWN, Substate.START_REQUESTED),
;
private final Substate before;
private final Substate after;
Transition(final Substate before, final Substate after) {
this.before = before;
this.after = after;
}
public Substate getBefore() {
return before;
}
public Substate getAfter() {
return after;
}
}
}
|
package org.jenkinsci.plugins.ovirt;
import hudson.model.TaskListener;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.SlaveComputer;
import java.io.IOException;
import org.kohsuke.stapler.DataBoundConstructor;
import org.ovirt.engine.sdk.decorators.VM;
import org.ovirt.engine.sdk.decorators.VMSnapshot;
import org.ovirt.engine.sdk.entities.Action;
public class OVirtVMLauncher extends ComputerLauncher {
private ComputerLauncher delegateLauncher;
private String hypervisorDescription;
private String virtualMachineName;
private String snapshotName;
private final int WAITING_TIME_MILLISECS;
private final int retries;
@DataBoundConstructor
public OVirtVMLauncher(ComputerLauncher delegateLauncher,
String hypervisorDescription, String virtualMachineName,
String snapshotName, int waitingTimeSecs, int retries) {
super();
this.delegateLauncher = delegateLauncher;
this.hypervisorDescription = hypervisorDescription;
this.virtualMachineName = virtualMachineName;
this.snapshotName = snapshotName;
this.WAITING_TIME_MILLISECS = secToMilliseconds(waitingTimeSecs);
this.retries = retries;
}
public ComputerLauncher getDelegateLauncher() {
return delegateLauncher;
}
public String getHypervisorDescription() {
return hypervisorDescription;
}
public String getVirtualMachineName() {
return virtualMachineName;
}
public String getSnapshotName() {
return snapshotName;
}
public int getWAITING_TIME_MILLISECS() {
return WAITING_TIME_MILLISECS;
}
/**
* Super fancy method to convert seconds to milliseconds. The
* implementation is O(1).
*
* @param seconds convert this value to milliseconds
* @return the converted value
*/
private static int secToMilliseconds(final int seconds) {
return seconds * 1000;
}
/**
* Get the current vm status. It does so by continuously getting a new VM
* object corresponding to 'virtualMachineName', and checking on its state.
*
* We expect the states to be 'up', 'down', 'powering_up', etc
*
* @return the vm status
*/
private String getVMStatus() {
return OVirtHypervisor.find(hypervisorDescription)
.getVM(virtualMachineName)
.getStatus()
.getState();
}
/**
* Helper method to print to the jenkins log output that you'll see on
* the jenkins webserver when you start a new node
*
* @param taskListener listener object
* @param text text to output
*/
private void printLog(TaskListener taskListener, final String text) {
taskListener.getLogger().println(text);
}
/**
* Returns a boolean that will return true if a snapshot is specified.
* A snapshot is specified when the snapshotName is NOT empty.
*
* @return true if snapshot name is specified
*/
private boolean isSnapshotSpecified() {
return !snapshotName.trim().equals("");
}
/**
* Check is the current vm bounded to this object is down!
*
* @return true if the vm is down
*/
private boolean isVMDown() {
return getVMStatus().equalsIgnoreCase("down");
}
/**
* Check is the current vm bounded to this object is up!
*
* @return true if the vm is up
*/
private boolean isVMUp() {
return getVMStatus().equalsIgnoreCase("up");
}
private boolean isVMImageLocked() {
return getVMStatus().equalsIgnoreCase("image_locked");
}
/**
* Try to wait for WAITING_TIME_MILLISECS' milliseconds to see if the vm
* is shutdown.
* This wait will be attempted 'retries' times before giving up, and
* throwing an exception to announce that we are giving up
*
* @param vm The vm that we are waiting to shutdown
* @param taskListener taskListener is needed to print to the jenkins log
* @throws Exception
*/
private void waitVMIsDown(VM vm, TaskListener taskListener)
throws Exception {
for (int i = 0; i < retries; ++i) {
printLog(taskListener, "Waiting for " + vm.getName() +
" to shutdown...");
Thread.sleep(WAITING_TIME_MILLISECS);
if (isVMDown()) {
printLog(taskListener, "VM is now shutdown");
return;
}
}
// if we reached here, vm did not shutdown after that many retries
printLog(taskListener, "VM did not shutdown properly. Giving up!");
throw new Exception("VM did not shutdown at all!");
}
/**
* Try to wait for WAITING_TIME_MILLISECS' milliseconds to see if the vm
* is up.
* This wait will be attempted 'retries' times before giving up, and
* throwing an exception to announce that we are giving up
*
* @param vm The vm that we are waiting to startup
* @param taskListener taskListener is needed to print to the jenkins log
* @throws Exception
*/
private void waitVMIsUp(VM vm, TaskListener taskListener) throws Exception {
for (int i = 0; i < retries; ++i) {
printLog(taskListener, "Waiting for " + vm.getName() +
" to start...");
Thread.sleep(WAITING_TIME_MILLISECS);
if (isVMUp()) {
printLog(taskListener, "VM is now online!");
return;
}
}
printLog(taskListener, "VM did not startup properly. Giving up!");
throw new Exception("VM did not startup at all!");
}
/**
* Asks ovirt server to shutdown a vm
*
* @param vm The vm to be stopped
* @throws Exception
*/
private void shutdownVM(VM vm) throws Exception {
Action actionParams = new Action();
actionParams.setVm(new org.ovirt.engine.sdk.entities.VM());
vm.shutdown(actionParams);
}
/**
* Asks ovirt server to start a vm
*
* @param vm The vm to be started
* @throws Exception
*/
private void startVM(VM vm) throws Exception {
Action actionParams = new Action();
actionParams.setVm(new org.ovirt.engine.sdk.entities.VM());
vm.start(actionParams);
}
/**
* Put the vm down, if it is not yet down, and wait for some time to see
* if the vm is actually down.
*
* @param vm The vm to be shutdown
* @param taskListener listener object
* @throws Exception
*/
private void putVMDown(VM vm, TaskListener taskListener) throws Exception {
if (!isVMDown()) {
printLog(taskListener, vm.getName() + " is to be shutdown");
shutdownVM(vm);
} else {
printLog(taskListener, vm.getName() + " is already shutdown");
return;
}
waitVMIsDown(vm, taskListener);
}
/**
* Put the vm up if it is not already up, and wait for some time to see
* if the vm is actually up.
*
* @param vm The vm to be started
* @param taskListener listener object
* @throws Exception
*/
private void putVMUp(VM vm, TaskListener taskListener) throws Exception {
if (isVMDown()) {
printLog(taskListener, vm.getName() + " is to be started");
startVM(vm);
waitVMIsUp(vm, taskListener);
} else {
printLog(taskListener, vm.getName() + " is already up");
}
}
/**
* Quick note: Don't try to cache the snapshot object. There are cases
* where I'll cache the snapshot object based on the name, but the snapshot
* on Ovirt will get deleted, and another snapshot with the same name will
* be created. In this scenario, the cached snapshot object becomes invalid
*
* Instead, just always ask Ovirt for the latest snapshot object
* @param vm
* @param snapshotName
* @return
* @throws Exception
*/
private VMSnapshot getSnapshot(VM vm, String snapshotName)
throws Exception {
if (!isSnapshotSpecified()) {
return null;
}
for (VMSnapshot snap: vm.getSnapshots().list()) {
if (snap.getDescription().equals(snapshotName)) {
return snap;
}
}
// if we reached here, then the snapshotName is not bound to that
// particular vm
throw new RuntimeException("No snapshot '" + snapshotName + "' " +
"for vm '" + vm.getName() + "' found");
}
/**
* If snapshot is specified, then this method will try to revert the vm
* to the snapshotName. Note that in most cases the vm should be shutdown
* before attempting to call this method, even though this claim was
* never tested
*
* If snapshot is not specified, then do nothing
*
* @param vm: vm to revert snapshot to
* @param snapshotName: the snapshotName that the vm will revert to
* @param taskListener: listener object
* @throws Exception
*/
private void revertSnapshot(VM vm,
String snapshotName,
TaskListener taskListener) throws Exception {
if (!isSnapshotSpecified()) {
throw new Exception("No snapshot specified!");
}
VMSnapshot snapshot = getSnapshot(vm, snapshotName);
// no snapshot to revert to
if (snapshot == null) {
throw new Exception("No snapshot specified!");
}
Action actionParams = new Action();
actionParams.setVm(new org.ovirt.engine.sdk.entities.VM());
snapshot.restore(actionParams);
printLog(taskListener, "Reverted '" + vm.getName() + "' to snapshot '"
+ snapshot.getDescription() + "'");
}
/**
* This method is called when the node is about to be used.
* So what it will do (in theory) is to start the vm (if
* needed), then find a way to link to the vm, and run slave.jar on the vm
*
* @param slaveComputer the node to be launched
* @param taskListener listener
*/
@Override
public void launch(SlaveComputer slaveComputer, TaskListener taskListener)
throws IOException, InterruptedException {
OVirtVMSlave slave = (OVirtVMSlave) slaveComputer.getNode();
printLog(taskListener, "Connecting to ovirt server...");
VM vm = OVirtHypervisor.find(hypervisorDescription)
.getVM(virtualMachineName);
try {
// only if snapshot is specified should we try to shut it down
// and revert to snapshot
if (isSnapshotSpecified()) {
putVMDown(vm, taskListener);
revertSnapshot(vm, slave.getSnapshotName(), taskListener);
waitTillSnapshotUnlocked(taskListener);
}
putVMUp(vm, taskListener);
delegateLauncher.launch(slaveComputer, taskListener);
} catch (Exception e) {
handleLaunchFailure(e, taskListener);
}
}
private void waitTillSnapshotUnlocked(TaskListener taskListener) throws InterruptedException {
while(true) {
if (isVMImageLocked()) {
printLog(taskListener, "VM is image locked. Waiting till it's really down...");
Thread.sleep(WAITING_TIME_MILLISECS);
} else {
break;
}
}
}
/**
* Put the exception in the launch method to the ovirt server log and
* throw an InterruptedException error about this failure.
*
* @param e: Exception to wrap around an InterruptedException
* @param taskListener: listener object
* @throws InterruptedException
*/
private void handleLaunchFailure(Exception e, TaskListener taskListener)
throws InterruptedException {
e.printStackTrace();
printLog(taskListener, e.toString());
InterruptedException ie = new InterruptedException();
ie.initCause(e);
throw ie;
}
/**
* This method should call the delegate `beforeDisconnect` method.
*
* @param computer node to be disconnected
* @param listener listener
*/
@Override
public synchronized void beforeDisconnect(SlaveComputer computer,
TaskListener listener) {
delegateLauncher.beforeDisconnect(computer, listener);
}
/**
* Try to shutdown the computer after the slave.jar has stopped running.
*
* @param computer node that has been disconnected
* @param listener listener
*/
@Override
public synchronized void afterDisconnect(SlaveComputer computer,
TaskListener listener) {
delegateLauncher.afterDisconnect(computer, listener);
}
}
|
package org.jtrfp.trcl.beh;
import java.util.concurrent.Callable;
import org.jtrfp.trcl.SpacePartitioningGrid;
import org.jtrfp.trcl.beh.DamageableBehavior.SupplyNotNeededException;
import org.jtrfp.trcl.core.ThreadManager;
import org.jtrfp.trcl.obj.WorldObject;
public class ResetsRandomlyAfterDeath extends Behavior implements DeathListener {
private double minWaitMillis=100,maxWaitMillis=1000;
private Runnable runOnReset;
@Override
public void notifyDeath() {
//Reset state
final WorldObject thisObject = getParent();
final Runnable _runOnReset = runOnReset;
final long waitTime = (long)(minWaitMillis+Math.random()*(maxWaitMillis-minWaitMillis));
final ThreadManager threadManager = thisObject.getTr().getThreadManager();
threadManager.submitToThreadPool(new Callable<Void>(){
@Override
public Void call() throws Exception {
try{Thread.currentThread().sleep(waitTime);}
catch(InterruptedException e){e.printStackTrace();}
threadManager.submitToGPUMemAccess(new Callable<Void>(){
@Override
public Void call() throws Exception {
unDamage();
reset();
reIntroduce();
runOnReset();
return null;
}
private void unDamage(){
try{thisObject.probeForBehavior(DamageableBehavior.class).unDamage();}
catch(SupplyNotNeededException e){e.printStackTrace();}
}
private void reset(){
SpacePartitioningGrid grid = thisObject.probeForBehavior(DeathBehavior.class).getGridOfLastDeath();
thisObject.probeForBehavior(DeathBehavior.class).reset();
if(grid!=null)grid.add(thisObject);
else throw new NullPointerException();
}
private void reIntroduce(){
thisObject.setActive(true);
thisObject.setVisible(true);
}
private void runOnReset(){
_runOnReset.run();
}
}).get();
return null;
}});
}//end notifyDeath
/**
* @return the minWaitMillis
*/
public double getMinWaitMillis() {
return minWaitMillis;
}
/**
* @param minWaitMillis the minWaitMillis to set
*/
public ResetsRandomlyAfterDeath setMinWaitMillis(double minWaitMillis) {
this.minWaitMillis = minWaitMillis;
return this;
}
/**
* @return the maxWaitMillis
*/
public double getMaxWaitMillis() {
return maxWaitMillis;
}
/**
* @param maxWaitMillis the maxWaitMillis to set
*/
public ResetsRandomlyAfterDeath setMaxWaitMillis(double maxWaitMillis) {
this.maxWaitMillis = maxWaitMillis;
return this;
}
/**
* @return the runOnReset
*/
public Runnable getRunOnReset() {
return runOnReset;
}
/**
* @param runOnReset the runOnReset to set
*/
public ResetsRandomlyAfterDeath setRunOnReset(Runnable runOnReset) {
this.runOnReset = runOnReset;
return this;
}
}//end ResetsRandomlyAfterDeath
|
package org.lazan.t5.stitch.model;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
public class DefaultPagerModel implements PagerModel {
private final int minStartPages;
private final int minEndPages;
private final int currentBuffer;
private final int showPreviousThreshold;
private final int showNextThreshold;
/**
* A default pager model implementation
* @param minStartPages The minimum number of pages to display at the start of the pager
* @param minEndPages The minimum number of pages to display at the end of the pager
* @param currentBuffer Number of pages to display at either side of the current page
* @param showPreviousThreshold Minimum number of pages before the previous link is displayed
* @param showNextThreshold Minimum number of pages before the next link is displayed
*/
public DefaultPagerModel(int minStartPages, int minEndPages, int currentBuffer, int showPreviousThreshold, int showNextThreshold) {
super();
this.minStartPages = minStartPages;
this.minEndPages = minEndPages;
this.currentBuffer = currentBuffer;
this.showPreviousThreshold = showPreviousThreshold;
this.showNextThreshold = showNextThreshold;
}
public Collection<Integer> getPages(int currentPage, int pageCount) {
Set<Integer> pages = new TreeSet<Integer>();
// we will always display the same number of pages
int requiredPages = minStartPages + minEndPages + 1 + (currentBuffer * 2);
if (pageCount <= requiredPages) {
addPages(pages, 1, pageCount, 1);
} else {
int bufferPages = 1 + (currentBuffer * 2);
addPages(pages, 1, minStartPages, 1);
addPages(pages, pageCount, minEndPages, -1);
if (currentPage <= minStartPages) {
// currentPage is within startPages
// add extra pages to the start
addPages(pages, minStartPages + 1, bufferPages, 1);
} else if (currentPage >= pageCount - minEndPages) {
// currentPage is within the endPages
// add extra pages to the end
addPages(pages, pageCount - minEndPages, bufferPages, -1);
} else {
// add buffer pages around currentPage
int start = Math.max(minStartPages + 1, currentPage - currentBuffer);
addPages(pages, start, bufferPages, 1);
}
}
return pages;
}
private void addPages(Set<Integer> pages, int start, int count, int increment) {
for (int i = 0; i < count; ++ i) {
int page = start + (increment * i);
pages.add(page);
}
}
public boolean isShowNext(int currentpage, int pageCount) {
return pageCount >= showNextThreshold;
}
public boolean isShowPrevious(int currentpage, int pageCount) {
return pageCount >= showPreviousThreshold;
}
}
|
package org.luxons.sevenwonders.game.boards;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Map;
public class Science {
private Map<ScienceType, Integer> quantities = new EnumMap<>(ScienceType.class);
private int jokers;
public void add(ScienceType type, int quantity) {
quantities.merge(type, quantity, (x, y) -> x + y);
}
public void addJoker(int quantity) {
jokers += quantity;
}
public int getJokers() {
return jokers;
}
public void addAll(Science science) {
science.quantities.forEach(this::add);
jokers += science.jokers;
}
public int getQuantity(ScienceType type) {
return quantities.getOrDefault(type, 0);
}
public int size() {
return quantities.values().stream().mapToInt(q -> q).sum() + jokers;
}
public int computePoints() {
ScienceType[] types = ScienceType.values();
Integer[] values = new Integer[types.length];
for (int i = 0; i < types.length; i++) {
values[i] = quantities.getOrDefault(types[i], 0);
}
return computePoints(values, jokers);
}
private static int computePoints(Integer[] values, int jokers) {
if (jokers == 0) {
return computePointsNoJoker(values);
}
int maxPoints = 0;
for (int i = 0; i < values.length; i++) {
values[i]++;
maxPoints = Math.max(maxPoints, computePoints(values, jokers - 1));
values[i]
}
return maxPoints;
}
private static int computePointsNoJoker(Integer[] values) {
int independentSquaresSum = Arrays.stream(values).mapToInt(i -> i * i).sum();
int nbGroupsOfAll = Arrays.stream(values).mapToInt(i -> i).min().orElse(0);
return independentSquaresSum + nbGroupsOfAll * 7;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Science{");
quantities.forEach((type, count) -> sb.append(type).append("=").append(count).append(" "));
return sb.append("*=").append(jokers).toString();
}
}
|
package org.openlmis.fulfillment.web;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
import java.util.stream.Collectors;
@RequestMapping("/api")
public abstract class BaseController {
protected Map<String, String> getErrors(BindingResult bindingResult) {
return bindingResult
.getFieldErrors()
.stream()
.collect(Collectors.toMap(FieldError::getField, FieldError::getCode));
}
}
|
package org.opentosca.csarrepo.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.opentosca.csarrepo.filesystem.FileSystem;
import org.opentosca.csarrepo.model.CsarFile;
public class WineryApiClient {
private Client client;
private String url;
public WineryApiClient(URL url) {
this.url = url.toExternalForm();
if(this.url.charAt(this.url.length() -1 ) != '/') {
this.url += "/";
}
this.client = ClientBuilder.newClient(new ClientConfig()
.register(MultiPartFeature.class));
}
public void uploadToWinery(CsarFile file) throws Exception {
FileSystem fs = new FileSystem();
File f = fs.getFile(file.getHashedFile().getFilename());
if (f == null) {
throw new FileNotFoundException(file.getName() + " not found");
}
// build form data
FormDataMultiPart multiPart = new FormDataMultiPart();
FormDataContentDisposition.FormDataContentDispositionBuilder dispositionBuilder = FormDataContentDisposition
.name("file");
dispositionBuilder.fileName(file.getName());
dispositionBuilder.size(f.getTotalSpace());
FormDataContentDisposition formDataContentDisposition = dispositionBuilder
.build();
multiPart.bodyPart(new FormDataBodyPart("file", f, MediaType.APPLICATION_OCTET_STREAM_TYPE)
.contentDisposition(formDataContentDisposition));
Entity<FormDataMultiPart> entity = Entity.entity(multiPart,
MediaType.MULTIPART_FORM_DATA_TYPE);
// send request
WebTarget target = client.target(this.url);
Builder request = target.request();
Response response = request.post(entity);
// handle response
if(Status.NO_CONTENT.getStatusCode() == response.getStatus()) {
return;
}
throw new Exception("failed to push to winery");
}
public InputStream pullFromWinery(String id) throws Exception {
// send request
WebTarget target = client.target(this.url + "servicetemplates/" + id);
Builder request = target.request();
request.accept("application/zip");
Response response = request.get();
if(Status.NOT_FOUND.getStatusCode() == response.getStatus()) {
// 404
throw new Exception("No corresponding servicetemplate found");
}
if(Status.OK.getStatusCode() == response.getStatus()) {
// 200
try {
InputStream stream = (InputStream) response.getEntity();
return stream;
} catch(Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
return null;
}
}
// other code
throw new Exception("Error connecting to winery");
}
}
|
package org.owasp.dependencycheck.data.nvdcve;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.data.cpe.Entry;
import org.owasp.dependencycheck.data.cwe.CweDB;
import org.owasp.dependencycheck.dependency.Reference;
import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.dependency.VulnerableSoftware;
import org.owasp.dependencycheck.utils.FileUtils;
import org.owasp.dependencycheck.utils.Settings;
/**
* The database holding information about the NVD CVE data.
*
* @author Jeremy Long (jeremy.long@owasp.org)
*/
public class CveDB {
//<editor-fold defaultstate="collapsed" desc="Constants to create, maintain, and retrieve data from the CVE Database">
/**
* SQL Statement to create an index on the reference table.
*/
public static final String CREATE_INDEX_IDXREFERENCE = "CREATE INDEX IF NOT EXISTS idxReference ON reference(cveid)";
/**
* SQL Statement to create an index on the software for finding CVE entries based on CPE data.
*/
public static final String CREATE_INDEX_IDXSOFTWARE = "CREATE INDEX IF NOT EXISTS idxSoftware ON software(product, vendor, version)";
/**
* SQL Statement to create an index for retrieving software by CVEID.
*/
public static final String CREATE_INDEX_IDXSOFTWARECVE = "CREATE INDEX IF NOT EXISTS idxSoftwareCve ON software(cveid)";
/**
* SQL Statement to create an index on the vulnerability table.
*/
public static final String CREATE_INDEX_IDXVULNERABILITY = "CREATE INDEX IF NOT EXISTS idxVulnerability ON vulnerability(cveid)";
/**
* SQL Statement to create the reference table.
*/
public static final String CREATE_TABLE_REFERENCE = "CREATE TABLE IF NOT EXISTS reference (cveid CHAR(13), "
+ "name varchar(1000), url varchar(1000), source varchar(255))";
/**
* SQL Statement to create the software table.
*/
public static final String CREATE_TABLE_SOFTWARE = "CREATE TABLE IF NOT EXISTS software (cveid CHAR(13), cpe varchar(500), "
+ "vendor varchar(255), product varchar(255), version varchar(50), previousVersion varchar(50))";
/**
* SQL Statement to create the vulnerability table.
*/
public static final String CREATE_TABLE_VULNERABILITY = "CREATE TABLE IF NOT EXISTS vulnerability (cveid CHAR(13) PRIMARY KEY, "
+ "description varchar(8000), cwe varchar(10), cvssScore DECIMAL(3,1), cvssAccessVector varchar(20), "
+ "cvssAccessComplexity varchar(20), cvssAuthentication varchar(20), cvssConfidentialityImpact varchar(20), "
+ "cvssIntegrityImpact varchar(20), cvssAvailabilityImpact varchar(20))";
/**
* SQL Statement to delete references by CVEID.
*/
public static final String DELETE_REFERENCE = "DELETE FROM reference WHERE cveid = ?";
/**
* SQL Statement to delete software by CVEID.
*/
public static final String DELETE_SOFTWARE = "DELETE FROM software WHERE cveid = ?";
/**
* SQL Statement to delete a vulnerability by CVEID.
*/
public static final String DELETE_VULNERABILITY = "DELETE FROM vulnerability WHERE cveid = ?";
/**
* SQL Statement to insert a new reference.
*/
public static final String INSERT_REFERENCE = "INSERT INTO reference (cveid, name, url, source) VALUES (?, ?, ?, ?)";
/**
* SQL Statement to insert a new software.
*/
public static final String INSERT_SOFTWARE = "INSERT INTO software (cveid, cpe, vendor, product, version, previousVersion) "
+ "VALUES (?, ?, ?, ?, ?, ?)";
/**
* SQL Statement to insert a new vulnerability.
*/
public static final String INSERT_VULNERABILITY = "INSERT INTO vulnerability (cveid, description, cwe, cvssScore, cvssAccessVector, "
+ "cvssAccessComplexity, cvssAuthentication, cvssConfidentialityImpact, cvssIntegrityImpact, cvssAvailabilityImpact) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
/**
* SQL Statement to find CVE entries based on CPE data.
*/
public static final String SELECT_CVE_FROM_SOFTWARE = "SELECT cveid FROM software WHERE Vendor = ? AND Product = ? AND "
+ "(version = '-' OR previousVersion IS NOT NULL OR version=?)";
/**
* SQL Statement to select references by CVEID.
*/
public static final String SELECT_REFERENCE = "SELECT source, name, url FROM reference WHERE cveid = ?";
/**
* SQL Statement to select software by CVEID.
*/
public static final String SELECT_SOFTWARE = "SELECT cpe, previousVersion FROM software WHERE cveid = ?";
/**
* SQL Statement to select a vulnerability by CVEID.
*/
public static final String SELECT_VULNERABILITY = "SELECT cveid, description, cwe, cvssScore, cvssAccessVector, cvssAccessComplexity, "
+ "cvssAuthentication, cvssConfidentialityImpact, cvssIntegrityImpact, cvssAvailabilityImpact FROM vulnerability WHERE cveid = ?";
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Collection of CallableStatements to work with the DB">
/**
* delete reference - parameters (cveid).
*/
private CallableStatement deleteReferences;
/**
* delete software - parameters (cveid).
*/
private CallableStatement deleteSoftware;
/**
* delete vulnerability - parameters (cveid).
*/
private CallableStatement deleteVulnerabilities;
/**
* insert reference - parameters (cveid, name, url, source).
*/
private CallableStatement insertReference;
/**
* insert software - parameters (cveid, cpe, vendor, product, version, previousVersion).
*/
private CallableStatement insertSoftware;
/**
* insert vulnerability - parameters (cveid, description, cwe, cvssScore, cvssAccessVector,
* cvssAccessComplexity, cvssAuthentication, cvssConfidentialityImpact, cvssIntegrityImpact, cvssAvailabilityImpact).
*/
private CallableStatement insertVulnerability;
/**
* select cve from software - parameters (vendor, product, version).
*/
private CallableStatement selectCveFromSoftware;
/**
* select vulnerability - parameters (cveid).
*/
private CallableStatement selectVulnerability;
/**
* select reference - parameters (cveid).
*/
private CallableStatement selectReferences;
/**
* select software - parameters (cveid).
*/
private CallableStatement selectSoftware;
//</editor-fold>
/**
* Database connection
*/
private Connection conn;
/**
* Opens the database connection. If the database does not exist, it will
* create a new one.
*
* @throws IOException thrown if there is an IO Exception
* @throws SQLException thrown if there is a SQL Exception
* @throws DatabaseException thrown if there is an error initializing a new database
* @throws ClassNotFoundException thrown if the h2 database driver cannot be loaded
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings(
value = "DMI_EMPTY_DB_PASSWORD",
justification = "Yes, I know... Blank password.")
public void open() throws IOException, SQLException, DatabaseException, ClassNotFoundException {
final String fileName = CveDB.getDataDirectory().getCanonicalPath()
+ File.separator
+ "cve";
final File f = new File(fileName);
final boolean createTables = !f.exists();
final String connStr = "jdbc:h2:file:" + fileName;
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection(connStr, "sa", "");
if (createTables) {
createTables();
}
buildStatements();
}
/**
* Cleans up the object and ensures that "close" has been called.
* @throws Throwable thrown if there is a problem
*/
@Override
protected void finalize() throws Throwable {
close();
super.finalize(); //not necessary if extending Object.
}
/**
* Closes the DB4O database. Close should be called on
* this object when it is done being used.
*/
public void close() {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex);
}
conn = null;
}
}
/**
* Retrieves the vulnerabilities associated with the specified CPE ID.
*
* @param cpeStr the CPE cpe name
* @return a list of Vulnerabilities
* @throws DatabaseException thrown if there is an exception retrieving data
*/
public List<Vulnerability> getVulnerabilities(String cpeStr) throws DatabaseException {
ResultSet rs = null;
final Entry cpe = new Entry();
try {
cpe.parseName(cpeStr);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex);
}
final List<Vulnerability> vulnerabilities = new ArrayList<Vulnerability>();
try {
selectCveFromSoftware.setString(1, cpe.getVendor());
selectCveFromSoftware.setString(2, cpe.getProduct());
selectCveFromSoftware.setString(3, cpe.getVersion());
rs = selectCveFromSoftware.executeQuery();
while (rs.next()) {
final Vulnerability v = getVulnerability(rs.getString("cveid"));
vulnerabilities.add(v);
}
} catch (SQLException ex) {
throw new DatabaseException("Exception retrieving vulnerability for " + cpeStr, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return vulnerabilities;
}
/**
* Gets a vulnerability for the provided CVE.
*
* @param cve the CVE to lookup
* @return a vulnerability object
* @throws DatabaseException if an exception occurs
*/
private Vulnerability getVulnerability(String cve) throws DatabaseException {
ResultSet rsV = null;
ResultSet rsR = null;
ResultSet rsS = null;
Vulnerability vuln = null;
try {
selectVulnerability.setString(1, cve);
rsV = selectVulnerability.executeQuery();
if (rsV.next()) {
vuln = new Vulnerability();
vuln.setName(cve);
vuln.setDescription(rsV.getString(2));
String cwe = rsV.getString(3);
if (cwe != null) {
final String name = CweDB.getCweName(cwe);
if (name != null) {
cwe += " " + name;
}
}
vuln.setCwe(cwe);
vuln.setCvssScore(rsV.getFloat(4));
vuln.setCvssAccessVector(rsV.getString(5));
vuln.setCvssAccessComplexity(rsV.getString(6));
vuln.setCvssAuthentication(rsV.getString(7));
vuln.setCvssConfidentialityImpact(rsV.getString(8));
vuln.setCvssIntegrityImpact(rsV.getString(9));
vuln.setCvssAvailabilityImpact(rsV.getString(10));
selectReferences.setString(1, cve);
rsR = selectReferences.executeQuery();
while (rsR.next()) {
vuln.addReference(rsR.getString(1), rsR.getString(2), rsR.getString(3));
}
selectSoftware.setString(1, cve);
rsS = selectSoftware.executeQuery();
while (rsS.next()) {
final String cpe = rsS.getString(1);
final String prevVersion = rsS.getString(2);
if (prevVersion == null) {
vuln.addVulnerableSoftware(cpe);
} else {
vuln.addVulnerableSoftware(cpe, prevVersion);
}
}
}
} catch (SQLException ex) {
throw new DatabaseException("Error retrieving " + cve, ex);
} finally {
if (rsV != null) {
try {
rsV.close();
} catch (SQLException ex) {
Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (rsR != null) {
try {
rsR.close();
} catch (SQLException ex) {
Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (rsS != null) {
try {
rsS.close();
} catch (SQLException ex) {
Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return vuln;
}
/**
* Updates the vulnerability within the database. If the vulnerability does not
* exist it will be added.
*
* @param vuln the vulnerability to add to the database
* @throws DatabaseException is thrown if the database
*/
public void updateVulnerability(Vulnerability vuln) throws DatabaseException {
try {
// first delete any existing vulnerability info.
deleteReferences.setString(1, vuln.getName());
deleteReferences.execute();
deleteSoftware.setString(1, vuln.getName());
deleteSoftware.execute();
deleteVulnerabilities.setString(1, vuln.getName());
deleteVulnerabilities.execute();
insertVulnerability.setString(1, vuln.getName());
insertVulnerability.setString(2, vuln.getDescription());
insertVulnerability.setString(3, vuln.getCwe());
insertVulnerability.setFloat(4, vuln.getCvssScore());
insertVulnerability.setString(5, vuln.getCvssAccessVector());
insertVulnerability.setString(6, vuln.getCvssAccessComplexity());
insertVulnerability.setString(7, vuln.getCvssAuthentication());
insertVulnerability.setString(8, vuln.getCvssConfidentialityImpact());
insertVulnerability.setString(9, vuln.getCvssIntegrityImpact());
insertVulnerability.setString(10, vuln.getCvssAvailabilityImpact());
insertVulnerability.execute();
insertReference.setString(1, vuln.getName());
for (Reference r : vuln.getReferences()) {
insertReference.setString(2, r.getName());
insertReference.setString(3, r.getUrl());
insertReference.setString(4, r.getSource());
insertReference.execute();
}
insertSoftware.setString(1, vuln.getName());
for (VulnerableSoftware s : vuln.getVulnerableSoftware()) {
//cveid, cpe, vendor, product, version, previousVersion
insertSoftware.setString(2, s.getName());
insertSoftware.setString(3, s.getVendor());
insertSoftware.setString(4, s.getProduct());
insertSoftware.setString(5, s.getVersion());
if (s.hasPreviousVersion()) {
insertSoftware.setString(6, s.getPreviousVersion());
} else {
insertSoftware.setNull(6, java.sql.Types.VARCHAR);
}
insertSoftware.execute();
}
} catch (SQLException ex) {
Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex);
throw new DatabaseException("Error updating '" + vuln.getName() + "'", ex);
}
}
/**
* Retrieves the directory that the JAR file exists in so that
* we can ensure we always use a common data directory.
*
* @return the data directory for this index.
* @throws IOException is thrown if an IOException occurs of course...
*/
public static File getDataDirectory() throws IOException {
final String fileName = Settings.getString(Settings.KEYS.CVE_INDEX);
final File path = FileUtils.getDataDirectory(fileName, CveDB.class);
if (!path.exists()) {
if (!path.mkdirs()) {
throw new IOException("Unable to create NVD CVE Data directory");
}
}
return path;
}
/**
* Creates the database structure (tables and indexes) to store the CVE data
*
* @throws SQLException thrown if there is a sql exception
* @throws DatabaseException thrown if there is a database exception
*/
protected void createTables() throws SQLException, DatabaseException {
Statement statement = null;
try {
statement = conn.createStatement();
statement.execute(CREATE_TABLE_VULNERABILITY);
statement.execute(CREATE_TABLE_REFERENCE);
statement.execute(CREATE_TABLE_SOFTWARE);
statement.execute(CREATE_INDEX_IDXSOFTWARE);
statement.execute(CREATE_INDEX_IDXREFERENCE);
statement.execute(CREATE_INDEX_IDXVULNERABILITY);
statement.execute(CREATE_INDEX_IDXSOFTWARECVE);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
/**
* Builds the CallableStatements used by the application.
* @throws DatabaseException thrown if there is a database exception
*/
private void buildStatements() throws DatabaseException {
try {
deleteReferences = conn.prepareCall(DELETE_REFERENCE);
deleteSoftware = conn.prepareCall(DELETE_SOFTWARE);
deleteVulnerabilities = conn.prepareCall(DELETE_VULNERABILITY);
insertReference = conn.prepareCall(INSERT_REFERENCE);
insertSoftware = conn.prepareCall(INSERT_SOFTWARE);
insertVulnerability = conn.prepareCall(INSERT_VULNERABILITY);
selectCveFromSoftware = conn.prepareCall(SELECT_CVE_FROM_SOFTWARE);
selectVulnerability = conn.prepareCall(SELECT_VULNERABILITY);
selectReferences = conn.prepareCall(SELECT_REFERENCE);
selectSoftware = conn.prepareCall(SELECT_SOFTWARE);
} catch (SQLException ex) {
throw new DatabaseException("Unable to prepare statements", ex);
}
}
}
|
package org.sagebionetworks.web.client;
import static org.sagebionetworks.web.client.ClientProperties.ALERT_CONTAINER_ID;
import static org.sagebionetworks.web.client.ClientProperties.DEFAULT_PLACE_TOKEN;
import static org.sagebionetworks.web.client.ClientProperties.ERROR_OBJ_REASON_KEY;
import static org.sagebionetworks.web.client.ClientProperties.ESCAPE_CHARACTERS_SET;
import static org.sagebionetworks.web.client.ClientProperties.FULL_ENTITY_TOP_MARGIN_PX;
import static org.sagebionetworks.web.client.ClientProperties.GB;
import static org.sagebionetworks.web.client.ClientProperties.IMAGE_CONTENT_TYPES_SET;
import static org.sagebionetworks.web.client.ClientProperties.KB;
import static org.sagebionetworks.web.client.ClientProperties.MB;
import static org.sagebionetworks.web.client.ClientProperties.REGEX_CLEAN_ANNOTATION_KEY;
import static org.sagebionetworks.web.client.ClientProperties.REGEX_CLEAN_ENTITY_NAME;
import static org.sagebionetworks.web.client.ClientProperties.STYLE_DISPLAY_INLINE;
import static org.sagebionetworks.web.client.ClientProperties.TB;
import static org.sagebionetworks.web.client.ClientProperties.WHITE_SPACE;
import static org.sagebionetworks.web.client.ClientProperties.WIKI_URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.gwtbootstrap3.client.ui.Modal;
import org.gwtbootstrap3.client.ui.ModalSize;
import org.gwtbootstrap3.client.ui.Popover;
import org.gwtbootstrap3.client.ui.Tooltip;
import org.gwtbootstrap3.client.ui.constants.Placement;
import org.gwtbootstrap3.client.ui.constants.Trigger;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.AlertCallback;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import org.sagebionetworks.gwt.client.schema.adapter.DateUtils;
import org.sagebionetworks.repo.model.AccessControlList;
import org.sagebionetworks.repo.model.AccessRequirement;
import org.sagebionetworks.repo.model.Analysis;
import org.sagebionetworks.repo.model.Annotations;
import org.sagebionetworks.repo.model.Code;
import org.sagebionetworks.repo.model.Data;
import org.sagebionetworks.repo.model.Entity;
import org.sagebionetworks.repo.model.EntityHeader;
import org.sagebionetworks.repo.model.EntityPath;
import org.sagebionetworks.repo.model.ExpressionData;
import org.sagebionetworks.repo.model.FileEntity;
import org.sagebionetworks.repo.model.Folder;
import org.sagebionetworks.repo.model.GenotypeData;
import org.sagebionetworks.repo.model.Link;
import org.sagebionetworks.repo.model.Page;
import org.sagebionetworks.repo.model.PhenotypeData;
import org.sagebionetworks.repo.model.Project;
import org.sagebionetworks.repo.model.RObject;
import org.sagebionetworks.repo.model.Reference;
import org.sagebionetworks.repo.model.Step;
import org.sagebionetworks.repo.model.Study;
import org.sagebionetworks.repo.model.Summary;
import org.sagebionetworks.repo.model.UserGroupHeader;
import org.sagebionetworks.repo.model.UserProfile;
import org.sagebionetworks.repo.model.UserSessionData;
import org.sagebionetworks.repo.model.Versionable;
import org.sagebionetworks.repo.model.file.FileHandle;
import org.sagebionetworks.repo.model.file.PreviewFileHandle;
import org.sagebionetworks.repo.model.table.TableEntity;
import org.sagebionetworks.schema.FORMAT;
import org.sagebionetworks.schema.ObjectSchema;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.web.client.cookie.CookieProvider;
import org.sagebionetworks.web.client.events.CancelEvent;
import org.sagebionetworks.web.client.events.CancelHandler;
import org.sagebionetworks.web.client.events.EntityUpdatedEvent;
import org.sagebionetworks.web.client.events.EntityUpdatedHandler;
import org.sagebionetworks.web.client.model.EntityBundle;
import org.sagebionetworks.web.client.place.Down;
import org.sagebionetworks.web.client.place.Help;
import org.sagebionetworks.web.client.place.Home;
import org.sagebionetworks.web.client.place.LoginPlace;
import org.sagebionetworks.web.client.place.PeopleSearch;
import org.sagebionetworks.web.client.place.Search;
import org.sagebionetworks.web.client.place.Synapse;
import org.sagebionetworks.web.client.place.Team;
import org.sagebionetworks.web.client.place.TeamSearch;
import org.sagebionetworks.web.client.place.Trash;
import org.sagebionetworks.web.client.place.Wiki;
import org.sagebionetworks.web.client.utils.Callback;
import org.sagebionetworks.web.client.utils.CallbackP;
import org.sagebionetworks.web.client.widget.Alert;
import org.sagebionetworks.web.client.widget.Alert.AlertType;
import org.sagebionetworks.web.client.widget.FitImage;
import org.sagebionetworks.web.client.widget.entity.JiraURLHelper;
import org.sagebionetworks.web.client.widget.entity.WidgetSelectionState;
import org.sagebionetworks.web.client.widget.entity.browse.EntityFinder;
import org.sagebionetworks.web.client.widget.entity.dialog.ANNOTATION_TYPE;
import org.sagebionetworks.web.client.widget.entity.download.Uploader;
import org.sagebionetworks.web.client.widget.sharing.AccessControlListEditor;
import org.sagebionetworks.web.client.widget.table.TableCellFileHandle;
import org.sagebionetworks.web.shared.EntityType;
import org.sagebionetworks.web.shared.EntityWrapper;
import org.sagebionetworks.web.shared.NodeType;
import org.sagebionetworks.web.shared.PublicPrincipalIds;
import org.sagebionetworks.web.shared.WebConstants;
import org.sagebionetworks.web.shared.WidgetConstants;
import org.sagebionetworks.web.shared.WikiPageKey;
import org.sagebionetworks.web.shared.exceptions.BadRequestException;
import org.sagebionetworks.web.shared.exceptions.ForbiddenException;
import org.sagebionetworks.web.shared.exceptions.NotFoundException;
import org.sagebionetworks.web.shared.exceptions.ReadOnlyModeException;
import org.sagebionetworks.web.shared.exceptions.RestServiceException;
import org.sagebionetworks.web.shared.exceptions.SynapseDownException;
import org.sagebionetworks.web.shared.exceptions.UnauthorizedException;
import org.sagebionetworks.web.shared.exceptions.UnknownErrorException;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.Text;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.SimpleComboBox;
import com.extjs.gxt.ui.client.widget.layout.CenterLayout;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.MarginData;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.DomEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.place.shared.Place;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FocusWidget;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
public class DisplayUtils {
private static DateTimeFormat prettyFormat = null;
private static Logger displayUtilsLogger = Logger.getLogger(DisplayUtils.class.getName());
public static PublicPrincipalIds publicPrincipalIds = null;
public static enum MessagePopup {
INFO,
WARNING,
QUESTION
}
public static final String[] ENTITY_TYPE_DISPLAY_ORDER = new String[] {
Folder.class.getName(), Study.class.getName(), Data.class.getName(),
Code.class.getName(), Link.class.getName(),
Analysis.class.getName(), Step.class.getName(),
RObject.class.getName(), PhenotypeData.class.getName(),
ExpressionData.class.getName(), GenotypeData.class.getName() };
/**
* Returns a properly aligned icon from an ImageResource
* @param icon
* @return
*/
public static String getIconHtml(ImageResource icon) {
if(icon == null) return null;
return "<span class=\"iconSpan\">" + AbstractImagePrototype.create(icon).getHTML() + "</span>";
}
/**
* Returns a properly aligned icon from an ImageResource
* @param icon
* @return
*/
public static String getIconThumbnailHtml(ImageResource icon) {
if(icon == null) return null;
return "<span class=\"thumbnail-image-container\">" + AbstractImagePrototype.create(icon).getHTML() + "</span>";
}
/**
* Returns a properly aligned name and description for a special user or group
* @param name of user or group
* @return
*/
public static String getUserNameDescriptionHtml(String name, String description) {
return DisplayUtilsGWT.TEMPLATES.nameAndUsername(name, description).asString();
}
/**
* Returns an HTML String of the suggestion of the user/group associated with the given header.
* @param header header of the displayed usergroup.
* @param width css style width of the created element (e.g. "150px", "3em")
* @param baseFileHandleUrl
* @param baseProfileAttachmentUrl
* @return
*/
public static String getUserGroupDisplaySuggestionHtml(UserGroupHeader header, String width, String baseFileHandleUrl, String baseProfileAttachmentUrl) {
StringBuilder result = new StringBuilder();
result.append("<div class=\"padding-left-5 userGroupSuggestion\" style=\"height:23px; width:" + width + ";\">");
result.append("<img class=\"margin-right-5 vertical-align-center tiny-thumbnail-image-container\" onerror=\"this.style.display=\'none\';\" src=\"");
if (header.getIsIndividual()) {
result.append(baseProfileAttachmentUrl);
result.append("?userId=" + header.getOwnerId() + "&waitForUrl=true\" />");
} else {
result.append(baseFileHandleUrl);
result.append("?teamId=" + header.getOwnerId() + "\" />");
}
result.append("<span class=\"search-item movedown-1 margin-right-5\">");
if (header.getIsIndividual()) {
result.append("<span class=\"font-italic\">" + header.getFirstName() + " " + header.getLastName() + "</span> ");
}
result.append("<span>" + header.getUserName() + "</span> ");
result.append("</span>");
if (!header.getIsIndividual()) {
result.append("(Team)");
}
result.append("</div>");
return result.toString();
}
/**
* Returns html for a thumbnail image.
*
* @param url
* @return
*/
public static String getThumbnailPicHtml(String url) {
if(url == null) return null;
return DisplayUtilsGWT.TEMPLATES.profilePicture(url).asString();
}
/**
* Converts all hrefs to gwt anchors, and handles the anchors by sending them to a new window.
* @param panel
*/
public static void sendAllLinksToNewWindow(HTMLPanel panel){
NodeList<com.google.gwt.dom.client.Element> anchors = panel.getElement().getElementsByTagName("a");
for ( int i = 0 ; i < anchors.getLength() ; i++ ) {
com.google.gwt.dom.client.Element a = anchors.getItem(i);
JSONObject jsonValue = new JSONObject(a);
JSONValue hrefJSONValue = jsonValue.get("href");
if (hrefJSONValue != null){
final String href = hrefJSONValue.toString().replaceAll("\"", "");
String innerText = a.getInnerText();
Anchor link = new Anchor();
link.setStylePrimaryName("link");
link.setText(innerText);
link.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
com.google.gwt.user.client.Window.open(href, "_blank", "");
}
});
panel.addAndReplaceElement(link, a);
}
}
}
/**
* Add a row to the provided FlexTable.
*
* @param key
* @param value
* @param table
*/
public static void addRowToTable(int row, String key, String value,
FlexTable table) {
addRowToTable(row, key, value, "boldRight", table);
table.setHTML(row, 1, value);
}
public static void addRowToTable(int row, String key, String value,
String styleName, FlexTable table) {
table.setHTML(row, 0, key);
table.getCellFormatter().addStyleName(row, 0, styleName);
table.setHTML(row, 1, value);
}
public static void addRowToTable(int row, String label, Anchor key, String value,
String styleName, FlexTable table) {
table.setHTML(row, 0, label);
table.getCellFormatter().addStyleName(row, 0, styleName);
table.setWidget(row, 1, key);
table.setHTML(row, 2, value);
}
public static String getFriendlySize(double size, boolean abbreviatedUnits) {
NumberFormat df = NumberFormat.getDecimalFormat();
if(size >= TB) {
return df.format(size/TB) + (abbreviatedUnits?" TB":" Terabytes");
}
if(size >= GB) {
return df.format(size/GB) + (abbreviatedUnits?" GB":" Gigabytes");
}
if(size >= MB) {
return df.format(size/MB) + (abbreviatedUnits?" MB":" Megabytes");
}
if(size >= KB) {
return df.format(size/KB) + (abbreviatedUnits?" KB":" Kilobytes");
}
return df.format(size) + " bytes";
}
/**
* Use an EntityWrapper instead and check for an exception there
* @param obj
* @throws RestServiceException
*/
@Deprecated
public static void checkForErrors(JSONObject obj) throws RestServiceException {
if(obj == null) return;
if(obj.containsKey("error")) {
JSONObject errorObj = obj.get("error").isObject();
if(errorObj.containsKey("statusCode")) {
JSONNumber codeObj = errorObj.get("statusCode").isNumber();
if(codeObj != null) {
int code = ((Double)codeObj.doubleValue()).intValue();
if(code == 401) { // UNAUTHORIZED
throw new UnauthorizedException();
} else if(code == 403) { // FORBIDDEN
throw new ForbiddenException();
} else if (code == 404) { // NOT FOUND
throw new NotFoundException();
} else if (code == 400) { // Bad Request
String message = "";
if(obj.containsKey(ERROR_OBJ_REASON_KEY)) {
message = obj.get(ERROR_OBJ_REASON_KEY).isString().stringValue();
}
throw new BadRequestException(message);
} else {
throw new UnknownErrorException("Unknown Service error. code: " + code);
}
}
}
}
}
public static String getFileNameFromExternalUrl(String path){
//grab the text between the last '/' and following '?'
String fileName = "";
if (path != null) {
int lastSlash = path.lastIndexOf("/");
if (lastSlash > -1) {
int firstQuestionMark = path.indexOf("?", lastSlash);
if (firstQuestionMark > -1) {
fileName = path.substring(lastSlash+1, firstQuestionMark);
} else {
fileName = path.substring(lastSlash+1);
}
}
}
return fileName;
}
/**
* Handles the exception. Returns true if the user has been alerted to the exception already
* @param ex
* @param placeChanger
* @return true if the user has been prompted
*/
public static boolean handleServiceException(Throwable ex, GlobalApplicationState globalApplicationState, boolean isLoggedIn, ShowsErrors view) {
//send exception to the javascript console
if (displayUtilsLogger != null && ex != null)
displayUtilsLogger.log(Level.SEVERE, ex.getMessage());
if(ex instanceof ReadOnlyModeException) {
view.showErrorMessage(DisplayConstants.SYNAPSE_IN_READ_ONLY_MODE);
return true;
} else if(ex instanceof SynapseDownException) {
globalApplicationState.getPlaceChanger().goTo(new Down(DEFAULT_PLACE_TOKEN));
return true;
} else if(ex instanceof UnauthorizedException) {
// send user to login page
showInfo(DisplayConstants.SESSION_TIMEOUT, DisplayConstants.SESSION_HAS_TIMED_OUT);
globalApplicationState.getPlaceChanger().goTo(new LoginPlace(LoginPlace.LOGOUT_TOKEN));
return true;
} else if(ex instanceof ForbiddenException) {
if(!isLoggedIn) {
view.showErrorMessage(DisplayConstants.ERROR_LOGIN_REQUIRED);
globalApplicationState.getPlaceChanger().goTo(new LoginPlace(LoginPlace.LOGIN_TOKEN));
} else {
view.showErrorMessage(DisplayConstants.ERROR_FAILURE_PRIVLEDGES + " " + ex.getMessage());
}
return true;
} else if(ex instanceof BadRequestException) {
//show error (not to file a jira though)
view.showErrorMessage(ex.getMessage());
return true;
} else if(ex instanceof NotFoundException) {
view.showErrorMessage(DisplayConstants.ERROR_NOT_FOUND);
globalApplicationState.getPlaceChanger().goTo(new Home(DEFAULT_PLACE_TOKEN));
return true;
} else if (ex instanceof UnknownErrorException) {
//An unknown error occurred.
//Exception handling on the backend now throws the reason into the exception message. Easy!
showErrorMessage(ex, globalApplicationState.getJiraURLHelper(), isLoggedIn, ex.getMessage());
return true;
}
// For other exceptions, allow the consumer to send a good message to the user
return false;
}
public static boolean checkForRepoDown(Throwable caught, PlaceChanger placeChanger, SynapseView view) {
if(caught instanceof ReadOnlyModeException) {
view.showErrorMessage(DisplayConstants.SYNAPSE_IN_READ_ONLY_MODE);
return true;
} else if(caught instanceof SynapseDownException) {
placeChanger.goTo(new Down(DEFAULT_PLACE_TOKEN));
return true;
}
return false;
}
/**
* Handle JSONObjectAdapterException. This will occur when the client is pointing to an incompatible repo version.
* @param ex
* @param placeChanger
*/
public static boolean handleJSONAdapterException(JSONObjectAdapterException ex, PlaceChanger placeChanger, UserSessionData currentUser) {
DisplayUtils.showInfoDialog("Incompatible Client Version", DisplayConstants.ERROR_INCOMPATIBLE_CLIENT_VERSION, null);
placeChanger.goTo(new Home(DEFAULT_PLACE_TOKEN));
return true;
}
/*
* Button Saving
*/
public static void changeButtonToSaving(Button button, SageImageBundle sageImageBundle) {
button.setText(DisplayConstants.BUTTON_SAVING);
button.setIcon(AbstractImagePrototype.create(sageImageBundle.loading16()));
}
/*
* Button Saving
*/
public static void changeButtonToSaving(com.google.gwt.user.client.ui.Button button) {
button.addStyleName("disabled");
button.setHTML(SafeHtmlUtils.fromSafeConstant(DisplayConstants.BUTTON_SAVING + "..."));
}
/*
* Button Saving
*/
public static void changeButtonToSaving(org.gwtbootstrap3.client.ui.Button button) {
button.setEnabled(false);
button.setText(SafeHtmlUtils.fromSafeConstant(DisplayConstants.BUTTON_SAVING + "...").asString());
}
/**
* Check if an Annotation key is valid with the repository service
* @param key
* @return
*/
public static boolean validateAnnotationKey(String key) {
if(key.matches(REGEX_CLEAN_ANNOTATION_KEY)) {
return true;
}
return false;
}
/**
* Check if an Entity (Node) name is valid with the repository service
* @param key
* @return
*/
public static boolean validateEntityName(String key) {
if(key.matches(REGEX_CLEAN_ENTITY_NAME)) {
return true;
}
return false;
}
/**
* Cleans any invalid name characters from a string
* @param str
* @return
*/
public static String getOffendingCharacterForEntityName(String key) {
return getOffendingCharacter(key, REGEX_CLEAN_ENTITY_NAME);
}
/**
* Cleans any invalid name characters from a string
* @param str
* @return
*/
public static String getOffendingCharacterForAnnotationKey(String key) {
return getOffendingCharacter(key, REGEX_CLEAN_ANNOTATION_KEY);
}
/**
* Returns a ContentPanel used to show a component is loading in the view
* @param sageImageBundle
* @return
*/
public static ContentPanel getLoadingWidget(SageImageBundle sageImageBundle) {
ContentPanel cp = new ContentPanel();
cp.setHeaderVisible(false);
cp.setCollapsible(true);
cp.setLayout(new CenterLayout());
cp.add(new HTML(SafeHtmlUtils.fromSafeConstant(DisplayUtils.getIconHtml(sageImageBundle.loading31()))));
return cp;
}
public static String getLoadingHtml(SageImageBundle sageImageBundle) {
return getLoadingHtml(sageImageBundle, DisplayConstants.LOADING);
}
public static String getLoadingHtml(SageImageBundle sageImageBundle, String message) {
return DisplayUtils.getIconHtml(sageImageBundle.loading16()) + " " + message + "...";
}
/**
* Shows an info message to the user in the "Global Alert area".
* For more precise control over how the message appears,
* use the {@link displayGlobalAlert(Alert)} method.
* @param title
* @param message
*/
public static void showInfo(String title, String message) {
Alert alert = new Alert(title, message, false);
alert.setAlertType(AlertType.Info);
alert.setTimeout(4000);
displayGlobalAlert(alert);
}
/**
* Shows an warning message to the user in the "Global Alert area".
* For more precise control over how the message appears,
* use the {@link displayGlobalAlert(Alert)} method.
* @param title
* @param message
*/
public static void showError(String title, String message, Integer timeout) {
Alert alert = new Alert(title, message, true);
alert.setAlertType(AlertType.Error);
if(timeout != null) {
alert.setTimeout(timeout);
}
displayGlobalAlert(alert);
}
public static void showErrorMessage(String message) {
showPopup("", message, MessagePopup.WARNING, null, null);
}
/**
* @param t
* @param jiraHelper
* @param profile
* @param friendlyErrorMessage
* (optional)
*/
public static void showErrorMessage(final Throwable t,
final JiraURLHelper jiraHelper, boolean isLoggedIn,
String friendlyErrorMessage) {
SynapseJSNIUtilsImpl._consoleError(getStackTrace(t));
if (!isLoggedIn) {
showErrorMessage(t.getMessage());
return;
}
final Dialog d = new Dialog();
d.addStyleName("padding-5");
final String errorMessage = friendlyErrorMessage == null ? t.getMessage() : friendlyErrorMessage;
HTML errorContent = new HTML(
getIcon("glyphicon-exclamation-sign margin-right-10 font-size-22 alert-danger")
+ errorMessage);
FlowPanel dialogContent = new FlowPanel();
dialogContent.addStyleName("margin-10");
dialogContent.add(errorContent);
// create text area for steps
FlowPanel formGroup = new FlowPanel();
formGroup.addStyleName("form-group margin-top-10");
formGroup.add(new HTML("<label>Describe the problem (optional)</label>"));
final TextArea textArea = new TextArea();
textArea.addStyleName("form-control");
textArea.getElement().setAttribute("placeholder","Steps to reproduce the error");
textArea.getElement().setAttribute("rows", "4");
formGroup.add(textArea);
dialogContent.add(formGroup);
d.add(dialogContent);
d.setAutoHeight(true);
d.setHideOnButtonClick(true);
d.setWidth(400);
d.setPlain(true);
d.setModal(true);
d.setLayout(new FitLayout());
d.setButtonAlign(HorizontalAlignment.RIGHT);
d.setHeading("Synapse Error");
d.yesText = DisplayConstants.SEND_BUG_REPORT;
d.noText = DisplayConstants.DO_NOT_SEND_BUG_REPORT;
d.setButtons(Dialog.YESNO);
com.extjs.gxt.ui.client.widget.button.Button yesButton = d.getButtonById(Dialog.YES);
yesButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
@Override
public void componentSelected(ButtonEvent ce) {
jiraHelper.createIssueOnBackend(textArea.getValue(), t,
errorMessage, new AsyncCallback<Void>() {
@Override
public void onSuccess(Void result) {
showInfo("Report sent", "Thank you!");
}
@Override
public void onFailure(Throwable caught) {
// failure to create issue!
DisplayUtils.showErrorMessage(DisplayConstants.ERROR_GENERIC_NOTIFY+"\n"
+ caught.getMessage() +"\n\n"
+ textArea.getValue());
}
});
}
});
d.show();
}
public static void showInfoDialog(
String title,
String message,
Callback okCallback
) {
showPopup(title, message, MessagePopup.INFO, okCallback, null);
}
public static void showConfirmDialog(
String title,
String message,
Callback yesCallback,
Callback noCallback
) {
showPopup(title, message, MessagePopup.QUESTION, yesCallback, noCallback);
}
public static void showConfirmDialog(
String title,
String message,
Callback yesCallback
) {
showConfirmDialog(title, message, yesCallback, new Callback() {
@Override
public void invoke() {
//do nothing when No is clicked
}
});
}
public static void showPopup(String title, String message,
DisplayUtils.MessagePopup iconStyle,
final Callback primaryButtonCallback,
final Callback secondaryButtonCallback) {
SafeHtml popupHtml = getPopupSafeHtml(title, message, iconStyle);
boolean isSecondaryButton = secondaryButtonCallback != null;
if (isSecondaryButton) {
Bootbox.confirm(popupHtml.asString(), new ConfirmCallback() {
@Override
public void callback(boolean isConfirmed) {
if (isConfirmed) {
if (primaryButtonCallback != null)
primaryButtonCallback.invoke();
} else {
if (secondaryButtonCallback != null)
secondaryButtonCallback.invoke();
}
}
});
} else {
Bootbox.alert(popupHtml.asString(), new AlertCallback() {
@Override
public void callback() {
if (primaryButtonCallback != null)
primaryButtonCallback.invoke();
}
});
}
}
public static SafeHtml getPopupSafeHtml(String title, String message, DisplayUtils.MessagePopup iconStyle) {
String iconHtml = "";
if (MessagePopup.INFO.equals(iconStyle))
iconHtml = getIcon("glyphicon-info-sign font-size-32 col-xs-1");
else if (MessagePopup.WARNING.equals(iconStyle))
iconHtml = getIcon("glyphicon-exclamation-sign font-size-32 col-xs-1");
else if (MessagePopup.QUESTION.equals(iconStyle))
iconHtml = getIcon("glyphicon-question-sign font-size-32 col-xs-1");
SafeHtmlBuilder builder = new SafeHtmlBuilder();
if (DisplayUtils.isDefined(title)) {
builder.appendHtmlConstant("<h5>");
builder.appendEscaped(title);
builder.appendHtmlConstant("</h5>");
}
builder.appendHtmlConstant("<div class=\"row\">");
if (iconHtml.length() > 0)
builder.appendHtmlConstant(iconHtml);
String messageWidth = DisplayUtils.isDefined(iconHtml) ? "col-xs-11" : "col-xs-12";
builder.appendHtmlConstant("<div class=\""+messageWidth+"\">");
builder.appendEscaped(message);
builder.appendHtmlConstant("</div></div>");
return builder.toSafeHtml();
}
public static void center(Window window) {
int left = (com.google.gwt.user.client.Window.getClientWidth() - window.getOffsetWidth()) / 2;
window.setPosition(left, 150);
scrollToTop();
}
public static void scrollToTop(){
com.google.gwt.user.client.Window.scrollTo(0, 0);
}
public static String getPrimaryEmail(UserProfile userProfile) {
List<String> emailAddresses = userProfile.getEmails();
if (emailAddresses == null || emailAddresses.isEmpty()) throw new IllegalStateException("UserProfile email list is empty");
return emailAddresses.get(0);
}
public static String getDisplayName(UserProfile profile) {
return getDisplayName(profile.getFirstName(), profile.getLastName(), profile.getUserName());
}
public static String getDisplayName(UserGroupHeader header) {
return DisplayUtils.getDisplayName(header.getFirstName(), header.getLastName(), header.getUserName());
}
public static String getDisplayName(String firstName, String lastName, String userName) {
StringBuilder sb = new StringBuilder();
boolean hasDisplayName = false;
if (firstName != null && firstName.length() > 0) {
sb.append(firstName.trim());
hasDisplayName = true;
}
if (lastName != null && lastName.length() > 0) {
sb.append(" ");
sb.append(lastName.trim());
hasDisplayName = true;
}
sb.append(getUserName(userName, hasDisplayName));
return sb.toString();
}
public static boolean isTemporaryUsername(String username){
if(username == null) throw new IllegalArgumentException("UserName cannot be null");
return username.startsWith(WebConstants.TEMPORARY_USERNAME_PREFIX);
}
public static String getUserName(String userName, boolean inParens) {
StringBuilder sb = new StringBuilder();
if (userName != null && !isTemporaryUsername(userName)) {
//if the name is filled in, then put the username in parens
if (inParens)
sb.append(" (");
sb.append(userName);
if (inParens)
sb.append(")");
}
return sb.toString();
}
/**
* Returns the NodeType for this entity class.
* TODO : This should be removed when we move to using the Synapse Java Client
* @param entity
* @return
*/
public static NodeType getNodeTypeForEntity(Entity entity) {
// DATASET, LAYER, PROJECT, EULA, AGREEMENT, ENTITY, ANALYSIS, STEP
if(entity instanceof org.sagebionetworks.repo.model.Study) {
return NodeType.STUDY;
} else if(entity instanceof org.sagebionetworks.repo.model.Data) {
return NodeType.DATA;
} else if(entity instanceof org.sagebionetworks.repo.model.Project) {
return NodeType.PROJECT;
} else if(entity instanceof org.sagebionetworks.repo.model.Analysis) {
return NodeType.ANALYSIS;
} else if(entity instanceof org.sagebionetworks.repo.model.Step) {
return NodeType.STEP;
} else if(entity instanceof org.sagebionetworks.repo.model.Code) {
return NodeType.CODE;
} else if(entity instanceof org.sagebionetworks.repo.model.Link) {
return NodeType.LINK;
}
return null;
}
public static String getEntityTypeDisplay(ObjectSchema schema) {
String title = schema.getTitle();
if(title == null){
title = "<Title missing for Entity: "+schema.getId()+">";
}
return title;
}
public static String getMarkdownWidgetWarningHtml(String warningText) {
return getWarningHtml(DisplayConstants.MARKDOWN_WIDGET_WARNING, warningText);
}
public static String getMarkdownAPITableWarningHtml(String warningText) {
return getWarningHtml(DisplayConstants.MARKDOWN_API_TABLE_WARNING, warningText);
}
public static String getWarningHtml(String title, String warningText) {
return getAlertHtml(title, warningText, BootstrapAlertType.WARNING);
}
public static String getAlertHtml(String title, String text, BootstrapAlertType type) {
return "<div class=\"alert alert-"+type.toString().toLowerCase()+"\"><span class=\"boldText\">"+ title + "</span> " + text + "</div>";
}
public static String getAlertHtmlSpan(String title, String text, BootstrapAlertType type) {
return "<span class=\"alert alert-"+type.toString().toLowerCase()+"\"><span class=\"boldText\">"+ title + "</span> " + text + "</span>";
}
public static String getBadgeHtml(String i) {
return "<span class=\"badge moveup-4\">"+i+"</span>";
}
public static String uppercaseFirstLetter(String display) {
return display.substring(0, 1).toUpperCase() + display.substring(1);
}
/**
* YYYY-MM-DD HH:mm:ss
* @param toFormat
* @return
*/
public static String converDataToPrettyString(Date toFormat) {
if(toFormat == null) throw new IllegalArgumentException("Date cannot be null");
if (prettyFormat == null) {
prettyFormat = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss");
}
return prettyFormat.format(toFormat);
}
/**
* Converts a date to just a date.
* @return yyyy-MM-dd
* @return
*/
public static String converDateaToSimpleString(Date toFormat) {
if(toFormat == null) throw new IllegalArgumentException("Date cannot be null");
return DateUtils.convertDateToString(FORMAT.DATE, toFormat);
}
public static String getSynapseWikiHistoryToken(String ownerId, String objectType, String wikiPageId) {
Wiki place = new Wiki(ownerId, objectType, wikiPageId);
return "#!" + getWikiPlaceString(Wiki.class) + ":" + place.toToken();
}
public static String getTeamHistoryToken(String teamId) {
Team place = new Team(teamId);
return "#!" + getTeamPlaceString(Team.class) + ":" + place.toToken();
}
public static String getTeamSearchHistoryToken(String searchTerm) {
TeamSearch place = new TeamSearch(searchTerm);
return "#!" + getTeamSearchPlaceString(TeamSearch.class) + ":" + place.toToken();
}
public static String getTeamSearchHistoryToken(String searchTerm, Integer start) {
TeamSearch place = new TeamSearch(searchTerm, start);
return "#!" + getTeamSearchPlaceString(TeamSearch.class) + ":" + place.toToken();
}
public static String getPeopleSearchHistoryToken(String searchTerm) {
PeopleSearch place = new PeopleSearch(searchTerm);
return "#!" + getPeopleSearchPlaceString(PeopleSearch.class) + ":" + place.toToken();
}
public static String getPeopleSearchHistoryToken(String searchTerm, Integer start) {
PeopleSearch place = new PeopleSearch(searchTerm, start);
return "#!" + getPeopleSearchPlaceString(PeopleSearch.class) + ":" + place.toToken();
}
public static String getTrashHistoryToken(String token, Integer start) {
Trash place = new Trash(token, start);
return "#!" + getTrashPlaceString(Trash.class) + ":" + place.toToken();
}
public static String getLoginPlaceHistoryToken(String token) {
LoginPlace place = new LoginPlace(token);
return "#!" + getLoginPlaceString(LoginPlace.class) + ":" + place.toToken();
}
public static String getHelpPlaceHistoryToken(String token) {
Help place = new Help(token);
return "#!" + getHelpPlaceString(Help.class) + ":" + place.toToken();
}
public static String getSearchHistoryToken(String searchQuery) {
Search place = new Search(searchQuery);
return "#!" + getSearchPlaceString(Search.class) + ":" + place.toToken();
}
public static String getSearchHistoryToken(String searchQuery, Long start) {
Search place = new Search(searchQuery, start);
return "#!" + getSearchPlaceString(Search.class) + ":" + place.toToken();
}
public static String getSynapseHistoryToken(String entityId) {
return "#" + getSynapseHistoryTokenNoHash(entityId, null);
}
public static String getSynapseHistoryTokenNoHash(String entityId) {
return getSynapseHistoryTokenNoHash(entityId, null);
}
public static String getSynapseHistoryToken(String entityId, Long versionNumber) {
return "#" + getSynapseHistoryTokenNoHash(entityId, versionNumber);
}
public static String getSynapseHistoryTokenNoHash(String entityId, Long versionNumber) {
return getSynapseHistoryTokenNoHash(entityId, versionNumber, null);
}
public static String getSynapseHistoryTokenNoHash(String entityId, Long versionNumber, Synapse.EntityArea area) {
return getSynapseHistoryTokenNoHash(entityId, versionNumber, area, null);
}
public static String getSynapseHistoryTokenNoHash(String entityId, Long versionNumber, Synapse.EntityArea area, String areaToken) {
Synapse place = new Synapse(entityId, versionNumber, area, areaToken);
return "!"+ getPlaceString(Synapse.class) + ":" + place.toToken();
}
/**
* Stub the string removing the last partial word
* @param str
* @param length
* @return
*/
public static String stubStr(String str, int length) {
if(str == null) {
return "";
}
if(str.length() > length) {
String sub = str.substring(0, length);
str = sub.replaceFirst(" \\w+$", "") + ".."; // clean off partial last word
}
return str;
}
/**
* Stub the string with partial word at end left in
* @param contents
* @param maxLength
* @return
*/
public static String stubStrPartialWord(String contents, int maxLength) {
String stub = contents;
if(contents != null && contents.length() > maxLength) {
stub = contents.substring(0, maxLength-3);
stub += " ..";
}
return stub;
}
/*
* Private methods
*/
private static String getPlaceString(Class<Synapse> place) {
return getPlaceString(place.getName());
}
private static String getWikiPlaceString(Class<Wiki> place) {
return getPlaceString(place.getName());
}
public static LayoutContainer wrap(Widget widget) {
LayoutContainer lc = new LayoutContainer();
lc.addStyleName("col-md-12");
lc.add(widget);
return lc;
}
public static SimplePanel wrapInDiv(Widget widget) {
SimplePanel lc = new SimplePanel();
lc.setWidget(widget);
return lc;
}
private static String getTeamPlaceString(Class<Team> place) {
return getPlaceString(place.getName());
}
private static String getTeamSearchPlaceString(Class<TeamSearch> place) {
return getPlaceString(place.getName());
}
private static String getPeopleSearchPlaceString(Class<PeopleSearch> place) {
return getPlaceString(place.getName());
}
private static String getTrashPlaceString(Class<Trash> place) {
return getPlaceString(place.getName());
}
private static String getLoginPlaceString(Class<LoginPlace> place) {
return getPlaceString(place.getName());
}
private static String getHelpPlaceString(Class<Help> place) {
return getPlaceString(place.getName());
}
private static String getSearchPlaceString(Class<Search> place) {
return getPlaceString(place.getName());
}
private static String getPlaceString(String fullPlaceName) {
fullPlaceName = fullPlaceName.replaceAll(".+\\.", "");
return fullPlaceName;
}
/**
* Returns the offending character given a regex string
* @param key
* @param regex
* @return
*/
private static String getOffendingCharacter(String key, String regex) {
String suffix = key.replaceFirst(regex, "");
if(suffix != null && suffix.length() > 0) {
return suffix.substring(0,1);
}
return null;
}
public static String createEntityLink(String id, String version,
String display) {
return "<a href=\"" + DisplayUtils.getSynapseHistoryToken(id) + "\">" + display + "</a>";
}
public static enum IconSize { PX16, PX24 };
public static ImageResource getSynapseIconForEntityType(EntityType type, IconSize iconSize, IconsImageBundle iconsImageBundle) {
String className = type == null ? null : type.getClassName();
return getSynapseIconForEntityClassName(className, iconSize, iconsImageBundle);
}
public static ImageResource getSynapseIconForEntity(Entity entity, IconSize iconSize, IconsImageBundle iconsImageBundle) {
String className = entity == null ? null : entity.getClass().getName();
return getSynapseIconForEntityClassName(className, iconSize, iconsImageBundle);
}
/**
* Create a loading window.
*
* @param sageImageBundle
* @param message
* @return
*/
public static Window createLoadingWindow(SageImageBundle sageImageBundle, String message) {
Window window = new Window();
window.setModal(true);
window.setHeight(114);
window.setWidth(221);
window.setBorders(false);
SafeHtmlBuilder shb = new SafeHtmlBuilder();
shb.appendHtmlConstant(DisplayUtils.getIconHtml(sageImageBundle.loading31()));
shb.appendEscaped(message);
window.add(new Html(shb.toSafeHtml().asString()), new MarginData(20, 0, 0, 45));
window.setBodyStyleName("whiteBackground");
return window;
}
/**
* Create a loading panel with a centered spinner.
*
* @param sageImageBundle
* @param width
* @param height
* @return
*/
public static Widget createFullWidthLoadingPanel(SageImageBundle sageImageBundle) {
return createFullWidthLoadingPanel(sageImageBundle, " Loading...");
}
/**
* Create a loading panel with a centered spinner.
*
* @param sageImageBundle
* @param width
* @param height
* @return
*/
public static Widget createFullWidthLoadingPanel(SageImageBundle sageImageBundle, String message) {
Widget w = new HTML(SafeHtmlUtils.fromSafeConstant(
DisplayUtils.getIconHtml(sageImageBundle.loading31()) +" "+ message));
LayoutContainer panel = new LayoutContainer();
panel.add(w, new MarginData(FULL_ENTITY_TOP_MARGIN_PX, 0, FULL_ENTITY_TOP_MARGIN_PX, 0));
panel.addStyleName("center");
return panel;
}
public static ImageResource getSynapseIconForEntityClassName(String className, IconSize iconSize, IconsImageBundle iconsImageBundle) {
ImageResource icon = null;
if(Link.class.getName().equals(className)) {
icon = iconsImageBundle.synapseLink16();
} else if(Analysis.class.getName().equals(className)) {
// Analysis
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseAnalysis16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseAnalysis24();
} else if(Code.class.getName().equals(className)) {
// Code
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseFile16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseFile24();
} else if(Data.class.getName().equals(className) ||
ExpressionData.class.getName().equals(className) ||
GenotypeData.class.getName().equals(className) ||
PhenotypeData.class.getName().equals(className)) {
// Data
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseFile16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseFile24();
} else if(Folder.class.getName().equals(className)) {
// Folder
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseFolder16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseFolder24();
} else if(FileEntity.class.getName().equals(className)) {
// File
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseFile16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseFile24();
} else if(Project.class.getName().equals(className)) {
// Project
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseProject16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseProject24();
} else if(RObject.class.getName().equals(className)) {
// RObject
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseRObject16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseRObject24();
} else if(Summary.class.getName().equals(className)) {
// Summary
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseSummary16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseSummary24();
} else if(Step.class.getName().equals(className)) {
// Step
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseStep16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseStep24();
} else if(Study.class.getName().equals(className)) {
// Study
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseFolder16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseFolder24();
} else if(Page.class.getName().equals(className)) {
// Page
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapsePage16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapsePage24();
} else if(TableEntity.class.getName().equals(className)) {
// TableEntity
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseData16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseData24();
} else {
// default to Model
if(iconSize == IconSize.PX16) icon = iconsImageBundle.synapseModel16();
else if (iconSize == IconSize.PX24) icon = iconsImageBundle.synapseModel24();
}
return icon;
}
/**
* Maps mime types to icons.
*/
private static Map<String, String> attachmentMap = new HashMap<String, String>();
public static String UNKNOWN_ICON = "220";
public static String DEFAULT_PDF_ICON = "222";
public static String DEFAULT_IMAGE_ICON = "242";
public static String DEFAULT_TEXT_ICON = "224";
public static String DEFAULT_COMPRESSED_ICON = "226";
static{
attachmentMap.put("pdf", DEFAULT_PDF_ICON);
attachmentMap.put("txt", DEFAULT_TEXT_ICON);
attachmentMap.put("doc", DEFAULT_TEXT_ICON);
attachmentMap.put("doc", DEFAULT_TEXT_ICON);
attachmentMap.put("docx", DEFAULT_TEXT_ICON);
attachmentMap.put("docx", DEFAULT_TEXT_ICON);
attachmentMap.put("zip", DEFAULT_COMPRESSED_ICON);
attachmentMap.put("tar", DEFAULT_COMPRESSED_ICON);
attachmentMap.put("gz", DEFAULT_COMPRESSED_ICON);
attachmentMap.put("rar", DEFAULT_COMPRESSED_ICON);
attachmentMap.put("png", DEFAULT_IMAGE_ICON);
attachmentMap.put("gif", DEFAULT_IMAGE_ICON);
attachmentMap.put("jpg", DEFAULT_IMAGE_ICON);
attachmentMap.put("jpeg", DEFAULT_IMAGE_ICON);
attachmentMap.put("bmp", DEFAULT_IMAGE_ICON);
attachmentMap.put("wbmp", DEFAULT_IMAGE_ICON);
}
/**
* Get the icon to be used with a given file type.
*/
public static String getAttachmentIcon(String fileName){
if(fileName == null) return UNKNOWN_ICON;
String mimeType = getMimeType(fileName);
if(mimeType == null) return UNKNOWN_ICON;
String icon = attachmentMap.get(mimeType.toLowerCase());
if(icon == null) return UNKNOWN_ICON;
return icon;
}
/**
* Get the mime type from a file name.
* @param fileName
* @return
*/
public static String getMimeType(String fileName){
if(fileName == null) return null;
int index = fileName.lastIndexOf('.');
if(index < 0) return null;
if(index+1 >= fileName.length()) return null;
return fileName.substring(index+1, fileName.length());
}
/**
* Replace all white space
* @param string
* @return
*/
public static String replaceWhiteSpace(String string){
if(string == null) return null;
string = string.replaceAll(" ", WHITE_SPACE);
return string;
}
/**
* Create the url to an attachment image.
* @param baseURl
* @param entityId
* @param tokenId
* @param fileName
* @return
*/
public static String createAttachmentUrl(String baseURl, String entityId, String tokenId, String fileName){
return createAttachmentUrl(baseURl, entityId, tokenId, fileName, WebConstants.ENTITY_PARAM_KEY);
}
/**
* Create the url to a profile attachment image.
* @param baseURl
* @param userId
* @param tokenId
* @param fileName
* @return
*/
public static String createUserProfileAttachmentUrl(String baseURl, String userId, String tokenId, String fileName){
return createAttachmentUrl(baseURl, userId, tokenId, fileName, WebConstants.USER_PROFILE_PARAM_KEY);
}
public static String createUserProfilePicUrl(String baseURl, String userId){
return createAttachmentUrl(baseURl, userId, "", null, WebConstants.USER_PROFILE_PARAM_KEY);
}
/**
* Create the url to an attachment image.
* @param baseURl
* @param id
* @param tokenId
* @param fileName
* @return
*/
public static String createAttachmentUrl(String baseURl, String id, String tokenId, String fileName, String paramKey){
StringBuilder builder = new StringBuilder();
builder.append(baseURl);
builder.append("?"+paramKey+"=");
builder.append(id);
builder.append("&"+WebConstants.TOKEN_ID_PARAM_KEY+"=");
builder.append(tokenId);
builder.append("&"+WebConstants.WAIT_FOR_URL+"=true");
return builder.toString();
}
/**
* Does this entity have attachmet previews?
* @param entity
* @return
*/
public static boolean hasChildrenOrPreview(EntityBundle bundle){
if(bundle == null) return true;
if(bundle.getEntity() == null) return true;
Boolean hasChildern = bundle.getHasChildren();
if(hasChildern == null) return true;
return hasChildern;
}
public static ArrayList<EntityType> orderForDisplay(List<EntityType> children) {
ArrayList<EntityType> ordered = new ArrayList<EntityType>();
if(children != null) {
// fill map
Map<String,EntityType> classToTypeMap = new HashMap<String, EntityType>();
for(EntityType child : children) {
classToTypeMap.put(child.getClassName(), child);
}
// add child tabs in order
for(String className : DisplayUtils.ENTITY_TYPE_DISPLAY_ORDER) {
if(classToTypeMap.containsKey(className)) {
EntityType child = classToTypeMap.get(className);
classToTypeMap.remove(className);
ordered.add(child);
}
}
// add any remaining tabs that weren't covered by the display order
for(String className : classToTypeMap.keySet()) {
EntityType child = classToTypeMap.get(className);
ordered.add(child);
}
}
return ordered;
}
public static Popover addPopover(Widget widget, String message) {
Popover popover = new Popover(widget);
popover.setPlacement(Placement.AUTO);
popover.setIsHtml(true);
popover.setContent(message);
return popover;
}
public static void addToolTip(final Component widget, String message) {
addTooltip(widget, message, Placement.AUTO);
}
/**
* A list of tags that core attributes like 'title' cannot be applied to.
* This prevents them from having methods like addToolTip applied to them
*/
public static final String[] CORE_ATTR_INVALID_ELEMENTS = {"base", "head", "html", "meta",
"param", "script", "style", "title"};
public static void addTooltip(Widget widget, String tooltipText){
addTooltip(widget, tooltipText, Placement.AUTO);
}
/**
* Adds a twitter bootstrap tooltip to the given widget using the standard Synapse configuration
*
* CAUTION - If not used with a non-block level element like
* an anchor, img, or span the results will probably not be
* quite what you want. Read the twitter bootstrap documentation
* for the options that you can specify in optionsMap
*
* @param util the JSNIUtils class (or mock)
* @param widget the widget to attach the tooltip to
* @param tooltipText text to display
* @param pos where to position the tooltip relative to the widget
*/
public static void addTooltip(Widget widget, String tooltipText, Placement pos){
//SWC-1884: current technique sometimes causes target to not be shown. Removing tooltips
// Tooltip t = new Tooltip();
// t.setWidget(widget);
// t.setPlacement(pos);
// t.setText(tooltipText);
// t.setIsHtml(true);
// t.setIsAnimated(false);
// t.setTrigger(Trigger.HOVER);
// return t;
}
/**
* Adds a popover to a target widget
*/
public static void addClickPopover(Widget widget, String title, String content, Placement placement) {
Popover popover = new Popover();
popover.setIsHtml(true);
popover.setIsAnimated(true);
popover.setTitle(title);
popover.setPlacement(placement);
popover.setTrigger(Trigger.CLICK);
popover.setWidget(widget);
popover.setContent(content);
}
/*
* Private methods
*/
private static boolean isNullOrEmpty(final String string) {
return string == null || string.isEmpty();
}
private static boolean isPresent(String needle, String[] haystack) {
for (String el : haystack) {
if (needle.equalsIgnoreCase(el)) {
return true;
}
}
return false;
}
/**
* The preferred method for creating new global alerts. For a
* default 'info' type alert, you can also use {@link showInfo(String, String)}
* @param alert
*/
public static void displayGlobalAlert(Alert alert) {
Element container = DOM.getElementById(ALERT_CONTAINER_ID);
DOM.insertChild(container, alert.getElement(), 0);
}
public static String getVersionDisplay(Versionable versionable) {
String version = "";
if(versionable == null || versionable.getVersionNumber() == null) return version;
if(versionable.getVersionLabel() != null && !versionable.getVersionNumber().toString().equals(versionable.getVersionLabel())) {
version = versionable.getVersionLabel() + " (" + versionable.getVersionNumber() + ")";
} else {
version = versionable.getVersionNumber().toString();
}
return version;
}
public static native JavaScriptObject newWindow(String url, String name, String features)/*-{
try {
var window = $wnd.open(url, name, features);
return window;
}catch(err) {
return null;
}
}-*/;
public static native void setWindowTarget(JavaScriptObject window, String target)/*-{
window.location = target;
}-*/;
/**
* links in the wiki pages that reference other wiki pages don't include the domain. this method adds the domain.
* @param html
* @return
*/
public static String fixWikiLinks(String html) {
//adjust all wiki links so that they include the wiki domain
return html.replaceAll("=\"/wiki", "=\""+WIKI_URL);
}
public static String fixEmbeddedYouTube(String html){
int startYouTubeLinkIndex = html.indexOf("www.youtube.com/embed");
while (startYouTubeLinkIndex > -1){
int endYoutubeLinkIndex = html.indexOf("<", startYouTubeLinkIndex);
StringBuilder sb = new StringBuilder();
sb.append(html.substring(0, startYouTubeLinkIndex));
sb.append("<iframe width=\"300\" height=\"169\" src=\"https://" + html.substring(startYouTubeLinkIndex, endYoutubeLinkIndex) + "\" frameborder=\"0\" allowfullscreen=\"true\"></iframe>");
int t = sb.length();
sb.append(html.substring(endYoutubeLinkIndex));
html = sb.toString();
//search after t (for the next embed)
startYouTubeLinkIndex = html.indexOf("www.youtube.com/embed", t);
}
return html;
}
public static String getYouTubeVideoUrl(String videoId) {
return "http:
}
public static String getYouTubeVideoId(String videoUrl) {
String videoId = null;
//parse out the video id from the url
int start = videoUrl.indexOf("v=");
if (start > -1) {
int end = videoUrl.indexOf("&", start);
if (end == -1)
end = videoUrl.length();
videoId = videoUrl.substring(start + "v=".length(), end);
}
if (videoId == null || videoId.trim().length() == 0) {
throw new IllegalArgumentException("Could not determine the video ID from the given URL.");
}
return videoId;
}
public static Anchor createIconLink(AbstractImagePrototype icon, ClickHandler clickHandler) {
Anchor anchor = new Anchor();
anchor.setHTML(icon.getHTML());
anchor.addClickHandler(clickHandler);
return anchor;
}
public static String getVersionDisplay(Reference ref) {
if (ref == null) return null;
return getVersionDisplay(ref.getTargetId(), ref.getTargetVersionNumber());
}
public static String getVersionDisplay(String id, Long versionNumber) {
String version = id;
if(versionNumber != null) {
version += " (#" + versionNumber + ")";
}
return version;
}
public static SafeHtml get404Html() {
return SafeHtmlUtils
.fromSafeConstant("<div class=\"row\"><div class=\"col-xs-12\"><p class=\"margin-left-15 error left colored\">404</p><h1 class=\"margin-top-60-imp\">"
+ DisplayConstants.PAGE_NOT_FOUND
+ "</h1>"
+ "<p>"
+ DisplayConstants.PAGE_NOT_FOUND_DESC + "</p></div></div>");
}
public static String getWidgetMD(String attachmentName) {
if (attachmentName == null)
return null;
StringBuilder sb = new StringBuilder();
sb.append(WidgetConstants.WIDGET_START_MARKDOWN);
sb.append(attachmentName);
sb.append("}");
return sb.toString();
}
public static SafeHtml get403Html() {
return SafeHtmlUtils
.fromSafeConstant("<div class=\"row\"><div class=\"col-xs-12\"><p class=\"margin-left-15 error left colored\">403</p><h1 class=\"margin-top-60-imp\">"
+ DisplayConstants.FORBIDDEN
+ "</h1>"
+ "<p>"
+ DisplayConstants.UNAUTHORIZED_DESC + "</p></div></div>");
}
/**
* Provides same functionality as java.util.Pattern.quote().
* @param pattern
* @return
*/
public static String quotePattern(String pattern) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < pattern.length(); i++) {
if (ESCAPE_CHARACTERS_SET.contains(pattern.charAt(i)))
output.append("\\");
output.append(pattern.charAt(i));
}
return output.toString();
}
public static void updateTextArea(TextArea textArea, String newValue) {
textArea.setValue(newValue);
DomEvent.fireNativeEvent(Document.get().createChangeEvent(), textArea);
}
public static boolean isInTestWebsite(CookieProvider cookies) {
return isInCookies(DisplayUtils.SYNAPSE_TEST_WEBSITE_COOKIE_KEY, cookies);
}
public static void setTestWebsite(boolean testWebsite, CookieProvider cookies) {
setInCookies(testWebsite, DisplayUtils.SYNAPSE_TEST_WEBSITE_COOKIE_KEY, cookies);
}
public static final String SYNAPSE_TEST_WEBSITE_COOKIE_KEY = "SynapseTestWebsite";
public static boolean isInCookies(String cookieKey, CookieProvider cookies) {
return cookies.getCookie(cookieKey) != null;
}
public static void setInCookies(boolean value, String cookieKey, CookieProvider cookies) {
if (value && !isInCookies(cookieKey, cookies)) {
//set the cookie
cookies.setCookie(cookieKey, "true");
} else{
cookies.removeCookie(cookieKey);
}
}
/**
* Create the URL to a version of a wiki's attachments.
* @param baseFileHandleUrl
* @param wikiKey
* @param fileName
* @param preview
* @param wikiVersion
* @return
*/
public static String createVersionOfWikiAttachmentUrl(String baseFileHandleUrl, WikiPageKey wikiKey, String fileName,
boolean preview, Long wikiVersion) {
String attachmentUrl = createWikiAttachmentUrl(baseFileHandleUrl, wikiKey, fileName, preview);
return attachmentUrl + "&" + WebConstants.WIKI_VERSION_PARAM_KEY + "=" + wikiVersion.toString();
}
/**
* Create the url to a wiki filehandle.
* @param baseURl
* @param id
* @param tokenId
* @param fileName
* @return
*/
public static String createWikiAttachmentUrl(String baseFileHandleUrl, WikiPageKey wikiKey, String fileName, boolean preview){
//direct approach not working. have the filehandleservlet redirect us to the temporary wiki attachment url instead
// String attachmentPathName = preview ? "attachmentpreview" : "attachment";
// return repoServicesUrl
// +"/" +wikiKey.getOwnerObjectType().toLowerCase()
// +"/"+ wikiKey.getOwnerObjectId()
// +"/wiki/"
// +wikiKey.getWikiPageId()
// +"/"+ attachmentPathName+"?fileName="+URL.encodePathSegment(fileName);
String wikiIdParam = wikiKey.getWikiPageId() == null ? "" : "&" + WebConstants.WIKI_ID_PARAM_KEY + "=" + wikiKey.getWikiPageId();
return baseFileHandleUrl + "?" +
WebConstants.WIKI_OWNER_ID_PARAM_KEY + "=" + wikiKey.getOwnerObjectId() + "&" +
WebConstants.WIKI_OWNER_TYPE_PARAM_KEY + "=" + wikiKey.getOwnerObjectType() + "&"+
WebConstants.WIKI_FILENAME_PARAM_KEY + "=" + fileName + "&" +
WebConstants.FILE_HANDLE_PREVIEW_PARAM_KEY + "=" + Boolean.toString(preview) +
wikiIdParam;
}
public static String createFileEntityUrl(String baseFileHandleUrl, String entityId, Long versionNumber, boolean preview){
return createFileEntityUrl(baseFileHandleUrl, entityId, versionNumber, preview, false);
}
public static String getParamForNoCaching() {
return WebConstants.NOCACHE_PARAM + new Date().getTime();
}
/**
* Create a url that points to the FileHandleServlet.
* WARNING: A GET request to this url will cause the file contents to be downloaded on the Servlet and sent back in the response.
* USE TO REQUEST SMALL FILES ONLY and CACHE THE RESULTS
* @param baseURl
* @param encodedRedirectUrl
* @return
*/
public static String createRedirectUrl(String baseFileHandleUrl, String encodedRedirectUrl){
return baseFileHandleUrl + "?" + WebConstants.PROXY_PARAM_KEY + "=" + Boolean.TRUE +"&" +
WebConstants.REDIRECT_URL_KEY + "=" + encodedRedirectUrl;
}
/**
* Create the url to a FileEntity filehandle.
* @param baseURl
* @param entityid
* @return
*/
public static String createFileEntityUrl(String baseFileHandleUrl, String entityId, Long versionNumber, boolean preview, boolean proxy){
String versionParam = versionNumber == null ? "" : "&" + WebConstants.ENTITY_VERSION_PARAM_KEY + "=" + versionNumber.toString();
return baseFileHandleUrl + "?" +
WebConstants.ENTITY_PARAM_KEY + "=" + entityId + "&" +
WebConstants.FILE_HANDLE_PREVIEW_PARAM_KEY + "=" + Boolean.toString(preview) + "&" +
WebConstants.PROXY_PARAM_KEY + "=" + Boolean.toString(proxy) +
versionParam;
}
/**
* Create the url to a Table cell file handle.
* @param baseFileHandleUrl
* @param details
* @param preview
* @param proxy
* @return
*/
public static String createTableCellFileEntityUrl(String baseFileHandleUrl, TableCellFileHandle details, boolean preview, boolean proxy){
return baseFileHandleUrl + "?" +
WebConstants.ENTITY_PARAM_KEY + "=" + details.getTableId() + "&" +
WebConstants.TABLE_COLUMN_ID + "=" + details.getColumnId() + "&" +
WebConstants.TABLE_ROW_ID + "=" + details.getRowId() + "&" +
WebConstants.TABLE_ROW_VERSION_NUMBER + "=" + details.getVersionNumber() + "&" +
WebConstants.FILE_HANDLE_PREVIEW_PARAM_KEY + "=" + Boolean.toString(preview) + "&" +
WebConstants.PROXY_PARAM_KEY + "=" + Boolean.toString(proxy);
}
/**
* Create the url to a Team icon filehandle.
* @param baseURl
* @param teamId
* @return
*/
public static String createTeamIconUrl(String baseFileHandleUrl, String teamId){
return baseFileHandleUrl + "?" +
WebConstants.TEAM_PARAM_KEY + "=" + teamId;
}
public static String createEntityVersionString(Reference ref) {
return createEntityVersionString(ref.getTargetId(), ref.getTargetVersionNumber());
}
public static String createEntityVersionString(String id, Long version) {
if(version != null)
return id+WebConstants.ENTITY_VERSION_STRING+version;
else
return id;
}
public static Reference parseEntityVersionString(String entityVersion) {
String[] parts = entityVersion.split(WebConstants.ENTITY_VERSION_STRING);
Reference ref = null;
if(parts.length > 0) {
ref = new Reference();
ref.setTargetId(parts[0]);
if(parts.length > 1) {
try {
ref.setTargetVersionNumber(Long.parseLong(parts[1]));
} catch(NumberFormatException e) {}
}
}
return ref;
}
public static boolean isWikiSupportedType(Entity entity) {
return (entity instanceof FileEntity || entity instanceof Folder || entity instanceof Project || entity instanceof TableEntity);
}
public static boolean isRecognizedImageContentType(String contentType) {
String lowerContentType = contentType.toLowerCase();
return IMAGE_CONTENT_TYPES_SET.contains(lowerContentType);
}
public static boolean isTextType(String contentType) {
return contentType.toLowerCase().startsWith("text/");
}
public static boolean isCSV(String contentType) {
return contentType != null && contentType.toLowerCase().startsWith("text/csv");
}
public static boolean isTAB(String contentType) {
return contentType != null && contentType.toLowerCase().startsWith(WebConstants.TEXT_TAB_SEPARATED_VALUES);
}
/**
* Return a preview filehandle associated with this bundle (or null if unavailable)
* @param bundle
* @return
*/
public static PreviewFileHandle getPreviewFileHandle(EntityBundle bundle) {
PreviewFileHandle fileHandle = null;
if (bundle.getFileHandles() != null) {
for (FileHandle fh : bundle.getFileHandles()) {
if (fh instanceof PreviewFileHandle) {
fileHandle = (PreviewFileHandle) fh;
break;
}
}
}
return fileHandle;
}
/**
* Return the filehandle associated with this bundle (or null if unavailable)
* @param bundle
* @return
*/
public static FileHandle getFileHandle(EntityBundle bundle) {
FileHandle fileHandle = null;
if (bundle.getFileHandles() != null) {
FileEntity entity = (FileEntity)bundle.getEntity();
String targetId = entity.getDataFileHandleId();
for (FileHandle fh : bundle.getFileHandles()) {
if (fh.getId().equals(targetId)) {
fileHandle = fh;
break;
}
}
}
return fileHandle;
}
public interface SelectedHandler<T> {
public void onSelected(T selected);
}
public static void configureAndShowEntityFinderWindow(final EntityFinder entityFinder, final Window window, final SelectedHandler<Reference> handler) {
window.setPlain(true);
window.setModal(true);
window.setHeading(DisplayConstants.FIND_ENTITIES);
window.setLayout(new FitLayout());
window.add(entityFinder.asWidget(), new FitData(4));
window.addButton(new Button(DisplayConstants.SELECT, new SelectionListener<ButtonEvent>() {
@Override
public void componentSelected(ButtonEvent ce) {
Reference selected = entityFinder.getSelectedEntity();
handler.onSelected(selected);
}
}));
window.addButton(new Button(DisplayConstants.BUTTON_CANCEL, new SelectionListener<ButtonEvent>() {
@Override
public void componentSelected(ButtonEvent ce) {
window.hide();
}
}));
window.setButtonAlign(HorizontalAlignment.RIGHT);
window.show();
window.setSize(entityFinder.getViewWidth(), entityFinder.getViewHeight());
entityFinder.refresh();
}
public static void loadTableSorters(final HTMLPanel panel, SynapseJSNIUtils synapseJSNIUtils) {
String id = WidgetConstants.MARKDOWN_TABLE_ID_PREFIX;
int i = 0;
Element table = panel.getElementById(id + i);
while (table != null) {
synapseJSNIUtils.tablesorter(id+i);
i++;
table = panel.getElementById(id + i);
}
}
public static Widget getShareSettingsDisplay(boolean isPublic, SynapseJSNIUtils synapseJSNIUtils) {
final SimplePanel lc = new SimplePanel();
lc.addStyleName(STYLE_DISPLAY_INLINE);
String styleName = isPublic ? "public-acl-image" : "private-acl-image";
String description = isPublic ? DisplayConstants.PUBLIC_ACL_ENTITY_PAGE : DisplayConstants.PRIVATE_ACL_ENTITY_PAGE;
String tooltip = isPublic ? DisplayConstants.PUBLIC_ACL_DESCRIPTION : DisplayConstants.PRIVATE_ACL_DESCRIPTION;
SafeHtmlBuilder shb = new SafeHtmlBuilder();
shb.appendHtmlConstant("<div class=\"" + styleName+ "\" style=\"display:inline; position:absolute\"></div>");
shb.appendHtmlConstant("<span style=\"margin-left: 20px;\">"+description+"</span>");
//form the html
HTMLPanel htmlPanel = new HTMLPanel(shb.toSafeHtml());
htmlPanel.addStyleName("inline-block");
DisplayUtils.addTooltip(htmlPanel, tooltip, Placement.BOTTOM);
lc.add(htmlPanel);
return lc;
}
public static Long getVersion(Entity entity) {
Long version = null;
if (entity != null && entity instanceof Versionable)
version = ((Versionable) entity).getVersionNumber();
return version;
}
public static void updateWidgetSelectionState(WidgetSelectionState state, String text, int cursorPos) {
state.setWidgetSelected(false);
state.setWidgetStartIndex(-1);
state.setWidgetEndIndex(-1);
state.setInnerWidgetText(null);
if (cursorPos > -1) {
//move back until I find a whitespace or the beginning
int startWord = cursorPos-1;
while(startWord > -1 && !Character.isSpace(text.charAt(startWord))) {
startWord
}
startWord++;
String possibleWidget = text.substring(startWord);
if (possibleWidget.startsWith(WidgetConstants.WIDGET_START_MARKDOWN)) {
//find the end
int endWord = cursorPos;
while(endWord < text.length() && !WidgetConstants.WIDGET_END_MARKDOWN.equals(String.valueOf(text.charAt(endWord)))) {
endWord++;
}
//invalid widget specification if we went all the way to the end of the markdown
if (endWord < text.length()) {
//it's a widget
//parse the type and descriptor
endWord++;
possibleWidget = text.substring(startWord, endWord);
//set editable
state.setWidgetSelected(true);
state.setInnerWidgetText(possibleWidget.substring(WidgetConstants.WIDGET_START_MARKDOWN.length(), possibleWidget.length() - WidgetConstants.WIDGET_END_MARKDOWN.length()));
state.setWidgetStartIndex(startWord);
state.setWidgetEndIndex(endWord);
}
}
}
}
/**
* Surround the selectedText with the given markdown. Or, if the selected text is already surrounded by the markdown, then remove it.
* @param text
* @param markdown
* @param startPos
* @param selectionLength
* @return
*/
public static String surroundText(String text, String startTag, String endTag, boolean isMultiline, int startPos, int selectionLength) throws IllegalArgumentException {
if (text != null && selectionLength > -1 && startPos >= 0 && startPos <= text.length() && isDefined(startTag)) {
if (endTag == null)
endTag = "";
int startTagLength = startTag.length();
int endTagLength = endTag.length();
int eolPos = text.indexOf('\n', startPos);
if (eolPos < 0)
eolPos = text.length();
int endPos = startPos + selectionLength;
if (eolPos < endPos && !isMultiline)
throw new IllegalArgumentException(DisplayConstants.SINGLE_LINE_COMMAND_MESSAGE);
String selectedText = text.substring(startPos, endPos);
//check to see if this text is already surrounded by the markdown.
int beforeSelectedTextPos = startPos - startTagLength;
int afterSelectedTextPos = endPos + endTagLength;
if (beforeSelectedTextPos > -1 && afterSelectedTextPos <= text.length()) {
if (startTag.equals(text.substring(beforeSelectedTextPos, startPos)) && endTag.equals(text.substring(endPos, afterSelectedTextPos))) {
//strip off markdown instead
return text.substring(0, beforeSelectedTextPos) + selectedText + text.substring(afterSelectedTextPos);
}
}
return text.substring(0, startPos) + startTag + selectedText + endTag + text.substring(endPos);
}
throw new IllegalArgumentException(DisplayConstants.INVALID_SELECTION);
}
public static boolean isDefined(String testString) {
return testString != null && testString.trim().length() > 0;
}
public static void addAnnotation(Annotations annos, String name, ANNOTATION_TYPE type) {
// Add a new annotation
if(ANNOTATION_TYPE.STRING == type){
annos.addAnnotation(name, "");
}else if(ANNOTATION_TYPE.DOUBLE == type){
annos.addAnnotation(name, 0.0);
}else if(ANNOTATION_TYPE.LONG == type){
annos.addAnnotation(name, 0l);
}else if(ANNOTATION_TYPE.DATE == type){
annos.addAnnotation(name, new Date());
}else{
throw new IllegalArgumentException("Unknown type: "+type);
}
}
public static void surroundWidgetWithParens(Panel container, Widget widget) {
Text paren = new Text("(");
paren.addStyleName("inline-block margin-left-5");
container.add(paren);
widget.addStyleName("inline-block");
container.add(widget);
paren = new Text(")");
paren.addStyleName("inline-block margin-right-10");
container.add(paren);
}
public static LayoutContainer createRowContainer() {
LayoutContainer row;
row = new LayoutContainer();
row.setStyleName("row");
return row;
}
public static FlowPanel createRowContainerFlowPanel() {
FlowPanel row = new FlowPanel();
row.setStyleName("row");
return row;
}
public static enum ButtonType { DEFAULT, PRIMARY, SUCCESS, INFO, WARNING, DANGER, LINK }
public static enum BootstrapAlertType { SUCCESS, INFO, WARNING, DANGER }
public static com.google.gwt.user.client.ui.Button createButton(String title) {
return createIconButton(title, ButtonType.DEFAULT, null);
}
public static com.google.gwt.user.client.ui.Button createButton(String title, ButtonType type) {
return createIconButton(title, type, null);
}
public static com.google.gwt.user.client.ui.Button createIconButton(String title, ButtonType type, String iconClass) {
com.google.gwt.user.client.ui.Button btn = new com.google.gwt.user.client.ui.Button();
relabelIconButton(btn, title, iconClass);
btn.removeStyleName("gwt-Button");
btn.addStyleName("btn btn-" + type.toString().toLowerCase());
return btn;
}
public static void relabelIconButton(com.google.gwt.user.client.ui.Button btn, String title, String iconClass) {
String style = iconClass == null ? "" : " class=\"glyphicon " + iconClass+ "\"" ;
btn.setHTML(SafeHtmlUtils.fromSafeConstant("<span" + style +"></span> " + title));
}
public static String getIcon(String iconClass) {
return "<span class=\"glyphicon " + iconClass + "\"></span>";
}
public static String getFontelloIcon(String iconClass) {
return "<span class=\"icon-" + iconClass + "\"></span>";
}
public static EntityHeader getProjectHeader(EntityPath entityPath) {
if(entityPath == null) return null;
for(EntityHeader eh : entityPath.getPath()) {
if(Project.class.getName().equals(eh.getType())) {
return eh;
}
}
return null;
}
public static FlowPanel getMediaObject(String heading, String description, ClickHandler clickHandler, String pictureUri, boolean defaultPictureSinglePerson, int headingLevel) {
FlowPanel panel = new FlowPanel();
panel.addStyleName("media");
String linkStyle = "";
if (clickHandler != null)
linkStyle = "link";
HTML headingHtml = new HTML("<h"+headingLevel+" class=\"media-heading "+linkStyle+"\">" + SafeHtmlUtils.htmlEscape(heading) + "</h"+headingLevel+">");
if (clickHandler != null)
headingHtml.addClickHandler(clickHandler);
if (pictureUri != null) {
FitImage profilePicture = new FitImage(pictureUri, 64, 64);
profilePicture.addStyleName("pull-left media-object imageButton");
if (clickHandler != null)
profilePicture.addClickHandler(clickHandler);
panel.add(profilePicture);
} else {
//display default picture
String iconClass = defaultPictureSinglePerson ? "user" : "users";
String clickableButtonCssClass = clickHandler != null ? "imageButton" : "";
HTML profilePicture = new HTML(DisplayUtils.getFontelloIcon(iconClass + " font-size-58 padding-2 " + clickableButtonCssClass + " userProfileImage lightGreyText margin-0-imp-before"));
profilePicture.addStyleName("pull-left media-object displayInline ");
if (clickHandler != null)
profilePicture.addClickHandler(clickHandler);
panel.add(profilePicture);
}
FlowPanel mediaBodyPanel = new FlowPanel();
mediaBodyPanel.addStyleName("media-body");
mediaBodyPanel.add(headingHtml);
if (description != null)
mediaBodyPanel.add(new HTML(SafeHtmlUtils.htmlEscape(description)));
panel.add(mediaBodyPanel);
return panel;
}
public static SimpleComboBox<String> createSimpleComboBox(List<String> values, String defaultValue){
final SimpleComboBox<String> cb = new SimpleComboBox<String>();
cb.add(values);
cb.setSimpleValue(defaultValue);
cb.setTypeAhead(false);
cb.setEditable(false);
cb.setForceSelection(true);
cb.setTriggerAction(TriggerAction.ALL);
return cb;
}
public static HTML getNewLabel(boolean superScript) {
final HTML label = new HTML(DisplayConstants.NEW);
label.addStyleName("label label-info margin-left-5");
if(superScript) label.addStyleName("tabLabel");
Timer t = new Timer() {
@Override
public void run() {
label.setVisible(false);
}
};
t.schedule(30000); // hide after 30 seconds
return label;
}
public static void setPlaceholder(Widget w, String placeholder) {
w.getElement().setAttribute("placeholder", placeholder);
}
public static InlineHTML createFormHelpText(String text) {
InlineHTML label = new InlineHTML(text);
label.addStyleName("help-block");
return label;
}
public static String getShareMessage(String displayName, String entityId, String hostUrl) {
return displayName + DisplayConstants.SHARED_ON_SYNAPSE + ":\n"+hostUrl+"#!Synapse:"+entityId+"\n\n"+DisplayConstants.TURN_OFF_NOTIFICATIONS+hostUrl+"#!Settings:0";
//alternatively, could use the gwt I18n Messages class client side
}
public static void getPublicPrincipalIds(UserAccountServiceAsync userAccountService, final AsyncCallback<PublicPrincipalIds> callback){
if (publicPrincipalIds == null) {
userAccountService.getPublicAndAuthenticatedGroupPrincipalIds(new AsyncCallback<PublicPrincipalIds>() {
@Override
public void onSuccess(PublicPrincipalIds result) {
publicPrincipalIds = result;
callback.onSuccess(result);
}
@Override
public void onFailure(Throwable caught) {
callback.onFailure(caught);
}
});
} else
callback.onSuccess(publicPrincipalIds);
}
public static String getPreviewSuffix(Boolean isPreview) {
return isPreview ? org.sagebionetworks.markdown.constants.WidgetConstants.DIV_ID_PREVIEW_SUFFIX : "";
}
public static void hide(UIObject uiObject) {
uiObject.setVisible(false);
}
public static void show(UIObject uiObject) {
uiObject.setVisible(true);
}
public static void hide(com.google.gwt.dom.client.Element elem) {
UIObject.setVisible(elem, false);
}
public static void show(com.google.gwt.dom.client.Element elem) {
UIObject.setVisible(elem, true);
}
public static void showFormError(DivElement parentElement, DivElement messageElement) {
parentElement.addClassName("has-error");
DisplayUtils.show(messageElement);
}
public static void hideFormError(DivElement parentElement, DivElement messageElement) {
parentElement.removeClassName("has-error");
DisplayUtils.hide(messageElement);
}
public static String getInfoHtml(String safeHtmlMessage) {
return "<div class=\"alert alert-info\">"+safeHtmlMessage+"</div>";
}
public static String getTableRowViewAreaToken(String id) {
return "row/" + id;
}
public static String getTableRowViewAreaToken(String id, String version) {
String str = "row/" + id;
if (version != null)
str += "/rowversion/" + version;
return str;
}
public static void goToLastPlace(GlobalApplicationState globalApplicationState) {
Place forwardPlace = globalApplicationState.getLastPlace();
if(forwardPlace == null) {
forwardPlace = new Home(ClientProperties.DEFAULT_PLACE_TOKEN);
}
globalApplicationState.getPlaceChanger().goTo(forwardPlace);
}
public static String getStackTrace(Throwable t) {
StringBuilder stackTrace = new StringBuilder();
if (t != null) {
for (StackTraceElement element : t.getStackTrace()) {
stackTrace.append(element + "\n");
}
}
return stackTrace.toString();
}
/**
* This is to work around a Chrome rendering bug, where some containers do not properly calculate their relative widths (in the dynamic bootstrap grid layout) when they are initially added.
* The most visible of these cases is the Wiki Subpages panel (see SWC-1450).
* @param e
*/
public static void clearElementWidth(Element e) {
if ( e != null) {
Style style = e.getStyle();
if (style != null) {
style.setWidth(1, Unit.PX);
style.clearWidth();
}
}
}
public static void configureShowHide(final InlineLabel label, final LayoutContainer content) {
label.setText(DisplayConstants.SHOW_LC);
label.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if (content.isVisible()) {
content.setVisible(false);
label.setText(DisplayConstants.SHOW_LC);
} else {
content.setVisible(true);
label.setText(DisplayConstants.HIDE_LC);
}
content.layout(true);
}
});
}
/**
* just return the empty string if input string parameter s is null, otherwise returns s.
*/
public static String replaceWithEmptyStringIfNull(String s) {
if (s == null)
return "";
else return s;
}
public static void setHighlightBoxUser(DivElement highlightBox, String displayName, String title) {
String prefix = displayName != null ? displayName+"'s " : "";
highlightBox.setAttribute("highlight-box-title", prefix + title);
}
}
|
package org.smoothbuild.parse;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static org.smoothbuild.lang.function.base.Scope.scope;
import static org.smoothbuild.util.Lists.map;
import java.util.List;
import java.util.Map;
import org.smoothbuild.antlr.SmoothParser.ExprContext;
import org.smoothbuild.lang.expr.ArrayExpression;
import org.smoothbuild.lang.expr.BoundValueExpression;
import org.smoothbuild.lang.expr.Expression;
import org.smoothbuild.lang.expr.StringLiteralExpression;
import org.smoothbuild.lang.function.Functions;
import org.smoothbuild.lang.function.base.Function;
import org.smoothbuild.lang.function.base.Name;
import org.smoothbuild.lang.function.base.Parameter;
import org.smoothbuild.lang.function.base.Scope;
import org.smoothbuild.lang.function.base.Signature;
import org.smoothbuild.lang.function.def.DefinedFunction;
import org.smoothbuild.lang.type.ArrayType;
import org.smoothbuild.lang.type.Conversions;
import org.smoothbuild.lang.type.Type;
import org.smoothbuild.lang.value.Value;
import org.smoothbuild.parse.ast.ArrayNode;
import org.smoothbuild.parse.ast.CallNode;
import org.smoothbuild.parse.ast.ExprNode;
import org.smoothbuild.parse.ast.FuncNode;
import org.smoothbuild.parse.ast.ParamNode;
import org.smoothbuild.parse.ast.StringNode;
public class DefinedFunctionLoader {
public static DefinedFunction loadDefinedFunction(Functions loadedFunctions,
FuncNode funcNode) {
return new Worker(loadedFunctions).loadFunction(funcNode);
}
private static class Worker {
private final Functions loadedFunctions;
private Scope<Name> scope;
public Worker(Functions loadedFunctions) {
this.loadedFunctions = loadedFunctions;
}
public DefinedFunction loadFunction(FuncNode func) {
List<Parameter> parameters = createParameters(func.params());
scope = scope();
parameters
.stream()
.forEach(p -> scope.add(p.name(), null));
Expression expression = createExpression(func.expr());
Signature signature = new Signature(expression.type(), func.name(), parameters);
return new DefinedFunction(signature, expression);
}
private static List<Parameter> createParameters(List<ParamNode> params) {
return params
.stream()
.map(p -> new Parameter(p.type().get(Type.class), p.name(), null))
.collect(toList());
}
private Expression createExpression(ExprNode expr) {
if (expr instanceof CallNode) {
CallNode call = (CallNode) expr;
if (call.has(CallNode.ParamRefFlag.class)) {
return createReference(call);
} else {
return createCall(call);
}
}
if (expr instanceof StringNode) {
return createStringLiteral((StringNode) expr);
}
if (expr instanceof ArrayNode) {
return createArray((ArrayNode) expr);
}
throw new RuntimeException("Illegal parse tree: " + ExprContext.class.getSimpleName()
+ " without children.");
}
private Expression createReference(CallNode ref) {
return new BoundValueExpression(ref.get(Type.class), ref.name(), ref.location());
}
private Expression createCall(CallNode call) {
Function function = loadedFunctions.get(call.name());
List<Expression> expressions = createSortedArgumentExpressions(call, function);
return function.createCallExpression(expressions, false, call.location());
}
private List<Expression> createSortedArgumentExpressions(CallNode call, Function function) {
Map<Parameter, Expression> assignedExpressions = call
.args()
.stream()
.collect(toMap(a -> a.get(Parameter.class), a -> createExpression(a.expr())));
return function
.parameters()
.stream()
.map(p -> assignedExpressions.containsKey(p)
? implicitConversion(p.type(), assignedExpressions.get(p))
: p.defaultValueExpression())
.collect(toImmutableList());
}
private Expression createStringLiteral(StringNode string) {
return new StringLiteralExpression(string.get(String.class), string.location());
}
private Expression createArray(ArrayNode array) {
List<Expression> exprList = map(array.elements(), this::createExpression);
return createArray(array, exprList);
}
private Expression createArray(ArrayNode array, List<Expression> elements) {
ArrayType type = (ArrayType) array.get(Type.class);
List<Expression> converted = map(elements, e -> implicitConversion(type.elemType(), e));
return new ArrayExpression(type, converted, array.location());
}
public <T extends Value> Expression implicitConversion(Type destinationType,
Expression source) {
Type sourceType = source.type();
if (sourceType == destinationType) {
return source;
}
Name functionName = Conversions.convertFunctionName(sourceType, destinationType);
Function function = loadedFunctions.get(functionName);
return function.createCallExpression(asList(source), true, source.location());
}
}
}
|
package org.softwareonpurpose.gauntlet;
import com.softwareonpurpose.uinavigator.UiHost;
import com.softwareonpurpose.uinavigator.web.WebUiHost;
import org.apache.commons.io.FileUtils;
import org.softwareonpurpose.coverage4test.CoverageReport;
import org.testng.ITestResult;
import org.testng.annotations.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
@Test
public abstract class GauntletTest {
private final UiHost host = WebUiHost.getInstance(ChromeUiDriver.getInstance());
private static final CoverageReport reportManager = CoverageReport.getInstance();
private String feature;
private String method;
@BeforeClass(alwaysRun = true)
protected void initialize() {
feature = this.getClass().getSimpleName().replace("Tests", "");
}
@BeforeMethod(alwaysRun = true)
protected void storeTestName(Method method) {
this.method = method.getName();
}
@AfterMethod(alwaysRun = true)
protected void reportMethod(ITestResult result) {
System.out.println(result.getMethod());
System.out.println(result.getName());
System.out.println(result.getParameters());
System.out.println(result.getTestClass());
}
@AfterClass(alwaysRun = true)
protected synchronized void reportClass() {
File reportFolder = new File("reports");
File[] reports = reportFolder.listFiles();
if (reports != null) {
for (File file : reports) {
file.delete();
}
reportFolder.delete();
}
boolean mkdir = reportFolder.mkdir();
File systemReport = new File("reports/system_coverage.rpt");
try {
FileUtils.writeStringToFile(systemReport, reportManager.getSystemCoverage(), StandardCharsets.UTF_8);
boolean newFile = systemReport.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package org.spongepowered.api.status;
import com.google.common.base.Optional;
import org.spongepowered.api.GameProfile;
import org.spongepowered.api.MinecraftVersion;
import org.spongepowered.api.event.server.StatusPingEvent;
import org.spongepowered.api.text.Text;
import java.util.List;
/**
* Represents the response to a status request. Unlike {@link StatusPingEvent}
* this is immutable.
* <p>
* This interface exists mostly for convenience and can be implemented in a
* library pinging other servers for example.
* </p>
*
* @see StatusPingEvent
*/
public interface StatusResponse {
/**
* Gets the description (MOTD) of the status response.
*
* @return The description to display
*/
Text getDescription();
/**
* Gets player count and the list of players currently playing on the
* server.
*
* @return The player information, or {@link Optional#absent()} if not
* available
*/
Optional<? extends Players> getPlayers();
/**
* Gets the version of the server displayed when the client or the server
* are outdated.
*
* @return The server version
*/
MinecraftVersion getVersion();
/**
* Gets the {@link Favicon} of the server.
*
* @return The favicon, or {@link Optional#absent()} if not available
*/
Optional<Favicon> getFavicon();
/**
* Represents the player count, slots and a list of players current playing
* on a server.
*/
interface Players {
/**
* Gets the amount of online players on the server.
*
* @return The amount of online players
*/
int getOnline();
/**
* Gets the maximum amount of allowed players on the server.
*
* @return The maximum amount of allowed players
*/
int getMax();
/**
* Gets an immutable list of online players on the server to display on
* the client.
*
* @return An immutable list of online players
*/
List<GameProfile> getProfiles();
}
/**
* Checks if this is a flowerpot.
*
* @return Whether this is a flowerpot
*/
boolean isFlowerPot();
}
|
package org.threadly.concurrent;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import org.threadly.concurrent.lock.StripedLock;
import org.threadly.concurrent.lock.VirtualLock;
/**
* <p>This abstraction is designed to make submitting {@link Callable} tasks with
* results easier. Tasks are submitted and results for those tasks can be
* captured when ready using .getNextResult() or .getAllResults().
* If multiple callables are submitted with the same key, they are guaranteed to
* never run in parallel.</p>
*
* @author jent - Mike Jensen
* @param <K> Key for distributing callables and getting results
* @param <R> Type of result that is returned
*/
public class CallableDistributor<K, R> {
protected static final boolean RESULTS_EXPECTED_DEFAULT = true;
protected static final float CONCURRENT_HASH_MAP_LOAD_FACTOR = (float)0.75; // 0.75 is ConcurrentHashMap default
protected static final int CONCURRENT_HASH_MAP_MAX_INITIAL_SIZE = 100;
protected static final int CONCURRENT_HASH_MAP_MAX_CONCURRENCY_LEVEL = 100;
protected final TaskExecutorDistributor taskDistributor;
protected final StripedLock sLock;
protected final ConcurrentHashMap<K, AtomicInteger> waitingCalls;
protected final ConcurrentHashMap<K, LinkedList<Result<R>>> results; // locked around sLock for key
/**
* Constructs a new {@link CallableDistributor} with giving parameters to
* help guide thread pool construction.
*
* @param expectedParallism expected qty of keys to be used in parallel
* @param maxThreadCount maximum threads to be used
*/
public CallableDistributor(int expectedParallism, int maxThreadCount) {
this(new TaskExecutorDistributor(expectedParallism, maxThreadCount));
}
/**
* Constructs a new {@link CallableDistributor} with a provided Executor.
* Executor should have enough available threads to be able to service the
* expected key quantity in parallel.
*
* @param executor Executor for new threads to be executed on
*/
public CallableDistributor(Executor executor) {
this(new TaskExecutorDistributor(executor));
}
/**
* Constructs a new {@link CallableDistributor} with a provided Executor.
* Executor should have enough available threads to be able to service the
* expected key quantity in parallel.
*
* @param expectedParallism level of expected qty of threads adding callables in parallel
* @param executor Executor for new threads to be executed on
*/
public CallableDistributor(int expectedParallism, Executor executor) {
this(new TaskExecutorDistributor(expectedParallism, executor));
}
/**
* Constructs a new {@link CallableDistributor} with a provided {@link TaskExecutorDistributor}.
*
* @param taskDistributor TaskDistributor used to execute callables
*/
public CallableDistributor(TaskExecutorDistributor taskDistributor) {
this(taskDistributor, new StripedLock(taskDistributor.sLock.getExpectedConcurrencyLevel(),
taskDistributor.sLock.getFactory()));
}
/**
* Constructor for Threadly internal unit testing. If you need to use a
* {@link CallableDistributor} in your unit testing, you should use the
* constructor where you provide a testable {@link TaskExecutorDistributor}.
*
* @param taskDistributor TaskDistributor used to execute callables
* @param sLock lock to be used for controlling access to results
*/
protected CallableDistributor(TaskExecutorDistributor taskDistributor,
StripedLock sLock) {
if (taskDistributor == null) {
throw new IllegalArgumentException("Must provide taskDistributor");
}
this.taskDistributor = taskDistributor;
this.sLock = sLock;
int mapInitialSize = Math.min(sLock.getExpectedConcurrencyLevel(),
CONCURRENT_HASH_MAP_MAX_INITIAL_SIZE);
int mapConcurrencyLevel = Math.min(sLock.getExpectedConcurrencyLevel(),
CONCURRENT_HASH_MAP_MAX_CONCURRENCY_LEVEL);
waitingCalls = new ConcurrentHashMap<K, AtomicInteger>(mapInitialSize,
CONCURRENT_HASH_MAP_LOAD_FACTOR,
mapConcurrencyLevel);
results = new ConcurrentHashMap<K, LinkedList<Result<R>>>(mapInitialSize,
CONCURRENT_HASH_MAP_LOAD_FACTOR,
mapConcurrencyLevel);
}
/**
* Submits a new {@link Callable} to be executed with a given key to determine
* thread to be run on, and how to get results for callable.
*
* @param key key for callable thread choice and to get result
* @param callable to be executed
*/
public void submit(K key, Callable<? extends R> callable) {
if (key == null) {
throw new IllegalArgumentException("key can not be null");
} else if (callable == null) {
throw new IllegalArgumentException("callable can not be null");
}
AtomicInteger waitingCount = waitingCalls.get(key);
if (waitingCount == null) {
waitingCount = new AtomicInteger();
AtomicInteger putResult = waitingCalls.putIfAbsent(key, waitingCount);
if (putResult != null) {
waitingCount = putResult;
}
}
waitingCount.incrementAndGet();
CallableContainer cc = new CallableContainer(key, callable);
taskDistributor.addTask(key, cc);
}
/**
* Call to check if results are, or will be ready for a given key.
*
* @param key key for submitted callables
* @return true if results are either ready, or currently processing for key
*/
public boolean waitingResults(K key) {
AtomicInteger waitingCount = waitingCalls.get(key);
return (waitingCount != null && waitingCount.get() > 0) ||
results.containsKey(key);
}
protected void verifyWaitingForResult(K key) {
if (! waitingResults(key)) {
throw new IllegalStateException("No submitted calls currently running for key: " + key);
}
}
public Result<R> getNextResult(K key) throws InterruptedException {
return getNextResult(key, RESULTS_EXPECTED_DEFAULT);
}
/**
* Call to get the next result for a given submission key. This
* call has the potential to block before a callable has been submitted.
*
* This has the risk of blocking forever if a result has already been
* consumed or the callable is never submitted. But could be useful if the
* thread that is polling for results is different from the one submitting.
*
* @param key used when submitted that results will be returned for
* @param resultsExpected if callable was guaranteed to be already submitted
* @return result from execution
* @throws InterruptedException exception if thread was interrupted while blocking
*/
public Result<R> getNextResult(K key, boolean resultsExpected) throws InterruptedException {
if (key == null) {
throw new IllegalArgumentException("key can not be null");
}
VirtualLock callLock = sLock.getLock(key);
synchronized (callLock) {
if (resultsExpected) {
verifyWaitingForResult(key);
}
LinkedList<Result<R>> resultList = results.get(key);
while (resultList == null) {
callLock.await();
resultList = results.get(key);
}
Result<R> result = resultList.removeFirst();
if (resultList.isEmpty()) {
results.remove(key);
}
return result;
}
}
public List<Result<R>> getAllResults(K key) throws InterruptedException {
return getAllResults(key, RESULTS_EXPECTED_DEFAULT);
}
/**
* Call to return all results currently available for a given submission
* key. If no results are available, but a callable is running that will
* produce one, this call will block till results are ready.
*
* This has the risk of blocking forever if a result has already been
* consumed or the callable is never submitted. But could be useful if the
* thread that is polling for results is different from the one submitting.
*
* @param key used when submitted that results will be returned for
* @param resultsExpected if callable was guaranteed to be already submitted
* @return a list of all results ready for the given key
* @throws InterruptedException exception if thread was interrupted while blocking
*/
public List<Result<R>> getAllResults(K key, boolean resultsExpected) throws InterruptedException {
if (key == null) {
throw new IllegalArgumentException("key can not be null");
}
VirtualLock callLock = sLock.getLock(key);
synchronized (callLock) {
if (resultsExpected) {
verifyWaitingForResult(key);
}
List<Result<R>> resultList = results.remove(key);
while (resultList == null) {
callLock.await();
resultList = results.remove(key);
}
return resultList;
}
}
protected void handleSuccessResult(K key, R result) {
handleResult(key, new Result<R>(result));
}
protected void handleFailureResult(K key, Throwable t) {
handleResult(key, new Result<R>(t));
}
protected void handleResult(K key, Result<R> r) {
VirtualLock callLock = sLock.getLock(key);
synchronized (callLock) {
AtomicInteger waitingCount = waitingCalls.get(key);
if (waitingCount == null || waitingCount.get() < 1) {
// something should always be waiting for result
throw new IllegalStateException();
}
LinkedList<Result<R>> resultList = results.get(key);
if (resultList == null) {
resultList = new LinkedList<Result<R>>();
results.put(key, resultList);
}
resultList.add(r);
waitingCount.decrementAndGet();
callLock.signalAll();
}
}
/**
* <p>Container for a callable which will record the result after completed.</p>
*
* @author jent - Mike Jensen
*/
protected class CallableContainer extends VirtualRunnable {
private final K key;
private final Callable<? extends R> callable;
public CallableContainer(K key, Callable<? extends R> callable) {
this.key = key;
this.callable = callable;
}
@SuppressWarnings("unchecked")
@Override
public void run() {
try {
R result;
if (factory != null && callable instanceof VirtualCallable) {
result = ((VirtualCallable<R>)callable).call(factory);
} else { // no reason to waste our time
result = callable.call();
}
handleSuccessResult(key, result);
} catch (Exception e) {
handleFailureResult(key, e);
}
}
}
/**
* <p>Result from a callable which can be either a computed
* result, or an exception due to failure. These are different
* from futures in that they represent the product of work, not
* work that has yet to occur.</p>
*
* @author jent - Mike Jensen
* @param <R> result type
*/
public static class Result<R> {
private final R successResult;
private final Throwable failureResult;
protected Result(R successResult) {
this.successResult = successResult;
failureResult = null;
}
protected Result(Throwable failureResult) {
successResult = null;
this.failureResult = failureResult;
}
/**
* Returns the result from the callable, or throws an ExecutionException
* if a failure occurred during execution.
*
* @return computed result
* @throws ExecutionException Exception to represent failure occurred during run
*/
public R get() throws ExecutionException {
if (failureResult != null) {
throw new ExecutionException(failureResult);
}
return successResult;
}
/**
* Retrieves the stored result, or null if
* no result was provided or Exception was thrown.
*
* @return result from execution, null if failure
*/
public R getResult() {
return successResult;
}
/**
* Provides the throwable that may have been thrown during
* execution, or null if none was thrown.
*
* @return throwable that was thrown during execution, or null if none was thrown
*/
public Throwable getFailure() {
return failureResult;
}
}
}
|
package org.vx68k.hudson.plugin.bds;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.EnvironmentSpecific;
import hudson.model.Hudson;
import hudson.model.Node;
import hudson.model.TaskListener;
import hudson.remoting.VirtualChannel;
import hudson.slaves.NodeSpecific;
import hudson.tools.ToolDescriptor;
import hudson.tools.ToolInstallation;
import hudson.tools.ToolProperty;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.vx68k.hudson.plugin.bds.resources.Messages;
/**
* RAD Studio installation.
* @author Kaz Nishimura
* @since 4.0
*/
public class BDSInstallation extends ToolInstallation
implements NodeSpecific<BDSInstallation>,
EnvironmentSpecific<BDSInstallation> {
private static final long serialVersionUID = 4L;
private static final String BIN_DIRECTORY_NAME = "bin";
private static final String BATCH_FILE_NAME = "rsvars.bat";
/**
* Constructs this object with immutable properties.
*
* @param name name of this installation
* @param home home directory (the value of <code>BDS</code>)
* @param properties properties for {@link ToolInstallation}
*/
@DataBoundConstructor
public BDSInstallation(String name, String home,
List<? extends ToolProperty<?>> properties) {
super(name, home, properties);
}
/**
* Returns the array of the RAD Studio installations.
* @return array of the RAD Studio installations
*/
public static BDSInstallation[] getInstallations() {
return Descriptor.getDescriptor().getInstallations();
}
/**
* Returns the RAD Studio installation identified by a name.
* @param name name of the RAD Studio installation
* @return RAD Studio installation, or <code>null</code> if no installation
* was found
*/
public static BDSInstallation getInstallation(String name) {
for (BDSInstallation i : getInstallations()) {
if (i.getName() != null && i.getName().equals(name)) {
return i;
}
}
return null;
}
/**
* Returns a {@link FilePath} object for the home directory.
*
* @param channel {@link VirtualChannel} object for {@link FilePath}
* @return {@link FilePath} object for the home directory
*/
protected FilePath getHome(VirtualChannel channel) {
return new FilePath(channel, getHome());
}
/**
* Returns a {@link FilePath} object for the batch file which initializes
* a RAD Studio Command Prompt.
*
* @param channel {@link VirtualChannel} object for {@link FilePath}
* @return {@link FilePath} object for the batch file
*/
protected FilePath getBatchFile(VirtualChannel channel) {
FilePath bin = new FilePath(getHome(channel), BIN_DIRECTORY_NAME);
return new FilePath(bin, BATCH_FILE_NAME);
}
/**
* Reads the RAD Studio environment variables from the batch file which
* initializes a RAD Studio Command Prompt.
*
* @param build {@link AbstractBuild} object
* @param launcher {@link Launcher} object
* @param listener {@link TaskListener} object
* @return environment variables read from the batch file
* @throws IOException if an I/O exception has occurred
* @throws InterruptedException if interrupted
*/
public Map<String, String> readVariables(AbstractBuild<?, ?> build,
Launcher launcher, TaskListener listener)
throws IOException, InterruptedException {
if (getHome().isEmpty()) {
listener.error(Messages.getHomeIsEmptyMessage());
return null;
}
InputStream batchStream = BDSUtilities.getInputStream(build,
launcher, listener, getBatchFile(launcher.getChannel()));
if (batchStream == null) {
// Any error messages must already be printed.
return null;
}
return BDSUtilities.readVariables(batchStream);
}
/**
* Returns a {@link NodeSpecific} version of this object.
*
* @param node node for which the return value is specialized.
* @param listener a {@link TaskListener} object
* @return {@link NodeSpecific} copy of this object
* @throws IOException if an I/O exception has occurred
* @throws InterruptedException if interrupted
*/
@Override
public BDSInstallation forNode(Node node, TaskListener listener)
throws IOException, InterruptedException {
return new BDSInstallation(getName(), translateFor(node, listener),
getProperties().toList());
}
/**
* Returns an {@link EnvironmentSpecific} version of this object.
*
* @param environment environment for which the return value is
* specialized.
* @return {@link EnvironmentSpecific} copy of this object
*/
@Override
public BDSInstallation forEnvironment(EnvVars environment) {
return new BDSInstallation(getName(), environment.expand(getHome()),
getProperties().toList());
}
/**
* Describes {@link BDSInstallation}.
* @author Kaz Nishimura
*/
@Extension
public static final class Descriptor
extends ToolDescriptor<BDSInstallation> {
/**
* Constructs this object by loading the saved installations.
*/
public Descriptor() {
// {@link ToolDescriptor#installations} can be <code>null</code>
// when there is no configuration.
setInstallations();
load();
}
/**
* Return the {@link Descriptor} instance.
* @return {@link Descriptor} instance
*/
public static Descriptor getDescriptor() {
return Hudson.getInstance().getDescriptorByType(Descriptor.class);
}
@Override
public BDSInstallation[] getInstallations() {
BDSInstallation[] installations;
synchronized (this) {
installations = super.getInstallations();
if (installations.length == 0) {
org.vx68k.jenkins.plugin.bds.BDSInstallation[] olds =
org.vx68k.jenkins.plugin.bds.BDSInstallation
.getInstallations();
installations = new BDSInstallation[olds.length];
for (int i = 0; i != installations.length; i += 1) {
installations[i] = olds[i].convert();
}
// Keeps the migrated installations without saving.
setInstallations(installations);
}
}
return installations;
}
@Override
public boolean configure(StaplerRequest req, JSONObject json)
throws FormException {
boolean ready = super.configure(req, json);
if (ready) {
save();
}
return ready;
}
// @Override
// protected FormValidation checkHomeDirectory(File home) {
// File bin = new File(home, BIN_DIRECTORY_NAME);
// File batch = new File(bin, BATCH_FILE_NAME);
// if (!batch.isFile()) {
// return FormValidation.error(NOT_INSTALLATION_DIRECTORY);
// return super.checkHomeDirectory(home);
/**
* Returns the display name for RAD Studio installations.
*
* @return display name for RAD Studio installations
*/
@Override
public String getDisplayName() {
return "RAD Studio";
}
}
}
|
package parking.implementation.gui.stages;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.stage.Window;
import parking.implementation.business.Client;
import parking.implementation.gui.ClientManager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class BookStage extends Stage {
private Collection<Client> clients = new ArrayList<>();
private Label titleLabel;
private Label label;
private ChoiceBox<Client> clientChoiceBox;
private ChoiceBox<Integer> durationChoiceBox;
private Button createButton;
private Button submitButton;
private Button cancelButton;
public BookStage(Window owner) {
this.initOwner(owner);
init();
BorderPane borderPane = new BorderPane();
FlowPane flowPane = new FlowPane();
//add Nodes to FlowPane
flowPane.getChildren().addAll(
titleLabel,
clientChoiceBox,
durationChoiceBox,
submitButton,
label,
createButton,
cancelButton
);
updateState();
flowPane.setMaxSize(200, 400);
//add FlowPane
flowPane.alignmentProperty().setValue(Pos.CENTER);
borderPane.setCenter(flowPane);
//createButton scene
Scene scene = new Scene(borderPane, 300, 200);
this.setResizable(false);
this.setScene(scene);
this.setTitle("Select Client");
}
private void createTitle() {
titleLabel = new Label("Select Client");
titleLabel.setFont(Font.font("Arial", 30));
titleLabel.setTextFill(Color.BLACK);
titleLabel.alignmentProperty().setValue(Pos.CENTER);
}
private void createLabel() {
label = new Label("Il n'y a pas de clients.");
label.setTextFill(Color.RED);
label.setAlignment(Pos.CENTER);
}
private void createSelect() {
clientChoiceBox = new ChoiceBox<>();
if (ClientManager.getInstance().count() != 0){
Iterator<Client> clientIterator = ClientManager.getInstance().iterator();
while (clientIterator.hasNext()){
Client tmp = clientIterator.next();
clientChoiceBox.getItems().add(tmp);
clients.add(tmp);
}
}
}
private void updateState() {
if (clients.isEmpty()) {
clientChoiceBox.setVisible(false);
submitButton.setVisible(false);
label.setVisible(true);
} else {
clientChoiceBox.setVisible(true);
submitButton.setVisible(true);
label.setVisible(false);
clientChoiceBox.getItems().setAll(clients);
}
}
private void createButtonCreate() {
createButton = new Button();
createButton.setText("New Client");
//add action
createButton.setOnAction(event -> {
ClientStage clientStage = new ClientStage(this);
clientStage.showAndWait();
Client newClient = clientStage.getClient();
if (newClient != null)
clients.add(newClient);
updateState();
});
//style
createButton.setStyle("-fx-background-color: blue");
createButton.setTextFill(Color.WHITE);
}
private void createButtonSubmit() {
submitButton = new Button();
submitButton.setText("Select");
//add action
submitButton.setOnAction(event -> {
this.close();
});
//style
submitButton.setStyle("-fx-background-color: green");
submitButton.setTextFill(Color.WHITE);
}
private void createButtonCancel() {
cancelButton = new Button();
cancelButton.setText("Cancel");
//add action
cancelButton.setOnAction(event -> {
this.close();
});
//style
cancelButton.setStyle("-fx-background-color: red");
cancelButton.setTextFill(Color.WHITE);
}
private void createDurationChoixBox() {
durationChoiceBox = new ChoiceBox<>();
Collection<Integer> during = new ArrayList<>();
for (int i = 1; i < 50; i++)
during.add(new Integer(i));
durationChoiceBox.getItems().setAll(during);
}
private void init() {
createTitle();
createLabel();
createSelect();
createButtonSubmit();
createButtonCreate();
createButtonCancel();
createDurationChoixBox();
}
public Client getClient() {
return this.clientChoiceBox.getValue();
}
public Integer getDuration() {
return durationChoiceBox.getValue();
}
}
|
package pixlepix.auracascade.item;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.world.World;
import pixlepix.auracascade.main.EnumColor;
import pixlepix.auracascade.registry.CraftingBenchRecipe;
import pixlepix.auracascade.registry.ITTinkererItem;
import pixlepix.auracascade.registry.ThaumicTinkererRecipe;
import java.util.ArrayList;
import java.util.List;
public class ItemPrismaticWand extends Item implements ITTinkererItem {
public static String[] modes = new String[]{EnumColor.AQUA + "Selection", EnumColor.YELLOW + "Copy", EnumColor.ORANGE + "Paste"};
public ItemPrismaticWand() {
super();
setMaxStackSize(1);
}
@Override
public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int p_77648_7_, float p_77648_8_, float p_77648_9_, float p_77648_10_) {
//More specific selections
if (!player.isSneaking() && !world.isRemote) {
if (stack.stackTagCompound == null) {
stack.stackTagCompound = new NBTTagCompound();
}
NBTTagCompound nbt = stack.stackTagCompound;
if (stack.getItemDamage() == 0) {
if (nbt.hasKey("x1")) {
nbt.setInteger("x2", nbt.getInteger("x1"));
nbt.setInteger("y2", nbt.getInteger("y1"));
nbt.setInteger("z2", nbt.getInteger("z1"));
}
nbt.setInteger("x1", x);
nbt.setInteger("y1", y);
nbt.setInteger("z1", z);
player.addChatComponentMessage(new ChatComponentText("Position set"));
return true;
}
}
return false;
}
@Override
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean p_77624_4_) {
super.addInformation(stack, player, list, p_77624_4_);
list.add(modes[stack.getItemDamage()]);
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
int mode = stack.getItemDamage();
if (player.isSneaking()) {
NBTTagCompound nbt = stack.stackTagCompound;
mode++;
mode = mode % modes.length;
stack.setItemDamage(mode);
stack.stackTagCompound = nbt;
if (!world.isRemote) {
player.addChatComponentMessage(new ChatComponentText("Switched to: " + modes[mode]));
}
} else {
if (stack.stackTagCompound == null) {
stack.stackTagCompound = new NBTTagCompound();
}
NBTTagCompound nbt = stack.stackTagCompound;
switch (mode) {
/*
case 0:
//Make sure onItemUseFirst hasn't already grabbed it
if (nbt.hasKey("x1")) {
nbt.setInteger("x2", nbt.getInteger("x1"));
nbt.setInteger("y2", nbt.getInteger("y1"));
nbt.setInteger("z2", nbt.getInteger("z1"));
}
nbt.setInteger("x1", (int) player.posX);
nbt.setInteger("y1", (int) player.posY);
nbt.setInteger("z1", (int) player.posZ);
player.addChatComponentMessage(new ChatComponentText("Position set"));
break;
*/
case 1:
if (nbt.hasKey("x1") && nbt.hasKey("x2")) {
nbt.setInteger("cx1", nbt.getInteger("x1"));
nbt.setInteger("cy1", nbt.getInteger("y1"));
nbt.setInteger("cz1", nbt.getInteger("z1"));
nbt.setInteger("cx2", nbt.getInteger("x2"));
nbt.setInteger("cy2", nbt.getInteger("y2"));
nbt.setInteger("cz2", nbt.getInteger("z2"));
//This is how far away the player is from the copy/paste
nbt.setInteger("cxo", (int) Math.floor(nbt.getInteger("x1") - player.posX) + 1);
nbt.setInteger("cyo", (int) Math.floor(nbt.getInteger("y1") - player.posY));
nbt.setInteger("czo", (int) Math.floor(nbt.getInteger("z1") - player.posZ) + 1);
if (!world.isRemote) {
player.addChatComponentMessage(new ChatComponentText("Copied to clipboard"));
}
} else {
if (!world.isRemote) {
player.addChatComponentMessage(new ChatComponentText("Invalid selection"));
}
}
break;
case 2:
int x = (int) player.posX;
int y = (int) player.posY;
int z = (int) player.posZ;
if (nbt.hasKey("cx1")) {
int cx1 = nbt.getInteger("cx1");
int cy1 = nbt.getInteger("cy1");
int cz1 = nbt.getInteger("cz1");
int cx2 = nbt.getInteger("cx2");
int cy2 = nbt.getInteger("cy2");
int cz2 = nbt.getInteger("cz2");
int xo = nbt.getInteger("cxo");
int yo = nbt.getInteger("cyo");
int zo = nbt.getInteger("czo");
//For simplicities sake, c*1 is lower than c*2
if (cx1 > cx2) {
//Yes, yes, bitwise
//But thats just a party trick
//I mean, if you go to some nerdy parties
int t = cx1;
cx1 = cx2;
cx2 = t;
}
if (cy1 > cy2) {
int t = cy1;
cy1 = cy2;
cy2 = t;
}
if (cz1 > cz2) {
int t = cz1;
cz1 = cz2;
cz2 = t;
}
int xi = cx1;
do {
int yi = cy1;
do {
int zi = cz1;
do {
int dx = xi - cx1;
int dy = yi - cy1;
int dz = zi - cz1;
if (world.isAirBlock(x + dx + xo, y + dy + yo, z + dz + zo)) {
Block block = world.getBlock(cx1 + dx, cy1 + dy, cz1 + dz);
Item item = block.getItem(world, cx1 + dx, cy1 + dy, cz1 + dz);
int worldDmg = world.getBlockMetadata(cx1 + dx, cy1 + dy, cz1 + dz);
int dmg = block.getDamageValue(world, cx1 + dx, cy1 + dy, cz1 + dz);
boolean usesMetadataForPlacing = false;
ArrayList<ItemStack> drops = block.getDrops(world, cx1 + dx, cy1 + dy, cz1 + dz, dmg, 0);
if (drops.size() == 1) {
ItemStack dropStack = drops.get(0);
usesMetadataForPlacing = dropStack.getItem() == item && dropStack.getItemDamage() == 0 && worldDmg != 0;
}
if (player.capabilities.isCreativeMode && !world.isRemote) {
world.setBlock(x + dx + xo, y + dy + yo, z + dz + zo, block, worldDmg, 3);
} else if (player.inventory.hasItemStack(new ItemStack(item, 1, dmg))) {
int slot = slotOfItemStack(new ItemStack(item, 1, dmg), player.inventory);
if (item instanceof ItemBlock) {
if (!world.isRemote) {
((ItemBlock) item).placeBlockAt(player.inventory.getStackInSlot(slot), player, world, x + dx + xo, y + dy + yo, z + dz + zo, 0, 0, 0, 0, dmg);
if (usesMetadataForPlacing) {
world.setBlockMetadataWithNotify(x + dx + xo, y + dy + yo, z + dz + zo, worldDmg, 3);
}
}
player.inventory.decrStackSize(slot, 1);
}
}
}
zi++;
} while (zi <= cz2);
yi++;
} while (yi <= cy2);
xi++;
} while (xi <= cx2);
if (!world.isRemote) {
player.addChatComponentMessage(new ChatComponentText("Successfully pasted building"));
}
} else {
if (!world.isRemote) {
player.addChatComponentMessage(new ChatComponentText("Nothing copied"));
}
}
break;
}
}
return stack;
}
//Adapted from InventoryPlayer.hasItemStack
public int slotOfItemStack(ItemStack stack, InventoryPlayer inv) {
int i;
for (i = 0; i < inv.mainInventory.length; ++i) {
if (inv.mainInventory[i] != null && inv.mainInventory[i].isItemEqual(stack)) {
return i;
}
}
return -1;
}
@Override
public ArrayList<Object> getSpecialParameters() {
return null;
}
@Override
public String getItemName() {
return "prismaticWand";
}
@Override
public boolean shouldRegister() {
return true;
}
@Override
public boolean shouldDisplayInTab() {
return true;
}
@Override
public ThaumicTinkererRecipe getRecipeItem() {
return new CraftingBenchRecipe(new ItemStack(this), " P ", " I ", " I ", 'P', ItemMaterial.getPrism(), 'I', new ItemStack(Items.blaze_rod));
}
@Override
public void registerIcons(IIconRegister register) {
itemIcon = register.registerIcon("aura:prismaticWand");
}
@Override
public int getCreativeTabPriority() {
return -25;
}
}
|
package psidev.psi.mi.jami.model.impl;
import psidev.psi.mi.jami.model.Alias;
import psidev.psi.mi.jami.model.Annotation;
import psidev.psi.mi.jami.model.CvTerm;
import psidev.psi.mi.jami.model.Xref;
import psidev.psi.mi.jami.utils.XrefUtils;
import psidev.psi.mi.jami.utils.collection.AbstractListHavingPoperties;
import psidev.psi.mi.jami.utils.comparator.cv.UnambiguousCvTermComparator;
import psidev.psi.mi.jami.utils.factory.CvTermFactory;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
/**
* Default implementation for CvTerm
*
* @author Marine Dumousseau (marine@ebi.ac.uk)
* @version $Id$
* @since <pre>21/01/13</pre>
*/
public class DefaultCvTerm implements CvTerm, Serializable {
protected String shortName;
protected String fullName;
protected Collection<Xref> xrefs;
protected Collection<Xref> identifiers;
protected Collection<Annotation> annotations;
protected Collection<Alias> synonyms;
protected Xref miIdentifier;
protected Xref modIdentifier;
public DefaultCvTerm(String shortName){
if (shortName == null){
throw new IllegalArgumentException("The short name is required and cannot be null");
}
this.shortName = shortName;
initializeAnnotations();
initializeIdentifiers();
initializeSynonyms();
initializeXrefs();
}
public DefaultCvTerm(String shortName, String miIdentifier){
this(shortName);
setMIIdentifier(miIdentifier);
}
public DefaultCvTerm(String shortName, String fullName, String miIdentifier){
this(shortName, miIdentifier);
this.fullName = fullName;
}
public DefaultCvTerm(String shortName, Xref ontologyId){
this(shortName);
if (ontologyId != null){
this.identifiers.add(ontologyId);
}
}
public DefaultCvTerm(String shortName, String fullName, Xref ontologyId){
this(shortName, ontologyId);
this.fullName = fullName;
}
public String getShortName() {
return shortName;
}
public void setShortName(String name) {
if (name == null){
throw new IllegalArgumentException("The short name cannot be null");
}
this.shortName = name;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String name) {
this.fullName = name;
}
protected void initializeXrefs(){
this.xrefs = new ArrayList<Xref>();
}
protected void initializeAnnotations(){
this.annotations = new ArrayList<Annotation>();
}
protected void initializeSynonyms(){
this.synonyms = new ArrayList<Alias>();
}
protected void initializeIdentifiers(){
this.identifiers = new CvTermIdentifierList();
}
public Collection<Xref> getIdentifiers() {
return identifiers;
}
public String getMIIdentifier() {
return this.miIdentifier != null ? this.miIdentifier.getId() : null;
}
public String getMODIdentifier() {
return this.modIdentifier != null ? this.modIdentifier.getId() : null;
}
public void setMIIdentifier(String mi) {
// add new mi if not null
if (mi != null){
CvTerm psiMiDatabase = CvTermFactory.createPsiMiDatabase();
CvTerm identityQualifier = CvTermFactory.createIdentityQualifier();
// first remove old psi mi if not null
if (this.miIdentifier != null){
identifiers.remove(this.miIdentifier);
}
this.miIdentifier = new DefaultXref(psiMiDatabase, mi, identityQualifier);
this.identifiers.add(this.miIdentifier);
}
// remove all mi if the collection is not empty
else if (!this.identifiers.isEmpty()) {
XrefUtils.removeAllXrefsWithDatabase(identifiers, CvTerm.PSI_MI_MI, CvTerm.PSI_MI);
this.miIdentifier = null;
}
}
public void setMODIdentifier(String mod) {
// add new mod if not null
if (mod != null){
CvTerm psiModDatabase = CvTermFactory.createPsiModDatabase();
CvTerm identityQualifier = CvTermFactory.createIdentityQualifier();
// first remove old psi mod if not null
if (this.modIdentifier != null){
identifiers.remove(this.modIdentifier);
}
this.modIdentifier = new DefaultXref(psiModDatabase, mod, identityQualifier);
this.identifiers.add(this.modIdentifier);
}
// remove all mod if the collection is not empty
else if (!this.identifiers.isEmpty()) {
XrefUtils.removeAllXrefsWithDatabase(identifiers, CvTerm.PSI_MOD_MI, CvTerm.PSI_MOD);
this.modIdentifier = null;
}
}
public Collection<Xref> getXrefs() {
return this.xrefs;
}
public Collection<Annotation> getAnnotations() {
return this.annotations;
}
public Collection<Alias> getSynonyms() {
return this.synonyms;
}
@Override
public int hashCode() {
return UnambiguousCvTermComparator.hashCode(this);
}
@Override
public boolean equals(Object o) {
if (this == o){
return true;
}
if (!(o instanceof CvTerm)){
return false;
}
return UnambiguousCvTermComparator.areEquals(this, (CvTerm) o);
}
@Override
public String toString() {
return (miIdentifier != null ? miIdentifier.getId() : (modIdentifier != null ? modIdentifier.getId() : "-")) + " ("+shortName+")";
}
private class CvTermIdentifierList extends AbstractListHavingPoperties<Xref> {
public CvTermIdentifierList(){
super();
}
@Override
protected void processAddedObjectEvent(Xref added) {
// the added identifier is psi-mi and it is not the current mi identifier
if (miIdentifier != added && XrefUtils.isXrefFromDatabase(added, CvTerm.PSI_MI_MI, CvTerm.PSI_MI)){
// the current psi-mi identifier is not identity, we may want to set miIdentifier
if (!XrefUtils.doesXrefHaveQualifier(miIdentifier, Xref.IDENTITY_MI, Xref.IDENTITY)){
// the miidentifier is not set, we can set the miidentifier
if (miIdentifier == null){
miIdentifier = added;
}
else if (XrefUtils.doesXrefHaveQualifier(added, Xref.IDENTITY_MI, Xref.IDENTITY)){
miIdentifier = added;
}
// the added xref is secondary object and the current mi is not a secondary object, we reset miidentifier
else if (!XrefUtils.doesXrefHaveQualifier(miIdentifier, Xref.SECONDARY_MI, Xref.SECONDARY)
&& XrefUtils.doesXrefHaveQualifier(added, Xref.SECONDARY_MI, Xref.SECONDARY)){
miIdentifier = added;
}
}
}
// the added identifier is psi-mod and it is not the current mod identifier
else if (modIdentifier != added && XrefUtils.isXrefFromDatabase(added, CvTerm.PSI_MOD_MI, CvTerm.PSI_MOD)){
// the current psi-mod identifier is not identity, we may want to set modIdentifier
if (!XrefUtils.doesXrefHaveQualifier(modIdentifier, Xref.IDENTITY_MI, Xref.IDENTITY)){
// the modIdentifier is not set, we can set the modIdentifier
if (modIdentifier == null){
modIdentifier = added;
}
else if (XrefUtils.doesXrefHaveQualifier(added, Xref.IDENTITY_MI, Xref.IDENTITY)){
modIdentifier = added;
}
// the added xref is secondary object and the current mi is not a secondary object, we reset miidentifier
else if (!XrefUtils.doesXrefHaveQualifier(modIdentifier, Xref.SECONDARY_MI, Xref.SECONDARY)
&& XrefUtils.doesXrefHaveQualifier(added, Xref.SECONDARY_MI, Xref.SECONDARY)){
modIdentifier = added;
}
}
}
}
@Override
protected void processRemovedObjectEvent(Xref removed) {
// the removed identifier is psi-mi
if (miIdentifier == removed){
miIdentifier = XrefUtils.collectFirstIdentifierWithDatabase(this, CvTerm.PSI_MI_MI, CvTerm.PSI_MI);
}
// the removed identifier is psi-mod
else if (modIdentifier == removed){
modIdentifier = XrefUtils.collectFirstIdentifierWithDatabase(this, CvTerm.PSI_MOD_MI, CvTerm.PSI_MOD);
}
}
@Override
protected void clearProperties() {
miIdentifier = null;
modIdentifier = null;
}
}
}
|
package reborncore.common.container;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import reborncore.RebornCore;
import reborncore.api.tile.IContainerLayout;
import reborncore.client.gui.slots.BaseSlot;
import reborncore.client.gui.slots.SlotFake;
import javax.annotation.Nullable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
public abstract class RebornContainer extends Container {
private static HashMap<String, RebornContainer> containerMap = new HashMap<>();
public HashMap<Integer, BaseSlot> slotMap = new HashMap<>();
public static
@Nullable
RebornContainer getContainerFromClass(Class<? extends RebornContainer> clazz, TileEntity tileEntity) {
return createContainer(clazz, tileEntity, RebornCore.proxy.getPlayer());
}
public static RebornContainer createContainer(Class<? extends RebornContainer> clazz, TileEntity tileEntity, EntityPlayer player) {
if (player == null && containerMap.containsKey(clazz.getCanonicalName())) {
return containerMap.get(clazz.getCanonicalName());
} else {
try {
RebornContainer container = null;
for (Constructor constructor : clazz.getConstructors()) {
if (constructor.getParameterCount() == 0) {
container = clazz.newInstance();
if (container instanceof IContainerLayout) {
((IContainerLayout) container).setTile(tileEntity);
((IContainerLayout) container).addInventorySlots();
}
continue;
} else if (constructor.getParameterCount() == 2) {
Class[] paramTypes = constructor.getParameterTypes();
if (paramTypes[0].isInstance(tileEntity) && paramTypes[1] == EntityPlayer.class) {
container = clazz.getDeclaredConstructor(tileEntity.getClass(), EntityPlayer.class).newInstance(tileEntity, player);
continue;
} else if (paramTypes[0] == EntityPlayer.class && paramTypes[1].isInstance(tileEntity)) {
container = clazz.getDeclaredConstructor(EntityPlayer.class, tileEntity.getClass()).newInstance(player, tileEntity);
continue;
}
}
}
if (container == null) {
RebornCore.logHelper.error("Failed to create container for " + clazz.getName() + " bad things may happen, please report to devs");
}
containerMap.put(clazz.getCanonicalName(), container);
return container;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
return null;
}
public static boolean canStacksMerge(ItemStack stack1, ItemStack stack2) {
if (stack1.isEmpty() || stack2.isEmpty()) {
return false;
}
if (!stack1.isItemEqual(stack2)) {
return false;
}
if (!ItemStack.areItemStackTagsEqual(stack1, stack2)) {
return false;
}
return true;
}
@Override
protected Slot addSlotToContainer(Slot slotIn) {
Slot slot = super.addSlotToContainer(slotIn);
if (slot instanceof BaseSlot) {
//TODO remove player slots
slotMap.put(slot.getSlotIndex(), (BaseSlot) slot);
}
return slot;
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) {
ItemStack originalStack = ItemStack.EMPTY;
Slot slot = (Slot) inventorySlots.get(slotIndex);
int numSlots = inventorySlots.size();
if (slot != null && slot.getHasStack()) {
ItemStack stackInSlot = slot.getStack();
originalStack = stackInSlot.copy();
if (slotIndex >= numSlots - 9 * 4 && tryShiftItem(stackInSlot, numSlots)) {
// NOOP
} else if (slotIndex >= numSlots - 9 * 4 && slotIndex < numSlots - 9) {
if (!shiftItemStack(stackInSlot, numSlots - 9, numSlots)) {
return ItemStack.EMPTY;
}
} else if (slotIndex >= numSlots - 9 && slotIndex < numSlots) {
if (!shiftItemStack(stackInSlot, numSlots - 9 * 4, numSlots - 9)) {
return ItemStack.EMPTY;
}
} else if (!shiftItemStack(stackInSlot, numSlots - 9 * 4, numSlots)) {
return ItemStack.EMPTY;
}
slot.onSlotChange(stackInSlot, originalStack);
if (stackInSlot.getCount() <= 0) {
slot.putStack(ItemStack.EMPTY);
} else {
slot.onSlotChanged();
}
if (stackInSlot.getCount() == originalStack.getCount()) {
return ItemStack.EMPTY;
}
slot.onTake(player, stackInSlot);
}
return originalStack;
}
protected boolean shiftItemStack(ItemStack stackToShift, int start, int end) {
boolean changed = false;
if (stackToShift.isStackable()) {
for (int slotIndex = start; stackToShift.getCount() > 0 && slotIndex < end; slotIndex++) {
Slot slot = (Slot) inventorySlots.get(slotIndex);
ItemStack stackInSlot = slot.getStack();
if (!stackInSlot.isEmpty()&& canStacksMerge(stackInSlot, stackToShift)) {
int resultingStackSize = stackInSlot.getCount() + stackToShift.getCount();
int max = Math.min(stackToShift.getMaxStackSize(), slot.getSlotStackLimit());
if (resultingStackSize <= max) {
stackToShift.setCount(0);
stackInSlot.setCount(resultingStackSize);
slot.onSlotChanged();
changed = true;
} else if (stackInSlot.getCount() < max) {
stackToShift.setCount(-(max - stackInSlot.getCount()));
stackInSlot.setCount(max);
slot.onSlotChanged();
changed = true;
}
}
}
}
if (stackToShift.getCount() > 0) {
for (int slotIndex = start; stackToShift.getCount() > 0 && slotIndex < end; slotIndex++) {
Slot slot = (Slot) inventorySlots.get(slotIndex);
ItemStack stackInSlot = slot.getStack();
if (stackInSlot.isEmpty()) {
int max = Math.min(stackToShift.getMaxStackSize(), slot.getSlotStackLimit());
stackInSlot = stackToShift.copy();
stackInSlot.setCount(Math.min(stackToShift.getCount(), max));
stackToShift.setCount(-stackInSlot.getCount());
slot.putStack(stackInSlot);
slot.onSlotChanged();
changed = true;
}
}
}
return changed;
}
private boolean tryShiftItem(ItemStack stackToShift, int numSlots) {
for (int machineIndex = 0; machineIndex < numSlots - 9 * 4; machineIndex++) {
Slot slot = (Slot) inventorySlots.get(machineIndex);
if (slot instanceof SlotFake) {
continue;
}
if (!slot.isItemValid(stackToShift))
continue;
if (shiftItemStack(stackToShift, machineIndex, machineIndex + 1))
return true;
}
return false;
}
public void addPlayersHotbar(EntityPlayer player) {
int i;
for (i = 0; i < 9; ++i) {
this.addSlotToContainer(new Slot(player.inventory, i, 8 + i * 18, 142));
}
}
public void addPlayersInventory(EntityPlayer player) {
int i;
for (i = 0; i < 3; ++i) {
for (int j = 0; j < 9; ++j) {
this.addSlotToContainer(new Slot(player.inventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
}
}
}
public void drawPlayersInv(EntityPlayer player) {
drawPlayersInv(player, 8, 81);
// int i;
// for (i = 0; i < 3; ++i)
// for (int j = 0; j < 9; ++j)
// this.addSlotToContainer(new BaseSlot(player.inventory, j + i * 9 + 9, 8 + j * 18, 81 + i * 18));
}
public void drawPlayersHotBar(EntityPlayer player) {
drawPlayersHotBar(player, 8, 139);
// int i;
// for (i = 0; i < 9; ++i)
// this.addSlotToContainer(new BaseSlot(player.inventory, i, 8 + i * 18, 139));
}
public void drawPlayersInv(EntityPlayer player, int x, int y) {
int i;
for (i = 0; i < 3; ++i) {
for (int j = 0; j < 9; ++j) {
this.addSlotToContainer(new BaseSlot(player.inventory, j + i * 9 + 9, x + j * 18, y + i * 18));
}
}
}
public void drawPlayersHotBar(EntityPlayer player, int x, int y) {
int i;
for (i = 0; i < 9; ++i) {
this.addSlotToContainer(new BaseSlot(player.inventory, i, x + i * 18, y));
}
}
public void drawPlayersInvAndHotbar(EntityPlayer player) {
drawPlayersInv(player);
drawPlayersHotBar(player);
}
public void drawPlayersInvAndHotbar(EntityPlayer player, int x, int y) {
drawPlayersInv(player, x, y);
drawPlayersHotBar(player, x, y + 58);
}
}
|
//@@author A0138474X
package seedu.address.logic.parser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_DATE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_DESCRIPTION;
import static seedu.address.logic.parser.CliSyntax.PREFIX_FAVOURITE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_PRIORITY;
import static seedu.address.logic.parser.CliSyntax.PREFIX_START;
import static seedu.address.logic.parser.CliSyntax.PREFIX_STARTTIME;
import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG;
import static seedu.address.logic.parser.CliSyntax.PREFIX_TIME;
import static seedu.address.logic.parser.CliSyntax.PREFIX_VENUE;
import java.util.NoSuchElementException;
import java.util.Optional;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.logic.commands.AddCommand;
import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.IncorrectCommand;
/**
* Parses input arguments and creates a new AddCommand object
*/
public class AddCommandParser {
private AddCommandParser() {
}
/**
* Parses the given {@code String} of arguments in the context of the AddCommand
* and returns an AddCommand object for execution.
*/
public static Command parse(String args) {
if (args == null) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
ArgumentTokenizer argsTokenizer =
new ArgumentTokenizer(PREFIX_DATE, PREFIX_TIME, PREFIX_TAG, PREFIX_DESCRIPTION,
PREFIX_VENUE, PREFIX_PRIORITY, PREFIX_FAVOURITE, PREFIX_START, PREFIX_STARTTIME);
argsTokenizer.tokenize(args);
try {
String name = argsTokenizer.getPreamble().get();
String date = checkString(argsTokenizer.getValue(PREFIX_DATE));
String startDate = checkString(argsTokenizer.getValue(PREFIX_START));
String time = checkString(argsTokenizer.getValue(PREFIX_TIME));
String startTime = checkString(argsTokenizer.getValue(PREFIX_STARTTIME));
String tag = checkString(argsTokenizer.getValue(PREFIX_TAG));
String description = checkString(argsTokenizer.getValue(PREFIX_DESCRIPTION));
String venue = checkString(argsTokenizer.getValue(PREFIX_VENUE));
String priority = checkString(argsTokenizer.getValue(PREFIX_PRIORITY));
boolean isEvent = checkStart(startDate);
boolean isFavourite = checkPresent(argsTokenizer.getValue(PREFIX_FAVOURITE));
return new AddCommand(name, date, startDate, time, startTime, tag,
description, venue, priority, isFavourite, isEvent);
} catch (NoSuchElementException ive) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
private static boolean checkStart(String start) {
return !start.isEmpty();
}
private static boolean checkPresent(Optional<String> args) {
return args.isPresent();
}
private static String checkString(Optional<String> args) {
return args.orElse("");
}
}
|
package seedu.address.model.tasklist;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.exceptions.DuplicateDataException;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.commons.util.CollectionUtil;
import seedu.address.model.task.ReadOnlyTask;
import seedu.address.model.task.Task;
import seedu.address.model.task.UniqueTaskList.DuplicateTaskException;
import seedu.address.model.task.UniqueTaskList.TaskNotFoundException;
/**
* A list of lists that enforces no nulls and uniqueness between its elements.
*
* Supports minimal set of list operations for the app's features.
*
* @see Tag#equals(Object)
* @see CollectionUtil#elementsAreUnique(Collection)
*/
public class UniqueListList implements Iterable<TaskList> {
private final ObservableList<TaskList> internalList = FXCollections.observableArrayList();
/**
* Constructs empty ListList.
*/
public UniqueListList() {}
/**
* Creates a UniqueListList using given String lists.
* Enforces no nulls or duplicates.
*/
public UniqueListList(String... lists) throws DuplicateListException, IllegalValueException {
final List<TaskList> listList = new ArrayList<TaskList>();
for (String list : lists) {
listList.add(new TaskList(list));
}
setLists(listList);
}
/**
* Creates a UniqueListList using given lists.
* Enforces no nulls or duplicates.
*/
public UniqueListList(TaskList... lists) throws DuplicateListException {
assert !CollectionUtil.isAnyNull((Object[]) lists);
final List<TaskList> initialLists = Arrays.asList(lists);
if (!CollectionUtil.elementsAreUnique(initialLists)) {
throw new DuplicateListException();
}
internalList.addAll(initialLists);
}
/**
* Creates a UniqueListList using given lists.
* Enforces no null or duplicate elements.
*/
public UniqueListList(Collection<TaskList> lists) throws DuplicateListException {
this();
setLists(lists);
}
/**
* Creates a UniqueListList using given lists.
* Enforces no nulls.
*/
public UniqueListList(Set<TaskList> lists) {
assert !CollectionUtil.isAnyNull(lists);
internalList.addAll(lists);
}
/**
* Creates a copy of the given list.
* Insulates from changes in source.
*/
public UniqueListList(UniqueListList source) {
internalList.addAll(source.internalList); // insulate internal list from changes in argument
}
/**
* Returns all lists in this list as a Set.
* This set is mutable and change-insulated against the internal list.
*/
public Set<TaskList> toSet() {
return new HashSet<>(internalList);
}
/**
* Replaces the Tags in this list with those in the argument tag list.
*/
public void setLists(UniqueListList replacement) {
this.internalList.setAll(replacement.internalList);
}
public void setLists(Collection<TaskList> lists) throws DuplicateListException {
assert !CollectionUtil.isAnyNull(lists);
if (!CollectionUtil.elementsAreUnique(lists)) {
throw new DuplicateListException();
}
internalList.setAll(lists);
}
/**
* Ensures every tag in the argument list exists in this object.
*/
public void mergeFrom(UniqueListList from) {
final Set<TaskList> alreadyInside = this.toSet();
from.internalList.stream()
.filter(tag -> !alreadyInside.contains(tag))
.forEach(internalList::add);
}
/**
* Returns true if the list contains an equivalent Tag as the given argument.
*/
public boolean contains(TaskList toCheck) {
assert toCheck != null;
return internalList.contains(toCheck);
}
/**
* Adds a List to the list.
*
* @throws DuplicateTagException if the List to add is a duplicate of an existing List in the list.
*/
public void add(TaskList toAdd) throws DuplicateListException {
assert toAdd != null;
if (contains(toAdd)) {
throw new DuplicateListException();
}
internalList.add(toAdd);
}
/**
* Updates the list in the list at position {@code index} with {@code editedTask}.
*
* @throws DuplicateTaskException if updating the list's details causes the list to be equivalent to
* another existing list in the list.
* @throws IndexOutOfBoundsException if {@code index} < 0 or >= the size of the list.
*/
public void updateList(int index, TaskList editedList) throws DuplicateListException {
assert editedList != null;
TaskList listToUpdate = internalList.get(index);
if (!listToUpdate.equals(editedList) && internalList.contains(editedList)) {
throw new DuplicateListException();
}
listToUpdate.resetData(editedList);
// TODO: The code below is just a workaround to notify observers of the updated task.
// The right way is to implement observable properties in the Task class.
// Then, TaskCard should then bind its text labels to those observable properties.
internalList.set(index, listToUpdate);
}
/**
* Removes the equivalent lsit from the list.
*
* @throws TaskNotFoundException if no such task could be found in the list.
*/
public boolean remove(TaskList toRemove) throws ListNotFoundException {
assert toRemove != null;
final boolean listFoundAndDeleted = internalList.remove(toRemove);
if (!listFoundAndDeleted) {
throw new ListNotFoundException();
}
return listFoundAndDeleted;
}
@Override
public Iterator<TaskList> iterator() {
return internalList.iterator();
}
public UnmodifiableObservableList<TaskList> asObservableList() {
return new UnmodifiableObservableList<>(internalList);
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof UniqueListList // instanceof handles nulls
&& this.internalList.equals(
((UniqueListList) other).internalList));
}
public boolean equalsOrderInsensitive(UniqueListList other) {
return this == other || new HashSet<>(this.internalList).equals(new HashSet<>(other.internalList));
}
@Override
public int hashCode() {
return internalList.hashCode();
}
/**
* Signals that an operation would have violated the 'no duplicates' property of the list.
*/
public static class DuplicateListException extends DuplicateDataException {
protected DuplicateListException() {
super("Operation would result in duplicate lists");
}
}
public static class ListNotFoundException extends Exception{
public ListNotFoundException() {
super("The list requested is not found");
}
}
}
|
package seedu.emeraldo.logic.commands;
import java.io.IOException;
import seedu.emeraldo.commons.core.Config;
import seedu.emeraldo.commons.core.EventsCenter;
import seedu.emeraldo.commons.events.storage.SaveLocationChangedEvent;
import seedu.emeraldo.commons.util.ConfigUtil;
import seedu.emeraldo.storage.StorageManager;
public class SaveToCommand extends Command{
public static final String COMMAND_WORD = "saveto";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Changes the location of the xml data file"
+ "Parameters: filepath"
+ "Example: " + COMMAND_WORD
+ " C:/emeraldo_task/";
public static final String MESSAGE_SUCCESS = "Save location changed";
public static final String MESSAGE_ERROR = "Failed to change save location";
public static final String FILE_NAME = "emeraldo.xml";
public static final String DEFAULT_LOCATION = "data/";
private String filepath;
public SaveToCommand(String filepath){
this.filepath = filepath;
}
public CommandResult execute() {
/*
TO-DO:
change filepath in XmlEmeraldoStorage
change filepath in Config.java
indicateEmeraldoSaveLocationChanged()
*/
try {
filepath = filepath + FILE_NAME;
Config config = new Config();
config.setEmeraldoFilePath(filepath);
ConfigUtil.saveConfig(config, Config.DEFAULT_CONFIG_FILE);
EventsCenter.getInstance().post(new SaveLocationChangedEvent(filepath));
return new CommandResult(MESSAGE_SUCCESS);
} catch (IOException e) {
return new CommandResult(MESSAGE_SUCCESS);
}
}
}
|
package org.codehaus.groovy.runtime;
import groovy.lang.Closure;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import groovy.lang.PropertyValue;
import groovy.lang.MetaProperty;
import groovy.lang.Range;
import groovy.lang.StringWriterIOException;
import groovy.lang.Writable;
import groovy.util.CharsetToolkit;
import groovy.util.ClosureComparator;
import groovy.util.OrderBy;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.MalformedURLException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class defines all the new groovy methods which appear on normal JDK
* classes inside the Groovy environment. Static methods are used with the
* first parameter the destination class.
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @author Sam Pullara
* @author Rod Cope
* @author Guillaume Laforge
* @author John Wilson
* @version $Revision$
*/
public class DefaultGroovyMethods {
private static Logger log = Logger.getLogger(DefaultGroovyMethods.class.getName());
private static final Integer ONE = new Integer(1);
private static final char ZERO_CHAR = '\u0000';
/**
* Allows the subscript operator to be used to lookup dynamic property values.
* <code>bean[somePropertyNameExpression]</code>. The normal property notation
* of groovy is neater and more concise but only works with compile time known
* property names.
*
* @param self
* @return
*/
public static Object getAt(Object self, String property) {
return InvokerHelper.getProperty(self, property);
}
/**
* Allows the subscript operator to be used to set dynamically named property values.
* <code>bean[somePropertyNameExpression] = foo</code>. The normal property notation
* of groovy is neater and more concise but only works with compile time known
* property names.
*
* @param self
*/
public static void putAt(Object self, String property, Object newValue) {
InvokerHelper.setProperty(self, property, newValue);
}
/**
* Generates a detailed dump string of an object showing its class,
* hashCode and fields
*/
public static String dump(Object self) {
if (self == null) {
return "null";
}
StringBuffer buffer = new StringBuffer("<");
Class klass = self.getClass();
buffer.append(klass.getName());
buffer.append("@");
buffer.append(Integer.toHexString(self.hashCode()));
boolean groovyObject = self instanceof GroovyObject;
/*jes this may be rewritten to use the new allProperties() stuff
* but the original pulls out private variables, whereas allProperties()
* does not. What's the real use of dump() here?
*/
while (klass != null) {
Field[] fields = klass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
final Field field = fields[i];
if ((field.getModifiers() & Modifier.STATIC) == 0) {
if (groovyObject && field.getName().equals("metaClass")) {
continue;
}
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
field.setAccessible(true);
return null;
}
});
buffer.append(" ");
buffer.append(field.getName());
buffer.append("=");
try {
buffer.append(InvokerHelper.toString(field.get(self)));
}
catch (Exception e) {
buffer.append(e);
}
}
}
klass = klass.getSuperclass();
}
/* here is a different implementation that uses allProperties(). I have left
* it commented out because it returns a slightly different list of properties;
* ie it does not return privates. I don't know what dump() really should be doing,
* although IMO showing private fields is a no-no
*/
/*
List props = allProperties(self);
for(Iterator itr = props.iterator(); itr.hasNext(); ) {
PropertyValue pv = (PropertyValue) itr.next();
// the original skipped this, so I will too
if(pv.getName().equals("metaClass")) continue;
if(pv.getName().equals("class")) continue;
buffer.append(" ");
buffer.append(pv.getName());
buffer.append("=");
try {
buffer.append(InvokerHelper.toString(pv.getValue()));
}
catch (Exception e) {
buffer.append(e);
}
}
*/
buffer.append(">");
return buffer.toString();
}
public static void eachPropertyName(Object self, Closure closure) {
List props = allProperties(self);
for(Iterator itr = props.iterator(); itr.hasNext(); ) {
PropertyValue pv = (PropertyValue) itr.next();
closure.call(pv.getName());
}
}
public static void eachProperty(Object self, Closure closure) {
List props = allProperties(self);
for(Iterator itr = props.iterator(); itr.hasNext(); ) {
PropertyValue pv = (PropertyValue) itr.next();
closure.call(pv);
}
}
public static List allProperties(Object self) {
List props = new ArrayList();
MetaClass metaClass = InvokerHelper.getMetaClass(self);
List mps;
if(self instanceof groovy.util.Expando) {
mps = ((groovy.util.Expando) self).getProperties();
}
else {
// get the MetaProperty list from the MetaClass
mps = metaClass.getProperties();
}
for(Iterator itr = mps.iterator(); itr.hasNext();) {
MetaProperty mp = (MetaProperty) itr.next();
PropertyValue pv = new PropertyValue(self, mp);
props.add(pv);
}
return props;
}
/**
* Scoped use method
*
*/
public static void use(Object self, Class categoryClass, Closure closure) {
GroovyCategorySupport.use(categoryClass, closure);
}
/**
* Scoped use method with list of categories
*
*/
public static void use(Object self, List categoryClassList, Closure closure) {
GroovyCategorySupport.use(categoryClassList, closure);
}
/**
* Print to a console in interactive format
*/
public static void print(Object self, Object value) {
System.out.print(InvokerHelper.toString(value));
}
/**
* Print to a console in interactive format along with a newline
*/
public static void println(Object self, Object value) {
System.out.println(InvokerHelper.toString(value));
}
/**
* @return a String that matches what would be typed into a terminal to
* create this object. e.g. [1, 'hello'].inspect() -> [1, "hello"]
*/
public static String inspect(Object self) {
return InvokerHelper.inspect(self);
}
/**
* Print to a console in interactive format
*/
public static void print(Object self, PrintWriter out) {
if (out == null) {
out = new PrintWriter(System.out);
}
out.print(InvokerHelper.toString(self));
}
/**
* Print to a console in interactive format
*
* @param out the PrintWriter used for printing
*/
public static void println(Object self, PrintWriter out) {
if (out == null) {
out = new PrintWriter(System.out);
}
InvokerHelper.invokeMethod(self, "print", out);
out.println();
}
/**
* Provide a dynamic method invocation method which can be overloaded in
* classes to implement dynamic proxies easily.
*/
public static Object invokeMethod(Object object, String method, Object arguments) {
return InvokerHelper.invokeMethod(object, method, arguments);
}
// isCase methods
public static boolean isCase(Object caseValue, Object switchValue) {
return caseValue.equals(switchValue);
}
public static boolean isCase(String caseValue, Object switchValue) {
if (switchValue == null) {
return caseValue == null;
}
return caseValue.equals(switchValue.toString());
}
public static boolean isCase(Class caseValue, Object switchValue) {
return caseValue.isInstance(switchValue);
}
public static boolean isCase(Collection caseValue, Object switchValue) {
return caseValue.contains(switchValue);
}
public static boolean isCase(Pattern caseValue, Object switchValue) {
Matcher matcher = caseValue.matcher(switchValue.toString());
if (matcher.matches()) {
RegexSupport.setLastMatcher(matcher);
return true;
} else {
return false;
}
}
// Collection based methods
/**
* Allows objects to be iterated through using a closure
*
* @param self the object over which we iterate
* @param closure the closure applied on each element found
*/
public static void each(Object self, Closure closure) {
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
closure.call(iter.next());
}
}
/**
* Allows object to be iterated through a closure with a counter
*
* @param self an Object
* @param closure a Closure
*/
public static void eachWithIndex(Object self, Closure closure) {
int counter = 0;
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
closure.call(new Object[] { iter.next(), new Integer(counter++) });
}
}
/**
* Allows objects to be iterated through using a closure
*
* @param self the collection over which we iterate
* @param closure the closure applied on each element of the collection
*/
public static void each(Collection self, Closure closure) {
for (Iterator iter = self.iterator(); iter.hasNext();) {
closure.call(iter.next());
}
}
/**
* Allows a Map to be iterated through using a closure. If the
* closure takes one parameter then it will be passed the Map.Entry
* otherwise if the closure takes two parameters then it will be
* passed the key and the value.
*
* @param self the map over which we iterate
* @param closure the closure applied on each entry of the map
*/
public static void each(Map self, Closure closure) {
if (closure.getParameterTypes().length == 2) {
for (Iterator iter = self.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
closure.call(new Object[] { entry.getKey(), entry.getValue()});
}
}
else {
for (Iterator iter = self.entrySet().iterator(); iter.hasNext();) {
closure.call(iter.next());
}
}
}
/**
* Iterates over every element of a collection, and check whether a predicate is valid for all elements.
*
* @param self the object over which we iterate
* @param closure the closure predicate used for matching
* @return true if every item in the collection matches the closure
* predicate
*/
public static boolean every(Object self, Closure closure) {
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
if (!InvokerHelper.asBool(closure.call(iter.next()))) {
return false;
}
}
return true;
}
/**
* Iterates over every element of a collection, and check whether a predicate is valid for at least one element
*
* @param self the object over which we iterate
* @param closure the closure predicate used for matching
* @return true if any item in the collection matches the closure predicate
*/
public static boolean any(Object self, Closure closure) {
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
if (InvokerHelper.asBool(closure.call(iter.next()))) {
return true;
}
}
return false;
}
/**
* Iterates over every element of the collection and return each object that matches
* the given filter - calling the isCase() method used by switch statements.
* This method can be used with different kinds of filters like regular expresions, classes, ranges etc.
*
* @param self the object over which we iterate
* @param filter the filter to perform on the collection (using the isCase(object) method)
* @return a list of objects which match the filter
*/
public static List grep(Object self, Object filter) {
List answer = new ArrayList();
MetaClass metaClass = InvokerHelper.getMetaClass(filter);
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
Object object = iter.next();
if (InvokerHelper.asBool(metaClass.invokeMethod(filter, "isCase", object))) {
answer.add(object);
}
}
return answer;
}
/**
* Counts the number of occurencies of the given value inside this collection
*
* @param self the collection within which we count the number of occurencies
* @param value the value
* @return the number of occurrencies
*/
public static int count(Collection self, Object value) {
int answer = 0;
for (Iterator iter = self.iterator(); iter.hasNext();) {
if (InvokerHelper.compareEqual(iter.next(), value)) {
++answer;
}
}
return answer;
}
/**
* Convert a collection to a List.
*
* @param self a collection
* @return a List
*/
public static List toList(Collection self) {
List answer = new ArrayList(self.size());
answer.addAll(self);
return answer;
}
/**
* Iterates through this object transforming each object into a new value using the closure
* as a transformer, returning a list of transformed values.
*
* @param self the values of the object to map
* @param closure the closure used to map each element of the collection
* @return a List of the mapped values
*/
public static List collect(Object self, Closure closure) {
List answer = new ArrayList();
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
answer.add(closure.call(iter.next()));
}
return answer;
}
/**
* Iterates through this collection transforming each entry into a new value using the closure
* as a transformer, returning a list of transformed values.
*
* @param self a collection
* @param closure the closure used for mapping
* @return a List of the mapped values
*/
public static List collect(Collection self, Closure closure) {
List answer = new ArrayList(self.size());
for (Iterator iter = self.iterator(); iter.hasNext();) {
answer.add(closure.call(iter.next()));
if (closure.getDirective() == Closure.DONE) {
break;
}
}
return answer;
}
/**
* Iterates through this Map transforming each entry into a new value using the closure
* as a transformer, returning a list of transformed values.
*
* @param self a Map
* @param closure the closure used for mapping
* @return a List of the mapped values
*/
public static List collect(Map self, Closure closure) {
List answer = new ArrayList(self.size());
for (Iterator iter = self.entrySet().iterator(); iter.hasNext();) {
answer.add(closure.call(iter.next()));
}
return answer;
}
/**
* Finds the first value matching the closure condition
*
* @param self an Object with an iterator returning its values
* @param closure a closure condition
* @return the first Object found
*/
public static Object find(Object self, Closure closure) {
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
Object value = iter.next();
if (InvokerHelper.asBool(closure.call(value))) {
return value;
}
}
return null;
}
/**
* Finds the first value matching the closure condition
*
* @param self a Collection
* @param closure a closure condition
* @return the first Object found
*/
public static Object find(Collection self, Closure closure) {
for (Iterator iter = self.iterator(); iter.hasNext();) {
Object value = iter.next();
if (InvokerHelper.asBool(closure.call(value))) {
return value;
}
}
return null;
}
/**
* Finds the first value matching the closure condition
*
* @param self a Map
* @param closure a closure condition
* @return the first Object found
*/
public static Object find(Map self, Closure closure) {
for (Iterator iter = self.entrySet().iterator(); iter.hasNext();) {
Object value = iter.next();
if (InvokerHelper.asBool(closure.call(value))) {
return value;
}
}
return null;
}
/**
* Finds all values matching the closure condition
*
* @param self an Object with an Iterator returning its values
* @param closure a closure condition
* @return a List of the values found
*/
public static List findAll(Object self, Closure closure) {
List answer = new ArrayList();
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
Object value = iter.next();
if (InvokerHelper.asBool(closure.call(value))) {
answer.add(value);
}
}
return answer;
}
/**
* Finds all values matching the closure condition
*
* @param self a Collection
* @param closure a closure condition
* @return a List of the values found
*/
public static List findAll(Collection self, Closure closure) {
List answer = new ArrayList(self.size());
for (Iterator iter = self.iterator(); iter.hasNext();) {
Object value = iter.next();
if (InvokerHelper.asBool(closure.call(value))) {
answer.add(value);
}
}
return answer;
}
/**
* Finds all values matching the closure condition
*
* @param self a Map
* @param closure a closure condition applying on the keys
* @return a List of keys
*/
public static List findAll(Map self, Closure closure) {
List answer = new ArrayList(self.size());
for (Iterator iter = self.entrySet().iterator(); iter.hasNext();) {
Object value = iter.next();
if (InvokerHelper.asBool(closure.call(value))) {
answer.add(value);
}
}
return answer;
}
/**
* Iterates through the given collection, passing in the initial value to
* the closure along with the current iterated item then passing into the
* next iteration the value of the previous closure.
*
* @param self a Collection
* @param value a value
* @param closure a closure
* @return the last value of the last iteration
*/
public static Object inject(Collection self, Object value, Closure closure) {
Object[] params = new Object[2];
for (Iterator iter = self.iterator(); iter.hasNext();) {
Object item = iter.next();
params[0] = value;
params[1] = item;
value = closure.call(params);
}
return value;
}
/**
* Concatenates all of the items of the collection together with the given String as a separator
*
* @param self a Collection of objects
* @param separator a String separator
* @return the joined String
*/
public static String join(Collection self, String separator) {
StringBuffer buffer = new StringBuffer();
boolean first = true;
for (Iterator iter = self.iterator(); iter.hasNext();) {
Object value = iter.next();
if (first) {
first = false;
}
else {
buffer.append(separator);
}
buffer.append(InvokerHelper.toString(value));
}
return buffer.toString();
}
/**
* Concatenates all of the elements of the array together with the given String as a separator
*
* @param self an array of Object
* @param separator a String separator
* @return the joined String
*/
public static String join(Object[] self, String separator) {
StringBuffer buffer = new StringBuffer();
boolean first = true;
for (int i = 0; i < self.length; i++) {
String value = InvokerHelper.toString(self[i]);
if (first) {
first = false;
}
else {
buffer.append(separator);
}
buffer.append(value);
}
return buffer.toString();
}
/**
* Selects the maximum value found in the collection
*
* @param self a Collection
* @return the maximum value
*/
public static Object max(Collection self) {
Object answer = null;
for (Iterator iter = self.iterator(); iter.hasNext();) {
Object value = iter.next();
if (value != null) {
if (answer == null || InvokerHelper.compareGreaterThan(value, answer)) {
answer = value;
}
}
}
return answer;
}
/**
* Selects the maximum value found in the collection using the given comparator
*
* @param self a Collection
* @param comparator a Comparator
* @return the maximum value
*/
public static Object max(Collection self, Comparator comparator) {
Object answer = null;
for (Iterator iter = self.iterator(); iter.hasNext();) {
Object value = iter.next();
if (answer == null || comparator.compare(value, answer) > 0) {
answer = value;
}
}
return answer;
}
/**
* Selects the minimum value found in the collection
*
* @param self a Collection
* @return the minimum value
*/
public static Object min(Collection self) {
Object answer = null;
for (Iterator iter = self.iterator(); iter.hasNext();) {
Object value = iter.next();
if (value != null) {
if (answer == null || InvokerHelper.compareLessThan(value, answer)) {
answer = value;
}
}
}
return answer;
}
/**
* Selects the minimum value found in the collection using the given comparator
*
* @param self a Collection
* @param comparator a Comparator
* @return the minimum value
*/
public static Object min(Collection self, Comparator comparator) {
Object answer = null;
for (Iterator iter = self.iterator(); iter.hasNext();) {
Object value = iter.next();
if (answer == null || comparator.compare(value, answer) < 0) {
answer = value;
}
}
return answer;
}
/**
* Selects the minimum value found in the collection using the given closure as a comparator
*
* @param self a Collection
* @param closure a closure used as a comparator
* @return the minimum value
*/
public static Object min(Collection self, Closure closure) {
return min(self, new ClosureComparator(closure));
}
/**
* Selects the maximum value found in the collection using the given closure as a comparator
*
* @param self a Collection
* @param closure a closure used as a comparator
* @return the maximum value
*/
public static Object max(Collection self, Closure closure) {
return max(self, new ClosureComparator(closure));
}
/**
* Makes a String look like a Collection by adding support for the size() method
*
* @param text a String
* @return the length of the String
*/
public static int size(String text) {
return text.length();
}
/**
* Makes an Array look like a Collection by adding support for the size() method
*
* @param self an Array of Object
* @return the size of the Array
*/
public static int size(Object[] self) {
return self.length;
}
/**
* Support the subscript operator for String.
*
* @param text a String
* @param index the index of the Character to get
* @return the Character at the given index
*/
public static CharSequence getAt(CharSequence text, int index) {
index = normaliseIndex(index, text.length());
return text.subSequence(index, index + 1);
}
/**
* Support the subscript operator for String
*
* @param text a String
* @return the Character object at the given index
*/
public static String getAt(String text, int index) {
index = normaliseIndex(index, text.length());
return text.substring(index, index + 1);
}
/**
* Support the range subscript operator for CharSequence
*
* @param text a CharSequence
* @param range a Range
* @return the subsequence CharSequence
*/
public static CharSequence getAt(CharSequence text, Range range) {
int from = normaliseIndex(InvokerHelper.asInt(range.getFrom()), text.length());
int to = normaliseIndex(InvokerHelper.asInt(range.getTo()), text.length());
// if this is a backwards range, reverse the arguments to substring
if (from > to) {
int tmp = from;
from = to;
to = tmp;
}
return text.subSequence(from, to + 1);
}
/**
* Support the range subscript operator for String
*
* @param text a String
* @param range a Range
* @return a substring corresponding to the Range
*/
public static String getAt(String text, Range range) {
int from = normaliseIndex(InvokerHelper.asInt(range.getFrom()), text.length());
int to = normaliseIndex(InvokerHelper.asInt(range.getTo()), text.length());
// if this is a backwards range, reverse the arguments to substring
boolean reverse = range.isReverse();
if (from > to) {
int tmp = to;
to = from;
from = tmp;
reverse = !reverse;
}
String answer = text.substring(from, to + 1);
if (reverse) {
answer = reverse(answer);
}
return answer;
}
/**
* Creates a new string which is the reverse (backwards) of this string
*
* @param self a String
* @return a new string with all the characters reversed.
*/
public static String reverse(String self) {
int size = self.length();
StringBuffer buffer = new StringBuffer(size);
for (int i = size - 1; i >= 0; i
buffer.append(self.charAt(i));
}
return buffer.toString();
}
/**
* Transforms a String representing a URL into a URL object.
*
* @param self the String representing a URL
* @return a URL
* @throws MalformedURLException is thrown if the URL is not well formed.
*/
public static URL toURL(String self) throws MalformedURLException {
return new URL(self);
}
private static String getPadding(String padding, int length) {
if (padding.length() < length) {
return multiply(padding, new Integer(length / padding.length() + 1)).substring(0, length);
} else {
return padding.substring(0, length);
}
}
/**
* Pad a String with the characters appended to the left
*
* @param numberOfChars the total number of characters
* @param padding the charaters used for padding
* @return the String padded to the left
*/
public static String padLeft(String self, Number numberOfChars, String padding) {
int numChars = numberOfChars.intValue();
if (numChars <= self.length()) {
return self;
} else {
return getPadding(padding, numChars - self.length()) + self;
}
}
/**
* Pad a String with the spaces appended to the left
*
* @param numberOfChars the total number of characters
* @return the String padded to the left
*/
public static String padLeft(String self, Number numberOfChars) {
return padLeft(self, numberOfChars, " ");
}
/**
* Pad a String with the characters appended to the right
*
* @param numberOfChars the total number of characters
* @param padding the charaters used for padding
* @return the String padded to the right
*/
public static String padRight(String self, Number numberOfChars, String padding) {
int numChars = numberOfChars.intValue();
if (numChars <= self.length()) {
return self;
}
else {
return self + getPadding(padding, numChars - self.length());
}
}
/**
* Pad a String with the spaces appended to the right
*
* @param numberOfChars the total number of characters
* @return the String padded to the right
*/
public static String padRight(String self, Number numberOfChars) {
return padRight(self, numberOfChars, " ");
}
/**
* Center a String and padd it with the characters appended around it
*
* @param numberOfChars the total number of characters
* @param padding the charaters used for padding
* @return the String centered with padded character around
*/
public static String center(String self, Number numberOfChars, String padding) {
int numChars = numberOfChars.intValue();
if (numChars <= self.length()) {
return self;
}
else {
int charsToAdd = numChars - self.length();
String semiPad = charsToAdd % 2 == 1 ?
getPadding(padding, charsToAdd / 2 + 1) :
getPadding(padding, charsToAdd / 2);
if (charsToAdd % 2 == 0)
return semiPad + self + semiPad;
else
return semiPad.substring(0, charsToAdd / 2) + self + semiPad;
}
}
/**
* Center a String and padd it with spaces appended around it
*
* @param numberOfChars the total number of characters
* @return the String centered with padded character around
*/
public static String center(String self, Number numberOfChars) {
return center(self, numberOfChars, " ");
}
/**
* Support the subscript operator for a regex Matcher
*
* @param matcher a Matcher
* @param idx an index
* @return the group at the given index
*/
public static String getAt(Matcher matcher, int idx) {
matcher.reset();
idx = normaliseIndex(idx, matcher.groupCount());
// are we using groups?
if (matcher.groupCount() > 0) {
// yes, so return the specified group
matcher.find();
return matcher.group(idx);
}
else {
// not using groups, so return the nth
// occurrence of the pattern
for (int i = 0; i <= idx; i++) {
matcher.find();
}
return matcher.group();
}
}
/**
* Support the range subscript operator for a List
*
* @param self a List
* @param range a Range
* @return a range of a list from the range's from index up to but not including the ranges's to value
*/
public static List getAt(List self, Range range) {
int size = self.size();
int from = normaliseIndex(InvokerHelper.asInt(range.getFrom()), size);
int to = normaliseIndex(InvokerHelper.asInt(range.getTo()), size);
boolean reverse = range.isReverse();
if (from > to) {
int tmp = to;
to = from;
from = tmp;
reverse = !reverse;
}
if (++to > size) {
to = size;
}
List answer = self.subList(from, to);
if (reverse) {
answer = reverse(answer);
}
return answer;
}
/**
* Allows a List to be used as the indices to be used on a List
*
* @param self a List
* @param indices a Collection of indices
* @return a new list of the values at the given indices
*/
public static List getAt(List self, Collection indices) {
List answer = new ArrayList(indices.size());
for (Iterator iter = indices.iterator(); iter.hasNext();) {
Object value = iter.next();
if (value instanceof Range) {
answer.addAll(getAt(self, (Range) value));
}
else if (value instanceof List) {
answer.addAll(getAt(self, (List) value));
}
else {
int idx = InvokerHelper.asInt(value);
answer.add(getAt(self, idx));
}
}
return answer;
}
/**
* Allows a List to be used as the indices to be used on a List
*
* @param self an Array of Objects
* @param indices a Collection of indices
* @return a new list of the values at the given indices
*/
public static List getAt(Object[] self, Collection indices) {
List answer = new ArrayList(indices.size());
for (Iterator iter = indices.iterator(); iter.hasNext();) {
Object value = iter.next();
if (value instanceof Range) {
answer.addAll(getAt(self, (Range) value));
}
else if (value instanceof Collection) {
answer.addAll(getAt(self, (Collection) value));
}
else {
int idx = InvokerHelper.asInt(value);
answer.add(getAt(self, idx));
}
}
return answer;
}
/**
* Allows a List to be used as the indices to be used on a CharSequence
*
* @param self a CharSequence
* @param indices a Collection of indices
* @return a String of the values at the given indices
*/
public static CharSequence getAt(CharSequence self, Collection indices) {
StringBuffer answer = new StringBuffer();
for (Iterator iter = indices.iterator(); iter.hasNext();) {
Object value = iter.next();
if (value instanceof Range) {
answer.append(getAt(self, (Range) value));
}
else if (value instanceof Collection) {
answer.append(getAt(self, (Collection) value));
}
else {
int idx = InvokerHelper.asInt(value);
answer.append(getAt(self, idx));
}
}
return answer.toString();
}
/**
* Allows a List to be used as the indices to be used on a String
*
* @param self a String
* @param indices a Collection of indices
* @return a String of the values at the given indices
*/
public static String getAt(String self, Collection indices) {
return (String) getAt((CharSequence) self, indices);
}
/**
* Allows a List to be used as the indices to be used on a Matcher
*
* @param self a Matcher
* @param indices a Collection of indices
* @return a String of the values at the given indices
*/
public static String getAt(Matcher self, Collection indices) {
StringBuffer answer = new StringBuffer();
for (Iterator iter = indices.iterator(); iter.hasNext();) {
Object value = iter.next();
if (value instanceof Range) {
answer.append(getAt(self, (Range) value));
}
else if (value instanceof Collection) {
answer.append(getAt(self, (Collection) value));
}
else {
int idx = InvokerHelper.asInt(value);
answer.append(getAt(self, idx));
}
}
return answer.toString();
}
/**
* Creates a sub-Map containing the given keys. This method is similar to
* List.subList() but uses keys rather than index ranges.
*
* @param map a Map
* @param keys a Collection of keys
* @return a new Map containing the given keys
*/
public static Map subMap(Map map, Collection keys) {
Map answer = new HashMap(keys.size());
for (Iterator iter = keys.iterator(); iter.hasNext();) {
Object key = iter.next();
answer.put(key, map.get(key));
}
return answer;
}
/**
* Looks up an item in a Map for the given key and returns the value - unless
* there is no entry for the given key in which case add the default value
* to the map and return that.
*
* @param map a Map
* @param key the key to lookup the value of
* @param defaultValue the value to return and add to the map for this key if
* there is no entry for the given key
* @return the value of the given key or the default value, added to the map if the
* key did not exist
*/
public static Object get(Map map, Object key, Object defaultValue) {
Object answer = map.get(key);
if (answer == null) {
answer = defaultValue;
map.put(key, answer);
}
return answer;
}
/**
* Support the range subscript operator for an Array
*
* @param array an Array of Objects
* @param range a Range
* @return a range of a list from the range's from index up to but not
* including the ranges's to value
*/
public static List getAt(Object[] array, Range range) {
List list = Arrays.asList(array);
return getAt(list, range);
}
/**
* Support the subscript operator for an Array
*
* @param array an Array of Objects
* @param idx an index
* @return the value at the given index
*/
public static Object getAt(Object[] array, int idx) {
return array[normaliseIndex(idx, array.length)];
}
/**
* Support the subscript operator for an Array
*
* @param array an Array of Objects
* @param idx an index
* @param value an Object to put at the given index
*/
public static void putAt(Object[] array, int idx, Object value) {
if(value instanceof Number) {
Class arrayComponentClass = array.getClass().getComponentType();
if(!arrayComponentClass.equals(value.getClass())) {
Object newVal = InvokerHelper.asType(value, arrayComponentClass);
array[normaliseIndex(idx, array.length)] = newVal;
return;
}
}
array[normaliseIndex(idx, array.length)] = value;
}
/**
* Allows conversion of arrays into a mutable List
*
* @param array an Array of Objects
* @return the array as a List
*/
public static List toList(Object[] array) {
int size = array.length;
List list = new ArrayList(size);
for (int i = 0; i < size; i++) {
list.add(array[i]);
}
return list;
}
/**
* Support the subscript operator for a List
*
* @param self a List
* @param idx an index
* @return the value at the given index
*/
public static Object getAt(List self, int idx) {
int size = self.size();
int i = normaliseIndex(idx, size);
if (i < size) {
return self.get(i);
}
else {
return null;
}
}
/**
* A helper method to allow lists to work with subscript operators
*
* @param self a List
* @param idx an index
* @param value the value to put at the given index
*/
public static void putAt(List self, int idx, Object value) {
int size = self.size();
idx = normaliseIndex(idx, size);
if (idx < size) {
self.set(idx, value);
}
else {
while (size < idx) {
self.add(size++, null);
}
self.add(idx, value);
}
}
/**
* Support the subscript operator for a List
*
* @param self a Map
* @param key an Object as a key for the map
* @return the value corresponding to the given key
*/
public static Object getAt(Map self, Object key) {
return self.get(key);
}
/**
* A helper method to allow lists to work with subscript operators
*
* @param self a Map
* @param key an Object as a key for the map
* @return the value corresponding to the given key
*/
public static Object putAt(Map self, Object key, Object value) {
return self.put(key, value);
}
/**
* This converts a possibly negative index to a real index into the array.
*
* @param i
* @param size
* @return
*/
protected static int normaliseIndex(int i, int size) {
int temp = i;
if (i < 0) {
i += size;
}
if (i < 0) {
throw new ArrayIndexOutOfBoundsException("Negative array index [" + temp + "] too large for array size " + size);
}
return i;
}
/**
* Support the subscript operator for List
*
* @param coll a Collection
* @param property a String
* @return a List
*/
public static List getAt(Collection coll, String property) {
List answer = new ArrayList(coll.size());
for (Iterator iter = coll.iterator(); iter.hasNext();) {
Object item = iter.next();
Object value = InvokerHelper.getProperty(item, property);
if (value instanceof Collection) {
answer.addAll((Collection) value);
}
else {
answer.add(value);
}
}
return answer;
}
/**
* A convenience method for creating an immutable map
*
* @param self a Map
* @return an immutable Map
*/
public static Map asImmutable(Map self) {
return Collections.unmodifiableMap(self);
}
/**
* A convenience method for creating an immutable sorted map
*
* @param self a SortedMap
* @return an immutable SortedMap
*/
public static SortedMap asImmutable(SortedMap self) {
return Collections.unmodifiableSortedMap(self);
}
/**
* A convenience method for creating an immutable list
*
* @param self a List
* @return an immutable List
*/
public static List asImmutable(List self) {
return Collections.unmodifiableList(self);
}
/**
* A convenience method for creating an immutable list
*
* @param self a Set
* @return an immutable Set
*/
public static Set asImmutable(Set self) {
return Collections.unmodifiableSet(self);
}
/**
* A convenience method for creating an immutable sorted set
*
* @param self a SortedSet
* @return an immutable SortedSet
*/
public static SortedSet asImmutable(SortedSet self) {
return Collections.unmodifiableSortedSet(self);
}
/**
* A convenience method for creating a synchronized Map
*
* @param self a Map
* @return a synchronized Map
*/
public static Map asSynchronized(Map self) {
return Collections.synchronizedMap(self);
}
/**
* A convenience method for creating a synchronized SortedMap
*
* @param self a SortedMap
* @return a synchronized SortedMap
*/
public static SortedMap asSynchronized(SortedMap self) {
return Collections.synchronizedSortedMap(self);
}
/**
* A convenience method for creating a synchronized Collection
*
* @param self a Collection
* @return a synchronized Collection
*/
public static Collection asSynchronized(Collection self) {
return Collections.synchronizedCollection(self);
}
/**
* A convenience method for creating a synchronized List
*
* @param self a List
* @return a synchronized List
*/
public static List asSynchronized(List self) {
return Collections.synchronizedList(self);
}
/**
* A convenience method for creating a synchronized Set
*
* @param self a Set
* @return a synchronized Set
*/
public static Set asSynchronized(Set self) {
return Collections.synchronizedSet(self);
}
/**
* A convenience method for creating a synchronized SortedSet
*
* @param self a SortedSet
* @return a synchronized SortedSet
*/
public static SortedSet asSynchronized(SortedSet self) {
return Collections.synchronizedSortedSet(self);
}
/**
* Sorts the given collection into a sorted list
*
* @param self the collection to be sorted
* @return the sorted collection as a List
*/
public static List sort(Collection self) {
List answer = asList(self);
Collections.sort(answer);
return answer;
}
/**
* Avoids doing unnecessary work when sorting an already sorted set
*
* @param self
* @return the sorted set
*/
public static SortedSet sort(SortedSet self) {
return self;
}
/**
* A convenience method for sorting a List
*
* @param self a List to be sorted
* @return the sorted List
*/
public static List sort(List self) {
Collections.sort(self);
return self;
}
/**
* Removes the last item from the List. Using add() and pop()
* is similar to push and pop on a Stack.
*
* @param self a List
* @return the item removed from the List
* @throws UnsupportedOperationException if the list is empty and you try to pop() it.
*/
public static Object pop(List self) {
if (self.isEmpty()) {
throw new UnsupportedOperationException("Cannot pop() an empty List");
}
return self.remove(self.size() - 1);
}
/**
* A convenience method for sorting a List with a specific comparator
*
* @param self a List
* @param comparator a Comparator used for the comparison
* @return a sorted List
*/
public static List sort(List self, Comparator comparator) {
Collections.sort(self, comparator);
return self;
}
/**
* A convenience method for sorting a Collection with a specific comparator
*
* @param self a collection to be sorted
* @param comparator a Comparator used for the comparison
* @return a newly created sorted List
*/
public static List sort(Collection self, Comparator comparator) {
return sort(asList(self), comparator);
}
/**
* A convenience method for sorting a List using a closure as a comparator
*
* @param self a List
* @param closure a Closure used as a comparator
* @return a sorted List
*/
public static List sort(List self, Closure closure) {
// use a comparator of one item or two
Class[] params = closure.getParameterTypes();
if (params.length == 1) {
Collections.sort(self, new OrderBy(closure));
}
else {
Collections.sort(self, new ClosureComparator(closure));
}
return self;
}
/**
* A convenience method for sorting a Collection using a closure as a comparator
*
* @param self a Collection to be sorted
* @param closure a Closure used as a comparator
* @return a newly created sorted List
*/
public static List sort(Collection self, Closure closure) {
return sort(asList(self), closure);
}
/**
* Converts the given collection into a List
*
* @param self a collection to be converted into a List
* @return a newly created List if this collection is not already a List
*/
public static List asList(Collection self) {
if (self instanceof List) {
return (List) self;
}
else {
return new ArrayList(self);
}
}
/**
* Reverses the list
*
* @param self a List
* @return a reversed List
*/
public static List reverse(List self) {
int size = self.size();
List answer = new ArrayList(size);
ListIterator iter = self.listIterator(size);
while (iter.hasPrevious()) {
answer.add(iter.previous());
}
return answer;
}
/**
* Create a List as a union of both Collections
*
* @param left the left Collection
* @param right the right Collection
* @return a List
*/
public static List plus(Collection left, Collection right) {
List answer = new ArrayList(left.size() + right.size());
answer.addAll(left);
answer.addAll(right);
return answer;
}
/**
* Create a List as a union of a Collection and an Object
*
* @param left a Collection
* @param right an object to append
* @return a List
*/
public static List plus(Collection left, Object right) {
List answer = new ArrayList(left.size() + 1);
answer.addAll(left);
answer.add(right);
return answer;
}
/**
* Create a List composed of the same elements repeated a certain number of times.
*
* @param self a Collection
* @param factor the number of times to append
* @return a List
*/
public static List multiply(Collection self, Number factor) {
int size = factor.intValue();
List answer = new ArrayList(self.size() * size);
for (int i = 0; i < size; i++) {
answer.addAll(self);
}
return answer;
}
/**
* Create a List composed of the intersection of both collections
*
* @param left a List
* @param right a Collection
* @return a List as an intersection of both collections
*/
public static List intersect(List left, Collection right) {
if (left.size() == 0)
return new ArrayList();
boolean nlgnSort = sameType(new Collection[] { left, right });
ArrayList result = new ArrayList();
//creates the collection to look for values.
Collection pickFrom = nlgnSort ? (Collection) new TreeSet(left) : left;
for (Iterator iter = right.iterator(); iter.hasNext();) {
final Object o = iter.next();
if (pickFrom.contains(o))
result.add(o);
}
return result;
}
/**
* Create a List composed of the elements of the first list minus the elements of the collection
*
* @param self a List
* @param removeMe a Collection of elements to remove
* @return a List with the common elements removed
*/
public static List minus(List self, Collection removeMe) {
if (self.size() == 0)
return new ArrayList();
boolean nlgnSort = sameType(new Collection[] { self, removeMe });
//we can't use the same tactic as for intersection
//since AbstractCollection only does a remove on the first
//element it encounter.
if (nlgnSort) {
//n*log(n) version
Set answer = new TreeSet(self);
answer.removeAll(removeMe);
return new ArrayList(answer);
}
else {
//n*n version
List tmpAnswer = new LinkedList(self);
for (Iterator iter = tmpAnswer.iterator(); iter.hasNext();) {
Object element = iter.next();
//boolean removeElement = false;
for (Iterator iterator = removeMe.iterator(); iterator.hasNext();) {
if (element.equals(iterator.next())) {
iter.remove();
}
}
}
//remove duplicates
//can't use treeset since the base classes are different
List answer = new LinkedList();
Object[] array = tmpAnswer.toArray(new Object[tmpAnswer.size()]);
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
for (int j = i + 1; j < array.length; j++) {
if (array[i].equals(array[j])) {
array[j] = null;
}
}
answer.add(array[i]);
}
}
return new ArrayList(answer);
}
}
/**
* Flatten a list
*
* @param self a List
* @return a flattened List
*/
public static List flatten(List self) {
return new ArrayList(flatten(self, new LinkedList()));
}
/**
* Iterate over each element of the list in the reverse order.
*
* @param self a List
* @param closure a closure
*/
public static void reverseEach(List self, Closure closure) {
List reversed = reverse(self);
for (Iterator iter = reversed.iterator(); iter.hasNext();) {
closure.call(iter.next());
}
}
private static List flatten(Collection elements, List addTo) {
Iterator iter = elements.iterator();
while (iter.hasNext()) {
Object element = iter.next();
if (element instanceof Collection) {
flatten((Collection) element, addTo);
}
else if (element instanceof Map) {
flatten(((Map) element).values(), addTo);
}
else {
addTo.add(element);
}
}
return addTo;
}
/**
* Overloads the left shift operator to provide an easy way to append objects to a list
*
* @param self a Collection
* @param value an Object to be added to the collection.
* @return a Collection with an Object added to it.
*/
public static Collection leftShift(Collection self, Object value) {
self.add(value);
return self;
}
/**
* Overloads the left shift operator to provide an easy way to append multiple
* objects as string representations to a String
*
* @param self a String
* @param value an Obect
* @return a StringWriter
*/
public static StringWriter leftShift(String self, Object value) {
StringWriter answer = createStringWriter(self);
try {
leftShift(answer, value);
}
catch (IOException e) {
throw new StringWriterIOException(e);
}
return answer;
}
protected static StringWriter createStringWriter(String self) {
StringWriter answer = new StringWriter();
answer.write(self);
return answer;
}
protected static StringBufferWriter createStringBufferWriter(StringBuffer self) {
return new StringBufferWriter(self);
}
/**
* Overloads the left shift operator to provide an easy way to append multiple
* objects as string representations to a StringBuffer
*
* @param self a StringBuffer
* @param value a value to append
* @return a StringWriter
*/
public static Writer leftShift(StringBuffer self, Object value) {
StringBufferWriter answer = createStringBufferWriter(self);
try {
leftShift(answer, value);
}
catch (IOException e) {
throw new StringWriterIOException(e);
}
return answer;
}
/**
* Overloads the left shift operator to provide an append mechanism to add things to a writer
*
* @param self a Writer
* @param value a value to append
* @return a StringWriter
*/
public static Writer leftShift(Writer self, Object value) throws IOException {
InvokerHelper.write(self, value);
return self;
}
/**
* Implementation of the left shift operator for integral types. Non integral
* Number types throw UnsupportedOperationException.
*/
public static Number leftShift(Number left, Number right) {
return NumberMath.leftShift(left, right);
}
/**
* Implementation of the right shift operator for integral types. Non integral
* Number types throw UnsupportedOperationException.
*/
public static Number rightShift(Number left, Number right) {
return NumberMath.rightShift(left, right);
}
/**
* Implementation of the right shift (unsigned) operator for integral types. Non integral
* Number types throw UnsupportedOperationException.
*/
public static Number rightShiftUnsigned(Number left, Number right) {
return NumberMath.rightShiftUnsigned(left, right);
}
/**
* A helper method so that dynamic dispatch of the writer.write(object) method
* will always use the more efficient Writable.writeTo(writer) mechanism if the
* object implements the Writable interface.
*
* @param self a Writer
* @param writable an object implementing the Writable interface
*/
public static void write(Writer self, Writable writable) throws IOException {
writable.writeTo(self);
}
/**
* Overloads the left shift operator to provide an append mechanism to add things to a stream
*
* @param self an OutputStream
* @param value a value to append
* @return a Writer
*/
public static Writer leftShift(OutputStream self, Object value) throws IOException {
OutputStreamWriter writer = new FlushingStreamWriter(self);
leftShift(writer, value);
return writer;
}
private static boolean sameType(Collection[] cols) {
List all = new LinkedList();
for (int i = 0; i < cols.length; i++) {
all.addAll(cols[i]);
}
if (all.size() == 0)
return true;
Object first = all.get(0);
//trying to determine the base class of the collections
//special case for Numbers
Class baseClass;
if (first instanceof Number) {
baseClass = Number.class;
}
else {
baseClass = first.getClass();
}
for (int i = 0; i < cols.length; i++) {
for (Iterator iter = cols[i].iterator(); iter.hasNext();) {
if (!baseClass.isInstance(iter.next())) {
return false;
}
}
}
return true;
}
// Primitive type array methods
public static Object getAt(byte[] array, int idx) {
return primitiveArrayGet(array, idx);
}
public static Object getAt(char[] array, int idx) {
return primitiveArrayGet(array, idx);
}
public static Object getAt(short[] array, int idx) {
return primitiveArrayGet(array, idx);
}
public static Object getAt(int[] array, int idx) {
return primitiveArrayGet(array, idx);
}
public static Object getAt(long[] array, int idx) {
return primitiveArrayGet(array, idx);
}
public static Object getAt(float[] array, int idx) {
return primitiveArrayGet(array, idx);
}
public static Object getAt(double[] array, int idx) {
return primitiveArrayGet(array, idx);
}
public static Object getAt(byte[] array, Range range) {
return primitiveArrayGet(array, range);
}
public static Object getAt(char[] array, Range range) {
return primitiveArrayGet(array, range);
}
public static Object getAt(short[] array, Range range) {
return primitiveArrayGet(array, range);
}
public static Object getAt(int[] array, Range range) {
return primitiveArrayGet(array, range);
}
public static Object getAt(long[] array, Range range) {
return primitiveArrayGet(array, range);
}
public static Object getAt(float[] array, Range range) {
return primitiveArrayGet(array, range);
}
public static Object getAt(double[] array, Range range) {
return primitiveArrayGet(array, range);
}
public static Object getAt(byte[] array, Collection indices) {
return primitiveArrayGet(array, indices);
}
public static Object getAt(char[] array, Collection indices) {
return primitiveArrayGet(array, indices);
}
public static Object getAt(short[] array, Collection indices) {
return primitiveArrayGet(array, indices);
}
public static Object getAt(int[] array, Collection indices) {
return primitiveArrayGet(array, indices);
}
public static Object getAt(long[] array, Collection indices) {
return primitiveArrayGet(array, indices);
}
public static Object getAt(float[] array, Collection indices) {
return primitiveArrayGet(array, indices);
}
public static Object getAt(double[] array, Collection indices) {
return primitiveArrayGet(array, indices);
}
public static void putAt(byte[] array, int idx, Object newValue) {
primitiveArrayPut(array, idx, newValue);
}
public static void putAt(char[] array, int idx, Object newValue) {
primitiveArrayPut(array, idx, newValue);
}
public static void putAt(short[] array, int idx, Object newValue) {
primitiveArrayPut(array, idx, newValue);
}
public static void putAt(int[] array, int idx, Object newValue) {
primitiveArrayPut(array, idx, newValue);
}
public static void putAt(long[] array, int idx, Object newValue) {
primitiveArrayPut(array, idx, newValue);
}
public static void putAt(float[] array, int idx, Object newValue) {
primitiveArrayPut(array, idx, newValue);
}
public static void putAt(double[] array, int idx, Object newValue) {
primitiveArrayPut(array, idx, newValue);
}
public static int size(byte[] array) {
return Array.getLength(array);
}
public static int size(char[] array) {
return Array.getLength(array);
}
public static int size(short[] array) {
return Array.getLength(array);
}
public static int size(int[] array) {
return Array.getLength(array);
}
public static int size(long[] array) {
return Array.getLength(array);
}
public static int size(float[] array) {
return Array.getLength(array);
}
public static int size(double[] array) {
return Array.getLength(array);
}
public static List toList(byte[] array) {
return InvokerHelper.primitiveArrayToList(array);
}
public static List toList(char[] array) {
return InvokerHelper.primitiveArrayToList(array);
}
public static List toList(short[] array) {
return InvokerHelper.primitiveArrayToList(array);
}
public static List toList(int[] array) {
return InvokerHelper.primitiveArrayToList(array);
}
public static List toList(long[] array) {
return InvokerHelper.primitiveArrayToList(array);
}
public static List toList(float[] array) {
return InvokerHelper.primitiveArrayToList(array);
}
public static List toList(double[] array) {
return InvokerHelper.primitiveArrayToList(array);
}
private static final char[] tTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();
public static Writable encodeBase64(final Byte[] data) {
return encodeBase64(InvokerHelper.convertToByteArray(data));
}
/**
* Produce a Writable object which writes the base64 encoding of the byte array
* Calling toString() on the result rerurns the encoding as a String
*
* @param data byte array to be encoded
* @return object which will write the base64 encoding of the byte array
*/
public static Writable encodeBase64(final byte[] data) {
return new Writable() {
public Writer writeTo(final Writer writer) throws IOException {
int charCount = 0;
final int dLimit = (data.length / 3) * 3;
for (int dIndex = 0; dIndex != dLimit; dIndex += 3) {
int d = ((data[dIndex] & 0XFF) << 16) | ((data[dIndex + 1] & 0XFF) << 8) | (data[dIndex + 2] & 0XFF);
writer.write(tTable[d >> 18]);
writer.write(tTable[(d >> 12) & 0X3F]);
writer.write(tTable[(d >> 6) & 0X3F]);
writer.write(tTable[d & 0X3F]);
if (++charCount == 18) {
writer.write('\n');
charCount = 0;
}
}
if (dLimit != data.length) {
int d = (data[dLimit] & 0XFF) << 16;
if (dLimit + 1 != data.length) {
d |= (data[dLimit + 1] & 0XFF) << 8;
}
writer.write(tTable[d >> 18]);
writer.write(tTable[(d >> 12) & 0X3F]);
writer.write((dLimit + 1 < data.length) ? tTable[(d >> 6) & 0X3F] : '=');
writer.write('=');
}
return writer;
}
public String toString() {
StringWriter buffer = new StringWriter();
try {
writeTo(buffer);
}
catch (IOException e) {
throw new RuntimeException(e); // TODO: change this exception type
}
return buffer.toString();
}
};
}
private static final byte[] translateTable = (
"\u0042\u0042\u0042\u0042\u0042\u0042\u0042\u0042"
// \t \n \r
+ "\u0042\u0042\u0041\u0041\u0042\u0042\u0041\u0042"
+ "\u0042\u0042\u0042\u0042\u0042\u0042\u0042\u0042"
+ "\u0042\u0042\u0042\u0042\u0042\u0042\u0042\u0042"
// sp ! "
+ "\u0041\u0042\u0042\u0042\u0042\u0042\u0042\u0042"
+ "\u0042\u0042\u0042\u003E\u0042\u0042\u0042\u003F"
// 0 1 2 3 4 5 6 7
+ "\u0034\u0035\u0036\u0037\u0038\u0039\u003A\u003B"
// 8 9 : ; < = > ?
+ "\u003C\u003D\u0042\u0042\u0042\u0040\u0042\u0042"
// @ A B C D E F G
+ "\u0042\u0000\u0001\u0002\u0003\u0004\u0005\u0006"
// H I J K L M N O
+ "\u0007\u0008\t\n\u000B\u000C\r\u000E"
// P Q R S T U V W
+ "\u000F\u0010\u0011\u0012\u0013\u0014\u0015\u0016"
// X Y Z [ \ ] ^ _
+ "\u0017\u0018\u0019\u0042\u0042\u0042\u0042\u0042"
// ' a b c d e f g
+ "\u0042\u001A\u001B\u001C\u001D\u001E\u001F\u0020"
// h i j k l m n o p
+ "\u0021\"\u0023\u0024\u0025\u0026\u0027\u0028"
// p q r s t u v w
+ "\u0029\u002A\u002B\u002C\u002D\u002E\u002F\u0030"
// x y z
+ "\u0031\u0032\u0033").getBytes();
/**
*
* Decode the Sting from base64 into a byte array
*
* @param value the string to be decoded
* @return the decoded bytes as an array
*/
public static byte[] decodeBase64(final String value) {
int byteShift = 4;
int tmp = 0;
boolean done = false;
final StringBuffer buffer = new StringBuffer();
for (int i = 0; i != value.length(); i++) {
final char c = value.charAt(i);
final int sixBit = (c < 123) ? translateTable[c] : 66;
if (sixBit < 64) {
if (done) throw new RuntimeException("= character not at end of base64 value"); // TODO: change this exception type
tmp = (tmp << 6) | sixBit;
if (byteShift
buffer.append((char)((tmp >> (byteShift * 2)) & 0XFF));
}
} else if (sixBit == 64) {
byteShift
done = true;
} else if (sixBit == 66) {
// RFC 2045 says that I'm allowed to take the presence of
// these characters as evedence of data corruption
// So I will
throw new RuntimeException("bad character in base64 value"); // TODO: change this exception type
}
if (byteShift == 0) byteShift = 4;
}
try {
return buffer.toString().getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Base 64 decode produced byte values > 255"); // TODO: change this exception type
}
}
/**
* Implements the getAt(int) method for primitve type arrays
*/
protected static Object primitiveArrayGet(Object array, int idx) {
return Array.get(array, normaliseIndex(idx, Array.getLength(array)));
}
/**
* Implements the getAt(Range) method for primitve type arrays
*/
protected static List primitiveArrayGet(Object array, Range range) {
List answer = new ArrayList();
for (Iterator iter = range.iterator(); iter.hasNext();) {
int idx = InvokerHelper.asInt(iter.next());
answer.add(primitiveArrayGet(array, idx));
}
return answer;
}
/**
* Implements the getAt(Collection) method for primitve type arrays
*/
protected static List primitiveArrayGet(Object self, Collection indices) {
List answer = new ArrayList();
for (Iterator iter = indices.iterator(); iter.hasNext();) {
Object value = iter.next();
if (value instanceof Range) {
answer.addAll(primitiveArrayGet(self, (Range) value));
}
else if (value instanceof List) {
answer.addAll(primitiveArrayGet(self, (List) value));
}
else {
int idx = InvokerHelper.asInt(value);
answer.add(primitiveArrayGet(self, idx));
}
}
return answer;
}
/**
* Implements the set(int idx) method for primitve type arrays
*/
protected static void primitiveArrayPut(Object array, int idx, Object newValue) {
Array.set(array, normaliseIndex(idx, Array.getLength(array)), newValue);
}
// String methods
/**
* Converts the given string into a Character object
* using the first character in the string
*
* @param self a String
* @return the first Character
*/
public static Character toCharacter(String self) {
/** @todo use cache? */
return new Character(self.charAt(0));
}
/**
* Tokenize a String
*
* @param self a String
* @param token the delimiter
* @return a List of tokens
*/
public static List tokenize(String self, String token) {
return InvokerHelper.asList(new StringTokenizer(self, token));
}
/**
* Tokenize a String (with a whitespace as delimiter)
*
* @param self a String
* @return a List of tokens
*/
public static List tokenize(String self) {
return InvokerHelper.asList(new StringTokenizer(self));
}
/**
* Appends a String
*
* @param left a String
* @param value a String
* @return a String
*/
public static String plus(String left, Object value) {
//return left + value;
return left + toString(value);
}
/**
* Appends a String
*
* @param value a Number
* @param right a String
* @return a String
*/
public static String plus(Number value, String right) {
return toString(value) + right;
}
/**
* Remove a part of a String
*
* @param left a String
* @param value a String part to remove
* @return a String minus the part to be removed
*/
public static String minus(String left, Object value) {
String text = toString(value);
return left.replaceFirst(text, "");
}
/**
* Provide an implementation of contains() like Collection to make Strings more polymorphic
* This method is not required on JDK 1.5 onwards
*
* @param self a String
* @param text a String to look for
* @return true if this string contains the given text
*/
public static boolean contains(String self, String text) {
int idx = self.indexOf(text);
return idx >= 0;
}
/**
* Count the number of occurencies of a substring
*
* @param self a String
* @param text a substring
* @return the number of occurrencies of the given string inside this String
*/
public static int count(String self, String text) {
int answer = 0;
for (int idx = 0; true; idx++) {
idx = self.indexOf(text, idx);
if (idx >= 0) {
++answer;
}
else {
break;
}
}
return answer;
}
/**
* Increments the last digit in the given string, resetting
* it and moving onto the next digit if increasing the digit
* no longer becomes a letter or digit.
*
* @param self a String
* @return a String with an incremented digit at the end
*/
public static String next(String self) {
StringBuffer buffer = new StringBuffer(self);
char firstCh = firstCharacter();
for (int idx = buffer.length() - 1; idx >= 0; idx
char ch = next(buffer.charAt(idx));
if (ch != ZERO_CHAR) {
buffer.setCharAt(idx, ch);
break;
}
else {
// lets find the first char
if (idx == 0) {
buffer.append("1");
}
else {
buffer.setCharAt(idx, firstCh);
}
}
}
return buffer.toString();
}
/**
* Decrements the last digit in the given string, resetting
* it and moving onto the next digit if increasing the digit
* no longer becomes a letter or digit.
*
* @param self a String
* @return a String with a decremented digit at the end
*/
public static String previous(String self) {
StringBuffer buffer = new StringBuffer(self);
char lastCh = lastCharacter();
for (int idx = buffer.length() - 1; idx >= 0; idx
char ch = previous(buffer.charAt(idx));
if (ch != ZERO_CHAR) {
buffer.setCharAt(idx, ch);
break;
}
else {
if (idx == 0) {
return null;
}
else {
// lets find the first char
buffer.setCharAt(idx, lastCh);
}
}
}
return buffer.toString();
}
/**
* Executes the given string as a command line process. For more control
* over the process mechanism in JDK 1.5 you can use java.lang.ProcessBuilder.
*
* @param self a command line String
* @return the Process which has just started for this command line string
*/
public static Process execute(String self) throws IOException {
return Runtime.getRuntime().exec(self);
}
private static char next(char ch) {
if (Character.isLetterOrDigit(++ch)) {
return ch;
}
else {
return ZERO_CHAR;
}
}
private static char previous(char ch) {
if (Character.isLetterOrDigit(--ch)) {
return ch;
}
else {
return ZERO_CHAR;
}
}
/**
* @return the first character used when a letter rolls over when incrementing
*/
private static char firstCharacter() {
char ch = ZERO_CHAR;
while (!Character.isLetterOrDigit(ch)) {
ch++;
}
return ch;
}
/**
* @return the last character used when a letter rolls over when decrementing
*/
private static char lastCharacter() {
char ch = firstCharacter();
while (Character.isLetterOrDigit(++ch));
return --ch;
}
public static String multiply(String self, Number factor) {
int size = factor.intValue();
if (size == 0)
return "";
else if (size < 0) {
throw new IllegalArgumentException(
"multiply() should be called with a number of 0 or greater not: " + size);
}
StringBuffer answer = new StringBuffer(self);
for (int i = 1; i < size; i++) {
answer.append(self);
}
return answer.toString();
}
protected static String toString(Object value) {
return (value == null) ? "null" : value.toString();
}
// Number based methods
/**
* Increment a Character by one
*
* @param self a Character
* @return an incremented Number
*/
public static Number next(Character self) {
return plus(self, ONE);
}
/**
* Increment a Number by one
*
* @param self a Number
* @return an incremented Number
*/
public static Number next(Number self) {
return plus(self, ONE);
}
/**
* Decrement a Character by one
*
* @param self a Character
* @return a decremented Number
*/
public static Number previous(Character self) {
return minus(self, ONE);
}
/**
* Decrement a Number by one
*
* @param self a Number
* @return a decremented Number
*/
public static Number previous(Number self) {
return minus(self, ONE);
}
/**
* Add a Character and a Number
*
* @param left a Character
* @param right a Number
* @return the addition of the Character and the Number
*/
public static Number plus(Character left, Number right) {
return plus(new Integer(left.charValue()), right);
}
/**
* Add a Number and a Character
*
* @param left a Number
* @param right a Character
* @return the addition of the Character and the Number
*/
public static Number plus(Number left, Character right) {
return plus(left, new Integer(right.charValue()));
}
/**
* Add two Characters
*
* @param left a Character
* @param right a Character
* @return the addition of both Characters
*/
public static Number plus(Character left, Character right) {
return plus(new Integer(left.charValue()), right);
}
/**
* Add two Numbers
*
* @param left a Number
* @param right another Number to add
* @return the addition of both Numbers
*/
public static Number plus(Number left, Number right) {
return NumberMath.add(left, right);
}
/**
* Compare a Character and a Number
*
* @param left a Character
* @param right a Number
* @return the result of the comparison
*/
public static int compareTo(Character left, Number right) {
return compareTo(new Integer(left.charValue()), right);
}
/**
* Compare a Number and a Character
*
* @param left a Number
* @param right a Character
* @return the result of the comparison
*/
public static int compareTo(Number left, Character right) {
return compareTo(left, new Integer(right.charValue()));
}
/**
* Compare two Characters
*
* @param left a Character
* @param right a Character
* @return the result of the comparison
*/
public static int compareTo(Character left, Character right) {
return compareTo(new Integer(left.charValue()), right);
}
/**
* Compare two Numbers
*
* @param left a Number
* @param right another Number to compare to
* @return the comparision of both numbers
*/
public static int compareTo(Number left, Number right) {
/** @todo maybe a double dispatch thing to handle new large numbers? */
return NumberMath.compareTo(left, right);
}
/**
* Subtract a Number from a Character
*
* @param left a Character
* @param right a Number
* @return the addition of the Character and the Number
*/
public static Number minus(Character left, Number right) {
return minus(new Integer(left.charValue()), right);
}
/**
* Subtract a Character from a Number
*
* @param left a Number
* @param right a Character
* @return the addition of the Character and the Number
*/
public static Number minus(Number left, Character right) {
return minus(left, new Integer(right.charValue()));
}
/**
* Subtraction two Characters
*
* @param left a Character
* @param right a Character
* @return the addition of both Characters
*/
public static Number minus(Character left, Character right) {
return minus(new Integer(left.charValue()), right);
}
/**
* Substraction of two Numbers
*
* @param left a Number
* @param right another Number to substract to the first one
* @return the substraction
*/
public static Number minus(Number left, Number right) {
return NumberMath.subtract(left,right);
}
/**
* Multiply a Character by a Number
*
* @param left a Character
* @param right a Number
* @return the multiplication of both
*/
public static Number multiply(Character left, Number right) {
return multiply(new Integer(left.charValue()), right);
}
/**
* Multiply a Number by a Character
*
* @param left a Number
* @param right a Character
* @return the multiplication of both
*/
public static Number multiply(Number left, Character right) {
return multiply(left, new Integer(right.charValue()));
}
/**
* Multiply two Characters
*
* @param left a Character
* @param right another Character
* @return the multiplication of both
*/
public static Number multiply(Character left, Character right) {
return multiply(new Integer(left.charValue()), right);
}
/**
* Multiply two Numbers
*
* @param left a Number
* @param right another Number
* @return the multiplication of both
*/
//Note: This method is NOT called if left AND right are both BigIntegers or BigDecimals because
//those classes implement a method with a better exact match.
public static Number multiply(Number left, Number right) {
return NumberMath.multiply(left, right);
}
/**
* Power of a Number to a certain exponent
*
* @param self a Number
* @param exponent a Number exponent
* @return a Number to the power of a certain exponent
*/
public static Number power(Number self, Number exponent) {
double answer = Math.pow(self.doubleValue(), exponent.doubleValue());
if (NumberMath.isFloatingPoint(self) || NumberMath.isFloatingPoint(exponent) || answer < 1) {
return new Double(answer);
}
else if (NumberMath.isLong(self) || NumberMath.isLong(exponent) || answer > Integer.MAX_VALUE) {
return new Long((long) answer);
}
else {
return new Integer((int) answer);
}
}
/**
* Divide a Character by a Number
*
* @param left a Character
* @param right a Number
* @return the multiplication of both
*/
public static Number div(Character left, Number right) {
return div(new Integer(left.charValue()), right);
}
/**
* Divide a Number by a Character
*
* @param left a Number
* @param right a Character
* @return the multiplication of both
*/
public static Number div(Number left, Character right) {
return div(left, new Integer(right.charValue()));
}
/**
* Divide two Characters
*
* @param left a Character
* @param right another Character
* @return the multiplication of both
*/
public static Number div(Character left, Character right) {
return div(new Integer(left.charValue()), right);
}
/**
* Divide two Numbers
*
* @param left a Number
* @param right another Number
* @return a Number resulting of the divide operation
*/
//Method name changed from 'divide' to avoid collision with BigInteger method that has
//different semantics. We want a BigDecimal result rather than a BigInteger.
public static Number div(Number left, Number right) {
return NumberMath.divide(left, right);
}
/**
* Integer Divide a Character by a Number
*
* @param left a Character
* @param right a Number
* @return the integer division of both
*/
public static Number intdiv(Character left, Number right) {
return intdiv(new Integer(left.charValue()), right);
}
/**
* Integer Divide a Number by a Character
*
* @param left a Number
* @param right a Character
* @return the integer division of both
*/
public static Number intdiv(Number left, Character right) {
return intdiv(left, new Integer(right.charValue()));
}
/**
* Integer Divide two Characters
*
* @param left a Character
* @param right another Character
* @return the integer division of both
*/
public static Number intdiv(Character left, Character right) {
return intdiv(new Integer(left.charValue()), right);
}
/**
* Integer Divide two Numbers
*
* @param left a Number
* @param right another Number
* @return a Number (an Integer) resulting of the integer division operation
*/
public static Number intdiv(Number left, Number right) {
return NumberMath.intdiv(left, right);
}
/**
* Bitwise OR together two numbers
*
* @param left a Number
* @param right another Number to bitwise OR
* @return the bitwise OR of both Numbers
*/
public static Number or(Number left, Number right) {
return NumberMath.or(left, right);
}
/**
* Bitwise AND together two Numbers
*
* @param left a Number
* @param right another Number to bitwse AND
* @return the bitwise AND of both Numbers
*/
public static Number and(Number left, Number right) {
return NumberMath.and(left, right);
}
/**
* Performs a division modulus operation
*
* @param left a Number
* @param right another Number to mod
* @return the modulus result
*/
public static Number mod(Number left, Number right) {
return NumberMath.mod(left, right);
}
/**
* Negates the number
*
* @param left a Number
* @return the negation of the number
*/
public static Number negate(Number left) {
return NumberMath.negate(left);
}
/**
* Iterates a number of times
*
* @param self a Number
* @param closure the closure to call a number of times
*/
public static void times(Number self, Closure closure) {
for (int i = 0, size = self.intValue(); i < size; i++) {
closure.call(new Integer(i));
if (closure.getDirective() == Closure.DONE){
break;
}
}
}
/**
* Iterates from this number up to the given number
*
* @param self a Number
* @param to another Number to go up to
* @param closure the closure to call
*/
public static void upto(Number self, Number to, Closure closure) {
for (int i = self.intValue(), size = to.intValue(); i <= size; i++) {
closure.call(new Integer(i));
}
}
/**
* Iterates from this number up to the given number using a step increment
*
* @param self a Number to start with
* @param to a Number to go up to
* @param stepNumber a Number representing the step increment
* @param closure the closure to call
*/
public static void step(Number self, Number to, Number stepNumber, Closure closure) {
for (int i = self.intValue(), size = to.intValue(), step = stepNumber.intValue(); i < size; i += step) {
closure.call(new Integer(i));
}
}
/**
* Get the absolute value
*
* @param number a Number
* @return the absolute value of that Number
*/
//Note: This method is NOT called if number is a BigInteger or BigDecimal because
//those classes implement a method with a better exact match.
public static int abs(Number number) {
return Math.abs(number.intValue());
}
/**
* Get the absolute value
*
* @param number a Long
* @return the absolute value of that Long
*/
public static long abs(Long number) {
return Math.abs(number.longValue());
}
/**
* Get the absolute value
*
* @param number a Float
* @return the absolute value of that Float
*/
public static float abs(Float number) {
return Math.abs(number.floatValue());
}
/**
* Get the absolute value
*
* @param number a Double
* @return the absolute value of that Double
*/
public static double abs(Double number) {
return Math.abs(number.doubleValue());
}
/**
* Get the absolute value
*
* @param number a Float
* @return the absolute value of that Float
*/
public static int round(Float number) {
return Math.round(number.floatValue());
}
/**
* Round the value
*
* @param number a Double
* @return the absolute value of that Double
*/
public static long round(Double number) {
return Math.round(number.doubleValue());
}
/**
* Parse a String into an Integer
*
* @param self a String
* @return an Integer
*/
public static Integer toInteger(String self) {
return Integer.valueOf(self);
}
/**
* Parse a String into a Long
*
* @param self a String
* @return a Long
*/
public static Long toLong(String self) {
return Long.valueOf(self);
}
/**
* Parse a String into a Float
*
* @param self a String
* @return a Float
*/
public static Float toFloat(String self) {
return Float.valueOf(self);
}
/**
* Parse a String into a Double
*
* @param self a String
* @return a Double
*/
public static Double toDouble(String self) {
return Double.valueOf(self);
}
/**
* Transform a Number into an Integer
*
* @param self a Number
* @return an Integer
*/
public static Integer toInteger(Number self) {
return new Integer(self.intValue());
}
// Date methods
/**
* Increments a Date by a day
*
* @param self a Date
* @return the next days date
*/
public static Date next(Date self) {
return plus(self, 1);
}
/**
* Decrement a Date by a day
*
* @param self a Date
* @return the previous days date
*/
public static Date previous(Date self) {
return minus(self, 1);
}
/**
* Adds a number of days to this date and returns the new date
*
* @param self a Date
* @param days the number of days to increase
* @return the new date
*/
public static Date plus(Date self, int days) {
Calendar calendar = (Calendar) Calendar.getInstance().clone();
calendar.setTime(self);
calendar.add(Calendar.DAY_OF_YEAR, days);
return calendar.getTime();
}
/**
* Subtracts a number of days from this date and returns the new date
*
* @param self a Date
* @return the new date
*/
public static Date minus(Date self, int days) {
return plus(self, -days);
}
// File and stream based methods
/**
* Iterates through the given file line by line
*
* @param self a File
* @param closure a closure
* @throws IOException
*/
public static void eachLine(File self, Closure closure) throws IOException {
eachLine(newReader(self), closure);
}
/**
* Iterates through the given reader line by line
*
* @param self a Reader
* @param closure a closure
* @throws IOException
*/
public static void eachLine(Reader self, Closure closure) throws IOException {
BufferedReader br = null;
if (self instanceof BufferedReader)
br = (BufferedReader) self;
else
br = new BufferedReader(self);
try {
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
else {
closure.call(line);
}
}
br.close();
}
catch (IOException e) {
if (self != null) {
try {
br.close();
}
catch (Exception e2) {
// ignore as we're already throwing
}
throw e;
}
}
}
/**
* Iterates through the given file line by line, splitting on the seperator
*
* @param self a File
* @param sep a String separator
* @param closure a closure
* @throws IOException
*/
public static void splitEachLine(File self, String sep, Closure closure) throws IOException {
splitEachLine(newReader(self), sep, closure);
}
/**
* Iterates through the given reader line by line, splitting on the seperator
*
* @param self a Reader
* @param sep a String separator
* @param closure a closure
* @throws IOException
*/
public static void splitEachLine(Reader self, String sep, Closure closure) throws IOException {
BufferedReader br = null;
if (self instanceof BufferedReader)
br = (BufferedReader) self;
else
br = new BufferedReader(self);
List args = new ArrayList();
try {
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
else {
List vals = Arrays.asList(line.split(sep));
args.clear();
args.add(vals);
closure.call(args);
}
}
br.close();
}
catch (IOException e) {
if (self != null) {
try {
br.close();
}
catch (Exception e2) {
// ignore as we're already throwing
}
throw e;
}
}
}
/**
* Read a single, whole line from the given Reader
*
* @param self a Reader
* @return a line
* @throws IOException
*/
public static String readLine(Reader self) throws IOException {
BufferedReader br = null;
if (self instanceof BufferedReader) {
br = (BufferedReader) self;
} else {
br = new BufferedReader(self);
}
return br.readLine();
}
/**
* Read a single, whole line from the given InputStream
*
* @param self an InputStream
* @return a line
* @throws IOException
*/
public static String readLine(InputStream stream) throws IOException {
return readLine(new InputStreamReader(stream));
}
/**
* Reads the file into a list of Strings for each line
*
* @param file a File
* @return a List of lines
* @throws IOException
*/
public static List readLines(File file) throws IOException {
IteratorClosureAdapter closure = new IteratorClosureAdapter(file);
eachLine(file, closure);
return closure.asList();
}
/**
* Reads the content of the File opened with the specified encoding and returns it as a String
*
* @param file the file whose content we want to read
* @param charset the charset used to read the content of the file
* @return a String containing the content of the file
* @throws IOException
*/
public static String getText(File file, String charset) throws IOException {
BufferedReader reader = newReader(file, charset);
return getText(reader);
}
/**
* Reads the content of the File and returns it as a String
*
* @param file the file whose content we want to read
* @return a String containing the content of the file
* @throws IOException
*/
public static String getText(File file) throws IOException {
BufferedReader reader = newReader(file);
return getText(reader);
}
/**
* Reads the content of this URL and returns it as a String
*
* @param url URL to read content from
* @return the text from that URL
* @throws IOException
*/
public static String getText(URL url) throws IOException {
return getText(url, CharsetToolkit.getDefaultSystemCharset().toString());
}
/**
* Reads the content of this URL and returns it as a String
*
* @param url URL to read content from
* @param charset opens the stream with a specified charset
* @return the text from that URL
* @throws IOException
*/
public static String getText(URL url, String charset) throws IOException {
BufferedReader reader = new BufferedReader(
new InputStreamReader(url.openConnection().getInputStream(), charset));
return getText(reader);
}
/**
* Reads the content of this InputStream and returns it as a String
*
* @param is an input stream
* @return the text from that URL
* @throws IOException
*/
public static String getText(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
return getText(reader);
}
/**
* Reads the content of this InputStream with a specified charset and returns it as a String
*
* @param is an input stream
* @param charset opens the stream with a specified charset
* @return the text from that URL
* @throws IOException
*/
public static String getText(InputStream is, String charset) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));
return getText(reader);
}
/**
* Reads the content of the BufferedReader and returns it as a String
*
* @param reader a BufferedReader whose content we want to read
* @return a String containing the content of the buffered reader
* @throws IOException
*/
public static String getText(BufferedReader reader) throws IOException {
StringBuffer answer = new StringBuffer();
// reading the content of the file within a char buffer allow to keep the correct line endings
char[] charBuffer = new char[4096];
int nbCharRead = 0;
while ((nbCharRead = reader.read(charBuffer)) != -1) {
if (nbCharRead == charBuffer.length) {
// appends a full buffer
answer.append(charBuffer);
}
else {
// appends the last incomplete buffer
char[] endBuffer = new char[nbCharRead];
System.arraycopy(charBuffer, 0, endBuffer, 0, nbCharRead);
answer.append(endBuffer);
}
}
reader.close();
return answer.toString();
}
/**
* Write the text and append a new line (depending on the platform line-ending)
*
* @param writer a BufferedWriter
* @param line the line to write
* @throws IOException
*/
public static void writeLine(BufferedWriter writer, String line) throws IOException {
writer.write(line);
writer.newLine();
}
/**
* Write the text to the File.
*
* @param file a File
* @param text the text to write to the File
* @throws IOException
*/
public static void write(File file, String text) throws IOException {
BufferedWriter writer = newWriter(file);
writer.write(text);
writer.close();
}
/**
* Write the text to the File with a specified encoding.
*
* @param file a File
* @param text the text to write to the File
* @param charset the charset used
* @throws IOException
*/
public static void write(File file, String text, String charset) throws IOException {
BufferedWriter writer = newWriter(file, charset);
writer.write(text);
writer.close();
}
/**
* Append the text at the end of the File
*
* @param file a File
* @param text the text to append at the end of the File
* @throws IOException
*/
public static void append(File file, String text) throws IOException {
BufferedWriter writer = newWriter(file, true);
writer.write(text);
writer.close();
}
/**
* Append the text at the end of the File with a specified encoding
*
* @param file a File
* @param text the text to append at the end of the File
* @param charset the charset used
* @throws IOException
*/
public static void append(File file, String text, String charset) throws IOException {
BufferedWriter writer = newWriter(file, charset, true);
writer.write(text);
writer.close();
}
/**
* Reads the reader into a list of Strings for each line
*
* @param reader a Reader
* @return a List of lines
* @throws IOException
*/
public static List readLines(Reader reader) throws IOException {
IteratorClosureAdapter closure = new IteratorClosureAdapter(reader);
eachLine(reader, closure);
return closure.asList();
}
/**
* Invokes the closure for each file in the given directory
*
* @param self a File
* @param closure a closure
*/
public static void eachFile(File self, Closure closure) {
File[] files = self.listFiles();
for (int i = 0; i < files.length; i++) {
closure.call(files[i]);
}
}
/**
* Invokes the closure for each file in the given directory and recursively.
* It is a depth-first exploration, directories are included in the search.
*
* @param self a File
* @param closure a closure
*/
public static void eachFileRecurse(File self, Closure closure) {
File[] files = self.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
closure.call(files[i]);
eachFileRecurse(files[i], closure);
} else {
closure.call(files[i]);
}
}
}
/**
* Helper method to create a buffered reader for a file
*
* @param file a File
* @return a BufferedReader
* @throws IOException
*/
public static BufferedReader newReader(File file) throws IOException {
CharsetToolkit toolkit = new CharsetToolkit(file);
return toolkit.getReader();
}
/**
* Helper method to create a buffered reader for a file, with a specified charset
*
* @param file a File
* @param charset the charset with which we want to write in the File
* @return a BufferedReader
* @throws FileNotFoundException if the File was not found
* @throws UnsupportedEncodingException if the encoding specified is not supported
*/
public static BufferedReader newReader(File file, String charset)
throws FileNotFoundException, UnsupportedEncodingException {
return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
}
/**
* Helper method to create a new BufferedReader for a file and then
* passes it into the closure and ensures its closed again afterwords
*
* @param file
* @throws FileNotFoundException
*/
public static void withReader(File file, Closure closure) throws IOException {
withReader(newReader(file), closure);
}
/**
* Helper method to create a buffered output stream for a file
*
* @param file
* @return
* @throws FileNotFoundException
*/
public static BufferedOutputStream newOutputStream(File file) throws IOException {
return new BufferedOutputStream(new FileOutputStream(file));
}
/**
* Helper method to create a new OutputStream for a file and then
* passes it into the closure and ensures its closed again afterwords
*
* @param file a File
* @throws FileNotFoundException
*/
public static void withOutputStream(File file, Closure closure) throws IOException {
withStream(newOutputStream(file), closure);
}
/**
* Helper method to create a new InputStream for a file and then
* passes it into the closure and ensures its closed again afterwords
*
* @param file a File
* @throws FileNotFoundException
*/
public static void withInputStream(File file, Closure closure) throws IOException {
withStream(newInputStream(file), closure);
}
/**
* Helper method to create a buffered writer for a file
*
* @param file a File
* @return a BufferedWriter
* @throws FileNotFoundException
*/
public static BufferedWriter newWriter(File file) throws IOException {
return new BufferedWriter(new FileWriter(file));
}
/**
* Helper method to create a buffered writer for a file in append mode
*
* @param file a File
* @param append true if in append mode
* @return a BufferedWriter
* @throws FileNotFoundException
*/
public static BufferedWriter newWriter(File file, boolean append) throws IOException {
return new BufferedWriter(new FileWriter(file, append));
}
/**
* Helper method to create a buffered writer for a file
*
* @param file a File
* @param charset the name of the encoding used to write in this file
* @param append true if in append mode
* @return a BufferedWriter
* @throws FileNotFoundException
*/
public static BufferedWriter newWriter(File file, String charset, boolean append) throws IOException {
if (append) {
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, append), charset));
}
else {
// first write the Byte Order Mark for Unicode encodings
FileOutputStream stream = new FileOutputStream(file);
if ("UTF-16BE".equals(charset)) {
writeUtf16Bom(stream, true);
}
else if ("UTF-16LE".equals(charset)) {
writeUtf16Bom(stream, false);
}
return new BufferedWriter(new OutputStreamWriter(stream, charset));
}
}
/**
* Helper method to create a buffered writer for a file
*
* @param file a File
* @param charset the name of the encoding used to write in this file
* @return a BufferedWriter
* @throws FileNotFoundException
*/
public static BufferedWriter newWriter(File file, String charset) throws IOException {
return newWriter(file, charset, false);
}
/**
* Write a Byte Order Mark at the begining of the file
*
* @param stream the FileOuputStream to write the BOM to
* @param bigEndian true if UTF 16 Big Endian or false if Low Endian
* @throws IOException
*/
private static void writeUtf16Bom(FileOutputStream stream, boolean bigEndian) throws IOException {
if (bigEndian) {
stream.write(-2);
stream.write(-1);
}
else {
stream.write(-1);
stream.write(-2);
}
}
/**
* Helper method to create a new BufferedWriter for a file and then
* passes it into the closure and ensures it is closed again afterwords
*
* @param file a File
* @param closure a closure
* @throws FileNotFoundException
*/
public static void withWriter(File file, Closure closure) throws IOException {
withWriter(newWriter(file), closure);
}
/**
* Helper method to create a new BufferedWriter for a file in a specified encoding
* and then passes it into the closure and ensures it is closed again afterwords
*
* @param file a File
* @param charset the charset used
* @param closure a closure
* @throws FileNotFoundException
*/
public static void withWriter(File file, String charset, Closure closure) throws IOException {
withWriter(newWriter(file, charset), closure);
}
/**
* Helper method to create a new BufferedWriter for a file in a specified encoding
* in append mode and then passes it into the closure and ensures it is closed again afterwords
*
* @param file a File
* @param charset the charset used
* @param closure a closure
* @throws FileNotFoundException
*/
public static void withWriterAppend(File file, String charset, Closure closure) throws IOException {
withWriter(newWriter(file, charset, true), closure);
}
/**
* Helper method to create a new PrintWriter for a file
*
* @param file a File
* @throws FileNotFoundException
*/
public static PrintWriter newPrintWriter(File file) throws IOException {
return new PrintWriter(newWriter(file));
}
/**
* Helper method to create a new PrintWriter for a file with a specified charset
*
* @param file a File
* @param charset the charset
* @return a PrintWriter
* @throws FileNotFoundException
*/
public static PrintWriter newPrintWriter(File file, String charset) throws IOException {
return new PrintWriter(newWriter(file, charset));
}
/**
* Helper method to create a new PrintWriter for a file and then
* passes it into the closure and ensures its closed again afterwords
*
* @param file a File
* @throws FileNotFoundException
*/
public static void withPrintWriter(File file, Closure closure) throws IOException {
withWriter(newPrintWriter(file), closure);
}
/**
* Allows a writer to be used, calling the closure with the writer
* and then ensuring that the writer is closed down again irrespective
* of whether exceptions occur or the
*
* @param writer the writer which is used and then closed
* @param closure the closure that the writer is passed into
* @throws IOException
*/
public static void withWriter(Writer writer, Closure closure) throws IOException {
try {
closure.call(writer);
// lets try close the writer & throw the exception if it fails
// but not try to reclose it in the finally block
Writer temp = writer;
writer = null;
temp.close();
}
finally {
if (writer != null) {
try {
writer.close();
}
catch (IOException e) {
log.warning("Caught exception closing writer: " + e);
}
}
}
}
/**
* Allows a Reader to be used, calling the closure with the writer
* and then ensuring that the writer is closed down again irrespective
* of whether exceptions occur or the
*
* @param writer the writer which is used and then closed
* @param closure the closure that the writer is passed into
* @throws IOException
*/
public static void withReader(Reader writer, Closure closure) throws IOException {
try {
closure.call(writer);
// lets try close the writer & throw the exception if it fails
// but not try to reclose it in the finally block
Reader temp = writer;
writer = null;
temp.close();
}
finally {
if (writer != null) {
try {
writer.close();
}
catch (IOException e) {
log.warning("Caught exception closing writer: " + e);
}
}
}
}
/**
* Allows a InputStream to be used, calling the closure with the stream
* and then ensuring that the stream is closed down again irrespective
* of whether exceptions occur or the
*
* @param stream the stream which is used and then closed
* @param closure the closure that the stream is passed into
* @throws IOException
*/
public static void withStream(InputStream stream, Closure closure) throws IOException {
try {
closure.call(stream);
// lets try close the stream & throw the exception if it fails
// but not try to reclose it in the finally block
InputStream temp = stream;
stream = null;
temp.close();
}
finally {
if (stream != null) {
try {
stream.close();
}
catch (IOException e) {
log.warning("Caught exception closing stream: " + e);
}
}
}
}
/**
* Reads the stream into a list of Strings for each line
*
* @param stream a stream
* @return a List of lines
* @throws IOException
*/
public static List readLines(InputStream stream) throws IOException {
return readLines(new BufferedReader(new InputStreamReader(stream)));
}
/**
* Iterates through the given stream line by line
*
* @param stream a stream
* @param closure a closure
* @throws IOException
*/
public static void eachLine(InputStream stream, Closure closure) throws IOException {
eachLine(new InputStreamReader(stream), closure);
}
/**
* Iterates through the lines read from the URL's associated input stream
*
* @param url a URL to open and read
* @param closure a closure to apply on each line
* @throws IOException
*/
public static void eachLine(URL url, Closure closure) throws IOException {
eachLine(url.openConnection().getInputStream(), closure);
}
/**
* Helper method to create a new BufferedReader for a URL and then
* passes it into the closure and ensures its closed again afterwords
*
* @param url a URL
* @throws FileNotFoundException
*/
public static void withReader(URL url, Closure closure) throws IOException {
withReader(url.openConnection().getInputStream(), closure);
}
/**
* Helper method to create a new BufferedReader for a stream and then
* passes it into the closure and ensures its closed again afterwords
*
* @param in a stream
* @throws FileNotFoundException
*/
public static void withReader(InputStream in, Closure closure) throws IOException {
withReader(new InputStreamReader(in), closure);
}
/**
* Allows an output stream to be used, calling the closure with the output stream
* and then ensuring that the output stream is closed down again irrespective
* of whether exceptions occur
*
* @param stream the stream which is used and then closed
* @param closure the closure that the writer is passed into
* @throws IOException
*/
public static void withWriter(OutputStream stream, Closure closure) throws IOException {
withWriter(new OutputStreamWriter(stream), closure);
}
/**
* Allows an output stream to be used, calling the closure with the output stream
* and then ensuring that the output stream is closed down again irrespective
* of whether exceptions occur.
*
* @param stream the stream which is used and then closed
* @param charset the charset used
* @param closure the closure that the writer is passed into
* @throws IOException
*/
public static void withWriter(OutputStream stream, String charset, Closure closure) throws IOException {
withWriter(new OutputStreamWriter(stream, charset), closure);
}
/**
* Allows a OutputStream to be used, calling the closure with the stream
* and then ensuring that the stream is closed down again irrespective
* of whether exceptions occur.
*
* @param stream the stream which is used and then closed
* @param closure the closure that the stream is passed into
* @throws IOException
*/
public static void withStream(OutputStream stream, Closure closure) throws IOException {
try {
closure.call(stream);
// lets try close the stream & throw the exception if it fails
// but not try to reclose it in the finally block
OutputStream temp = stream;
stream = null;
temp.close();
}
finally {
if (stream != null) {
try {
stream.close();
}
catch (IOException e) {
log.warning("Caught exception closing stream: " + e);
}
}
}
}
/**
* Helper method to create a buffered input stream for a file
*
* @param file a File
* @return a BufferedInputStream of the file
* @throws FileNotFoundException
*/
public static BufferedInputStream newInputStream(File file) throws FileNotFoundException {
return new BufferedInputStream(new FileInputStream(file));
}
/**
* Traverse through each byte of the specified File
*
* @param self a File
* @param closure a closure
*/
public static void eachByte(File self, Closure closure) throws IOException {
BufferedInputStream is = newInputStream(self);
eachByte(is, closure);
}
/**
* Traverse through each byte of the specified stream
*
* @param is stream to iterate over
* @param closure closure to apply to each byte
* @throws IOException
*/
public static void eachByte(InputStream is, Closure closure) throws IOException {
try {
while (true) {
int b = is.read();
if (b == -1) {
break;
}
else {
closure.call(new Byte((byte) b));
}
}
is.close();
}
catch (IOException e) {
if (is != null) {
try {
is.close();
}
catch (Exception e2) {
// ignore as we're already throwing
}
throw e;
}
}
}
/**
* Traverse through each byte of the specified URL
*
* @param url url to iterate over
* @param closure closure to apply to each byte
* @throws IOException
*/
public static void eachByte(URL url, Closure closure) throws IOException {
InputStream is = url.openConnection().getInputStream();
eachByte(is, closure);
}
/**
* Transforms the characters from a reader with a Closure and write them to a writer
*
* @param reader
* @param writer
* @param closure
*/
public static void transformChar(Reader reader, Writer writer, Closure closure) {
int c;
try {
char[] chars = new char[1];
while ((c = reader.read()) != -1) {
chars[0] = (char)c;
writer.write((String)closure.call(new String(chars)));
}
} catch (IOException e) {
}
}
/**
* Transforms the lines from a reader with a Closure and write them to a writer
*
* @param reader
* @param writer
* @param closure
*/
public static void transformLine(Reader reader, Writer writer, Closure closure) throws IOException {
BufferedReader br = new BufferedReader(reader);
BufferedWriter bw = new BufferedWriter(writer);
String line;
while ((line = br.readLine()) != null) {
Object o = closure.call(line);
if (o != null) {
bw.write(o.toString());
bw.newLine();
}
}
}
/**
* Filter the lines from a reader and write them on the writer, according to a closure
* which returns true or false.
*
* @param reader a reader
* @param writer a writer
* @param closure the closure which returns booleans
* @throws IOException
*/
public static void filterLine(Reader reader, Writer writer, Closure closure) throws IOException {
BufferedReader br = new BufferedReader(reader);
BufferedWriter bw = new BufferedWriter(writer);
String line;
while ((line = br.readLine()) != null) {
if (InvokerHelper.asBool(closure.call(line))) {
bw.write(line);
bw.newLine();
}
}
}
/**
* Filter the lines of a Reader and create a Writable in return to stream the filtered lines
*
* @param reader a reader
* @param closure a closure returning a boolean indicating to filter or not a line
* @return a Writable closure
*/
public static Writable filterLine(Reader reader, final Closure closure) {
final BufferedReader br = new BufferedReader(reader);
return new Writable() {
public Writer writeTo(Writer out) throws IOException {
BufferedWriter bw = new BufferedWriter(out);
String line;
while ((line = br.readLine()) != null) {
if (InvokerHelper.asBool(closure.call(line))) {
bw.write(line);
bw.newLine();
}
}
bw.flush();
return out;
}
public String toString() {
StringWriter buffer = new StringWriter();
try {
writeTo(buffer);
}
catch (IOException e) {
throw new RuntimeException(e); // TODO: change this exception type
}
return buffer.toString();
}
};
}
/**
* Reads the content of the file into an array of byte
*
* @param file a File
* @return a List of Bytes
*/
public static byte[] readBytes(File file) throws IOException {
byte[] bytes = new byte[(int) file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(bytes);
fileInputStream.close();
return bytes;
}
// Socket and ServerSocket methods
/**
* Allows an InputStream and an OutputStream from a Socket to be used,
* calling the closure with the streams and then ensuring that the streams are closed down again
* irrespective of whether exceptions occur.
*
* @param socket a Socket
* @param closure a Closure
* @throws IOException
*/
public static void withStreams(Socket socket, Closure closure) throws IOException {
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
try {
closure.call(new Object[]{input, output});
} finally {
try {
input.close();
} catch (IOException e) {
// noop
}
try {
output.close();
} catch (IOException e) {
// noop
}
}
}
/**
* Allow to pass a Closure to the accept methods of ServerSocket
*
* @param serverSocket a ServerSocket
* @param closure a Closure
* @return a Socket
* @throws IOException
*/
public static Socket accept(ServerSocket serverSocket, final Closure closure) throws IOException {
final Socket socket = serverSocket.accept();
new Thread(new Runnable()
{
public void run() {
try {
closure.call(socket);
} finally {
try {
socket.close();
} catch (IOException e) {
// noop
}
}
}
}).start();
return socket;
}
/**
* @param file a File
* @return a File which wraps the input file and which implements Writable
*/
public static File asWritable(File file) {
return new WritableFile(file);
}
/**
* @param file a File
* @param encoding the encoding to be used when reading the file's contents
* @return File which wraps the input file and which implements Writable
*/
public static File asWritable(File file, String encoding) {
return new WritableFile(file, encoding);
}
/**
* Converts the given String into a List of strings of one character
*
* @param self a String
* @return a List of characters (a 1-character String)
*/
public static List toList(String self) {
int size = self.length();
List answer = new ArrayList(size);
for (int i = 0; i < size; i++) {
answer.add(self.substring(i, i + 1));
}
return answer;
}
// Process methods
/**
* An alias method so that a process appears similar to System.out, System.in, System.err;
* you can use process.in, process.out, process.err in a similar way
*
* @return an InputStream
*/
public static InputStream getIn(Process self) {
return self.getInputStream();
}
/**
* Read the text of the output stream of the Process.
*
* @param self a Process
* @return the text of the output
* @throws IOException
*/
public static String getText(Process self) throws IOException {
return getText(new BufferedReader(new InputStreamReader(self.getInputStream())));
}
/**
* An alias method so that a process appears similar to System.out, System.in, System.err;
* you can use process.in, process.out, process.err in a similar way
*
* @return an InputStream
*/
public static InputStream getErr(Process self) {
return self.getErrorStream();
}
/**
* An alias method so that a process appears similar to System.out, System.in, System.err;
* you can use process.in, process.out, process.err in a similar way
*
* @return an OutputStream
*/
public static OutputStream getOut(Process self) {
return self.getOutputStream();
}
/**
* Wait for the process to finish during a certain amount of time, otherwise stops the process.
*
* @param self a Process
* @param numberOfMillis the number of milliseconds to wait before stopping the process
*/
public static void waitForOrKill(Process self, long numberOfMillis) {
ProcessRunner runnable = new ProcessRunner(self);
Thread thread = new Thread(runnable);
thread.start();
runnable.waitForOrKill(numberOfMillis);
}
/**
* process each regex matched substring of a string object. The object
* passed to the closure is a matcher with rich information of the last
* successful match
*
* @author bing ran
* @param str the target string
* @param regex a Regex string
* @param closure a closure
*/
public static void eachMatch(String str, String regex, Closure closure) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
int count = m.groupCount();
ArrayList groups = new ArrayList();
for (int i = 0; i <= count; i++) {
groups.add(m.group(i));
}
closure.call(groups);
}
}
public static void each (Matcher matcher, Closure closure) {
Matcher m = matcher;
while (m.find()) {
int count = m.groupCount();
ArrayList groups = new ArrayList();
for (int i = 0; i <= count; i++) {
groups.add(m.group(i));
}
closure.call(groups);
}
}
/**
* Iterates over every element of the collection and return the index of the first object
* that matches the condition specified in the closure
*
* @param self the iteration object over which we iterate
* @param closure the filter to perform a match on the collection
* @return an integer that is the index of the first macthed object.
*/
public static int findIndexOf(Object self, Closure closure) {
int i = 0;
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) {
Object value = iter.next();
if (InvokerHelper.asBool(closure.call(value))) {
break;
}
}
return i;
}
/**
* A Runnable which waits for a process to complete together with a notification scheme
* allowing another thread to wait a maximum number of seconds for the process to complete
* before killing it.
*/
protected static class ProcessRunner implements Runnable {
Process process;
private boolean finished;
public ProcessRunner(Process process) {
this.process = process;
}
public void run() {
try {
process.waitFor();
}
catch (InterruptedException e) {
}
synchronized (this) {
notifyAll();
finished = true;
}
}
public synchronized void waitForOrKill(long millis) {
if (!finished) {
try {
wait(millis);
}
catch (InterruptedException e) {
}
if (!finished) {
process.destroy();
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.