answer
stringlengths 17
10.2M
|
|---|
package com.yahoo.vespa.flags;
import com.yahoo.component.Vtag;
import com.yahoo.vespa.defaults.Defaults;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME;
import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE;
import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION;
import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID;
/**
* Definitions of feature flags.
*
* <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag}
* or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p>
*
* <ol>
* <li>The unbound flag</li>
* <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding
* an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li>
* <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should
* declare this in the unbound flag definition in this file (referring to
* {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g.
* {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li>
* </ol>
*
* <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically
* there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p>
*
* @author hakonhall
*/
public class Flags {
private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>();
public static final UnboundStringFlag ALLOCATE_OS_REQUIREMENT = defineStringFlag(
"allocate-os-requirement", "rhel7",
List.of("hakonhall"), "2021-01-26", "2021-07-26",
"Allocations of new nodes are limited to the given host OS. Must be one of 'rhel7', " +
"'rhel8', or 'any'",
"Takes effect on next (re)deployment.",
APPLICATION_ID);
public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag(
"default-term-wise-limit", 1.0,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Default limit for when to apply termwise query evaluation",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag(
"feed-sequencer-type", "LATENCY",
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Selects type of sequenced executor used for feeding, valid values are LATENCY, ADAPTIVE, THROUGHPUT",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag(
"response-sequencer-type", "ADAPTIVE",
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag(
"response-num-threads", 2,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Number of threads used for mbus responses, default is 2, negative number = numcores/4",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag(
"skip-communicatiomanager-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the communicationmanager thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag(
"skip-mbus-request-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the mbus request thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag(
"skip-mbus-reply-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the mbus reply thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag(
"use-three-phase-updates", false,
List.of("vekterli"), "2020-12-02", "2021-03-01",
"Whether to enable the use of three-phase updates when bucket replicas are out of sync.",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_CLIENT_SERVER_COMMUNICATION = defineStringFlag(
"tls-for-zookeeper-client-server-communication", "OFF",
List.of("hmusum"), "2020-12-02", "2021-04-01",
"How to setup TLS for ZooKeeper client/server communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY",
"Takes effect on restart of config server",
NODE_TYPE, HOSTNAME);
public static final UnboundBooleanFlag USE_TLS_FOR_ZOOKEEPER_CLIENT = defineFeatureFlag(
"use-tls-for-zookeeper-client", false,
List.of("hmusum"), "2020-12-02", "2021-04-01",
"Whether to use TLS for ZooKeeper clients",
"Takes effect on restart of process",
NODE_TYPE, HOSTNAME);
public static final UnboundBooleanFlag PROVISION_TENANT_ROLES = defineFeatureFlag(
"provision-tenant-roles", false,
List.of("tokle"), "2020-12-02", "2021-04-01",
"Whether tenant roles should be provisioned",
"Takes effect on next deployment (controller)",
TENANT_ID);
public static final UnboundBooleanFlag TENANT_IAM_ROLE = defineFeatureFlag(
"application-iam-roles", false,
List.of("tokle"), "2020-12-02", "2021-04-01",
"Allow separate iam roles when provisioning/assigning hosts",
"Takes effect immediately on new hosts, on next redeploy for applications",
TENANT_ID);
public static final UnboundIntFlag MAX_TRIAL_TENANTS = defineIntFlag(
"max-trial-tenants", -1,
List.of("ogronnesby"), "2020-12-03", "2021-04-01",
"The maximum nr. of tenants with trial plan, -1 is unlimited",
"Takes effect immediately"
);
public static final UnboundBooleanFlag HIDE_SHARED_ROUTING_ENDPOINT = defineFeatureFlag(
"hide-shared-routing-endpoint", false,
List.of("tokle"), "2020-12-02", "2021-06-01",
"Whether the controller should hide shared routing layer endpoint",
"Takes effect immediately",
APPLICATION_ID
);
public static final UnboundBooleanFlag USE_ACCESS_CONTROL_CLIENT_AUTHENTICATION = defineFeatureFlag(
"use-access-control-client-authentication", false,
List.of("tokle"), "2020-12-02", "2021-03-01",
"Whether application container should set up client authentication on default port based on access control element",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag(
"async-message-handling-on-schedule", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Optionally deliver async messages in own thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_PENDING_MOVE_OPS = defineIntFlag(
"max-pending-move-ops", 10,
List.of("baldersheim"), "2021-02-15", "2021-04-01",
"Max number of move operations inflight",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag(
"feed-concurrency", 0.5,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"How much concurrency should be allowed for feed",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_BUCKET_EXECUTOR_FOR_LID_SPACE_COMPACT = defineFeatureFlag(
"use-bucket-executor-for-lid-space-compact", false,
List.of("baldersheim"), "2021-01-24", "2021-03-01",
"Wheter to use content-level bucket executor or legacy frozen buckets",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_BUCKET_EXECUTOR_FOR_BUCKET_MOVE = defineFeatureFlag(
"use-bucket-executor-for-bucket-move", false,
List.of("baldersheim"), "2021-02-15", "2021-04-01",
"Wheter to use content-level bucket executor or legacy frozen buckets",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_POWER_OF_TWO_CHOICES_LOAD_BALANCING = defineFeatureFlag(
"use-power-of-two-choices-load-balancing", false,
List.of("tokle"), "2020-12-02", "2021-04-01",
"Whether to use Power of two load balancing algorithm for application",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag GROUP_SUSPENSION = defineFeatureFlag(
"group-suspension", false,
List.of("hakon"), "2021-01-22", "2021-03-22",
"Allow all content nodes in a hierarchical group to suspend at the same time",
"Takes effect on the next suspension request to the Orchestrator.",
APPLICATION_ID);
public static final UnboundBooleanFlag RECONFIGURABLE_ZOOKEEPER_SERVER_FOR_CLUSTER_CONTROLLER = defineFeatureFlag(
"reconfigurable-zookeeper-server-for-cluster-controller", false,
List.of("musum", "mpolden"), "2020-12-16", "2021-03-16",
"Whether to use reconfigurable zookeeper server for cluster controller",
"Takes effect on (re)redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag ENABLE_FEED_BLOCK_IN_DISTRIBUTOR = defineFeatureFlag(
"enable-feed-block-in-distributor", false,
List.of("geirst"), "2021-01-27", "2021-04-01",
"Enables blocking of feed in the distributor if resource usage is above limit on at least one content node",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag MAX_DEAD_BYTES_RATIO = defineDoubleFlag(
"max-dead-bytes-ratio", 0.2,
List.of("baldersheim", "geirst","toregge"), "2021-02-03", "2021-04-01",
"max ratio of dead to used memory bytes in large data structures before compaction is attempted",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag SYNC_HOST_LOGS_TO_S3_BUCKET = defineStringFlag(
"sync-host-logs-to-s3-bucket", "", List.of("andreer", "valerijf"), "2021-02-10", "2021-03-01",
"Host-admin should sync host logs to an S3 bucket named by this flag. If left empty, sync is disabled",
"Takes effect on next run of S3 log sync task in host-admin",
APPLICATION_ID, NODE_TYPE);
public static final UnboundIntFlag CLUSTER_CONTROLLER_MAX_HEAP_SIZE_IN_MB = defineIntFlag(
"cluster-controller-max-heap-size-in-mb", 512,
List.of("hmusum"), "2021-02-10", "2021-04-10",
"JVM max heap size for cluster controller in Mb",
"Takes effect when restarting cluster controller");
public static final UnboundBooleanFlag DEDICATED_CLUSTER_CONTROLLER_CLUSTER = defineFeatureFlag(
"dedicated-cluster-controller-cluster", false,
List.of("jonmv"), "2021-02-15", "2021-04-15",
"Makes application eligible for switching to a dedicated, shared cluster controller cluster, by a maintainer",
"Takes effect immediately",
APPLICATION_ID);
public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag(
"allowed-athenz-proxy-identities", List.of(), String.class,
List.of("bjorncs", "tokle"), "2021-02-10", "2021-08-01",
"Allowed Athenz proxy identities",
"takes effect at redeployment");
public static final UnboundBooleanFlag GENERATE_NON_MTLS_ENDPOINT = defineFeatureFlag(
"generate-non-mtls-endpoint", true,
List.of("tokle"), "2021-02-18", "2021-10-01",
"Whether to generate the non-mtls endpoint",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag(
"max-activation-inhibited-out-of-sync-groups", 0,
List.of("vekterli"), "2021-02-19", "2021-05-01",
"Allows replicas in up to N content groups to not be activated " +
"for query visibility if they are out of sync with a majority of other replicas",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass),
flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass,
List<String> owners, String createdAt, String expiresAt,
String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec),
flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
@FunctionalInterface
private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> {
U create(FlagId id, T defaultVale, FetchVector defaultFetchVector);
}
/**
* Defines a Flag.
*
* @param factory Factory for creating unbound flag of type U
* @param flagId The globally unique FlagId.
* @param defaultValue The default value if none is present after resolution.
* @param description Description of how the flag is used.
* @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc.
* @param dimensions What dimensions will be set in the {@link FetchVector} when fetching
* the flag value in
* {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}.
* For instance, if APPLICATION is one of the dimensions here, you should make sure
* APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag
* from the FlagSource.
* @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features.
* @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag.
* @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and
* {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment
* is typically implicit.
*/
private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory,
String flagId,
T defaultValue,
List<String> owners,
String createdAt,
String expiresAt,
String description,
String modificationEffect,
FetchVector.Dimension[] dimensions) {
FlagId id = new FlagId(flagId);
FetchVector vector = new FetchVector()
.with(HOSTNAME, Defaults.getDefaults().vespaHostname())
// Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0
// (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0.
.with(VESPA_VERSION, Vtag.currentVersion.toFullString());
U unboundFlag = factory.create(id, defaultValue, vector);
FlagDefinition definition = new FlagDefinition(
unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions);
flags.put(id, definition);
return unboundFlag;
}
private static Instant parseDate(String rawDate) {
return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC);
}
public static List<FlagDefinition> getAllFlags() {
return List.copyOf(flags.values());
}
public static Optional<FlagDefinition> getFlag(FlagId flagId) {
return Optional.ofNullable(flags.get(flagId));
}
/**
* Allows the statically defined flags to be controlled in a test.
*
* <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block,
* the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from
* before the block is reinserted.
*
* <p>NOT thread-safe. Tests using this cannot run in parallel.
*/
public static Replacer clearFlagsForTesting() {
return new Replacer();
}
public static class Replacer implements AutoCloseable {
private static volatile boolean flagsCleared = false;
private final TreeMap<FlagId, FlagDefinition> savedFlags;
private Replacer() {
verifyAndSetFlagsCleared(true);
this.savedFlags = Flags.flags;
Flags.flags = new TreeMap<>();
}
@Override
public void close() {
verifyAndSetFlagsCleared(false);
Flags.flags = savedFlags;
}
/**
* Used to implement a simple verification that Replacer is not used by multiple threads.
* For instance two different tests running in parallel cannot both use Replacer.
*/
private static void verifyAndSetFlagsCleared(boolean newValue) {
if (flagsCleared == newValue) {
throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?");
}
flagsCleared = newValue;
}
}
}
|
package org.rstudio.studio.client.workbench.views.source.editors.text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.rstudio.core.client.CommandWithArg;
import org.rstudio.core.client.DebouncedCommand;
import org.rstudio.core.client.Debug;
import org.rstudio.core.client.Pair;
import org.rstudio.core.client.Rendezvous;
import org.rstudio.core.client.SerializedCommand;
import org.rstudio.core.client.SerializedCommandQueue;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.AppCommand;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.patch.TextChange;
import org.rstudio.core.client.widget.HasFindReplace;
import org.rstudio.core.client.widget.ProgressPanel;
import org.rstudio.core.client.widget.images.ProgressImages;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.panmirror.PanmirrorCode;
import org.rstudio.studio.client.panmirror.PanmirrorContext;
import org.rstudio.studio.client.panmirror.PanmirrorKeybindings;
import org.rstudio.studio.client.panmirror.PanmirrorOptions;
import org.rstudio.studio.client.panmirror.PanmirrorUIContext;
import org.rstudio.studio.client.panmirror.PanmirrorUIDisplay;
import org.rstudio.studio.client.panmirror.PanmirrorWidget;
import org.rstudio.studio.client.panmirror.PanmirrorWidget.FormatSource;
import org.rstudio.studio.client.panmirror.PanmirrorWriterOptions;
import org.rstudio.studio.client.panmirror.command.PanmirrorCommands;
import org.rstudio.studio.client.panmirror.format.PanmirrorExtendedDocType;
import org.rstudio.studio.client.panmirror.format.PanmirrorFormat;
import org.rstudio.studio.client.panmirror.format.PanmirrorHugoExtensions;
import org.rstudio.studio.client.panmirror.format.PanmirrorRmdExtensions;
import org.rstudio.studio.client.panmirror.location.PanmirrorEditingLocation;
import org.rstudio.studio.client.panmirror.location.PanmirrorEditingOutlineLocation;
import org.rstudio.studio.client.panmirror.location.PanmirrorEditingOutlineLocationItem;
import org.rstudio.studio.client.panmirror.outline.PanmirrorOutlineItemType;
import org.rstudio.studio.client.panmirror.pandoc.PanmirrorPandocFormat;
import org.rstudio.studio.client.panmirror.uitools.PanmirrorFormatComment;
import org.rstudio.studio.client.panmirror.uitools.PanmirrorUITools;
import org.rstudio.studio.client.panmirror.uitools.PanmirrorUIToolsFormat;
import org.rstudio.studio.client.panmirror.uitools.PanmirrorUIToolsSource;
import org.rstudio.studio.client.rmarkdown.model.YamlFrontMatter;
import org.rstudio.studio.client.server.VoidServerRequestCallback;
import org.rstudio.studio.client.workbench.WorkbenchContext;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.model.BlogdownConfig;
import org.rstudio.studio.client.workbench.model.Session;
import org.rstudio.studio.client.workbench.model.SessionInfo;
import org.rstudio.studio.client.workbench.prefs.model.UserPrefs;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position;
import org.rstudio.studio.client.workbench.views.source.model.DirtyState;
import org.rstudio.studio.client.workbench.views.source.model.DocUpdateSentinel;
import org.rstudio.studio.client.workbench.views.source.model.SourceServerOperations;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Command;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.inject.Inject;
public class TextEditingTargetVisualMode
{
public TextEditingTargetVisualMode(TextEditingTarget target,
TextEditingTarget.Display view,
DocDisplay docDisplay,
DirtyState dirtyState,
DocUpdateSentinel docUpdateSentinel,
EventBus eventBus,
final ArrayList<HandlerRegistration> releaseOnDismiss)
{
RStudioGinjector.INSTANCE.injectMembers(this);
target_ = target;
view_ = view;
docDisplay_ = docDisplay;
dirtyState_ = dirtyState;
docUpdateSentinel_ = docUpdateSentinel;
progress_ = new ProgressPanel(ProgressImages.createSmall(), 200);
// if visual mode isn't enabled then reflect that (if it is enabled we'll
// defer initialization work until after the tab is actually activated)
if (!isActivated())
manageUI(false, false);
// track changes over time
releaseOnDismiss.add(onDocPropChanged(TextEditingTarget.RMD_VISUAL_MODE, (value) -> {
manageUI(isActivated(), true);
}));
// sync to outline visible prop
releaseOnDismiss.add(onDocPropChanged(TextEditingTarget.DOC_OUTLINE_VISIBLE, (value) -> {
withPanmirror(() -> {
panmirror_.showOutline(getOutlineVisible(), getOutlineWidth(), true);
});
}));
// sync to user pref changed
releaseOnDismiss.add(prefs_.enableVisualMarkdownEditingMode().addValueChangeHandler((value) -> {
view_.manageCommandUI();
}));
// changes to line wrapping prefs make us dirty
releaseOnDismiss.add(prefs_.visualMarkdownEditingWrapAuto().addValueChangeHandler((value) -> {
isDirty_ = true;
}));
releaseOnDismiss.add(prefs_.visualMarkdownEditingWrapColumn().addValueChangeHandler((value) -> {
isDirty_ = true;
}));
}
@Inject
public void initialize(Commands commands,
UserPrefs prefs,
SourceServerOperations source,
WorkbenchContext context,
Session session)
{
commands_ = commands;
prefs_ = prefs;
source_ = source;
context_ = context;
sessionInfo_ = session.getSessionInfo();
}
public boolean isActivated()
{
return docUpdateSentinel_.getBoolProperty(TextEditingTarget.RMD_VISUAL_MODE, false);
}
public void deactivate(ScheduledCommand completed)
{
if (isActivated())
{
docUpdateSentinel_.setBoolProperty(TextEditingTarget.RMD_VISUAL_MODE, false);
manageUI(false, true, completed);
}
else
{
completed.execute();
}
}
public void syncToEditor(boolean activatingEditor)
{
syncToEditor(activatingEditor, null);
}
public void syncToEditor(boolean activatingEditor, Command ready)
{
// This is an asynchronous task, that we want to behave in a mostly FIFO
// way when overlapping calls to syncToEditor are made.
// Each syncToEditor operation can be thought of as taking place in three
// phases:
// 1 - Synchronously gathering state from panmirror, and kicking off the
// async pandoc operation
// 2 - The pandoc operation itself--this happens completely off the UI
// thread (in a different process in fact)
// 3 - With the result from pandoc, do some synchronous processing, sync
// the source editor, and invoke the `ready` parameter
// Part 2 is a "pure" operation so it doesn't matter when it runs. What
// matters is that phase 1 gathers state at the moment it's called, and
// if there are multiple operations in progress simultaneously, that the
// order in which different phase 3's are invoked reflect the order the
// operations were started. For example, if syncToEditor was called once
// (A) and then again (B), any of these sequences are fine:
// A1->A2->A3->B1->B2->B3
// A1->B1->A2->B2->A3->B3
// or even
// A1->B1->B2->A2->A3->B3
// but NOT
// A1->A2->B1->B2->B3->A3
// because if A1 comes before B1, then A3 must come before B3.
// Our plan of execution is:
// 1. Start the async operation
// 2a. Wait for the async operation to finish
// 2b. Wait for all preceding async operations to finish
// 3. Run our phase 3 logic and ready.execute()
// 4. Signal to the next succeeding async operation (if any) that we're
// done
// We use syncToEditorQueue_ to enforce the FIFO ordering. Because we
// don't know whether the syncToEditorQueue_ or the pandoc operation will
// finish first, we use a Rendezvous object to make sure both conditions
// are satisfied before we proceed.
Rendezvous rv = new Rendezvous(2);
syncToEditorQueue_.addCommand(new SerializedCommand() {
@Override
public void onExecute(Command continuation)
{
// We pass false to arrive() because it's important to not invoke
// the continuation before our phase 3 work has completed; the whole
// point is to enforce ordering of phase 3.
rv.arrive(() -> {
continuation.execute();
}, false);
}
});
if (isPanmirrorActive() && (activatingEditor || isDirty_)) {
// set flags
isDirty_ = false;
withPanmirror(() -> {
getMarkdown(markdown -> {
rv.arrive(() -> {
if (markdown == null) {
// note that ready.execute() is never called in the error case
return;
}
// determine changes
TextEditorContainer.Changes changes = toEditorChanges(markdown);
// apply them
getSourceEditor().applyChanges(changes, activatingEditor);
// callback
if (ready != null) {
ready.execute();
}
}, true);
});
});
} else {
// Even if ready is null, it's important to arrive() so the
// syncToEditorQueue knows it can continue
rv.arrive(() -> {
if (ready != null) {
ready.execute();
}
}, true);
}
}
private void syncFromEditor(Command ready, boolean focus)
{
// flag to prevent the document being set to dirty when loading
// from source mode
loadingFromSource_ = true;
// if there is a previous format comment and it's changed then
// we need to tear down the editor instance and create a new one
if (panmirrorFormatComment_ != null && panmirrorFormatComment_.hasChanged())
{
panmirrorFormatComment_ = null;
view_.editorContainer().removeWidget(panmirror_);
panmirror_ = null;
}
withPanmirror(() -> {
String editorCode = getEditorCode();
panmirror_.setMarkdown(editorCode, this.panmirrorWriterOptions(), true, (markdown) -> {
// bail on error
if (markdown == null)
return;
// activate editor
if (ready != null)
ready.execute();
// update flags
isDirty_ = false;
loadingFromSource_ = false;
// if pandoc's view of the document doesn't match the editor's we
// need to reset the editor's code (for both dirty state and
// so that diffs are efficient)
if (markdown != null && markdown != editorCode)
getSourceEditor().setCode(markdown);
Scheduler.get().scheduleDeferred(() -> {
// set editing location
panmirror_.setEditingLocation(getOutlineLocation(), savedEditingLocation());
// set focus
if (focus)
panmirror_.focus();
// show any format or extension warnings
PanmirrorPandocFormat format = panmirror_.getPandocFormat();
if (format.warnings.invalidFormat.length() > 0)
{
view_.showWarningBar("Invalid Pandoc format: " + format.warnings.invalidFormat);
}
else if (format.warnings.invalidOptions.length > 0)
{
view_.showWarningBar("Unsupported extensions for markdown mode: " + String.join(", ", format.warnings.invalidOptions));
;
}
});
});
});
}
public void syncFromEditorIfActivated()
{
if (isActivated())
{
// get reference to the editing container
TextEditorContainer editorContainer = view_.editorContainer();
// show progress
progress_.beginProgressOperation(400);
editorContainer.activateWidget(progress_);
syncFromEditor(() -> {
// clear progress
progress_.endProgressOperation();
// re-activate panmirror widget
editorContainer.activateWidget(panmirror_, false);
}, false);
}
}
public void manageCommands()
{
if (isActivated())
{
// if this is the first time we've switched to the doc
// while in visual mode then complete initialization
if (!haveEditedInVisualMode_)
{
haveEditedInVisualMode_ = true;
manageUI(true, true);
}
else
{
onActivating();
}
}
disableForVisualMode(
commands_.insertChunk(),
commands_.jumpTo(),
commands_.jumpToMatching(),
commands_.showDiagnosticsActiveDocument(),
commands_.goToHelp(),
commands_.goToDefinition(),
commands_.extractFunction(),
commands_.extractLocalVariable(),
commands_.renameInScope(),
commands_.reflowComment(),
commands_.commentUncomment(),
commands_.insertRoxygenSkeleton(),
commands_.reindent(),
commands_.reformatCode(),
commands_.findSelectAll(),
commands_.findFromSelection(),
commands_.executeSetupChunk(),
commands_.executeAllCode(),
commands_.executeCode(),
commands_.executeCodeWithoutFocus(),
commands_.executeCodeWithoutMovingCursor(),
commands_.executeCurrentChunk(),
commands_.executeCurrentFunction(),
commands_.executeCurrentLine(),
commands_.executeCurrentParagraph(),
commands_.executeCurrentSection(),
commands_.executeCurrentStatement(),
commands_.executeFromCurrentLine(),
commands_.executeLastCode(),
commands_.executeNextChunk(),
commands_.executePreviousChunks(),
commands_.executeSubsequentChunks(),
commands_.executeToCurrentLine(),
commands_.sendToTerminal(),
commands_.runSelectionAsJob(),
commands_.runSelectionAsLauncherJob(),
commands_.sourceActiveDocument(),
commands_.sourceActiveDocumentWithEcho(),
commands_.pasteWithIndentDummy(),
commands_.fold(),
commands_.foldAll(),
commands_.unfold(),
commands_.unfoldAll(),
commands_.yankAfterCursor(),
commands_.notebookExpandAllOutput(),
commands_.notebookCollapseAllOutput(),
commands_.notebookClearAllOutput(),
commands_.notebookClearOutput(),
commands_.goToLine(),
commands_.wordCount(),
commands_.restartRClearOutput(),
commands_.restartRRunAllChunks(),
commands_.profileCode()
);
}
public void unmanageCommands()
{
restoreDisabledForVisualMode();
}
public HasFindReplace getFindReplace()
{
if (panmirror_ != null) {
return panmirror_.getFindReplace();
} else {
return new HasFindReplace() {
public boolean isFindReplaceShowing() { return false; }
public void showFindReplace(boolean defaultForward) {}
public void hideFindReplace() {}
public void findNext() {}
public void findPrevious() {}
public void replaceAndFind() {}
};
}
}
public void activateDevTools()
{
withPanmirror(() -> {
panmirror_.activateDevTools();
});
}
public void onClosing()
{
if (syncOnIdle_ != null)
syncOnIdle_.suspend();
if (saveLocationOnIdle_ != null)
saveLocationOnIdle_.suspend();
}
private void manageUI(boolean activate, boolean focus)
{
manageUI(activate, focus, () -> {});
}
private void manageUI(boolean activate, boolean focus, ScheduledCommand completed)
{
// validate the activation
if (activate)
{
String invalid = validateActivation();
if (invalid != null)
{
docUpdateSentinel_.setBoolProperty(TextEditingTarget.RMD_VISUAL_MODE, false);
view_.showWarningBar(invalid);
return;
}
}
// manage commands
manageCommands();
// manage toolbar buttons / menus in display
view_.manageCommandUI();
// get references to the editing container and it's source editor
TextEditorContainer editorContainer = view_.editorContainer();
// visual mode enabled (panmirror editor)
if (activate)
{
// show progress (as this may well require either loading the
// panmirror library for the first time or a reload of visual mode,
// which is normally instant but for very, very large documents
// can take a couple of seconds)
progress_.beginProgressOperation(400);
editorContainer.activateWidget(progress_);
Command activator = () -> {
// clear progress
progress_.endProgressOperation();
// sync to editor outline prefs
panmirror_.showOutline(getOutlineVisible(), getOutlineWidth());
// activate widget
editorContainer.activateWidget(panmirror_, focus);
// begin save-on-idle behavior
syncOnIdle_.resume();
saveLocationOnIdle_.resume();
// run activating logic
onActivating();
// execute completed hook
Scheduler.get().scheduleDeferred(completed);
};
withPanmirror(() -> {
// if we aren't currently active then set our markdown based
// on what's currently in the source ditor
if (!isPanmirrorActive())
{
syncFromEditor(activator, focus);
}
else
{
activator.execute();
}
});
}
// visual mode not enabled (source editor)
else
{
// sync any pending edits, then activate the editor
syncToEditor(true, () -> {
unmanageCommands();
editorContainer.activateEditor(focus);
if (syncOnIdle_ != null)
syncOnIdle_.suspend();
if (saveLocationOnIdle_ != null)
saveLocationOnIdle_.suspend();
// execute completed hook
Scheduler.get().scheduleDeferred(completed);
});
}
}
private void onActivating()
{
syncDevTools();
target_.checkForExternalEdit(500);
}
private void syncDevTools()
{
if (panmirror_ != null && panmirror_.devToolsLoaded())
panmirror_.activateDevTools();
}
private void withPanmirror(Command ready)
{
if (panmirror_ == null)
{
// create panmirror
PanmirrorContext context = new PanmirrorContext(uiContext(), uiDisplay());
PanmirrorOptions options = panmirrorOptions();
PanmirrorWidget.Options widgetOptions = new PanmirrorWidget.Options();
PanmirrorWidget.create(context, panmirrorFormat(), options, widgetOptions, (panmirror) -> {
// save reference to panmirror
panmirror_ = panmirror;
// track format comment (used to detect when we need to reload for a new format)
panmirrorFormatComment_ = new FormatComment(new PanmirrorUITools().format);
// remove some keybindings that conflict with the ide
disableKeys(
PanmirrorCommands.Paragraph,
PanmirrorCommands.Heading1, PanmirrorCommands.Heading2, PanmirrorCommands.Heading3,
PanmirrorCommands.Heading4, PanmirrorCommands.Heading5, PanmirrorCommands.Heading6,
PanmirrorCommands.TightList
);
// periodically sync edits back to main editor
syncOnIdle_ = new DebouncedCommand(1000)
{
@Override
protected void execute()
{
if (isDirty_ && !panmirror_.isInitialDoc())
syncToEditor(false);
}
};
// periodically save selection
saveLocationOnIdle_ = new DebouncedCommand(1000)
{
@Override
protected void execute()
{
PanmirrorEditingLocation location = panmirror_.getEditingLocation();
String locationProp = + location.pos + ":" + location.scrollTop;
docUpdateSentinel_.setProperty(RMD_VISUAL_MODE_LOCATION, locationProp);
}
};
// set dirty flag + nudge idle sync on change
panmirror_.addChangeHandler(new ChangeHandler()
{
@Override
public void onChange(ChangeEvent event)
{
// set flag and nudge sync on idle
isDirty_ = true;
syncOnIdle_.nudge();
// update editor dirty state if necessary
if (!loadingFromSource_ && !dirtyState_.getValue())
{
dirtyState_.markDirty(false);
source_.setSourceDocumentDirty(
docUpdateSentinel_.getId(), true,
new VoidServerRequestCallback());
}
}
});
// save selection
panmirror_.addSelectionChangeHandler(new SelectionChangeEvent.Handler()
{
@Override
public void onSelectionChange(SelectionChangeEvent event)
{
saveLocationOnIdle_.nudge();
}
});
// track changes in outline sidebar and save as prefs
panmirror_.addPanmirrorOutlineVisibleHandler((event) -> {
setOutlineVisible(event.getVisible());
});
panmirror_.addPanmirrorOutlineWidthHandler((event) -> {
setOutlineWidth(event.getWidth());
});
// good to go!
ready.execute();
});
}
else
{
// panmirror already created
ready.execute();
}
}
// bizzarly, removing this method triggers a gwt compiler issue that
// results in the Panmirror interop breaking! we need to investigate
// this, but in the meantime the method remains. note that this method
// *should not* be called as it doesn't handle re-entrancy correctly
// (the restoring of the getActiveWidget can result in forever progress
// when 2 calls to withProgress are in the promise chain)
@SuppressWarnings("unused")
private void withProgress(int delayMs, CommandWithArg<Command> command)
{
TextEditorContainer editorContainer = view_.editorContainer();
/*
IsHideableWidget prevWidget = editorContainer.getActiveWidget();
progress_.beginProgressOperation(delayMs);
editorContainer.activateWidget(progress_);
command.execute(() -> {
progress_.endProgressOperation();
editorContainer.activateWidget(prevWidget);
});
*/
}
private void getMarkdown(CommandWithArg<PanmirrorCode> completed)
{
panmirror_.getMarkdown(panmirrorWriterOptions(), completed);
}
private PanmirrorWriterOptions panmirrorWriterOptions()
{
PanmirrorWriterOptions options = new PanmirrorWriterOptions();
options.atxHeaders = true;
if (prefs_.visualMarkdownEditingWrapAuto().getValue())
options.wrapColumn = prefs_.visualMarkdownEditingWrapColumn().getValue();
return options;
}
private String getEditorCode()
{
TextEditorContainer editorContainer = view_.editorContainer();
TextEditorContainer.Editor editor = editorContainer.getEditor();
return editor.getCode();
}
// is our widget active in the editor container
private boolean isPanmirrorActive()
{
return view_.editorContainer().isWidgetActive(panmirror_);
}
private TextEditorContainer.Editor getSourceEditor()
{
return view_.editorContainer().getEditor();
}
private boolean getOutlineVisible()
{
return target_.getPreferredOutlineWidgetVisibility();
}
private void setOutlineVisible(boolean visible)
{
target_.setPreferredOutlineWidgetVisibility(visible);
}
private double getOutlineWidth()
{
return target_.getPreferredOutlineWidgetSize();
}
private void setOutlineWidth(double width)
{
target_.setPreferredOutlineWidgetSize(width);
}
private PanmirrorEditingLocation savedEditingLocation()
{
String location = docUpdateSentinel_.getProperty(RMD_VISUAL_MODE_LOCATION, null);
if (StringUtil.isNullOrEmpty(location))
return null;
String[] parts = location.split(":");
if (parts.length != 2)
return null;
try
{
PanmirrorEditingLocation editingLocation = new PanmirrorEditingLocation();
editingLocation.pos = Integer.parseInt(parts[0]);
editingLocation.scrollTop = Integer.parseInt(parts[1]);
return editingLocation;
}
catch(Exception ex)
{
Debug.logException(ex);
return null;
}
}
private PanmirrorEditingOutlineLocation getOutlineLocation()
{
// if we are at the very top of the file then this is a not a good 'hint'
// for where to navigate to, in that case return null
Position cursorPosition = docDisplay_.getCursorPosition();
if (cursorPosition.getRow() == 0 && cursorPosition.getColumn() == 0)
return null;
// build the outline
ArrayList<Pair<PanmirrorEditingOutlineLocationItem, Scope>> outlineItems =
new ArrayList<Pair<PanmirrorEditingOutlineLocationItem, Scope>>();
buildOutlineLocation(docDisplay_.getScopeTree(), outlineItems);
// return the location, set the active item by scanning backwards until
// we find an item with a position before the cursor
boolean foundActive = false;
Position cursorPos = docDisplay_.getCursorPosition();
ArrayList<PanmirrorEditingOutlineLocationItem> items = new ArrayList<PanmirrorEditingOutlineLocationItem>();
for (int i = outlineItems.size() - 1; i >= 0; i
{
Pair<PanmirrorEditingOutlineLocationItem, Scope> outlineItem = outlineItems.get(i);
PanmirrorEditingOutlineLocationItem item = outlineItem.first;
Scope scope = outlineItem.second;
if (!foundActive && scope.getPreamble().isBefore(cursorPos))
{
item.active = true;
foundActive = true;
}
items.add(0, item);
}
PanmirrorEditingOutlineLocation location = new PanmirrorEditingOutlineLocation();
location.items = items.toArray(new PanmirrorEditingOutlineLocationItem[] {});
return location;
}
private void buildOutlineLocation(JsArray<Scope> scopes,
ArrayList<Pair<PanmirrorEditingOutlineLocationItem, Scope>> outlineItems)
{
for (int i = 0; i<scopes.length(); i++)
{
// get scope
Scope scope = scopes.get(i);
// create item + default values
PanmirrorEditingOutlineLocationItem item = new PanmirrorEditingOutlineLocationItem();
item.level = scope.getDepth();
item.title = scope.getLabel();
item.active = false;
// process yaml, headers, and chunks
if (scope.isYaml())
{
item.type = PanmirrorOutlineItemType.YamlMetadata;
outlineItems.add(new Pair<PanmirrorEditingOutlineLocationItem, Scope>(item, scope));
}
else if (scope.isMarkdownHeader())
{
item.type = PanmirrorOutlineItemType.Heading;
outlineItems.add(new Pair<PanmirrorEditingOutlineLocationItem, Scope>(item, scope));
buildOutlineLocation(scope.getChildren(), outlineItems);
}
else if (scope.isChunk())
{
item.type = PanmirrorOutlineItemType.RmdChunk;
item.title = scope.getChunkLabel();
outlineItems.add(new Pair<PanmirrorEditingOutlineLocationItem, Scope>(item, scope));
}
}
}
private void disableKeys(String... commands)
{
PanmirrorKeybindings keybindings = disabledKeybindings(commands);
panmirror_.setKeybindings(keybindings);
}
private PanmirrorKeybindings disabledKeybindings(String... commands)
{
PanmirrorKeybindings keybindings = new PanmirrorKeybindings();
for (String command : commands)
keybindings.add(command, new String[0]);
return keybindings;
}
private void disableForVisualMode(AppCommand... commands)
{
if (isActivated())
{
for (AppCommand command : commands)
{
if (command.isVisible() &&
command.isEnabled() &&
!disabledForVisualMode_.contains(command))
{
command.setEnabled(false);
disabledForVisualMode_.add(command);
}
}
}
}
private void restoreDisabledForVisualMode()
{
disabledForVisualMode_.forEach((command) -> {
command.setEnabled(true);
});
disabledForVisualMode_.clear();
}
private HandlerRegistration onDocPropChanged(String prop, ValueChangeHandler<String> handler)
{
return docUpdateSentinel_.addPropertyValueChangeHandler(prop, handler);
}
private PanmirrorUIContext uiContext()
{
PanmirrorUIContext uiContext = new PanmirrorUIContext();
uiContext.getDefaultResourceDir = () -> {
if (docUpdateSentinel_.getPath() != null)
return FileSystemItem.createDir(docUpdateSentinel_.getPath()).getParentPathString();
else
return context_.getCurrentWorkingDir().getPath();
};
uiContext.mapPathToResource = path -> {
FileSystemItem resourceDir = FileSystemItem.createDir(uiContext.getDefaultResourceDir.get());
FileSystemItem file = FileSystemItem.createFile(path);
String resourcePath = file.getPathRelativeTo(resourceDir);
if (resourcePath != null)
{
return resourcePath;
}
else
{
// try for hugo asset
return pathToHugoAsset(path);
}
};
uiContext.mapResourceToURL = path -> {
// see if this a hugo asset
String hugoPath = hugoAssetPath(path);
if (hugoPath != null)
path = hugoPath;
FileSystemItem resourceDir = FileSystemItem.createDir(uiContext.getDefaultResourceDir.get());
return ImagePreviewer.imgSrcPathFromHref(resourceDir.getPath(), path);
};
uiContext.translateText = text -> {
return text;
};
return uiContext;
}
private PanmirrorUIDisplay uiDisplay()
{
PanmirrorUIDisplay uiDisplay = new PanmirrorUIDisplay();
uiDisplay.showContextMenu = (commands, clientX, clientY) -> {
panmirror_.showContextMenu(commands, clientX, clientY);
};
return uiDisplay;
}
private PanmirrorOptions panmirrorOptions()
{
// create options
PanmirrorOptions options = new PanmirrorOptions();
// use embedded codemirror for code blocks
options.codemirror = true;
// enable rmdImagePreview if we are an executable rmd
options.rmdImagePreview = target_.canExecuteChunks();
// hide the format comment so that users must go into
// source mode to change formats
options.hideFormatComment = true;
// add focus-visible class to prevent interaction with focus-visible.js
// (it ends up attempting to apply the "focus-visible" class b/c ProseMirror
// is contentEditable, and that triggers a dom mutation event for ProseMirror,
// which in turn causes us to lose table selections)
options.className = "focus-visible";
return options;
}
private FormatSource panmirrorFormat()
{
return new PanmirrorWidget.FormatSource()
{
@Override
public PanmirrorFormat getFormat(PanmirrorUIToolsFormat formatTools)
{
// create format
PanmirrorFormat format = new PanmirrorFormat();
// see if we have a format comment
PanmirrorFormatComment formatComment = formatTools.parseFormatComment(getEditorCode());
// doctypes
List<String> docTypes = new ArrayList<String>();
if (formatComment.doctypes == null || formatComment.doctypes.length == 0)
{
if (isXRefDocument())
docTypes.add(PanmirrorExtendedDocType.xref);
if (isBookdownDocument())
docTypes.add(PanmirrorExtendedDocType.bookdown);
if (isBlogdownDocument())
docTypes.add(PanmirrorExtendedDocType.blogdown);
if (isHugoDocument())
docTypes.add(PanmirrorExtendedDocType.hugo);
format.docTypes = docTypes.toArray(new String[] {});
}
docTypes = Arrays.asList(format.docTypes);
// mode and extensions
// non-standard mode and extension either come from a format comment,
// a detection of an alternate engine (likely due to blogdown/hugo)
Pair<String,String> alternateEngine = alternateMarkdownEngine();
if (formatComment.mode != null)
{
format.pandocMode = formatComment.mode;
format.pandocExtensions = StringUtil.notNull(formatComment.extensions);
}
else if (alternateEngine != null)
{
format.pandocMode = alternateEngine.first;
format.pandocExtensions = alternateEngine.second;
if (formatComment.extensions != null)
format.pandocExtensions += formatComment.extensions;
}
else
{
format.pandocMode = "markdown";
format.pandocExtensions = "+autolink_bare_uris+tex_math_single_backslash";
if (formatComment.extensions != null)
format.pandocExtensions += formatComment.extensions;
}
// rmdExtensions
format.rmdExtensions = new PanmirrorRmdExtensions();
format.rmdExtensions.codeChunks = target_.canExecuteChunks();
// support for bookdown cross-references is always enabled b/c they would not
// serialize correctly in markdown modes that don't escape @ if not enabled,
// and the odds that someone wants to literally write @ref(foo) w/o the leading
// \ are vanishingly small)
format.rmdExtensions.bookdownXRef = true;
// support for bookdown part headers is always enabled b/c typing
// (PART\*) in the visual editor would result in an escaped \, which
// wouldn't parse as a port. the odds of (PART\*) occurring naturally
// in an H1 are also vanishingly small
format.rmdExtensions.bookdownPart = true;
// enable blogdown math in code (e.g. `$math$`) if we have a blogdown
// doctype along with a custom markdown engine
format.rmdExtensions.blogdownMathInCode =
docTypes.contains(PanmirrorExtendedDocType.blogdown) &&
(getBlogdownConfig().markdown_engine != null);
// hugoExtensions
format.hugoExtensions = new PanmirrorHugoExtensions();
// always enable hugo shortcodes (w/o this we can end up destroying
// shortcodes during round-tripping, and we don't want to require that
// blogdown files be opened within projects). this idiom is obscure
// enough that it's vanishingly unlikely to affect non-blogdown docs
format.hugoExtensions.shortcodes = true;
// fillColumn
format.wrapColumn = formatComment.fillColumn;
// return format
return format;
}
};
}
private String validateActivation()
{
if (this.docDisplay_.hasActiveCollabSession())
{
return "You cannot enter visual mode while using realtime collaboration.";
}
else if (isXaringanDocument())
{
return "Xaringan presentations cannot be edited in visual mode.";
}
else
{
return null;
}
}
private boolean isXRefDocument()
{
return isBookdownDocument() || isBlogdownDocument() || isDistillDocument();
}
private boolean isBookdownDocument()
{
return sessionInfo_.getBuildToolsBookdownWebsite() && isDocInProject();
}
private boolean isBlogdownDocument()
{
return getBlogdownConfig().is_blogdown_project && isDocInProject();
}
private boolean isHugoDocument()
{
return getBlogdownConfig().is_hugo_project && isDocInProject();
}
private String pathToHugoAsset(String path)
{
if (isHugoDocument())
{
FileSystemItem file = FileSystemItem.createFile(path);
for (FileSystemItem dir : hugoStaticDirs())
{
String assetPath = file.getPathRelativeTo(dir);
if (assetPath != null)
return "/" + assetPath;
}
return null;
}
else
{
return null;
}
}
// TODO: currently can only serve image preview out of main static dir
// (to resolve we'd need to create a server-side handler that presents
// a union view of the various static dirs, much as hugo does internally)
private String hugoAssetPath(String asset)
{
if (isHugoDocument() && asset.startsWith("/"))
{
return hugoStaticDirs().get(0).completePath(asset.substring(1));
}
else
{
return null;
}
}
private List<FileSystemItem> hugoStaticDirs()
{
FileSystemItem siteDir = getBlogdownConfig().site_dir;
List<FileSystemItem> staticDirs = new ArrayList<FileSystemItem>();
for (String dir : getBlogdownConfig().static_dirs)
staticDirs.add(FileSystemItem.createDir(siteDir.completePath(dir)));
return staticDirs;
}
private BlogdownConfig getBlogdownConfig()
{
return sessionInfo_.getBlogdownConfig();
}
private boolean isDistillDocument()
{
return (sessionInfo_.getIsDistillProject() && isDocInProject()) ||
getOutputFormats().contains("distill::distill_article");
}
private boolean isXaringanDocument()
{
List<String> formats = getOutputFormats();
for (String format : formats)
{
if (format.startsWith("xaringan"))
return true;
}
return false;
}
// see if there's an alternate markdown engine in play
private Pair<String,String> alternateMarkdownEngine()
{
// if we have a doc
String docPath = docUpdateSentinel_.getPath();
if (docPath != null)
{
// collect any alternate mode we may have
BlogdownConfig config = getBlogdownConfig();
Pair<String,String> alternateMode = new Pair<String,String>(
config.markdown_engine,
config.markdown_extensions
);
// if it's a blogdown document
if (isBlogdownDocument())
{
// if it has an extension indicating hugo will render markdown
String extension = FileSystemItem.getExtensionFromPath(docPath);
if (extension.compareToIgnoreCase(".md") == 0 ||
extension.compareToIgnoreCase("Rmarkdown") == 0)
{
return alternateMode;
}
}
// if it's a hugo document (that is not a blogdown document)
else if (isHugoDocument())
{
return alternateMode;
}
}
return null;
}
private boolean isDocInProject()
{
// if we are in a project
if (context_.isProjectActive())
{
// if the doc path is null let's assume it's going to be saved
// within the current project
String docPath = docUpdateSentinel_.getPath();
if (docPath != null)
{
// if the doc is in the project directory
FileSystemItem docFile = FileSystemItem.createFile(docPath);
FileSystemItem projectDir = context_.getActiveProjectDir();
return docFile.getPathRelativeTo(projectDir) != null;
}
else
{
return true;
}
}
else
{
return false;
}
}
private List<String> getOutputFormats()
{
String yaml = YamlFrontMatter.getFrontMatter(docDisplay_);
if (yaml == null)
{
return new ArrayList<String>();
}
else
{
List<String> formats = TextEditingTargetRMarkdownHelper.getOutputFormats(yaml);
if (formats == null)
return new ArrayList<String>();
else
return formats;
}
}
private class FormatComment
{
public FormatComment(PanmirrorUIToolsFormat formatTools)
{
formatTools_ = formatTools;
comment_ = formatTools_.parseFormatComment(getEditorCode());
}
public boolean hasChanged()
{
PanmirrorFormatComment comment = formatTools_.parseFormatComment(getEditorCode());
return !PanmirrorFormatComment.areEqual(comment, comment_);
}
private final PanmirrorUIToolsFormat formatTools_;
private final PanmirrorFormatComment comment_;
}
private TextEditorContainer.Changes toEditorChanges(PanmirrorCode panmirrorCode)
{
// code to diff
String fromCode = getEditorCode();
String toCode = panmirrorCode.code;
// do the diff (timeout after 1 second). note that we only do this
// once the user has stopped typing for 1 second so it's not something
// that will run continuously during editing (in which case a much
// lower timeout would be warranted). note also that timeouts are for
// the diff planning phase so we will still get a valid diff back
// even if the timeout occurs.
PanmirrorUIToolsSource sourceTools = new PanmirrorUITools().source;
TextChange[] changes = sourceTools.diffChars(fromCode, toCode, 1);
// return changes w/ cursor
return new TextEditorContainer.Changes(
changes,
panmirrorCode.cursor != null
? new TextEditorContainer.Cursor(
panmirrorCode.cursor.row, panmirrorCode.cursor.column
)
: null
);
}
private Commands commands_;
private UserPrefs prefs_;
private WorkbenchContext context_;
private SessionInfo sessionInfo_;
private SourceServerOperations source_;
private final TextEditingTarget target_;
private final TextEditingTarget.Display view_;
private final DocDisplay docDisplay_;
private final DirtyState dirtyState_;
private final DocUpdateSentinel docUpdateSentinel_;
private DebouncedCommand syncOnIdle_;
private DebouncedCommand saveLocationOnIdle_;
private boolean isDirty_ = false;
private boolean loadingFromSource_ = false;
private boolean haveEditedInVisualMode_ = false;
private PanmirrorWidget panmirror_;
private FormatComment panmirrorFormatComment_;
private ArrayList<AppCommand> disabledForVisualMode_ = new ArrayList<AppCommand>();
private final ProgressPanel progress_;
private SerializedCommandQueue syncToEditorQueue_ = new SerializedCommandQueue();
private static final String RMD_VISUAL_MODE_LOCATION = "rmdVisualModeLocation";
}
|
package com.yahoo.vespa.flags;
import com.yahoo.component.Vtag;
import com.yahoo.vespa.defaults.Defaults;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.CLUSTER_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.CLUSTER_TYPE;
import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME;
import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE;
import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION;
import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID;
/**
* Definitions of feature flags.
*
* <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag}
* or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p>
*
* <ol>
* <li>The unbound flag</li>
* <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding
* an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li>
* <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should
* declare this in the unbound flag definition in this file (referring to
* {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g.
* {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li>
* </ol>
*
* <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically
* there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p>
*
* @author hakonhall
*/
public class Flags {
private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>();
public static final UnboundStringFlag ALLOCATE_OS_REQUIREMENT = defineStringFlag(
"allocate-os-requirement", "rhel7",
List.of("hakonhall"), "2021-01-26", "2021-07-26",
"Allocations of new nodes are limited to the given host OS. Must be one of 'rhel7', " +
"'rhel8', or 'any'",
"Takes effect on next (re)deployment.",
APPLICATION_ID);
public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag(
"default-term-wise-limit", 1.0,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Default limit for when to apply termwise query evaluation",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag(
"feed-sequencer-type", "LATENCY",
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Selects type of sequenced executor used for feeding, valid values are LATENCY, ADAPTIVE, THROUGHPUT",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag(
"response-sequencer-type", "ADAPTIVE",
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag(
"response-num-threads", 2,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Number of threads used for mbus responses, default is 2, negative number = numcores/4",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag(
"skip-communicatiomanager-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the communicationmanager thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag(
"skip-mbus-request-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the mbus request thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag(
"skip-mbus-reply-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the mbus reply thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag(
"use-three-phase-updates", false,
List.of("vekterli"), "2020-12-02", "2021-06-01",
"Whether to enable the use of three-phase updates when bucket replicas are out of sync.",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_CLIENT_SERVER_COMMUNICATION = defineStringFlag(
"tls-for-zookeeper-client-server-communication", "TLS_WITH_PORT_UNIFICATION",
List.of("hmusum"), "2020-12-02", "2021-06-01",
"How to setup TLS for ZooKeeper client/server communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY",
"Takes effect on restart of config server",
NODE_TYPE, HOSTNAME);
public static final UnboundBooleanFlag USE_TLS_FOR_ZOOKEEPER_CLIENT = defineFeatureFlag(
"use-tls-for-zookeeper-client", true,
List.of("hmusum"), "2020-12-02", "2021-05-01",
"Whether to use TLS for ZooKeeper clients",
"Takes effect on restart of process",
NODE_TYPE, HOSTNAME);
public static final UnboundBooleanFlag PROVISION_TENANT_ROLES = defineFeatureFlag(
"provision-tenant-roles", false,
List.of("tokle"), "2020-12-02", "2021-06-01",
"Whether tenant roles should be provisioned",
"Takes effect on next deployment (controller)",
TENANT_ID);
public static final UnboundBooleanFlag TENANT_IAM_ROLE = defineFeatureFlag(
"application-iam-roles", false,
List.of("tokle"), "2020-12-02", "2021-06-01",
"Allow separate iam roles when provisioning/assigning hosts",
"Takes effect immediately on new hosts, on next redeploy for applications",
TENANT_ID);
public static final UnboundBooleanFlag HIDE_SHARED_ROUTING_ENDPOINT = defineFeatureFlag(
"hide-shared-routing-endpoint", false,
List.of("tokle"), "2020-12-02", "2021-06-01",
"Whether the controller should hide shared routing layer endpoint",
"Takes effect immediately",
APPLICATION_ID
);
public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag(
"async-message-handling-on-schedule", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Optionally deliver async messages in own thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_PENDING_MOVE_OPS = defineIntFlag(
"max-pending-move-ops", 100,
List.of("baldersheim"), "2021-02-15", "2021-05-01",
"Max number of move operations inflight",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag(
"feed-concurrency", 0.5,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"How much concurrency should be allowed for feed",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_BUCKET_EXECUTOR_FOR_LID_SPACE_COMPACT = defineFeatureFlag(
"use-bucket-executor-for-lid-space-compact", true,
List.of("baldersheim"), "2021-01-24", "2021-05-01",
"Wheter to use content-level bucket executor or legacy frozen buckets",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_BUCKET_EXECUTOR_FOR_BUCKET_MOVE = defineFeatureFlag(
"use-bucket-executor-for-bucket-move", true,
List.of("baldersheim"), "2021-02-15", "2021-05-01",
"Wheter to use content-level bucket executor or legacy frozen buckets",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag GROUP_SUSPENSION = defineFeatureFlag(
"group-suspension", true,
List.of("hakon"), "2021-01-22", "2021-04-22",
"Allow all content nodes in a hierarchical group to suspend at the same time",
"Takes effect on the next suspension request to the Orchestrator.",
APPLICATION_ID);
public static final UnboundBooleanFlag ENABLE_FEED_BLOCK_IN_DISTRIBUTOR = defineFeatureFlag(
"enable-feed-block-in-distributor", true,
List.of("geirst"), "2021-01-27", "2021-05-01",
"Enables blocking of feed in the distributor if resource usage is above limit on at least one content node",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag MAX_DEAD_BYTES_RATIO = defineDoubleFlag(
"max-dead-bytes-ratio", 0.15,
List.of("baldersheim", "geirst","toregge"), "2021-02-03", "2021-05-01",
"max ratio of dead to used memory bytes in large data structures before compaction is attempted",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag SYNC_HOST_LOGS_TO_S3_BUCKET = defineStringFlag(
"sync-host-logs-to-s3-bucket", "", List.of("andreer", "valerijf"), "2021-02-10", "2021-05-01",
"Host-admin should sync host logs to an S3 bucket named by this flag. If left empty, sync is disabled",
"Takes effect on next run of S3 log sync task in host-admin",
TENANT_ID, ZONE_ID);
public static final UnboundIntFlag CLUSTER_CONTROLLER_MAX_HEAP_SIZE_IN_MB = defineIntFlag(
"cluster-controller-max-heap-size-in-mb", 128,
List.of("hmusum"), "2021-02-10", "2021-04-10",
"JVM max heap size for cluster controller in Mb",
"Takes effect when restarting cluster controller");
public static final UnboundIntFlag METRICS_PROXY_MAX_HEAP_SIZE_IN_MB = defineIntFlag(
"metrics-proxy-max-heap-size-in-mb", 256,
List.of("hmusum"), "2021-03-01", "2021-05-01",
"JVM max heap size for metrics proxy in Mb",
"Takes effect when restarting metrics proxy",
CLUSTER_TYPE);
public static final UnboundIntFlag CONFIG_PROXY_MAX_HEAP_SIZE_IN_MB = defineIntFlag(
"config-proxy-max-heap-size-in-mb", 256,
List.of("hmusum"), "2021-03-15", "2021-05-15",
"JVM max heap size for config proxy in Mb",
"Takes effect on restart of Docker container",
CLUSTER_TYPE, CLUSTER_ID);
public static final UnboundStringFlag DEDICATED_CLUSTER_CONTROLLER_FLAVOR = defineStringFlag(
"dedicated-cluster-controller-flavor", "", List.of("jonmv"), "2021-02-25", "2021-04-25",
"Flavor as <vpu>-<memgb>-<diskgb> to use for dedicated cluster controller nodes",
"Takes effect immediately, for subsequent provisioning",
APPLICATION_ID);
public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag(
"allowed-athenz-proxy-identities", List.of(), String.class,
List.of("bjorncs", "tokle"), "2021-02-10", "2021-08-01",
"Allowed Athenz proxy identities",
"takes effect at redeployment");
public static final UnboundBooleanFlag GENERATE_NON_MTLS_ENDPOINT = defineFeatureFlag(
"generate-non-mtls-endpoint", true,
List.of("tokle"), "2021-02-18", "2021-10-01",
"Whether to generate the non-mtls endpoint",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag(
"max-activation-inhibited-out-of-sync-groups", 0,
List.of("vekterli"), "2021-02-19", "2021-05-01",
"Allows replicas in up to N content groups to not be activated " +
"for query visibility if they are out of sync with a majority of other replicas",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag WAIT_FOR_ALL_CONFIG_SERVERS_WHEN_DELETING_APPLICATION = defineFeatureFlag(
"wait-for-all-config-servers-when-deleting-application", false,
List.of("hmusum"), "2021-03-24", "2021-06-24",
"Whether to wait for all participating servers to delete application on config servers (with timeout) on",
"Takes effect on next delete of an application");
public static final UnboundBooleanFlag REBUILD_HOST = defineFeatureFlag(
"rebuild-host", false,
List.of("mpolden"), "2021-04-09", "2021-06-01",
"Whether HostRebuilder should rebuild hosts marked wantToRebuild",
"Takes effect on next HostRebuilder maintenance run");
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass),
flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass,
List<String> owners, String createdAt, String expiresAt,
String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec),
flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
@FunctionalInterface
private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> {
U create(FlagId id, T defaultVale, FetchVector defaultFetchVector);
}
/**
* Defines a Flag.
*
* @param factory Factory for creating unbound flag of type U
* @param flagId The globally unique FlagId.
* @param defaultValue The default value if none is present after resolution.
* @param description Description of how the flag is used.
* @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc.
* @param dimensions What dimensions will be set in the {@link FetchVector} when fetching
* the flag value in
* {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}.
* For instance, if APPLICATION is one of the dimensions here, you should make sure
* APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag
* from the FlagSource.
* @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features.
* @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag.
* @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and
* {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment
* is typically implicit.
*/
private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory,
String flagId,
T defaultValue,
List<String> owners,
String createdAt,
String expiresAt,
String description,
String modificationEffect,
FetchVector.Dimension[] dimensions) {
FlagId id = new FlagId(flagId);
FetchVector vector = new FetchVector()
.with(HOSTNAME, Defaults.getDefaults().vespaHostname())
// Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0
// (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0.
.with(VESPA_VERSION, Vtag.currentVersion.toFullString());
U unboundFlag = factory.create(id, defaultValue, vector);
FlagDefinition definition = new FlagDefinition(
unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions);
flags.put(id, definition);
return unboundFlag;
}
private static Instant parseDate(String rawDate) {
return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC);
}
public static List<FlagDefinition> getAllFlags() {
return List.copyOf(flags.values());
}
public static Optional<FlagDefinition> getFlag(FlagId flagId) {
return Optional.ofNullable(flags.get(flagId));
}
/**
* Allows the statically defined flags to be controlled in a test.
*
* <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block,
* the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from
* before the block is reinserted.
*
* <p>NOT thread-safe. Tests using this cannot run in parallel.
*/
public static Replacer clearFlagsForTesting() {
return new Replacer();
}
public static class Replacer implements AutoCloseable {
private static volatile boolean flagsCleared = false;
private final TreeMap<FlagId, FlagDefinition> savedFlags;
private Replacer() {
verifyAndSetFlagsCleared(true);
this.savedFlags = Flags.flags;
Flags.flags = new TreeMap<>();
}
@Override
public void close() {
verifyAndSetFlagsCleared(false);
Flags.flags = savedFlags;
}
/**
* Used to implement a simple verification that Replacer is not used by multiple threads.
* For instance two different tests running in parallel cannot both use Replacer.
*/
private static void verifyAndSetFlagsCleared(boolean newValue) {
if (flagsCleared == newValue) {
throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?");
}
flagsCleared = newValue;
}
}
}
|
package com.azure.tools.apiview.processor.analysers;
import com.azure.tools.apiview.processor.diagnostics.Diagnostics;
import com.azure.tools.apiview.processor.model.APIListing;
import com.azure.tools.apiview.processor.model.ChildItem;
import com.azure.tools.apiview.processor.model.Token;
import com.azure.tools.apiview.processor.model.TypeKind;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.AnnotationDeclaration;
import com.github.javaparser.ast.body.AnnotationMemberDeclaration;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.CallableDeclaration;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.ConstructorDeclaration;
import com.github.javaparser.ast.body.EnumConstantDeclaration;
import com.github.javaparser.ast.body.EnumDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.ReferenceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import com.github.javaparser.symbolsolver.JavaSymbolSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static com.azure.tools.apiview.processor.analysers.util.ASTUtils.getPackageName;
import static com.azure.tools.apiview.processor.analysers.util.ASTUtils.isPrivateOrPackagePrivate;
import static com.azure.tools.apiview.processor.analysers.util.ASTUtils.isTypeAPublicAPI;
import static com.azure.tools.apiview.processor.analysers.util.ASTUtils.makeId;
import static com.azure.tools.apiview.processor.model.TokenKind.KEYWORD;
import static com.azure.tools.apiview.processor.model.TokenKind.MEMBER_NAME;
import static com.azure.tools.apiview.processor.model.TokenKind.NEW_LINE;
import static com.azure.tools.apiview.processor.model.TokenKind.PUNCTUATION;
import static com.azure.tools.apiview.processor.model.TokenKind.TEXT;
import static com.azure.tools.apiview.processor.model.TokenKind.TYPE_NAME;
import static com.azure.tools.apiview.processor.model.TokenKind.WHITESPACE;
public class ASTAnalyser implements Analyser {
private final APIListing apiListing;
private final Map<String, ChildItem> packageNameToNav;
private int indent;
public ASTAnalyser(File inputFile, APIListing apiListing) {
this.apiListing = apiListing;
this.indent = 0;
this.packageNameToNav = new HashMap<>();
}
@Override
public void analyse(List<Path> allFiles) {
// firstly we filter out the files we don't care about
allFiles = allFiles.stream()
.filter(path -> {
String inputFileName = path.toString();
if (Files.isDirectory(path)) return false;
else if (inputFileName.contains("implementation")) return false;
else if (inputFileName.contains("package-info.java")) return false;
else if (inputFileName.contains("module-info.java")) return false;
else return inputFileName.endsWith(".java");
}).collect(Collectors.toList());
// then we do a pass to build a map of all known types and package names, and a map of package names to nav items,
// followed by a pass to tokenise each file
allFiles.stream()
.map(this::scanForTypes)
.filter(Optional::isPresent)
.map(Optional::get)
.sorted(Comparator.comparing(s -> s.path))
.forEach(this::processSingleFile);
// build the navigation
packageNameToNav.values().stream()
.filter(childItem -> !childItem.getChildItem().isEmpty())
.sorted(Comparator.comparing(ChildItem::getText))
.forEach(apiListing::addChildItem);
}
private static class ScanClass {
private CompilationUnit compilationUnit;
private Path path;
public ScanClass(Path path, CompilationUnit compilationUnit) {
this.compilationUnit = compilationUnit;
this.path = path;
}
}
private Optional<ScanClass> scanForTypes(Path path) {
try {
// Set up a minimal type solver that only looks at the classes used to run this sample.
CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver();
combinedTypeSolver.add(new ReflectionTypeSolver());
// Configure JavaParser to use type resolution
StaticJavaParser.getConfiguration()
.setStoreTokens(true)
.setSymbolResolver(new JavaSymbolSolver(combinedTypeSolver));
CompilationUnit compilationUnit = StaticJavaParser.parse(path);
new ScanForClassTypeVisitor().visit(compilationUnit, null);
return Optional.of(new ScanClass(path, compilationUnit));
} catch (IOException e) {
e.printStackTrace();
return Optional.empty();
}
}
private void processSingleFile(ScanClass scanClass) {
new ClassOrInterfaceVisitor().visit(scanClass.compilationUnit, null);
}
private class ClassOrInterfaceVisitor extends VoidVisitorAdapter<Void> {
private ChildItem parentNav;
ClassOrInterfaceVisitor() { }
ClassOrInterfaceVisitor(ChildItem parentNav) {
this.parentNav = parentNav;
}
@Override
public void visit(CompilationUnit compilationUnit, Void args) {
NodeList<TypeDeclaration<?>> types = compilationUnit.getTypes();
for (final TypeDeclaration<?> typeDeclaration : types) {
visitClassOrInterfaceOrEnumDeclaration(typeDeclaration);
}
Diagnostics.scan(compilationUnit, apiListing);
}
private void visitClassOrInterfaceOrEnumDeclaration(TypeDeclaration<?> typeDeclaration) {
// public custom annotation @interface's annotations
if (typeDeclaration.isAnnotationDeclaration() && !isPrivateOrPackagePrivate(typeDeclaration.getAccessSpecifier())) {
final AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration) typeDeclaration;
// Annotations on top of AnnotationDeclaration class, for example
// @Retention(RUNTIME)
// @Target(PARAMETER)
// public @interface BodyParam {}
final NodeList<AnnotationExpr> annotations = annotationDeclaration.getAnnotations();
for (AnnotationExpr annotation : annotations) {
final Optional<TokenRange> tokenRange = annotation.getTokenRange();
if (!tokenRange.isPresent()) {
continue;
}
final TokenRange annotationTokenRange = tokenRange.get();
// TODO: could be more specified instead of string
final String name = annotationTokenRange.toString();
addToken(new Token(KEYWORD, name));
addToken(new Token(NEW_LINE, ""));
}
}
// Skip if the class is private or package-private
final boolean isPrivate = getTypeDeclaration(typeDeclaration);
// Skip rest of code if the class, interface, or enum declaration is private or package private
if (isPrivate) {
return;
}
if (typeDeclaration.isEnumDeclaration()) {
getEnumEntries((EnumDeclaration)typeDeclaration);
}
// Get if the declaration is interface or not
boolean isInterfaceDeclaration = false;
if (typeDeclaration.isClassOrInterfaceDeclaration()) {
// could be interface or custom annotation @interface
isInterfaceDeclaration = typeDeclaration.asClassOrInterfaceDeclaration().isInterface();
}
// public custom annotation @interface's members
if (typeDeclaration.isAnnotationDeclaration() && !isPrivateOrPackagePrivate(typeDeclaration.getAccessSpecifier())) {
final AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration) typeDeclaration;
tokeniseAnnotationMember(annotationDeclaration);
}
// get fields
tokeniseFields(isInterfaceDeclaration, typeDeclaration);
// get Constructors
final List<ConstructorDeclaration> constructors = typeDeclaration.getConstructors();
if (constructors.isEmpty()) {
// add default constructor if there is no constructor at all
addDefaultConstructor(typeDeclaration);
} else {
tokeniseConstructorsOrMethods(isInterfaceDeclaration, constructors);
}
// get Methods
tokeniseConstructorsOrMethods(isInterfaceDeclaration, typeDeclaration.getMethods());
// get Inner classes
tokeniseInnerClasses(typeDeclaration.getMembers());
// close class
addToken(makeWhitespace());
addToken(new Token(PUNCTUATION, "}"));
addToken(new Token(NEW_LINE, ""));
}
private void getEnumEntries(EnumDeclaration enumDeclaration) {
final NodeList<EnumConstantDeclaration> enumConstantDeclarations = enumDeclaration.getEntries();
int size = enumConstantDeclarations.size();
indent();
AtomicInteger counter = new AtomicInteger();
enumConstantDeclarations.forEach(enumConstantDeclaration -> {
addToken(makeWhitespace());
// create a unique id for enum constants
final String name = enumConstantDeclaration.getNameAsString();
final String definitionId = makeId(enumDeclaration.getFullyQualifiedName().get() + "." + counter);
addToken(new Token(MEMBER_NAME, name, definitionId));
enumConstantDeclaration.getArguments().forEach(expression -> {
addToken(new Token(PUNCTUATION, "("));
addToken(new Token(TEXT, expression.toString()));
addToken(new Token(PUNCTUATION, ")"));
});
if (counter.getAndIncrement() < size - 1) {
addToken(new Token(PUNCTUATION, ","));
} else {
addToken(new Token(PUNCTUATION, ";"));
}
addToken(new Token(NEW_LINE, ""));
});
unindent();
}
private boolean getTypeDeclaration(TypeDeclaration<?> typeDeclaration) {
// Skip if the class is private or package-private, unless it is a nested type defined inside a public interface
if (!isTypeAPublicAPI(typeDeclaration)) {
return true;
}
// public class or interface or enum
addToken(makeWhitespace());
// Get modifiers
getModifiers(typeDeclaration.getModifiers());
// Get type kind
TypeKind typeKind;
if (typeDeclaration.isClassOrInterfaceDeclaration()) {
typeKind = ((ClassOrInterfaceDeclaration)typeDeclaration).isInterface() ? TypeKind.INTERFACE : TypeKind.CLASS;
} else if (typeDeclaration.isEnumDeclaration()) {
typeKind = TypeKind.ENUM;
} else if (typeDeclaration.isAnnotationDeclaration()) {
typeKind = TypeKind.INTERFACE;
} else {
typeKind = TypeKind.UNKNOWN;
}
// Create navigation for this class and add it to the parent
final String className = typeDeclaration.getNameAsString();
final String packageName = getPackageName(typeDeclaration);
final String classId = makeId(typeDeclaration);
ChildItem classNav = new ChildItem(classId, className, typeKind);
if (parentNav == null) {
packageNameToNav.get(packageName).addChildItem(classNav);
} else {
parentNav.addChildItem(classNav);
}
parentNav = classNav;
if (typeDeclaration.isAnnotationDeclaration()) {
addToken(new Token(KEYWORD, "@"));
}
addToken(new Token(KEYWORD, typeKind.getName()));
addToken(new Token(WHITESPACE, " "));
addToken(new Token(TYPE_NAME, className, classId));
NodeList<ClassOrInterfaceType> implementedTypes = null;
// Type parameters of class definition
if (typeDeclaration.isClassOrInterfaceDeclaration()) {
final ClassOrInterfaceDeclaration classOrInterfaceDeclaration = (ClassOrInterfaceDeclaration)typeDeclaration;
// Get type parameters
getTypeParameters(classOrInterfaceDeclaration.getTypeParameters());
// Extends a class
final NodeList<ClassOrInterfaceType> extendedTypes = classOrInterfaceDeclaration.getExtendedTypes();
if (!extendedTypes.isEmpty()) {
addToken(new Token(WHITESPACE, " "));
addToken(new Token(KEYWORD, "extends"));
addToken(new Token(WHITESPACE, " "));
// Java only extends one class if it is class, but can extends multiple interfaces if it is interface itself
if (extendedTypes.isNonEmpty()) {
for (int i = 0, max = extendedTypes.size() ; i < max; i++) {
final ClassOrInterfaceType extendedType = extendedTypes.get(i);
getType(extendedType);
if (i < max - 1) {
addToken(new Token(PUNCTUATION, ","));
addToken(new Token(WHITESPACE, " "));
}
}
}
}
// Assign implement types
implementedTypes = classOrInterfaceDeclaration.getImplementedTypes();
} else if (typeDeclaration.isEnumDeclaration()) {
final EnumDeclaration enumDeclaration = (EnumDeclaration)typeDeclaration;
// Assign implement types
implementedTypes = enumDeclaration.getImplementedTypes();
} else if (typeDeclaration.isAnnotationDeclaration()) {
// no-op
} else {
System.err.println("Not a class, interface or enum declaration");
}
// implements interfaces
if (implementedTypes != null && !implementedTypes.isEmpty()) {
addToken(new Token(WHITESPACE, " "));
addToken(new Token(KEYWORD, "implements"));
addToken(new Token(WHITESPACE, " "));
for (final ClassOrInterfaceType implementedType : implementedTypes) {
getType(implementedType);
addToken(new Token(PUNCTUATION, ","));
addToken(new Token(WHITESPACE, " "));
}
if (!implementedTypes.isEmpty()) {
apiListing.getTokens().remove(apiListing.getTokens().size() - 1);
apiListing.getTokens().remove(apiListing.getTokens().size() - 1);
}
}
// open ClassOrInterfaceDeclaration
addToken(new Token(WHITESPACE, " "));
addToken(new Token(PUNCTUATION, "{"));
addToken(new Token(NEW_LINE, ""));
return false;
}
private void tokeniseAnnotationMember(AnnotationDeclaration annotationDeclaration) {
indent();
// Member methods in the annotation declaration
NodeList<BodyDeclaration<?>> annotationDeclarationMembers = annotationDeclaration.getMembers();
for (BodyDeclaration<?> bodyDeclaration : annotationDeclarationMembers) {
Optional<AnnotationMemberDeclaration> annotationMemberDeclarationOptional = bodyDeclaration.toAnnotationMemberDeclaration();
if (!annotationMemberDeclarationOptional.isPresent()) {
continue;
}
final AnnotationMemberDeclaration annotationMemberDeclaration = annotationMemberDeclarationOptional.get();
addToken(makeWhitespace());
getClassType(annotationMemberDeclaration.getType());
addToken(new Token(WHITESPACE, " "));
final String name = annotationMemberDeclaration.getNameAsString();
final String definitionId = makeId(annotationDeclaration);
addToken(new Token(MEMBER_NAME, name, definitionId));
addToken(new Token(PUNCTUATION, "("));
addToken(new Token(PUNCTUATION, ")"));
// default value
final Optional<Expression> defaultValueOptional = annotationMemberDeclaration.getDefaultValue();
if (defaultValueOptional.isPresent()) {
addToken(new Token(WHITESPACE, " "));
addToken(new Token(KEYWORD, "default"));
addToken(new Token(WHITESPACE, " "));
final Expression defaultValueExpr = defaultValueOptional.get();
final String value = defaultValueExpr.toString();
addToken(new Token(KEYWORD, value));
}
addToken(new Token(PUNCTUATION, ";"));
addToken(new Token(NEW_LINE, ""));
}
unindent();
}
private void tokeniseFields(boolean isInterfaceDeclaration, TypeDeclaration<?> typeDeclaration) {
final List<? extends FieldDeclaration> fieldDeclarations = typeDeclaration.getFields();
final String fullPathName = typeDeclaration.getFullyQualifiedName().get();
indent();
for (FieldDeclaration fieldDeclaration : fieldDeclarations) {
// By default , interface has public abstract methods if there is no access specifier declared
if (isInterfaceDeclaration) {
// no-op - we take all methods in the method
} else if (isPrivateOrPackagePrivate(fieldDeclaration.getAccessSpecifier())) {
// Skip if not public API
continue;
}
addToken(makeWhitespace());
final NodeList<Modifier> fieldModifiers = fieldDeclaration.getModifiers();
// public, protected, static, final
for (final Modifier fieldModifier: fieldModifiers) {
addToken(new Token(KEYWORD, fieldModifier.toString()));
}
// field type and name
final NodeList<VariableDeclarator> variableDeclarators = fieldDeclaration.getVariables();
if (variableDeclarators.size() > 1) {
getType(fieldDeclaration);
for (VariableDeclarator variableDeclarator : variableDeclarators) {
final String name = variableDeclarator.getNameAsString();
final String definitionId = makeId(fullPathName + "." + variableDeclarator.getName());
addToken(new Token(MEMBER_NAME, name, definitionId));
addToken(new Token(PUNCTUATION, ","));
addToken(new Token(WHITESPACE, " "));
}
apiListing.getTokens().remove(apiListing.getTokens().size() - 1);
apiListing.getTokens().remove(apiListing.getTokens().size() - 1);
} else if (variableDeclarators.size() == 1) {
getType(fieldDeclaration);
final VariableDeclarator variableDeclarator = variableDeclarators.get(0);
final String name = variableDeclarator.getNameAsString();
final String definitionId = makeId(fullPathName + "." + variableDeclarator.getName());
addToken(new Token(MEMBER_NAME, name, definitionId));
final Optional<Expression> variableDeclaratorOption = variableDeclarator.getInitializer();
if (variableDeclaratorOption.isPresent()) {
addToken(new Token(WHITESPACE, " "));
addToken(new Token(PUNCTUATION, "="));
addToken(new Token(WHITESPACE, " "));
addToken(new Token(TEXT, variableDeclaratorOption.get().toString()));
}
}
// close the variable declaration
addToken(new Token(PUNCTUATION, ";"));
addToken(new Token(NEW_LINE, ""));
}
unindent();
}
private void tokeniseConstructorsOrMethods(boolean isInterfaceDeclaration, List<? extends CallableDeclaration<?>> callableDeclarations) {
indent();
boolean isAllPrivateOrPackagePrivate = callableDeclarations.stream()
.filter(BodyDeclaration::isConstructorDeclaration)
.allMatch(callableDeclaration -> isPrivateOrPackagePrivate(callableDeclaration.getAccessSpecifier()));
for (final CallableDeclaration<?> callableDeclaration : callableDeclarations) {
// By default , interface has public abstract methods if there is no access specifier declared
if (isInterfaceDeclaration) {
// no-op - we take all methods in the method
} else if (callableDeclaration.isConstructorDeclaration()) {
if (!isAllPrivateOrPackagePrivate && isPrivateOrPackagePrivate(callableDeclaration.getAccessSpecifier())) {
continue;
}
} else if (isPrivateOrPackagePrivate(callableDeclaration.getAccessSpecifier())) {
// Skip if not public API
continue;
}
addToken(makeWhitespace());
// modifiers
getModifiers(callableDeclaration.getModifiers());
// type parameters of methods
getTypeParameters(callableDeclaration.getTypeParameters());
// type name
if (callableDeclaration instanceof MethodDeclaration) {
getType(callableDeclaration);
}
// method name and parameters
getDeclarationNameAndParameters(callableDeclaration, callableDeclaration.getParameters());
// throw exceptions
getThrowException(callableDeclaration);
// close statements
addToken(new Token(PUNCTUATION, "{"));
addToken(new Token(PUNCTUATION, "}"));
addToken(new Token(NEW_LINE, ""));
}
unindent();
}
private void tokeniseInnerClasses(NodeList<BodyDeclaration<?>> bodyDeclarations) {
for (final BodyDeclaration<?> bodyDeclaration : bodyDeclarations) {
if (bodyDeclaration.isEnumDeclaration() || bodyDeclaration.isClassOrInterfaceDeclaration()) {
indent();
new ClassOrInterfaceVisitor(parentNav).visitClassOrInterfaceOrEnumDeclaration(bodyDeclaration.asTypeDeclaration());
unindent();
}
}
}
private void getModifiers(NodeList<Modifier> modifiers) {
for (final Modifier modifier : modifiers) {
addToken(new Token(KEYWORD, modifier.toString()));
}
}
private void getDeclarationNameAndParameters(CallableDeclaration callableDeclaration, NodeList<Parameter> parameters) {
// create a unique definition id
final String name = callableDeclaration.getNameAsString();
final String definitionId = makeId(callableDeclaration);
addToken(new Token(MEMBER_NAME, name, definitionId));
addToken(new Token(PUNCTUATION, "("));
if (!parameters.isEmpty()) {
for (int i = 0, max = parameters.size(); i < max; i++) {
final Parameter parameter = parameters.get(i);
getType(parameter);
addToken(new Token(WHITESPACE, " "));
addToken(new Token(TEXT, parameter.getNameAsString()));
if (i < max - 1) {
addToken(new Token(PUNCTUATION, ","));
addToken(new Token(WHITESPACE, " "));
}
}
}
// close declaration
addToken(new Token(PUNCTUATION, ")"));
addToken(new Token(WHITESPACE, " "));
}
private void getTypeParameters(NodeList<TypeParameter> typeParameters) {
final int size = typeParameters.size();
if (size == 0) {
return;
}
addToken(new Token(PUNCTUATION, "<"));
for (int i = 0; i < size; i++) {
final TypeParameter typeParameter = typeParameters.get(i);
getGenericTypeParameter(typeParameter);
if (i != size - 1) {
addToken(new Token(PUNCTUATION, ","));
addToken(new Token(WHITESPACE, " "));
}
}
addToken(new Token(PUNCTUATION, ">"));
addToken(new Token(WHITESPACE, " "));
}
private void getGenericTypeParameter(TypeParameter typeParameter) {
// set navigateToId
final String typeName = typeParameter.getNameAsString();
final Token token = new Token(TYPE_NAME, typeName);
if (apiListing.getKnownTypes().containsKey(typeName)) {
token.setNavigateToId(apiListing.getKnownTypes().get(typeName));
}
addToken(token);
// get type bounds
final NodeList<ClassOrInterfaceType> typeBounds = typeParameter.getTypeBound();
final int size = typeBounds.size();
if (size != 0) {
addToken(new Token(WHITESPACE, " "));
addToken(new Token(KEYWORD, "extends"));
addToken(new Token(WHITESPACE, " "));
for (int i = 0; i < size; i++) {
getType(typeBounds.get(i));
}
}
}
private void getThrowException(CallableDeclaration callableDeclaration) {
final NodeList<ReferenceType> thrownExceptions = callableDeclaration.getThrownExceptions();
if (thrownExceptions.size() == 0) {
return;
}
addToken(new Token(KEYWORD, "throws"));
addToken(new Token(WHITESPACE, " "));
for (int i = 0, max = thrownExceptions.size(); i < max; i++) {
addToken(new Token(TYPE_NAME, thrownExceptions.get(i).getElementType().toString()));
if (i < max - 1) {
addToken(new Token(PUNCTUATION, ","));
addToken(new Token(WHITESPACE, " "));
}
}
addToken(new Token(WHITESPACE, " "));
}
private void getType(Object type) {
if (type instanceof Parameter) {
getClassType(((NodeWithType) type).getType());
if (((Parameter) type).isVarArgs()) {
addToken(new Token(PUNCTUATION, "..."));
}
} else if (type instanceof MethodDeclaration) {
getClassType(((MethodDeclaration)type).getType());
addToken(new Token(WHITESPACE, " "));
} else if (type instanceof FieldDeclaration) {
getClassType(((FieldDeclaration)type).getElementType());
addToken(new Token(WHITESPACE, " "));
} else if (type instanceof ClassOrInterfaceType) {
getClassType(((Type)type));
} else {
System.err.println("Unknown type " + type + " of type " + type.getClass());
}
}
private void getClassType(Type type) {
if (type.isArrayType()) {
getClassType(type.getElementType());
//TODO: need to correct int[][] scenario
addToken(new Token(PUNCTUATION, "[]"));
} else if (type.isPrimitiveType() || type.isVoidType()) {
addToken(new Token(TYPE_NAME, type.toString()));
} else if (type.isReferenceType() || type.isTypeParameter() || type.isWildcardType()) {
getTypeDFS(type);
} else {
System.err.println("Unknown type");
}
}
private void getTypeDFS(Node node) {
final List<Node> nodes = node.getChildNodes();
final int childrenSize = nodes.size();
if (childrenSize <= 1) {
final String typeName = node.toString();
final Token token = new Token(TYPE_NAME, typeName);
if (apiListing.getKnownTypes().containsKey(typeName)) {
token.setNavigateToId(apiListing.getKnownTypes().get(typeName));
}
addToken(token);
return;
}
for (int i = 0; i < childrenSize; i++) {
final Node currentNode = nodes.get(i);
if (i == 1) {
addToken(new Token(PUNCTUATION, "<"));
}
getTypeDFS(currentNode);
if (i != 0) {
if (i == childrenSize - 1) {
addToken(new Token(PUNCTUATION, ">"));
} else {
addToken(new Token(PUNCTUATION, ","));
addToken(new Token(WHITESPACE, " "));
}
}
}
}
private void addDefaultConstructor(TypeDeclaration<?> typeDeclaration) {
indent();
addToken(makeWhitespace());
addToken(new Token(KEYWORD, "public"));
addToken(new Token(WHITESPACE, " "));
final String name = typeDeclaration.getNameAsString();
final String definitionId = makeId(typeDeclaration.getNameAsString());
addToken(new Token(MEMBER_NAME, name, definitionId));
addToken(new Token(PUNCTUATION, "("));
addToken(new Token(PUNCTUATION, ")"));
addToken(new Token(WHITESPACE, " "));
// close statements
addToken(new Token(PUNCTUATION, "{"));
addToken(new Token(PUNCTUATION, "}"));
addToken(new Token(NEW_LINE, ""));
unindent();
}
}
private class ScanForClassTypeVisitor extends VoidVisitorAdapter<Map<String, String>> {
@Override
public void visit(CompilationUnit compilationUnit, Map<String, String> arg) {
for (final TypeDeclaration<?> typeDeclaration : compilationUnit.getTypes()) {
getTypeDeclaration(typeDeclaration);
}
// we build up a map between types and the packages they are in, for use in our diagnostic rules
compilationUnit.getImports().stream()
.map(ImportDeclaration::getName)
.forEach(name -> name.getQualifier().ifPresent(packageName -> {
apiListing.addPackageTypeMapping(packageName.toString(), name.getIdentifier());
}));
}
}
/*
* This method is only called in relation to building up the types for linking, it does not build up the actual
* text output that is displayed to the user.
*/
private void getTypeDeclaration(TypeDeclaration<?> typeDeclaration) {
// Skip if the class is private or package-private, unless it is a nested type defined inside a public interface
if (!isTypeAPublicAPI(typeDeclaration)) {
return;
}
final boolean isInterfaceType = typeDeclaration.isClassOrInterfaceDeclaration();
if (! (isInterfaceType || typeDeclaration.isEnumDeclaration())) {
return;
}
final String fullQualifiedName = typeDeclaration.getFullyQualifiedName().get();
// determine the package name for this class
final String typeName = typeDeclaration.getNameAsString();
final String packageName = fullQualifiedName.substring(0, fullQualifiedName.lastIndexOf("."));
apiListing.addPackageTypeMapping(packageName, typeName);
// generate a navigation item for each new package, but we don't add them to the parent yet
packageNameToNav.computeIfAbsent(packageName, name -> new ChildItem(packageName, TypeKind.NAMESPACE));
apiListing.getKnownTypes().put(typeName, makeId(typeDeclaration));
// now do internal types
typeDeclaration.getMembers().stream()
.filter(m -> m.isEnumDeclaration() || m.isClassOrInterfaceDeclaration())
.forEach(m -> getTypeDeclaration(m.asTypeDeclaration()));
}
private void indent() {
indent += 4;
}
private void unindent() {
indent = Math.max(indent - 4, 0);
}
private Token makeWhitespace() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indent; i++) {
sb.append(" ");
}
return new Token(WHITESPACE, sb.toString());
}
private void addToken(Token token) {
apiListing.getTokens().add(token);
}
}
|
import lejos.nxt.*;
public class FilteredUltrasonicSensor {
private static final int MAX = 255;
private final UltrasonicSensor handle;
private volatile int sampleCount;
public FilteredUltrasonicSensor(SensorPort port) {
handle = new UltrasonicSensor(port);
}
public void setSampleCount(int sampleCount) {
this.sampleCount = sampleCount;
}
public int getDistanceData() {
// Thread safety precautions, make a local copy of sample count
final int count = sampleCount;
// Sample the sensor and save these as a sorted list
final int[] samples = new int[count];
for (int i = 0; i < count; i++) {
insertSorted(samples, i, handle.getDistance());
}
// Apply a median filter
final int mid = count >> 1;
if ((count & 1) == 0) {
// Even sample count
final int first = samples[mid - 1];
final int second = samples[mid];
if (first == MAX && second == MAX) {
// More than half the samples are MAX, so MAX is returned
return MAX;
}
// Else we'll average all the non-max samples
} else {
// Odd sample count
final int first = samples[mid];
if (first == MAX) {
// More than half the samples are MAX, so MAX is returned
return MAX;
}
// Else we'll average all the non-max samples
}
// Average the results
int sum = 0;
for (int i = 0, sample; i < count && (sample = samples[i]) < MAX; i++) {
sum += sample;
}
// Make sure we're not dividing by zero
if (count == 0) {
return 0;
}
return sum / count;
}
private static void insertSorted(int[] list, int size, int element) {
int i, e, t;
// Find the index at which to insert
for (i = 0; i < size && (e = list[i]) <= element; i++) {
}
// If at end, just insert and return
if (i == size) {
list[i] = element;
return;
}
// Else shift all the elements right, inserting the new one first
for (e = element; i < size; i += 2) {
t = list[i];
list[i] = e;
e = list[i + 1];
list[i + 1] = t;
}
// Edge case for the last element
if (i == size) {
list[i] = e;
}
}
}
|
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.N3ValidatorVTwo;
import edu.cornell.mannlib.vitro.webapp.web.AntiScript;
/**
* Check if the submitted text has potential XSS problems.
* Error messages from this validator always start with XSS_ERROR_MESSAGE
*
* @author bdc34
*/
public class AntiXssValidation implements N3ValidatorVTwo{
List<String> fieldNamesToValidate;
/**
* Validate all fields on submission.
*/
public AntiXssValidation(){
this.fieldNamesToValidate = ALL_FIELDS;
}
/**
* Validate only fields specified in fieldNamesToValidate.
*/
public AntiXssValidation(List<String> fieldNamesToValidate){
this.fieldNamesToValidate = fieldNamesToValidate;
}
@Override
public Map<String, String> validate(EditConfigurationVTwo editConfig,
MultiValueEditSubmission editSub) {
if( editSub == null ) {
return null;
}
Map<String,String>varToErrMsg = new HashMap<String,String>();
if( fieldNamesToValidate == null ){
if( editSub.getLiteralsFromForm() != null ){
for( String name : editSub.getLiteralsFromForm().keySet()){
varToErrMsg.putAll( checkSubmissionForField( name, editSub));
}
}
if( editSub.getUrisFromForm() != null ){
for( String name : editSub.getUrisFromForm().keySet()){
varToErrMsg.putAll( checkSubmissionForField( name, editSub));
}
}
}else{
for( String fieldName : fieldNamesToValidate){
varToErrMsg.putAll( checkSubmissionForField(fieldName, editSub));
}
}
if( varToErrMsg.isEmpty() )
return null;
else
return varToErrMsg;
}
/**
* Check for XSS for a single field. Returns NO_ERROR if there
* are no errors so it can be added to a map with putAll()
*/
protected Map<String,String> checkSubmissionForField(
String fieldName, MultiValueEditSubmission editSub){
if( fieldName == null || fieldName.isEmpty() || editSub == null)
return NO_ERROR;
if( editSub.getLiteralsFromForm() != null &&
editSub.getLiteralsFromForm().containsKey(fieldName) ){
String error = null;
try {
error = literalHasXSS( editSub.getLiteralsFromForm().get(fieldName) );
} catch (ScanException e) {
error = e.getMessage();
} catch (PolicyException e) {
error = e.getMessage();
}
if( error != null ){
return Collections.singletonMap(fieldName, XSS_ERROR_MESSAGE + " " + error);
}else{
return NO_ERROR;
}
} else if (editSub.getUrisFromForm() != null &&
editSub.getUrisFromForm().containsKey(fieldName)){
String error;
try {
error = uriHasXSS( editSub.getUrisFromForm().get(fieldName));
} catch (ScanException e) {
error = e.getMessage();
} catch (PolicyException e) {
error = e.getMessage();
}
if( error != null ){
return Collections.singletonMap(fieldName, XSS_ERROR_MESSAGE + " " + error);
}else{
return NO_ERROR;
}
}else{
//field wasn't in submission
return NO_ERROR;
}
}
/**
* Check if a list of URIs has any XSS problems.
* Return null if there are none and return an error message if there are problems.
*/
private String uriHasXSS(List<String> uriList) throws ScanException, PolicyException {
AntiSamy antiSamy = AntiScript.getAntiSamyScanner();
ArrayList errorMsgs = new ArrayList();
for( String uri : uriList ){
CleanResults cr = antiSamy.scan( uri );
errorMsgs.addAll( cr.getErrorMessages() );
}
if( errorMsgs.isEmpty() ){
return null;
}else{
return StringUtils.join(errorMsgs, ", ");
}
}
/**
* Check if a List of Literals has any XSS problems.
* Return null if there are none and return an error message if there are problems.
*/
private String literalHasXSS(List<Literal> list) throws ScanException, PolicyException {
AntiSamy antiSamy = AntiScript.getAntiSamyScanner();
ArrayList errorMsgs = new ArrayList();
for( Literal literal : list ){
if(literal != null) {
CleanResults cr = antiSamy.scan(literal.getLexicalForm());
errorMsgs.addAll( cr.getErrorMessages() );
String dt = literal.getDatatypeURI();
if( dt != null ){
cr = antiSamy.scan( dt );
errorMsgs.addAll( cr.getErrorMessages() );
}
String lang = literal.getLanguage() ;
if( lang != null ){
cr = antiSamy.scan( lang );
errorMsgs.addAll( cr.getErrorMessages() );
}
}
}
if( errorMsgs.isEmpty() )
return null;
else
return StringUtils.join(errorMsgs,", ");
}
/**
* All error messages will start with this string.
*/
public static String XSS_ERROR_MESSAGE = "Field contains unacceptable markup";
private static final Map<String,String>NO_ERROR = Collections.emptyMap();
//value indicates that all fields should be validated.
private static final List<String> ALL_FIELDS = null;
}
|
package org.flymine.gbrowse;
import junit.framework.TestCase;
import java.util.Map;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Collections;
import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.io.*;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
import org.intermine.objectstore.*;
import org.intermine.objectstore.query.*;
import org.intermine.dataloader.IntegrationWriterFactory;
import org.intermine.dataloader.XmlDataLoader;
import org.intermine.dataloader.IntegrationWriter;
import org.intermine.metadata.Model;
import org.intermine.model.InterMineObject;
import org.intermine.model.datatracking.Source;
import org.intermine.util.DynamicUtil;
import org.intermine.xml.full.FullRenderer;
import org.intermine.xml.full.FullParser;
import org.intermine.xml.full.Item;
import org.flymine.postprocess.*;
import org.flymine.model.genomic.*;
import org.apache.log4j.Logger;
/**
* Tests for WriteGFFTask.
*/
public class WriteGFFTaskTest extends TestCase
{
private ObjectStoreWriter osw;
private Model model;
private Organism storedOrganism = null;
private Sequence storedSequence = null;
private Chromosome storedChromosome = null;
private Gene storedGene = null;
private Transcript storedTranscript1 = null;
private Transcript storedTranscript2 = null;
private Exon storedExon1 = null;
private Exon storedExon2 = null;
private Exon storedExon3 = null;
private Location storedExon1Location = null;
private Location storedExon2Location = null;
private Location storedExon3Location = null;
private Location storedTranscript1Location = null;
private Location storedTranscript2Location = null;
private Location storedGeneLocation = null;
private static final Logger LOG = Logger.getLogger(WriteGFFTaskTest.class);
public void setUp() throws Exception {
osw = ObjectStoreWriterFactory.getObjectStoreWriter("osw.genomic-test");
osw.getObjectStore().flushObjectById();
model = Model.getInstanceByName("genomic");
createData();
}
public void tearDown() throws Exception {
LOG.info("in tear down");
Query q = new Query();
QueryClass qc = new QueryClass(InterMineObject.class);
q.addFrom(qc);
q.addToSelect(qc);
ObjectStore os = osw.getObjectStore();
SingletonResults res = new SingletonResults(q, osw.getObjectStore(), osw.getObjectStore()
.getSequence());
LOG.info("created results");
Iterator resIter = res.iterator();
osw.beginTransaction();
while (resIter.hasNext()) {
InterMineObject o = (InterMineObject) resIter.next();
LOG.info("deleting: " +o.getId());
osw.delete(o);
}
osw.commitTransaction();
LOG.info("committed transaction");
osw.close();
LOG.info("closed objectstore");
}
public void testWriteGFF() throws Exception {
TransferSequences ts = new TransferSequences(osw);
ts.transferToLocatedSequenceFeatures();
WriteGFFTask task = new WriteGFFTask();
task.writeGFF(osw.getObjectStore(), new File("build/gbrowse/data"));
}
private void createData() throws Exception {
osw.flushObjectById();
storedOrganism = (Organism) DynamicUtil.createObject(Collections.singleton(Organism.class));
storedOrganism.setGenus("Drosophila");
storedOrganism.setSpecies("melanogaster");
String residues =
"ggcgaggcggggaaagcactgcgcgctgacggtggtgctgattgtattttttcagcgtct" +
"cagcgcgtcgtgacggcacttagtctgcccgttgaggcgttgtgtgtctgcggggtgttt" +
"tgtgcggtggtgagcgtgtgaggggggatgacggggtgtaaaaaagccgcccgcaggcgg" +
"cgatgttcagtcgttgtcagtgtccagtgagtagtttttaaagcggatgacctcctgacc" +
"gagccagccgtttatctcgcggatcctgtcctgtaacgggataagctcattgcggacaaa" +
"gacctttgccactttctcaatatcacccagcgacccgacgttctccggcttgccacccat" +
"caactgaaaggggatgcggtgcgcgtccagcaggtcagcggcgctggcttttttgatatt" +
"aaaaaaatcgtccttcgtcgccacttcactgagggggataattttaatgccgtcggcttt" +
"cccctgtggggcatagagaaacaggtttttaaagttgttgcggcctttcgacttgaccat" +
"gttttcgcgaagcatttcgatatcgttgcgatcctgcacggcatcggtgacatacatgat" +
"gtatccggcatgtgcgccattttcgtaatacttgcggcggaacaacgtggccgactcatt" +
"cagccaggcagagttaagggcgctgagatattccggcaggccgtacagctcctgattaat" +
"atccggctccagcaggtgaaacacggagccgggcgcgaaggctgtcggctcgttgaagga" +
"cggcacccaccagtaaacatcctcttccacgccacggcgggtatattttgccggtgaggt" +
"ttccagtctgatgaccttaccggtggtgctgtaacgcttttccagaaacgcattaccgaa" +
"caccagaaaatccagcacaaagcggctgaaatcctgctgggaaagccatggatgcgggat" +
"aaatgtcgaggccagaatattgcgtttgacgtaaatcggcgagctgtgatgcacggcagc" +
"ccgcaggctttttgccagaccggtaaagctgaccggtggctcataccatctgccgttact" +
"gatgcactcgacgtaatccagaatgtcacggcggtcgagtaccggcaccggctcaccaaa" +
"ggtgaatgcctccattttcgggccgctggcggtcattgtttttgccgcaggttgcggtgt" +
"tttcccttttttcttgctcatcagtaaaactccagaatggtggatgtcagcggggtgctg" +
"ataccggcggtgagtggctcatttaacagggcgtgcatggtcgcccaggcgaggtcggcg" +
"tggctggcttcctcgctgcggctggcctcataggtggcgctgcgtccgctgctggtcatg" +
"gtcttgcggatagccataaacgagctggtgatgtcggtggcgctgacgtcgtattccaga" +
"cagccacggcggataacgtcttttgccttgagcaccattgcggttttcatttccggcgtg";
storedSequence = (Sequence) DynamicUtil.createObject(Collections.singleton(Sequence.class));
storedSequence.setResidues(residues);
storedChromosome =
(Chromosome) DynamicUtil.createObject(Collections.singleton(Chromosome.class));
storedChromosome.setIdentifier("1");
storedChromosome.setLength(new Integer(residues.length()));
storedChromosome.setOrganism(storedOrganism);
storedChromosome.setSequence(storedSequence);
storedGene = (Gene) DynamicUtil.createObject(Collections.singleton(Gene.class));
storedGene.setIdentifier("gene1");
storedTranscript1 =
(Transcript) DynamicUtil.createObject(Collections.singleton(Transcript.class));
storedTranscript1.setIdentifier("trans1");
storedTranscript1.setGene(storedGene);
storedTranscript2 =
(Transcript) DynamicUtil.createObject(Collections.singleton(Transcript.class));
storedTranscript2.setIdentifier("trans2");
storedTranscript2.setGene(storedGene);
storedExon1 = (Exon) DynamicUtil.createObject(Collections.singleton(Exon.class));
storedExon1.setIdentifier("exon1");
storedExon1.setTranscripts(Arrays.asList(new Object[] {storedTranscript1}));
storedExon2 = (Exon) DynamicUtil.createObject(Collections.singleton(Exon.class));
storedExon2.setIdentifier("exon2");
storedExon2.setTranscripts(Arrays.asList(new Object[] {storedTranscript1,
storedTranscript2}));
storedExon3 = (Exon) DynamicUtil.createObject(Collections.singleton(Exon.class));
storedExon3.setIdentifier("exon3");
storedExon3.setTranscripts(Arrays.asList(new Object[] {storedTranscript2}));
storedTranscript1Location =
(Location) DynamicUtil.createObject(Collections.singleton(Location.class));
storedTranscript1Location.setObject(storedChromosome);
storedTranscript1Location.setSubject(storedTranscript1);
storedTranscript1Location.setStart(new Integer(201));
storedTranscript1Location.setEnd(new Integer(400));
storedTranscript1Location.setStrand(new Integer(1));
storedTranscript2Location =
(Location) DynamicUtil.createObject(Collections.singleton(Location.class));
storedTranscript2Location.setObject(storedChromosome);
storedTranscript2Location.setSubject(storedTranscript2);
storedTranscript2Location.setStart(new Integer(351));
storedTranscript2Location.setEnd(new Integer(620));
storedTranscript2Location.setStrand(new Integer(1));
storedGeneLocation =
(Location) DynamicUtil.createObject(Collections.singleton(Location.class));
storedGeneLocation.setObject(storedChromosome);
storedGeneLocation.setSubject(storedGene);
storedGeneLocation.setStart(new Integer(201));
storedGeneLocation.setEnd(new Integer(620));
storedGeneLocation.setStrand(new Integer(1));
storedExon1Location =
(Location) DynamicUtil.createObject(Collections.singleton(Location.class));
storedExon1Location.setObject(storedChromosome);
storedExon1Location.setSubject(storedExon1);
storedExon1Location.setStart(new Integer(201));
storedExon1Location.setEnd(new Integer(300));
storedExon1Location.setStrand(new Integer(1));
storedExon2Location =
(Location) DynamicUtil.createObject(Collections.singleton(Location.class));
storedExon2Location.setObject(storedChromosome);
storedExon2Location.setSubject(storedExon2);
storedExon2Location.setStart(new Integer(351));
storedExon2Location.setEnd(new Integer(400));
storedExon2Location.setStrand(new Integer(1));
storedExon3Location =
(Location) DynamicUtil.createObject(Collections.singleton(Location.class));
storedExon3Location.setObject(storedChromosome);
storedExon3Location.setSubject(storedExon3);
storedExon3Location.setStart(new Integer(591));
storedExon3Location.setEnd(new Integer(620));
storedExon3Location.setStrand(new Integer(1));
Set toStore = new HashSet(Arrays.asList(new Object[] {
storedOrganism, storedChromosome,
storedGene, storedTranscript1,
storedTranscript2,
storedExon1, storedExon2,
storedExon3,
storedExon1Location, storedExon2Location,
storedExon3Location,
storedTranscript1Location,
storedTranscript2Location,
storedGeneLocation, storedSequence
}));
Iterator i = toStore.iterator();
osw.beginTransaction();
LOG.info("begun transaction in createData()");
while (i.hasNext()) {
osw.store((InterMineObject) i.next());
}
osw.commitTransaction();
LOG.info("committed transaction in createData()");
}
private Item toItem(InterMineObject o) {
if (o.getId() == null) {
o.setId(new Integer(0));
}
Item item = FullRenderer.toItem(o, model);
return item;
}
}
|
package org.eclipse.birt.report.designer.ui.dialogs;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.format.DateFormatter;
import org.eclipse.birt.core.format.NumberFormatter;
import org.eclipse.birt.core.format.StringFormatter;
import org.eclipse.birt.report.designer.internal.ui.dialogs.BaseDialog;
import org.eclipse.birt.report.designer.internal.ui.dialogs.ImportValueDialog;
import org.eclipse.birt.report.designer.internal.ui.dialogs.SelectionChoiceDialog;
import org.eclipse.birt.report.designer.internal.ui.swt.custom.ITableAreaModifier;
import org.eclipse.birt.report.designer.internal.ui.swt.custom.TableArea;
import org.eclipse.birt.report.designer.internal.ui.util.DataUtil;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.IReportGraphicConstants;
import org.eclipse.birt.report.designer.ui.ReportPlatformUIImages;
import org.eclipse.birt.report.designer.ui.actions.NewDataSetAction;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.ScalarParameterHandle;
import org.eclipse.birt.report.model.api.SelectionChoiceHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.structures.SelectionChoice;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.metadata.IChoiceSet;
import org.eclipse.birt.report.model.api.util.StringUtil;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.ISharedImages;
import com.ibm.icu.util.ULocale;
/**
* The dialog used to create or edit a parameter
*/
public class ParameterDialog extends BaseDialog
{
private static final String CHOICE_NO_DEFAULT = Messages.getString( "ParameterDialog.Choice.NoDefault" ); //$NON-NLS-1$
private static final String GROUP_PROPERTIES = Messages.getString( "ParameterDialog.Group.Properties" ); //$NON-NLS-1$
private static final String GROUP_MORE_OPTION = Messages.getString( "ParameterDialog.Group.MoreOption" ); //$NON-NLS-1$
private static final String LABEL_NAME = Messages.getString( "ParameterDialog.Label.Name" ); //$NON-NLS-1$
private static final String LABEL_DATETIME_PROMPT = Messages.getString( "ParameterDialog.Label.DateTImePrompt" ); //$NON-NLS-1$
private static final String LABEL_PROMPT_TEXT = Messages.getString( "ParameterDialog.Label.PromptText" ); //$NON-NLS-1$
private static final String LABEL_PARAM_DATA_TYPE = Messages.getString( "ParameterDialog.Label.DataType" ); //$NON-NLS-1$
private static final String LABEL_DISPALY_TYPE = Messages.getString( "ParameterDialog.Label.DisplayType" ); //$NON-NLS-1$
private static final String LABEL_DEFAULT_VALUE = Messages.getString( "ParameterDialog.Label.DefaultValue" ); //$NON-NLS-1$
private static final String LABEL_HELP_TEXT = Messages.getString( "ParameterDialog.Label.HelpText" ); //$NON-NLS-1$
private static final String LABEL_LIST_OF_VALUE = Messages.getString( "ParameterDialog.Label.ListOfValue" ); //$NON-NLS-1$
private static final String LABEL_VALUES = Messages.getString( "ParameterDialog.Label.Value" ); //$NON-NLS-1$
private static final String LABEL_FORMAT = Messages.getString( "ParameterDialog.Label.Format" ); //$NON-NLS-1$
private static final String LABEL_LIST_LIMIT = Messages.getString( "ParameterDialog.Label.Listlimit" ); //$NON-NLS-1$
private static final String LABEL_NULL = Messages.getString( "ParameterDialog.Label.Null" ); //$NON-NLS-1$
private static final String LABEL_SELECT_DISPLAY_TEXT = Messages.getString( "ParameterDialog.Label.SelectDisplayText" ); //$NON-NLS-1$
private static final String LABEL_SELECT_VALUE_COLUMN = Messages.getString( "ParameterDialog.Label.SelectValueColumn" ); //$NON-NLS-1$
private static final String LABEL_SELECT_DATA_SET = Messages.getString( "ParameterDialog.Label.SelectDataSet" ); //$NON-NLS-1$
private static final String LABEL_PREVIEW = Messages.getString( "ParameterDialog.Label.Preview" ); //$NON-NLS-1$
private static final String CHECKBOX_ALLOW_NULL = Messages.getString( "ParameterDialog.CheckBox.AllowNull" ); //$NON-NLS-1$
private static final String CHECKBOX_ALLOW_BLANK = Messages.getString( "ParameterDialog.CheckBox.AllowBlank" ); //$NON-NLS-1$
private static final String CHECKBOX_DO_NOT_ECHO = Messages.getString( "ParameterDialog.CheckBox.DoNotEchoInput" ); //$NON-NLS-1$
private static final String CHECKBOX_SORT = Messages.getString( "ParameterDialog.CheckBox.Sort" ); //$NON-NLS-1$
private static final String CHECKBOX_HIDDEN = Messages.getString( "ParameterDialog.CheckBox.Hidden" ); //$NON-NLS-1$
private static final String BUTTON_LABEL_CHANGE_FORMAT = Messages.getString( "ParameterDialog.Button.ChangeFormat" ); //$NON-NLS-1$
private static final String BUTTON_LABEL_IMPORT = Messages.getString( "ParameterDialog.Button.ImportValue" ); //$NON-NLS-1$
private static final String BUTTON_LABEL_SET_DEFAULT = Messages.getString( "ParameterDialog.Button.SetDefault" ); //$NON-NLS-1$
private static final String BUTTON_LABEL_REMOVE_DEFAULT = Messages.getString( "ParameterDialog.Button.RemoveDefault" ); //$NON-NLS-1$
private static final String BUTTON_CREATE_DATA_SET = Messages.getString( "ParameterDialog.Button.CreateDataSet" ); //$NON-NLS-1$
private static final String RADIO_DYNAMIC = Messages.getString( "ParameterDialog.Radio.Dynamic" ); //$NON-NLS-1$
private static final String RADIO_STATIC = Messages.getString( "ParameterDialog.Radio.Static" ); //$NON-NLS-1$
private static final String ERROR_TITLE_INVALID_LIST_LIMIT = Messages.getString( "ParameterDialog.ErrorTitle.InvalidListLimit" ); //$NON-NLS-1$
private static final String ERROR_MSG_CANNOT_BE_BLANK = Messages.getString( "ParameterDialog.ErrorMessage.CanootBeBlank" ); //$NON-NLS-1$
private static final String ERROR_MSG_CANNOT_BE_NULL = Messages.getString( "ParameterDialog.ErrorMessage.CanootBeNull" ); //$NON-NLS-1$
private static final String ERROR_MSG_DUPLICATED_VALUE = Messages.getString( "ParameterDialog.ErrorMessage.DuplicatedValue" ); //$NON-NLS-1$
private static final String ERROR_MSG_DUPLICATED_LABEL = Messages.getString( "ParameterDialog.ErrorMessage.DuplicatedLabel" ); //$NON-NLS-1$
private static final String ERROR_MSG_MISMATCH_DATA_TYPE = Messages.getString( "ParameterDialog.ErrorMessage.MismatchDataType" ); //$NON-NLS-1$
private static final String ERROR_MSG_DUPLICATED_NAME = Messages.getString( "ParameterDialog.ErrorMessage.DuplicatedName" ); //$NON-NLS-1$
private static final String ERROR_MSG_NAME_IS_EMPTY = Messages.getString( "ParameterDialog.ErrorMessage.EmptyName" ); //$NON-NLS-1$
private static final String ERROR_MSG_NO_DEFAULT_VALUE = Messages.getString( "ParameterDialog.ErrorMessage.NoDefaultValue" ); //$NON-NLS-1$
private static final String ERROR_MSG_NO_AVAILABLE_COLUMN = Messages.getString( "ParameterDialog.ErrorMessage.NoAvailableColumn" ); //$NON-NLS-1$
private static final String ERROR_MSG_INVALID_LIST_LIMIT = Messages.getString( "ParameterDialog.ErrorMessage.InvalidListLimit" ); //$NON-NLS-1$
private static final String FLAG_DEFAULT = Messages.getString( "ParameterDialog.Flag.Default" ); //$NON-NLS-1$
private static final String COLUMN_VALUE = Messages.getString( "ParameterDialog.Column.Value" ); //$NON-NLS-1$
private static final String COLUMN_DISPLAY_TEXT = Messages.getString( "ParameterDialog.Column.DisplayText" ); //$NON-NLS-1$
private static final String COLUMN_IS_DEFAULT = Messages.getString( "ParameterDialog.Column.Default" ); //$NON-NLS-1$
private static final String BOOLEAN_TRUE = Messages.getString( "ParameterDialog.Boolean.True" ); //$NON-NLS-1$
private static final String BOOLEAN_FALSE = Messages.getString( "ParameterDialog.Boolean.False" ); //$NON-NLS-1$
private static final String PARAM_CONTROL_LIST = DesignChoiceConstants.PARAM_CONTROL_LIST_BOX
+ "/List"; //$NON-NLS-1$
private static final String PARAM_CONTROL_COMBO = DesignChoiceConstants.PARAM_CONTROL_LIST_BOX
+ "/Combo"; //$NON-NLS-1$
private static final String DISPLAY_NAME_CONTROL_LIST = Messages.getString( "ParameterDialog.DisplayLabel.List" ); //$NON-NLS-1$
private static final String DISPLAY_NAME_CONTROL_COMBO = Messages.getString( "ParameterDialog.DisplayLabel.Combo" ); //$NON-NLS-1$
private static final String NONE_DISPLAY_TEXT = Messages.getString( "ParameterDialog.Label.None" ); //$NON-NLS-1$
private static final Image DEFAULT_ICON = ReportPlatformUIImages.getImage( IReportGraphicConstants.ICON_DEFAULT );
private static final Image ERROR_ICON = ReportPlatformUIImages.getImage( ISharedImages.IMG_OBJS_ERROR_TSK );
private static final String STANDARD_DATE_TIME_PATTERN = "MM/dd/yyyy hh:mm:ss a"; //$NON-NLS-1$
private HashMap dirtyProperties = new HashMap( 5 );
private ArrayList choiceList = new ArrayList( );
private static IChoiceSet dataType = DEUtil.getMetaDataDictionary( )
.getChoiceSet( DesignChoiceConstants.CHOICE_PARAM_TYPE );
private static IChoiceSet controlType = DEUtil.getMetaDataDictionary( )
.getChoiceSet( DesignChoiceConstants.CHOICE_PARAM_CONTROL );
private ScalarParameterHandle inputParameter;
private boolean loading = true;
private Text nameEditor, promptTextEditor, defaultValueEditor,
helpTextEditor, formatField;
// Prompt message line
private Label promptMessageLine;
// Error message line
private CLabel errorMessageLine;
// Check boxes
private Button allowNull, allowBlank, doNotEcho, isHidden, needSort;
// Push buttons
private Button importValue, changeDefault, changeFormat, createDataSet;
// Radio buttons
private Button dynamicRadio, staticRadio;
// Combo chooser for static
private Combo dataTypeChooser, controlTypeChooser, defaultValueChooser;
// Combo chooser for dynamic
private Combo dataSetChooser, columnChooser, displayTextChooser;
// Label
private Label previewLabel;
private TableViewer valueTable;
private String lastDataType, lastControlType;
private String formatCategroy, formatPattern;
private String defaultValue;
private Composite valueArea;
private List columnList;
private IStructuredContentProvider contentProvider = new IStructuredContentProvider( ) {
public void dispose( )
{
}
public void inputChanged( Viewer viewer, Object oldInput,
Object newInput )
{
}
public Object[] getElements( Object inputElement )
{
ArrayList list = ( (ArrayList) inputElement );
ArrayList elementsList = (ArrayList) list.clone( );
return elementsList.toArray( );
}
};
private ITableLabelProvider labelProvider = new ITableLabelProvider( ) {
public Image getColumnImage( Object element, int columnIndex )
{
if ( valueTable.getColumnProperties( ).length == 4
&& columnIndex == 1 )
{
SelectionChoice choice = ( (SelectionChoice) element );
if ( isDefaultChoice( choice ) )
{
return DEFAULT_ICON;
}
}
return null;
}
public String getColumnText( Object element, int columnIndex )
{
SelectionChoice choice = ( (SelectionChoice) element );
final int valueIndex = valueTable.getColumnProperties( ).length - 2;
String text = null;
if ( valueTable.getColumnProperties( ).length == 4
&& columnIndex == 1 )
{
if ( isDefaultChoice( choice ) )
{
text = FLAG_DEFAULT;
}
}
else if ( columnIndex == valueIndex )
{
text = choice.getValue( );
}
else if ( columnIndex == valueIndex + 1 )
{
text = choice.getLabel( );
if ( text == null )
{
text = format( choice.getValue( ) );
}
}
if ( text == null )
{
text = ""; //$NON-NLS-1$
}
return text;
}
public void addListener( ILabelProviderListener listener )
{
}
public void dispose( )
{
}
public boolean isLabelProperty( Object element, String property )
{
return false;
}
public void removeListener( ILabelProviderListener listener )
{
}
};
private final ITableAreaModifier tableAreaModifier = new ITableAreaModifier( ) {
public boolean editItem( final Object element )
{
final SelectionChoice choice = (SelectionChoice) element;
boolean isDefault = isDefaultChoice( choice );
SelectionChoiceDialog dialog = new SelectionChoiceDialog( Messages.getString( "ParameterDialog.SelectionDialog.Edit" ) ); //$NON-NLS-1$
dialog.setInput( choice );
dialog.setValidator( new SelectionChoiceDialog.ISelectionChoiceValidator( ) {
public String validate( String displayLabel, String value )
{
return validateChoice( choice, displayLabel, value );
}
} );
if ( dialog.open( ) == Dialog.OK )
{
choice.setValue( convertToStandardFormat( choice.getValue( ) ) );
if ( isDefault )
{
changeDefaultValue( choice.getValue( ) );
}
return true;
}
return false;
}
public boolean newItem( )
{
SelectionChoice choice = StructureFactory.createSelectionChoice( );
SelectionChoiceDialog dialog = new SelectionChoiceDialog( Messages.getString( "ParameterDialog.SelectionDialog.New" ) ); //$NON-NLS-1$
dialog.setInput( choice );
dialog.setValidator( new SelectionChoiceDialog.ISelectionChoiceValidator( ) {
public String validate( String displayLabel, String value )
{
return validateChoice( null, displayLabel, value );
}
} );
if ( dialog.open( ) == Dialog.OK )
{
choice.setValue( convertToStandardFormat( choice.getValue( ) ) );
choiceList.add( choice );
return true;
}
return false;
}
public boolean removeItem( Object[] elements )
{
for ( int i = 0; i < elements.length; i++ )
{
if ( isDefaultChoice( (SelectionChoice) elements[i] ) )
{
changeDefaultValue( null );
}
choiceList.remove( elements[i] );
}
return true;
}
};
private Text listLimit;
/**
* Create a new parameter dialog with given title under the active shell
*
* @param title
* the title of the dialog
*/
public ParameterDialog( String title )
{
this( UIUtil.getDefaultShell( ), title );
}
/**
* Create a new parameter dialog with given title under the specified shell
*
* @param parentShell
* the parent shell of the dialog
* @param title
* the title of the dialog
*/
public ParameterDialog( Shell parentShell, String title )
{
super( parentShell, title );
}
protected Control createDialogArea( Composite parent )
{
Composite composite = (Composite) super.createDialogArea( parent );
createPropertiesSection( composite );
createMoreOptionSection( composite );
UIUtil.bindHelp( parent, IHelpContextIds.PARAMETER_DIALOG_ID );
return composite;
}
private void createPropertiesSection( Composite composite )
{
Group propertiesSection = new Group( composite, SWT.NONE );
propertiesSection.setText( GROUP_PROPERTIES );
propertiesSection.setLayout( new GridLayout( 2, false ) );
propertiesSection.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
createLabel( propertiesSection, LABEL_NAME );
nameEditor = new Text( propertiesSection, SWT.BORDER );
nameEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
nameEditor.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
updateMessageLine( );
}
} );
createLabel( propertiesSection, LABEL_PROMPT_TEXT );
promptTextEditor = new Text( propertiesSection, SWT.BORDER );
promptTextEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
createLabel( propertiesSection, LABEL_PARAM_DATA_TYPE );
dataTypeChooser = new Combo( propertiesSection, SWT.READ_ONLY
| SWT.DROP_DOWN );
dataTypeChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
dataTypeChooser.setItems( ChoiceSetFactory.getDisplayNamefromChoiceSet( dataType ) );
dataTypeChooser.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
changeDataType( );
updateCheckBoxArea( );
}
} );
createLabel( propertiesSection, LABEL_DISPALY_TYPE );
controlTypeChooser = new Combo( propertiesSection, SWT.READ_ONLY
| SWT.DROP_DOWN );
controlTypeChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
controlTypeChooser.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
changeControlType( );
}
} );
createLabel( propertiesSection, LABEL_LIST_OF_VALUE );
Composite choiceArea = new Composite( propertiesSection, SWT.NONE );
choiceArea.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
choiceArea.setLayout( UIUtil.createGridLayoutWithoutMargin( 2, true ) );
staticRadio = new Button( choiceArea, SWT.RADIO );
staticRadio.setText( RADIO_STATIC );
staticRadio.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
switchParamterType( );
}
} );
dynamicRadio = new Button( choiceArea, SWT.RADIO );
dynamicRadio.setText( RADIO_DYNAMIC );
dynamicRadio.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
switchParamterType( );
}
} );
valueArea = new Composite( propertiesSection, SWT.NONE );
valueArea.setLayout( UIUtil.createGridLayoutWithoutMargin( 2, false ) );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.heightHint = 150;
gd.widthHint = 550;
gd.horizontalSpan = 2;
valueArea.setLayoutData( gd );
createLabel( propertiesSection, null );
errorMessageLine = new CLabel( propertiesSection, SWT.NONE );
errorMessageLine.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
private void createMoreOptionSection( Composite composite )
{
Group moreOptionSection = new Group( composite, SWT.NONE );
moreOptionSection.setText( GROUP_MORE_OPTION );
moreOptionSection.setLayout( new GridLayout( 2, false ) );
moreOptionSection.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
createLabel( moreOptionSection, LABEL_HELP_TEXT );
helpTextEditor = new Text( moreOptionSection, SWT.BORDER );
helpTextEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
createLabel( moreOptionSection, LABEL_FORMAT );
Composite formatSection = new Composite( moreOptionSection, SWT.NONE );
formatSection.setLayout( UIUtil.createGridLayoutWithoutMargin( 2, false ) );
formatSection.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
formatField = new Text( formatSection, SWT.BORDER
| SWT.SINGLE
| SWT.READ_ONLY );
formatField.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
changeFormat = new Button( formatSection, SWT.PUSH );
changeFormat.setText( BUTTON_LABEL_CHANGE_FORMAT );
setButtonLayoutData( changeFormat );
changeFormat.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
popupFormatBuilder( true );
}
} );
createLabel( moreOptionSection, null );
Group previewArea = new Group( moreOptionSection, SWT.NONE );
previewArea.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
previewArea.setLayout( UIUtil.createGridLayoutWithoutMargin( ) );
previewArea.setText( LABEL_PREVIEW );
previewLabel = new Label( previewArea, SWT.NONE );
previewLabel.setAlignment( SWT.CENTER );
previewLabel.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
// start create list limitation area
createLabel( moreOptionSection, LABEL_LIST_LIMIT ); //$NON-NLS-1$
Composite limitArea = new Composite( moreOptionSection, SWT.NULL );
GridLayout layout = new GridLayout( 2, false );
layout.marginWidth = 0;
layout.marginHeight = 0;
limitArea.setLayout( layout );
GridData data = new GridData( GridData.FILL_HORIZONTAL );
data.verticalSpan = 1;
limitArea.setLayoutData( data );
listLimit = new Text( limitArea, SWT.BORDER );
data = new GridData( );
data.widthHint = 80;
listLimit.setLayoutData( data );
listLimit.addVerifyListener( new VerifyListener( ) {
public void verifyText( VerifyEvent e )
{
e.doit = ( "0123456789\0\b\u007f".indexOf( e.character ) != -1 ); //$NON-NLS-1$
}
} );
Label values = new Label( limitArea, SWT.NULL );
values.setText( Messages.getString( "ParameterDialog.Label.values" ) ); //$NON-NLS-1$
values.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
// end
createLabel( moreOptionSection, null ); // Dummy
Composite checkBoxArea = new Composite( moreOptionSection, SWT.NONE );
checkBoxArea.setLayout( UIUtil.createGridLayoutWithoutMargin( 2, false ) );
checkBoxArea.setLayoutData( new GridData( GridData.FILL_BOTH ) );
allowNull = new Button( checkBoxArea, SWT.CHECK );
allowNull.setText( CHECKBOX_ALLOW_NULL );
addCheckBoxListener( allowNull, CHECKBOX_ALLOW_NULL );
allowBlank = new Button( checkBoxArea, SWT.CHECK );
allowBlank.setText( CHECKBOX_ALLOW_BLANK );
addCheckBoxListener( allowBlank, CHECKBOX_ALLOW_BLANK );
doNotEcho = new Button( checkBoxArea, SWT.CHECK );
doNotEcho.setText( CHECKBOX_DO_NOT_ECHO );
addCheckBoxListener( doNotEcho, CHECKBOX_DO_NOT_ECHO );
isHidden = new Button( checkBoxArea, SWT.CHECK );
isHidden.setText( CHECKBOX_HIDDEN );
addCheckBoxListener( isHidden, CHECKBOX_HIDDEN );
needSort = new Button( checkBoxArea, SWT.CHECK );
needSort.setText( CHECKBOX_SORT );
addCheckBoxListener( needSort, CHECKBOX_SORT );
}
/**
* Set the input of the dialog, which cannot be null
*
* @param input
* the input of the dialog, which cannot be null
*/
public void setInput( Object input )
{
Assert.isNotNull( input );
Assert.isLegal( input instanceof ScalarParameterHandle );
inputParameter = (ScalarParameterHandle) input;
}
protected boolean initDialog( )
{
Assert.isNotNull( inputParameter );
nameEditor.setText( inputParameter.getName( ) );
if ( !StringUtil.isBlank( inputParameter.getPromptText( ) ) )
{
promptTextEditor.setText( inputParameter.getPromptText( ) );
}
helpTextEditor.setText( UIUtil.convertToGUIString( inputParameter.getHelpText( ) ) );
if ( inputParameter.getValueType( )
.equals( DesignChoiceConstants.PARAM_VALUE_TYPE_STATIC ) )
{
staticRadio.setSelection( true );
for ( Iterator iter = inputParameter.getPropertyHandle( ScalarParameterHandle.SELECTION_LIST_PROP )
.iterator( ); iter.hasNext( ); )
{
SelectionChoiceHandle choiceHandle = (SelectionChoiceHandle) iter.next( );
choiceList.add( choiceHandle.getStructure( ) );
}
}
else
{
dynamicRadio.setSelection( true );
}
defaultValue = inputParameter.getDefaultValue( );
if ( inputParameter.getPropertyHandle( ScalarParameterHandle.LIST_LIMIT_PROP )
.isSet( ) )
{
listLimit.setText( String.valueOf( inputParameter.getListlimit( ) ) );
}
isHidden.setSelection( inputParameter.isHidden( ) );
allowNull.setSelection( inputParameter.allowNull( ) );
allowBlank.setSelection( inputParameter.allowBlank( ) );
doNotEcho.setSelection( inputParameter.isConcealValue( ) );
needSort.setSelection( !inputParameter.isFixedOrder( ) );
changeDataType( );
dataTypeChooser.setText( dataType.findChoice( inputParameter.getDataType( ) )
.getDisplayName( ) );
switchParamterType( );
loading = false;
return true;
}
private void initValueArea( )
{
if ( isStatic( ) )
{
if ( DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX.equals( getSelectedControlType( ) ) )
{
if ( isValidValue( defaultValue ) != null )
{
defaultValue = null;
defaultValueChooser.select( 0 );
}
else
{
if ( Boolean.valueOf( defaultValue ).booleanValue( ) )
{
defaultValueChooser.select( 1 );
}
else
{
defaultValueChooser.select( 2 );
}
}
}
else
{
if ( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX.equals( getSelectedControlType( ) )
&& defaultValue != null )
{
defaultValueEditor.setText( defaultValue );
}
}
refreshValueTable( );
}
else
{
refreshDataSets( );
if ( inputParameter.getDataSetName( ) != null )
{
dataSetChooser.setText( inputParameter.getDataSetName( ) );
}
refreshColumns( false );
String columnName = getColumnName( inputParameter.getValueExpr( ) );
if ( columnName != null )
{
columnChooser.setText( columnName );
}
columnName = getColumnName( inputParameter.getLabelExpr( ) );
if ( columnName != null )
{
displayTextChooser.setText( columnName );
}
if ( defaultValue != null )
{
defaultValueEditor.setText( defaultValue );
}
}
updateMessageLine( );
}
private void initFormatField( )
{
if ( ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( lastControlType ) && DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( getSelectedDataType( ) ) )
|| ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( lastControlType ) && DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( getSelectedDataType( ) ) ) )
{
return;
}
IChoiceSet choiceSet = getFormatChoiceSet( getSelectedDataType( ) );
if ( choiceSet == null )
{
formatCategroy = formatPattern = null;
}
else
{
if ( !loading
|| ( ( inputParameter.getCategory( ) == null && inputParameter.getPattern( ) == null ) ) )
{
if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( getSelectedDataType( ) ) )
{
formatCategroy = choiceSet.findChoice( DesignChoiceConstants.STRING_FORMAT_TYPE_UNFORMATTED )
.getName( );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( getSelectedDataType( ) ) )
{
formatCategroy = choiceSet.findChoice( DesignChoiceConstants.DATETIEM_FORMAT_TYPE_UNFORMATTED )
.getName( );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( getSelectedDataType( ) )
|| DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( getSelectedDataType( ) )
|| DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( getSelectedDataType( ) ) )
{
formatCategroy = choiceSet.findChoice( DesignChoiceConstants.NUMBER_FORMAT_TYPE_UNFORMATTED )
.getName( );
}
formatPattern = null;
}
else
{
formatCategroy = inputParameter.getCategory( );
if ( formatCategroy == null )
{
formatCategroy = DesignChoiceConstants.STRING_FORMAT_TYPE_UNFORMATTED;
}
formatPattern = inputParameter.getPattern( );
}
}
updateFormatField( );
}
private void refreshDataSets( )
{
String selectedDataSetName = dataSetChooser.getText( );
String[] oldList = dataSetChooser.getItems( );
List dataSetList = new ArrayList( );
for ( Iterator iterator = inputParameter.getModuleHandle( )
.getVisibleDataSets( )
.iterator( ); iterator.hasNext( ); )
{
DataSetHandle DataSetHandle = (DataSetHandle) iterator.next( );
dataSetList.add( DataSetHandle.getQualifiedName( ) );
}
if ( inputParameter.getDataSetName( ) != null
&& !dataSetList.contains( inputParameter.getDataSetName( ) ) )
{
dataSetList.add( 0, inputParameter.getDataSetName( ) );
}
if ( oldList.length != dataSetList.size( ) )
{
dataSetChooser.setItems( (String[]) dataSetList.toArray( new String[]{} ) );
if ( StringUtil.isBlank( selectedDataSetName ) )
{
dataSetChooser.select( 0 );
refreshColumns( false );
}
else
{
dataSetChooser.setText( selectedDataSetName );
}
}
}
private void refreshColumns( boolean onlyFilter )
{
if ( columnChooser == null )
{
return;
}
if ( !onlyFilter )
{
DataSetHandle dataSetHandle = inputParameter.getModuleHandle( )
.findDataSet( dataSetChooser.getText( ) );
try
{
columnList = DataUtil.getColumnList( dataSetHandle );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
displayTextChooser.removeAll( );
displayTextChooser.add( NONE_DISPLAY_TEXT );
for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); )
{
displayTextChooser.add( ( (ResultSetColumnHandle) iter.next( ) ).getColumnName( ) );
}
displayTextChooser.setText( NONE_DISPLAY_TEXT );
}
String originalSelection = columnChooser.getText( );
columnChooser.removeAll( );
for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); )
{
ResultSetColumnHandle cachedColumn = (ResultSetColumnHandle) iter.next( );
if ( matchDataType( cachedColumn ) )
{
columnChooser.add( cachedColumn.getColumnName( ) );
}
}
if ( columnChooser.indexOf( originalSelection ) != -1 )
{
columnChooser.setText( originalSelection );
}
else if ( columnChooser.getItemCount( ) > 0 )
{
columnChooser.select( 0 );
}
columnChooser.setEnabled( columnChooser.getItemCount( ) > 0 );
updateMessageLine( );
}
private boolean matchDataType( ResultSetColumnHandle column )
{
String type = getSelectedDataType( );
if ( type.equals( DesignChoiceConstants.PARAM_TYPE_STRING )
|| DesignChoiceConstants.COLUMN_DATA_TYPE_ANY.equals( column.getDataType( ) ) )
{
return true;
}
if ( DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME.equals( column.getDataType( ) ) )
{
return type.equals( DesignChoiceConstants.PARAM_TYPE_DATETIME );
}
else if ( DesignChoiceConstants.COLUMN_DATA_TYPE_DECIMAL.equals( column.getDataType( ) ) )
{
return type.equals( DesignChoiceConstants.PARAM_TYPE_DECIMAL );
}
else if ( DesignChoiceConstants.COLUMN_DATA_TYPE_FLOAT.equals( column.getDataType( ) ) )
{
return type.equals( DesignChoiceConstants.PARAM_TYPE_FLOAT );
}
else if ( DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER.equals( column.getDataType( ) ) )
{
return type.equals( DesignChoiceConstants.PARAM_TYPE_INTEGER );
}
return false;
}
private String getInputControlType( )
{
String type = null;
if ( inputParameter.getControlType( ) == null )
{
type = DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX;
}
else if ( DesignChoiceConstants.PARAM_CONTROL_LIST_BOX.equals( inputParameter.getControlType( ) ) )
{
if ( inputParameter.isMustMatch( ) )
{
type = PARAM_CONTROL_COMBO;
}
else
{
type = PARAM_CONTROL_LIST;
}
}
else
{
type = inputParameter.getControlType( );
}
return type;
}
private String getSelectedDataType( )
{
String type = null;
if ( StringUtil.isBlank( dataTypeChooser.getText( ) ) )
{
type = inputParameter.getDataType( );
}
else
{
IChoice choice = dataType.findChoiceByDisplayName( dataTypeChooser.getText( ) );
type = dataType.findChoiceByDisplayName( dataTypeChooser.getText( ) )
.getName( );
type = choice.getName( );
}
return type;
}
/**
* Gets the internal name of the control type from the display name
*/
private String getSelectedControlType( )
{
String displayText = controlTypeChooser.getText( );
if ( StringUtil.isBlank( displayText ) )
{
return getInputControlType( );
}
if ( DISPLAY_NAME_CONTROL_COMBO.equals( displayText ) )
{
return PARAM_CONTROL_COMBO;
}
if ( DISPLAY_NAME_CONTROL_LIST.equals( displayText ) )
{
return PARAM_CONTROL_LIST;
}
return controlType.findChoiceByDisplayName( displayText ).getName( );
}
private void changeDataType( )
{
String type = getSelectedDataType( );
if ( type.equals( lastDataType ) )
{
return;
}
if ( buildControlTypeList( type ) )
{
changeControlType( );
}
lastDataType = type;
initFormatField( );
if ( isStatic( ) )
{
makeUniqueAndValid( );
refreshValueTable( );
}
else
{
refreshColumns( true );
}
updateMessageLine( );
}
private boolean buildControlTypeList( String type )
{
String[] choices;
if ( isStatic( ) )
{
if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) )
{
choices = new String[3];
}
else
{
choices = new String[4];
}
}
else
{
choices = new String[2];
}
if ( controlTypeChooser.getItemCount( ) != choices.length )
{
String originalSelection = controlTypeChooser.getText( );
if ( isStatic( ) )
{
if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) )
{
choices[0] = controlType.findChoice( DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX )
.getDisplayName( );
}
else
{
choices[0] = controlType.findChoice( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX )
.getDisplayName( );
choices[1] = DISPLAY_NAME_CONTROL_LIST;
}
choices[choices.length - 2] = DISPLAY_NAME_CONTROL_COMBO;
choices[choices.length - 1] = controlType.findChoice( DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON )
.getDisplayName( );
}
else
{
choices[0] = DISPLAY_NAME_CONTROL_COMBO;
choices[1] = DISPLAY_NAME_CONTROL_LIST;
}
controlTypeChooser.setItems( choices );
if ( originalSelection.length( ) == 0 )
{// initialize
controlTypeChooser.setText( getInputControlDisplayName( ) );
}
else
{
int index = controlTypeChooser.indexOf( originalSelection );
if ( index == -1 )
{// The original control type cannot be
// supported
controlTypeChooser.select( 0 );
return true;
}
controlTypeChooser.setText( originalSelection );
}
}
return false;
}
private void makeUniqueAndValid( )
{
for ( Iterator iter = choiceList.iterator( ); iter.hasNext( ); )
{
SelectionChoice choice = (SelectionChoice) iter.next( );
if ( isValidValue( choice.getValue( ) ) != null
|| containValue( choice, choice.getValue( ), COLUMN_VALUE ) )
{
iter.remove( );
}
}
}
private void changeControlType( )
{
if ( isStatic( ) )
{
String type = getSelectedControlType( );
if ( !type.equals( lastControlType ) )
{
if ( DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX.equals( type ) )
{
clearArea( valueArea );
switchToCheckBox( );
}
else if ( PARAM_CONTROL_COMBO.equals( type )
|| PARAM_CONTROL_LIST.equals( type )
|| DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON.equals( type ) )
{
// Radio ,Combo and List has the same UI
if ( !PARAM_CONTROL_COMBO.equals( lastControlType )
&& !PARAM_CONTROL_LIST.equals( lastControlType )
&& !DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON.equals( lastControlType ) )
{
clearArea( valueArea );
switchToList( );
}
}
else if ( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX.equals( type ) )
{
clearArea( valueArea );
switchToText( );
}
valueArea.layout( );
initValueArea( );
lastControlType = type;
}
}
updateCheckBoxArea( );
updateMessageLine( );
boolean radioEnable = false;
if ( PARAM_CONTROL_COMBO.equals( getSelectedControlType( ) )
|| PARAM_CONTROL_LIST.equals( getSelectedControlType( ) ) )
{
radioEnable = true;
}
if ( radioEnable != staticRadio.isEnabled( ) )
{
staticRadio.setEnabled( radioEnable );
dynamicRadio.setEnabled( radioEnable );
}
}
private void switchParamterType( )
{
clearArea( valueArea );
lastControlType = null;
if ( isStatic( ) )
{
switchToStatic( );
}
else
{
switchToDynamic( );
}
buildControlTypeList( getSelectedDataType( ) );
valueArea.layout( );
initValueArea( );
updateCheckBoxArea( );
}
private void switchToCheckBox( )
{
createLabel( valueArea, LABEL_DEFAULT_VALUE );
defaultValueChooser = new Combo( valueArea, SWT.READ_ONLY | SWT.BORDER );
defaultValueChooser.add( CHOICE_NO_DEFAULT );
defaultValueChooser.add( BOOLEAN_TRUE );
defaultValueChooser.add( BOOLEAN_FALSE );
defaultValueChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
defaultValueChooser.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
switch ( defaultValueChooser.getSelectionIndex( ) )
{
case 0 :
defaultValue = null;
break;
case 1 :
defaultValue = Boolean.toString( true );
break;
case 2 :
defaultValue = Boolean.toString( false );
break;
}
}
} );
}
private void switchToList( )
{
createLabel( valueArea, LABEL_VALUES );
Composite tableAreaComposite = new Composite( valueArea, SWT.NONE );
tableAreaComposite.setLayout( UIUtil.createGridLayoutWithoutMargin( ) );
tableAreaComposite.setLayoutData( new GridData( GridData.FILL_BOTH ) );
TableArea tableArea = new TableArea( tableAreaComposite, SWT.SINGLE
| SWT.FULL_SELECTION
| SWT.BORDER, tableAreaModifier );
tableArea.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Table table = tableArea.getTable( );
table.setLinesVisible( true );
table.setHeaderVisible( true );
String[] columns;
int[] columnWidth;
columns = new String[]{
null, COLUMN_IS_DEFAULT, COLUMN_VALUE, COLUMN_DISPLAY_TEXT
};
columnWidth = new int[]{
20, 70, 145, 145,
};
for ( int i = 0; i < columns.length; i++ )
{
TableColumn column = new TableColumn( table, SWT.LEFT );
column.setResizable( columns[i] != null );
if ( columns[i] != null )
{
column.setText( columns[i] );
}
column.setWidth( columnWidth[i] );
}
valueTable = tableArea.getTableViewer( );
valueTable.setColumnProperties( columns );
valueTable.setContentProvider( contentProvider );
valueTable.setLabelProvider( labelProvider );
tableArea.setInput( choiceList );
valueTable.addSelectionChangedListener( new ISelectionChangedListener( ) {
public void selectionChanged( SelectionChangedEvent event )
{
updateTableButtons( );
}
} );
Composite buttonBar = new Composite( tableAreaComposite, SWT.NONE );
buttonBar.setLayout( UIUtil.createGridLayoutWithoutMargin( 4, false ) );
buttonBar.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
importValue = new Button( buttonBar, SWT.PUSH );
importValue.setText( BUTTON_LABEL_IMPORT );
setButtonLayoutData( importValue );
// Disabled when no date set defined
importValue.setEnabled( !inputParameter.getModuleHandle( )
.getVisibleDataSets( )
.isEmpty( ) );
importValue.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
String type = getSelectedDataType( );
ImportValueDialog dialog = new ImportValueDialog( type );
if ( dialog.open( ) == OK )
{
String[] importValues = (String[]) dialog.getResult( );
for ( int i = 0; i < importValues.length; i++ )
{
if ( !containValue( null, importValues[i], COLUMN_VALUE ) )
{
SelectionChoice choice = StructureFactory.createSelectionChoice( );
choice.setValue( importValues[i] );
choiceList.add( choice );
}
}
refreshValueTable( );
}
}
} );
changeDefault = new Button( buttonBar, SWT.TOGGLE );
changeDefault.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
SelectionChoice choice = (SelectionChoice) ( (IStructuredSelection) valueTable.getSelection( ) ).getFirstElement( );
if ( isDefaultChoice( choice ) )
{
changeDefaultValue( null );
}
else
{
changeDefaultValue( choice.getValue( ) );
}
refreshValueTable( );
changeDefault.getParent( ).layout( );
}
} );
createPromptLine( tableAreaComposite );
updateTableButtons( );
}
private void switchToText( )
{
createDefaultEditor( );
createLabel( valueArea, null );
createPromptLine( valueArea );
}
private void switchToStatic( )
{
changeControlType( );
listLimit.setEditable( false );
}
private void switchToDynamic( )
{
Composite composite = new Composite( valueArea, SWT.NONE );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
composite.setLayoutData( gd );
composite.setLayout( UIUtil.createGridLayoutWithoutMargin( 3, false ) );
createLabel( composite, LABEL_SELECT_DATA_SET );
dataSetChooser = new Combo( composite, SWT.BORDER | SWT.READ_ONLY );
dataSetChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
dataSetChooser.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
refreshColumns( false );
}
}
);
createDataSet = new Button( composite, SWT.PUSH );
createDataSet.setText( BUTTON_CREATE_DATA_SET );
setButtonLayoutData( createDataSet );
createDataSet.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
new NewDataSetAction( ).run( );
refreshDataSets( );
}
} );
createLabel( composite, LABEL_SELECT_VALUE_COLUMN );
columnChooser = new Combo( composite, SWT.BORDER | SWT.READ_ONLY );
columnChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
columnChooser.addSelectionListener( new SelectionAdapter( ) {
public void widgetDefaultSelected( SelectionEvent e )
{
updateButtons( );
}
} );
createLabel( composite, null );
createLabel( composite, LABEL_SELECT_DISPLAY_TEXT );
displayTextChooser = new Combo( composite, SWT.BORDER | SWT.READ_ONLY );
displayTextChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
createLabel( composite, null );
createDefaultEditor( );
listLimit.setEditable( true );
}
private void createDefaultEditor( )
{
createLabel( valueArea, LABEL_DEFAULT_VALUE );
defaultValueEditor = new Text( valueArea, SWT.BORDER );
defaultValueEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
defaultValueEditor.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
changeDefaultValue( UIUtil.convertToModelString( defaultValueEditor.getText( ),
false ) );
if ( isStatic( ) )
{
refreshValueTable( );
}
}
} );
}
private void createPromptLine( Composite parent )
{
promptMessageLine = new Label( parent, SWT.NONE );
promptMessageLine.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
protected void okPressed( )
{
try
{
// Save the name and display name
inputParameter.setName( nameEditor.getText( ) );
inputParameter.setPromptText( UIUtil.convertToModelString( promptTextEditor.getText( ),
true ) );
String newControlType = getSelectedControlType( );
if ( PARAM_CONTROL_COMBO.equals( newControlType ) )
{
newControlType = DesignChoiceConstants.PARAM_CONTROL_LIST_BOX;
inputParameter.setMustMatch( true );
}
else if ( PARAM_CONTROL_LIST.equals( newControlType ) )
{
newControlType = DesignChoiceConstants.PARAM_CONTROL_LIST_BOX;
inputParameter.setMustMatch( false );
}
else
{
inputParameter.setProperty( ScalarParameterHandle.MUCH_MATCH_PROP,
null );
}
// Save control type
inputParameter.setControlType( newControlType );
// Save default value
inputParameter.setDefaultValue( defaultValue );
// Set data type
inputParameter.setDataType( dataType.findChoiceByDisplayName( dataTypeChooser.getText( ) )
.getName( ) );
// Clear original choices list
PropertyHandle selectionChioceList = inputParameter.getPropertyHandle( ScalarParameterHandle.SELECTION_LIST_PROP );
selectionChioceList.setValue( null );
if ( isStatic( ) )
{
// Save static choices list
inputParameter.setValueType( DesignChoiceConstants.PARAM_VALUE_TYPE_STATIC );
if ( !DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX.equals( newControlType )
&& !DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX.equals( newControlType ) )
{
for ( Iterator iter = choiceList.iterator( ); iter.hasNext( ); )
{
SelectionChoice choice = (SelectionChoice) iter.next( );
if ( isValidValue( choice.getValue( ) ) == null )
{
selectionChioceList.addItem( choice );
}
}
}
inputParameter.setDataSetName( null );
inputParameter.setValueExpr( null );
inputParameter.setLabelExpr( null );
}
else
{
// Save dynamic settings
inputParameter.setValueType( DesignChoiceConstants.PARAM_VALUE_TYPE_DYNAMIC );
inputParameter.setDataSetName( dataSetChooser.getText( ) );
inputParameter.setValueExpr( getExpression( columnChooser.getText( ) ) );
inputParameter.setLabelExpr( getExpression( displayTextChooser.getText( ) ) );
}
// Save help text
inputParameter.setHelpText( UIUtil.convertToModelString( helpTextEditor.getText( ),
false ) );
// Save format
inputParameter.setCategory( formatCategroy );
inputParameter.setPattern( formatPattern );
if ( isStatic( )
&& ( PARAM_CONTROL_COMBO.equals( getSelectedControlType( ) ) || DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON.equals( getSelectedControlType( ) ) )
&& !containValue( null, defaultValue, COLUMN_VALUE ) )
{
defaultValue = null;
}
// Save options
if ( dirtyProperties.containsKey( CHECKBOX_HIDDEN ) )
{
inputParameter.setHidden( getProperty( CHECKBOX_HIDDEN ) );
}
if ( dirtyProperties.containsKey( CHECKBOX_ALLOW_NULL ) )
{
inputParameter.setAllowNull( getProperty( CHECKBOX_ALLOW_NULL ) );
}
if ( allowBlank.isEnabled( ) )
{
if ( dirtyProperties.containsKey( CHECKBOX_ALLOW_BLANK ) )
{
inputParameter.setAllowBlank( getProperty( CHECKBOX_ALLOW_BLANK ) );
}
}
else
{
inputParameter.setProperty( ScalarParameterHandle.ALLOW_BLANK_PROP,
null );
}
if ( doNotEcho.isEnabled( ) )
{
if ( dirtyProperties.containsKey( CHECKBOX_DO_NOT_ECHO ) )
{
inputParameter.setConcealValue( getProperty( CHECKBOX_DO_NOT_ECHO ) );
}
}
else
{
inputParameter.setProperty( ScalarParameterHandle.CONCEAL_VALUE_PROP,
null );
}
if ( needSort.isEnabled( ) )
{
if ( dirtyProperties.containsKey( CHECKBOX_SORT ) )
{
inputParameter.setFixedOrder( !getProperty( CHECKBOX_SORT ) );
}
}
else
{
inputParameter.setProperty( ScalarParameterHandle.FIXED_ORDER_PROP,
null );
}
// Save limits
if ( !isStatic( ) && !StringUtil.isBlank( listLimit.getText( ) ) )
{
try
{
inputParameter.setListlimit( Integer.parseInt( listLimit.getText( ) ) );
}
catch ( NumberFormatException ex )
{
ExceptionHandler.openErrorMessageBox( ERROR_TITLE_INVALID_LIST_LIMIT,
MessageFormat.format( ERROR_MSG_INVALID_LIST_LIMIT,
new Object[]{
Integer.toString( Integer.MAX_VALUE )
} ) );
}
}
else
{
inputParameter.setProperty( ScalarParameterHandle.LIST_LIMIT_PROP,
null );
}
}
catch ( Exception e )
{
ExceptionHandler.handle( e );
return;
}
setResult( inputParameter );
super.okPressed( );
}
private void createLabel( Composite parent, String content )
{
Label label = new Label( parent, SWT.NONE );
if ( content != null )
{
label.setText( content );
}
setLabelLayoutData( label );
}
private void setLabelLayoutData( Label label )
{
GridData gd = new GridData( );
if ( label.getText( ).equals( LABEL_VALUES ) )
{
gd.verticalAlignment = GridData.BEGINNING;
}
label.setLayoutData( gd );
}
private void addCheckBoxListener( final Button checkBox, final String key )
{
checkBox.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
checkBoxChange( checkBox, key );
}
} );
}
/**
* @param key
* @param checkBox
*
*/
protected void checkBoxChange( Button checkBox, String key )
{
dirtyProperties.put( key, new Boolean( checkBox.getSelection( ) ) );
if ( CHECKBOX_ALLOW_BLANK.equals( key )
|| CHECKBOX_ALLOW_NULL.equals( key ) )
{
if ( isStatic( ) )
{
makeUniqueAndValid( );
refreshValueTable( );
}
updateMessageLine( );
}
}
private void clearArea( Composite area )
{
Control[] children = area.getChildren( );
for ( int i = 0; i < children.length; i++ )
{
children[i].dispose( );
}
}
private void updateTableButtons( )
{
boolean isEnable = true;
SelectionChoice selectedChoice = null;
if ( valueTable.getSelection( ).isEmpty( ) )
{
isEnable = false;
}
else
{
selectedChoice = (SelectionChoice) ( (IStructuredSelection) valueTable.getSelection( ) ).getFirstElement( );
// if ( selectedChoice == dummyChoice )
// isEnable = false;
}
boolean isDefault = isEnable && isDefaultChoice( selectedChoice );
if ( isDefault )
{
changeDefault.setText( BUTTON_LABEL_REMOVE_DEFAULT );
}
else
{
changeDefault.setText( BUTTON_LABEL_SET_DEFAULT );
}
changeDefault.setSelection( isDefault );
changeDefault.setEnabled( isEnable );
}
private void updateButtons( )
{
boolean canFinish = !StringUtil.isBlank( nameEditor.getText( ) );
if ( canFinish )
{
if ( errorMessageLine != null && !errorMessageLine.isDisposed( ) )
{
canFinish = ( errorMessageLine.getImage( ) == null );
}
if ( columnChooser != null && !isStatic( ) )
{
canFinish &= ( getExpression( columnChooser.getText( ) ) != null );
}
}
getOkButton( ).setEnabled( canFinish );
}
private void updateCheckBoxArea( )
{
// Allow blank check
if ( ( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX.equals( getSelectedControlType( ) ) || PARAM_CONTROL_LIST.equals( getSelectedControlType( ) ) )
&& DesignChoiceConstants.PARAM_TYPE_STRING.equals( getSelectedDataType( ) ) )
{
allowBlank.setEnabled( true );
}
else
{
allowBlank.setEnabled( false );
}
// Do not echo check
if ( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX.equals( getSelectedControlType( ) ) )
{
doNotEcho.setEnabled( true );
}
else
{
doNotEcho.setEnabled( false );
}
// Fix order check
if ( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX.equals( getSelectedControlType( ) )
|| DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX.equals( getSelectedControlType( ) ) )
{
needSort.setEnabled( false );
}
else
{
needSort.setEnabled( true );
}
}
private void updateMessageLine( )
{
String errorMessage = validateName( );
if ( errorMessage == null )
{
if ( !isStatic( )
&& columnChooser != null
&& columnChooser.getItemCount( ) == 0 )
{
errorMessage = ERROR_MSG_NO_AVAILABLE_COLUMN;
}
else if ( defaultValue == null
&& ( PARAM_CONTROL_COMBO.equals( getSelectedControlType( ) ) || DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON.equals( getSelectedControlType( ) ) ) )
{
// Now combo and radio must specify an default value
errorMessage = ERROR_MSG_NO_DEFAULT_VALUE;
}
}
if ( errorMessage != null )
{
errorMessageLine.setText( errorMessage );
errorMessageLine.setImage( ERROR_ICON );
}
else
{
errorMessageLine.setText( "" ); //$NON-NLS-1$
errorMessageLine.setImage( null );
}
if ( promptMessageLine != null && !promptMessageLine.isDisposed( ) )
{
if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( getSelectedDataType( ) ) )
{
promptMessageLine.setText( LABEL_DATETIME_PROMPT );
}
else
{
promptMessageLine.setText( "" ); //$NON-NLS-1$
}
}
updateButtons( );
}
private String validateName( )
{
String name = nameEditor.getText( ).trim( );
if ( name.length( ) == 0 )
{
return ERROR_MSG_NAME_IS_EMPTY;
}
if ( !name.equals( inputParameter.getName( ) )
&& inputParameter.getModuleHandle( ).findParameter( name ) != null )
{
return ERROR_MSG_DUPLICATED_NAME;
}
return null;
}
private void refreshValueTable( )
{
if ( valueTable != null && !valueTable.getTable( ).isDisposed( ) )
{
valueTable.refresh( );
updateTableButtons( );
}
}
private boolean getProperty( String key )
{
return ( (Boolean) dirtyProperties.get( key ) ).booleanValue( );
}
private String format( String string )
{
if ( canBeNull( ) && string == null )
{
return LABEL_NULL;
}
if ( StringUtil.isBlank( string ) || formatCategroy == null )
{
return string;
}
try
{
String pattern = formatPattern;
if ( formatPattern == null )
{
if ( isCustom( ) )
{
return string;
}
pattern = formatCategroy;
}
if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( getSelectedDataType( ) ) )
{
Date date = DataTypeUtil.toDate( string, ULocale.US );
DateFormatter formatter = new DateFormatter( pattern );
string = formatter.format( date );
}
else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( getSelectedDataType( ) ) )
{
string = new NumberFormatter( pattern ).format( DataTypeUtil.toDouble( string )
.doubleValue( ) );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( getSelectedDataType( ) ) )
{
string = new NumberFormatter( pattern ).format( DataTypeUtil.toBigDecimal( string ) );
}
else if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( getSelectedDataType( ) ) )
{
string = new StringFormatter( pattern ).format( string );
}
}
catch ( BirtException e )
{
// e.printStackTrace( );
}
return string;
}
/**
* Check if the specified value is valid
*
* @param value
* the value to check
* @return Returns the error message if the input value is invalid,or null
* if it is valid
*/
private String isValidValue( String value )
{
if ( canBeNull( ) )
{
if ( value == null || value.length( ) == 0 )
{
return null;
}
}
else
{
if ( value == null || value.length( ) == 0 )
{
return ERROR_MSG_CANNOT_BE_NULL;
}
}
if ( canBeBlank( ) )
{
if ( StringUtil.isBlank( value ) )
{
return null;
}
}
else
{
if ( StringUtil.isBlank( value ) )
{
return ERROR_MSG_CANNOT_BE_BLANK;
}
}
try
{
getValue( value );
}
catch ( BirtException e )
{
return ERROR_MSG_MISMATCH_DATA_TYPE;
}
return null;
}
private boolean isEqual( String value1, String value2 )
{
Object v1 = null;
Object v2 = null;
try
{
v1 = getValue( value1 );
v2 = getValue( value2 );
}
catch ( BirtException e )
{
}
if ( v1 == null )
{
return v2 == null;
}
if ( v1 instanceof Double && v2 instanceof Double )
{
return ( (Double) v1 ).compareTo( (Double) v2 ) == 0;
}
if ( v1 instanceof BigDecimal && v2 instanceof BigDecimal )
{
return ( (BigDecimal) v1 ).compareTo( (BigDecimal) v2 ) == 0;
}
if ( v1 instanceof Integer && v2 instanceof Integer )
{
return ( (Integer) v1 ).compareTo( (Integer) v2 ) == 0;
}
return v1.equals( v2 );
}
private Object getValue( String value ) throws BirtException
{
if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( getSelectedDataType( ) ) )
{
return DataTypeUtil.toBoolean( value );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( getSelectedDataType( ) ) )
{
return DataTypeUtil.toBigDecimal( value );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( getSelectedDataType( ) ) )
{
return DataTypeUtil.toDate( value, ULocale.US );
}
else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( getSelectedDataType( ) ) )
{
return DataTypeUtil.toDouble( value );
}
else if ( DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( getSelectedDataType( ) ) )
{
return DataTypeUtil.toInteger( value );
}
return value;
}
private IChoiceSet getFormatChoiceSet( String type )
{
IChoiceSet choiceSet = null;
if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) )
{
choiceSet = DEUtil.getMetaDataDictionary( )
.getChoiceSet( DesignChoiceConstants.CHOICE_STRING_FORMAT_TYPE );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) )
{
choiceSet = DEUtil.getMetaDataDictionary( )
.getChoiceSet( DesignChoiceConstants.CHOICE_DATETIME_FORMAT_TYPE );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type )
|| DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type )
|| DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( type ) )
{
choiceSet = DEUtil.getMetaDataDictionary( )
.getChoiceSet( DesignChoiceConstants.CHOICE_NUMBER_FORMAT_TYPE );
}
return choiceSet;
}
private void updateFormatField( )
{
String displayFormat;
String previewString;
String type = getSelectedDataType( );
IChoiceSet choiceSet = getFormatChoiceSet( type );
if ( choiceSet == null )
{// Boolean type;
displayFormat = DEUtil.getMetaDataDictionary( )
.getChoiceSet( DesignChoiceConstants.CHOICE_STRING_FORMAT_TYPE )
.findChoice( DesignChoiceConstants.STRING_FORMAT_TYPE_UNFORMATTED )
.getDisplayName( );
previewString = "True"; //$NON-NLS-1$
}
else
{
displayFormat = choiceSet.findChoice( formatCategroy )
.getDisplayName( );
if ( defaultValue != null )
{
previewString = format( defaultValue );
}
else
{
if ( isCustom( ) )
{
displayFormat += ": " + formatPattern; //$NON-NLS-1$
}
if ( type.equals( DesignChoiceConstants.PARAM_TYPE_DATETIME ) )
{
previewString = new DateFormatter( isCustom( ) ? formatPattern
: formatCategroy,
ULocale.getDefault( ) ).format( new Date( ) );
}
else if ( type.equals( DesignChoiceConstants.PARAM_TYPE_STRING ) )
{
previewString = new StringFormatter( isCustom( ) ? formatPattern
: formatCategroy,
ULocale.getDefault( ) ).format( Messages.getString( "ParameterDialog.Label.Sample" ) ); //$NON-NLS-1$
}
else if ( type.equals( DesignChoiceConstants.PARAM_TYPE_INTEGER ) )
{
previewString = new NumberFormatter( isCustom( ) ? formatPattern
: formatCategroy,
ULocale.getDefault( ) ).format( 1234567890 );
}
else
{
previewString = new NumberFormatter( isCustom( ) ? formatPattern
: formatCategroy,
ULocale.getDefault( ) ).format( 123456789.01234 );
}
}
}
formatField.setText( displayFormat );
previewLabel.setText( convertNullString( previewString ) );
changeFormat.setEnabled( choiceSet != null );
}
private String convertNullString( String str )
{
if ( str == null )
{
return "";//$NON-NLS-1$
}
return str;
}
private boolean containValue( SelectionChoice selectedChoice,
String newValue, String property )
{
for ( Iterator iter = choiceList.iterator( ); iter.hasNext( ); )
{
SelectionChoice choice = (SelectionChoice) iter.next( );
if ( choice != selectedChoice )
{
String value = null;
if ( COLUMN_VALUE.equals( property ) )
{
value = choice.getValue( );
if ( isEqual( value, newValue ) )
{
return true;
}
}
else if ( COLUMN_DISPLAY_TEXT.equals( property ) )
{
value = choice.getLabel( );
if ( value == null )
{
value = choice.getValue( );
}
if ( value == null )
{
value = LABEL_NULL;
}
if ( value.equals( newValue ) )
{
return true;
}
}
}
}
return false;
}
private void popupFormatBuilder( boolean refresh )
{
String type = getSelectedDataType( );
int style;
if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) )
{
return;
}
if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) )
{
style = FormatBuilder.STRING;
}
else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) )
{
style = FormatBuilder.DATETIME;
}
else
{
style = FormatBuilder.NUMBER;
}
FormatBuilder formatBuilder = new FormatBuilder( style );
formatBuilder.setInputFormat( formatCategroy, formatPattern );
formatBuilder.setPreviewText( defaultValue );
if ( formatBuilder.open( ) == OK )
{
formatCategroy = ( (String[]) formatBuilder.getResult( ) )[0];
formatPattern = ( (String[]) formatBuilder.getResult( ) )[1];
updateFormatField( );
if ( refresh )
{
refreshValueTable( );
}
}
}
private boolean canBeBlank( )
{
boolean canBeBlank = false;
if ( PARAM_CONTROL_LIST.equals( getSelectedControlType( ) )
|| DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX.equals( getSelectedControlType( ) ) )
{
if ( dirtyProperties.containsKey( CHECKBOX_ALLOW_BLANK ) )
{
canBeBlank = ( (Boolean) dirtyProperties.get( CHECKBOX_ALLOW_BLANK ) ).booleanValue( );
}
else
{
canBeBlank = inputParameter.allowBlank( );
}
}
return canBeBlank;
}
private boolean canBeNull( )
{
boolean canBeNull = false;
if ( dirtyProperties.containsKey( CHECKBOX_ALLOW_NULL ) )
{
canBeNull = ( (Boolean) dirtyProperties.get( CHECKBOX_ALLOW_NULL ) ).booleanValue( );
}
else
{
canBeNull = inputParameter.allowNull( );
}
return canBeNull;
}
private boolean isDefaultChoice( SelectionChoice choice )
{
String choiceValue = choice.getValue( );
String defaultValue = convertToStandardFormat( this.defaultValue );
if ( canBeNull( ) && choiceValue == null && defaultValue == null )
{
return true;
}
return choiceValue != null && isEqual( choiceValue, defaultValue );
}
private boolean isStatic( )
{
return staticRadio.getSelection( );
}
private String convertToStandardFormat( String string )
{
if ( string != null
&& DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( getSelectedDataType( ) ) )
{
try
{
string = new DateFormatter( STANDARD_DATE_TIME_PATTERN,
ULocale.US ).format( DataTypeUtil.toDate( string,
ULocale.US ) );
}
catch ( BirtException e )
{
}
}
return string;
}
private String getExpression( String columnName )
{
for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); )
{
ResultSetColumnHandle cachedColumn = (ResultSetColumnHandle) iter.next( );
if ( cachedColumn.getColumnName( ).equals( columnName ) )
{
return DEUtil.getExpression( cachedColumn );
}
}
return null;
}
private String getColumnName( String expression )
{
for ( Iterator iter = columnList.iterator( ); iter.hasNext( ); )
{
ResultSetColumnHandle cachedColumn = (ResultSetColumnHandle) iter.next( );
if ( DEUtil.getExpression( cachedColumn ).equals( expression ) )
{
return cachedColumn.getColumnName( );
}
}
return null;
}
private String getInputControlDisplayName( )
{
String type = getInputControlType( );
String displayName = null;
if ( controlType.findChoice( type ) != null )
{
displayName = controlType.findChoice( type ).getDisplayName( );
}
else
{
if ( PARAM_CONTROL_COMBO.equals( type ) )
{
displayName = DISPLAY_NAME_CONTROL_COMBO;
}
else if ( PARAM_CONTROL_LIST.equals( type ) )
{
displayName = DISPLAY_NAME_CONTROL_LIST;
}
}
return displayName;
}
private String validateChoice( SelectionChoice choice, String displayLabel,
String value )
{
String errorMessage = isValidValue( value );
if ( errorMessage != null )
{
return errorMessage;
}
String newValue = convertToStandardFormat( value );
if ( ( displayLabel == null && containValue( choice,
newValue,
COLUMN_DISPLAY_TEXT ) )
|| ( containValue( choice, displayLabel, COLUMN_DISPLAY_TEXT ) ) )
{
return ERROR_MSG_DUPLICATED_LABEL;
}
if ( containValue( choice, newValue, COLUMN_VALUE ) )
{
return ERROR_MSG_DUPLICATED_VALUE;
}
return null;
}
private void changeDefaultValue( String value )
{
defaultValue = value;
updateFormatField( );
updateMessageLine( );
}
private boolean isCustom( )
{
if ( DesignChoiceConstants.STRING_FORMAT_TYPE_CUSTOM.equals( formatCategroy )
|| DesignChoiceConstants.NUMBER_FORMAT_TYPE_CUSTOM.equals( formatCategroy )
|| DesignChoiceConstants.DATETIEM_FORMAT_TYPE_CUSTOM.equals( formatCategroy ) )
{
return true;
}
return false;
}
}
|
package edu.pitt.apollo.db;
//import edu.pitt.apollo.types.UrlOutputResource;
//import edu.pitt.apollo.types.VisualizerResult;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import com.mysql.jdbc.Statement;
import edu.pitt.apollo.types.v2_0_1.ApolloSoftwareTypeEnum;
import edu.pitt.apollo.types.v2_0_1.Authentication;
import edu.pitt.apollo.types.v2_0_1.Role;
import edu.pitt.apollo.types.v2_0_1.RunSimulationMessage;
import edu.pitt.apollo.types.v2_0_1.RunVisualizationMessage;
import edu.pitt.apollo.types.v2_0_1.ServiceRegistrationRecord;
import edu.pitt.apollo.types.v2_0_1.SoftwareIdentification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ApolloDbUtils {
static Logger logger = LoggerFactory.getLogger(ApolloDbUtils.class);
static Map<String, Integer> populationAxisCache = new HashMap<String, Integer>();
static Map<String, Integer> simulatedPopulationCache = new HashMap<String, Integer>();
Connection dbcon = null;
Properties properties;
// public final int RECORD_NOT_FOUND = -1;
// public final int PASSWORD_NOT_CORRECT = -2;
// public final int RECORD_ALREADY_EXISTS = -3;
// public final int SOFTWARE_ID_RECORD_NOT_FOUND = -4;
// public final int KEY_NOT_FOUND = -5;
// public final int RECORD_NOT_INSERTED = -6;
public enum DbContentDataFormatEnum {
TEXT, URL, ZIP,};
public enum DbContentDataType {
CONFIGURATION_FILE
};
public ApolloDbUtils(File databasePropertiesFile) throws IOException {
FileInputStream fis = new FileInputStream(databasePropertiesFile);
properties = new Properties();
properties.load(fis);
fis.close();
}
public String getSoftwareIdAsDbString(SoftwareIdentification softwareIdentification) {
return softwareIdentification.getSoftwareDeveloper() + "#" + softwareIdentification.getSoftwareName() + "#"
+ softwareIdentification.getSoftwareVersion();
}
private void establishDbConn() throws ClassNotFoundException, SQLException {
String dbClass = properties.getProperty("class");
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
try {
if (dbcon != null) {
dbcon.close();
}
} catch (SQLException e) {
// who cares, making a new one anyway
}
dbcon = null;
try {
Class.forName(dbClass);
dbcon = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
throw new SQLException("Error getting connection to database: " + url + " using username " + user
+ ". Specific error was:\n" + e.getMessage());
}
}
private ByteArrayOutputStream getJsonBytes(Object obj) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mapper.writeValue(baos, obj);
return baos;
} catch (IOException ex) {
System.err.println("IO Exception JSON encoding and getting bytes from RunSimulationMessage");
return null;
}
}
public Connection getConn() throws ClassNotFoundException, SQLException {
if (dbcon == null) {
establishDbConn();
} else {
boolean connIsValid = false;
try {
connIsValid = dbcon.isValid(1000);
} catch (SQLException e1) {
// who cares, we are making a new one anyway!
}
if (!connIsValid) {
establishDbConn();
}
}
return dbcon;
}
// public Map<String, String> getStoredRuns() throws SQLException,
// ClassNotFoundException {
// try {
// String query = "SELECT LABEL,MD5HASHOFCONFIGURATIONFILE from run";
// PreparedStatement pstmt = getConn().prepareStatement(query);
// ResultSet rs = pstmt.executeQuery();
// Map<String, String> hashLabelMap = new HashMap<String, String>();
// while (rs.next()) {
// String hash = rs.getString("md5HashOfConfigurationFile");
// String label = rs.getString("label");
// if (label != null) {
// hashLabelMap.put(label, hash);
// return hashLabelMap;
// } catch (SQLException e) {
// throw new
// SQLException("Error retreiving all stored run hashes. Specific error was:\n"
// + e.getMessage());
public int getUserKey(String requesterId, String requesterPassword) throws SQLException, ClassNotFoundException,
ApolloDatabaseUserPasswordException, ApolloDatabaseKeyNotFoundException {
String query = "SELECT id, requester_password FROM users WHERE requester_id = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, requesterId);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String password = rs.getString("requester_password");
if (requesterPassword.equals(password)) {
return rs.getInt("id");
} else {
throw new ApolloDatabaseUserPasswordException("No entry in the users table where requester_id = " + requesterId
+ " for the given password.");
}
} else {
throw new ApolloDatabaseKeyNotFoundException("No entry in the users table where requester_id = " + requesterId);
}
}
// user key doesn't exist
public int addUser(String requesterId, String requesterPassword, String email) throws SQLException, ClassNotFoundException,
ApolloDatabaseRecordAlreadyExistsException {
// check authorization?!
try {
int userKey = getUserKey(requesterId, requesterPassword);
throw new ApolloDatabaseRecordAlreadyExistsException("User " + requesterId + " already exists in the database.");
} catch (ApolloDatabaseKeyNotFoundException e) {
// good this means the user doesn't already exist
} catch (ApolloDatabaseUserPasswordException e) {
// error
}
String query = "INSERT INTO users (requester_id,requester_password,requester_email) VALUES (?,?,?)";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, requesterId);
pstmt.setString(2, requesterPassword);
pstmt.setString(3, email);
pstmt.execute();
query = "SELECT LAST_INSERT_ID()";
pstmt = getConn().prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
rs.next();
return rs.getInt(1);
}
public int getSoftwareIdentificationKey(SoftwareIdentification softwareIdentification) throws SQLException,
ClassNotFoundException, ApolloDatabaseKeyNotFoundException {
String query = "SELECT id FROM software_identification where developer = ? and name = ? and version = ? and service_type = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, softwareIdentification.getSoftwareDeveloper());
pstmt.setString(2, softwareIdentification.getSoftwareName());
pstmt.setString(3, softwareIdentification.getSoftwareVersion());
pstmt.setString(4, softwareIdentification.getSoftwareType().toString());
ResultSet rs = pstmt.executeQuery();
int softwareIdKey = -1;
if (rs.next()) {
softwareIdKey = rs.getInt(1);
return softwareIdKey;
} else {
throw new ApolloDatabaseKeyNotFoundException("No entry in the software_identification table where developer = "
+ softwareIdentification.getSoftwareDeveloper() + " and name = " + softwareIdentification.getSoftwareName()
+ " and version = " + softwareIdentification.getSoftwareVersion() + " and service_type = "
+ softwareIdentification.getSoftwareType().toString());
}
}
private String getMd5(Object object) {
return DigestUtils.md5Hex(getJsonBytes(object).toString());
}
public int getRunKey(RunSimulationMessage runSimulationMessage) throws SQLException, ClassNotFoundException,
ApolloDatabaseException {
Authentication auth = runSimulationMessage.getAuthentication();
int userKey = getUserKey(auth.getRequesterId(), auth.getRequesterPassword());
int softwareKey = getSoftwareIdentificationKey(runSimulationMessage.getSimulatorIdentification());
String hash = getMd5(runSimulationMessage);
String query = "SELECT id FROM run WHERE md5_hash_of_run_message = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, hash);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getInt(1);
} else {
query = "INSERT INTO run (requester_id, software_id, md5_hash_of_run_message) VALUES (?,?,?)";
pstmt = getConn().prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt(1, userKey);
pstmt.setInt(2, softwareKey);
pstmt.setString(3, hash);
pstmt.execute();
rs = pstmt.getGeneratedKeys();
rs.next();
return rs.getInt(1);
}
}
public int addRole(SoftwareIdentification softwareIdentification, boolean canRun, boolean canViewCache) throws SQLException,
ClassNotFoundException, ApolloDatabaseException {
int softwareIdKey;
try {
softwareIdKey = getSoftwareIdentificationKey(softwareIdentification);
} catch (ApolloDatabaseKeyNotFoundException e) {
throw new ApolloDatabaseKeyNotFoundException(
"The softwareIdentifiation object provided to addRole() does not have an entry in the software_identification table. Error was: "
+ e.getMessage());
}
int roleKey;
try {
roleKey = getRoleKey(softwareIdKey, canRun, canViewCache);
return roleKey;
} catch (ApolloDatabaseKeyNotFoundException e) {
// this means that we need to insert
}
String query = "INSERT INTO ROLES (software_id, can_run, can_view_cached_results) values (?, ?, ?)";
PreparedStatement pstmt = getConn().prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
try {
pstmt.setInt(1, softwareIdKey);
pstmt.setBoolean(2, canRun);
pstmt.setBoolean(3, canViewCache);
pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
roleKey = rs.getInt(1);
return roleKey;
} else {
throw new ApolloDatabaseException("No primary key returned from addRole().");
}
} finally {
pstmt.close();
}
}
private int getRoleKey(int softwareIdKey, boolean canRun, boolean canViewCache) throws SQLException, ClassNotFoundException,
ApolloDatabaseKeyNotFoundException {
if (softwareIdKey >= 1) {
// software id found...now lets see if this specific role exists...
String query = "SELECT id FROM roles WHERE software_id = ? AND can_run = ? AND can_view_cached_results = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
try {
pstmt.setInt(1, softwareIdKey);
pstmt.setBoolean(2, canRun);
pstmt.setBoolean(3, canViewCache);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
throw new ApolloDatabaseKeyNotFoundException("No entry found in the roles table where software_id = "
+ softwareIdKey + " and can_run = " + canRun + " and can_view_cached_resuls = " + canViewCache);
} else {
return rs.getInt(1);
}
} finally {
pstmt.close();
}
} else {
throw new ApolloDatabaseKeyNotFoundException("getRoleKey() called with invalid softwareIdKey: " + softwareIdKey);
}
}
public Map<Integer, ServiceRegistrationRecord> getRegisteredSoftware() throws SQLException, ClassNotFoundException {
Map<Integer, ServiceRegistrationRecord> result = new HashMap<Integer, ServiceRegistrationRecord>();
// get all of the users that are an admin of a software
String query = "SELECT u.id, u.requester_id FROM users u, software_identification s WHERE " + "s.admin_id = u.id";
Map<Integer, String> userIdMap = new HashMap<Integer, String>();
PreparedStatement pstmt = getConn().prepareStatement(query);
try {
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
int userId = rs.getInt(1);
String requester_id = rs.getString(2);
userIdMap.put(userId, requester_id);
}
} finally {
pstmt.close();
}
query = "SELECT id, developer, name, version, service_type, wsdl_url, admin_id FROM software_identification";
pstmt = getConn().prepareStatement(query);
try {
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
ServiceRegistrationRecord srr = new ServiceRegistrationRecord();
srr.setSoftwareIdentification(new SoftwareIdentification());
srr.setAuthentication(new Authentication());
int id = rs.getInt(1);
srr.getSoftwareIdentification().setSoftwareDeveloper(rs.getString(2));
srr.getSoftwareIdentification().setSoftwareName(rs.getString(3));
srr.getSoftwareIdentification().setSoftwareType(ApolloSoftwareTypeEnum.valueOf(rs.getString(4)));
srr.setUrl(rs.getString(5));
srr.getAuthentication().setRequesterId(userIdMap.get(rs.getInt(6)));
srr.getAuthentication().setRequesterPassword("");
result.put(id, srr);
}
} finally {
pstmt.close();
}
return result;
}
// okay so user A can see...?
private List<Role> getUserRoles(int userId) throws SQLException, ClassNotFoundException {
// List<Role> roles = new ArrayList<Role>();
// String query =
// "SELECT r.software_id, r.can_run, r.can_view_cached_results from roles r, user_roles ur where "
// + "r.id = ur.role_id AND ur.user_id = ?";
// PreparedStatement pstmt = getConn().prepareStatement(query);
// try {
// pstmt.setInt(1, userId);
// ResultSet rs = pstmt.executeQuery();
// while (rs.next()) {
// Role r = new Role();
// r.setSoftwareIdentification(getSoftwareIdentification(rs.getInt(1)));
// r.setCanRun(rs.getBoolean(2));
// r.setCanViewCachedResults(rs.getBoolean(3));
// roles.add(r);
// } finally {
// pstmt.close();
// return roles;
return null;
}
private int addUserRole(int userId, int roleId) {
return 0;
}
public int addTextDataContent(InputStream content) throws SQLException, ClassNotFoundException, IOException {
return addTextDataContent(IOUtils.toString(content));
}
public int addTextDataContent(String content) throws SQLException, ClassNotFoundException {
String md5 = DigestUtils.md5Hex(content);
// is the data already in the table?
String query = "SELECT id FROM run_data_content where md5_hash_of_content = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, md5);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
// no need to store the data twice
return rs.getInt(1);
} else {
pstmt.close();
// store it
query = "INSERT INTO run_data_content (text_content, md5_hash_of_content) values (?,?)";
pstmt = getConn().prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
try {
pstmt.setString(1, content);
pstmt.setString(2, md5);
pstmt.execute();
rs = pstmt.getGeneratedKeys();
rs.next();
return rs.getInt(1);
} finally {
pstmt.close();
}
}
}
public int associateContentWithRunId(int runKey, int dataContentKey, DbContentDataFormatEnum dataFormat, String dataLabel,
DbContentDataType dataType, String dataSourceSoftware, String dataDestinationSoftware) throws ClassNotFoundException,
SQLException, ApolloDatabaseKeyNotFoundException {
int runDataDescriptionId;
try {
runDataDescriptionId = getRunDataDescriptionId(dataFormat, dataLabel, dataType, dataSourceSoftware,
dataDestinationSoftware);
} catch (ApolloDatabaseKeyNotFoundException e) {
throw new ApolloDatabaseKeyNotFoundException(
"Unable to associate data content with run id. The runDataDescriptionId was not found. Error was: "
+ e.getMessage());
}
return associateContentWithRunId(runKey, dataContentKey, runDataDescriptionId);
}
public int associateContentWithRunId(int runKey, int dataContentKey, int runDataDescriptionId) throws ClassNotFoundException,
SQLException, ApolloDatabaseKeyNotFoundException {
if (runDataDescriptionId >= 0) {
String query = "SELECT id FROM run_data WHERE run_id = ? AND description_id = ? and content_id = ?";
PreparedStatement pstmt = null;
try {
pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, runKey);
pstmt.setInt(2, runDataDescriptionId);
pstmt.setInt(3, dataContentKey);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getInt(1);
}
} finally {
pstmt.close();
}
query = "INSERT INTO run_data (run_id, description_id, content_id) values (?,?,?)";
try {
pstmt = getConn().prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt(1, runKey);
pstmt.setInt(2, runDataDescriptionId);
pstmt.setInt(3, dataContentKey);
pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
rs.next();
return rs.getInt(1);
} finally {
pstmt.close();
}
} else {
throw new ApolloDatabaseKeyNotFoundException("associateContentWithRunId() called with an invalid key: " + runKey);
}
}
public int getRunDataDescriptionId(DbContentDataFormatEnum dataFormat, String dataLabel, DbContentDataType dataType,
String dataSourceSoftware, String dataDestinationSoftware) throws SQLException, ClassNotFoundException,
ApolloDatabaseKeyNotFoundException {
String query = "SELECT v.run_data_description_id FROM run_data_description_view v WHERE "
+ "v.format = ? AND v.label = ? and v.type = ? and v.source_software = ? and v.destination_software = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, dataFormat.toString());
pstmt.setString(2, dataLabel);
pstmt.setString(3, dataType.toString());
pstmt.setString(4, dataSourceSoftware);
pstmt.setString(5, dataDestinationSoftware);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getInt(1);
} else {
throw new ApolloDatabaseKeyNotFoundException("No entry found in run_data_description_view where format = "
+ dataFormat.toString() + " and label = " + dataLabel + " and type = " + dataType.toString()
+ " and source_software = " + dataSourceSoftware + " and destination_software = " + dataDestinationSoftware);
}
}
public int addRunDataDescription(String description, String dataFormat, String dataLabel, String dataType,
String dataSourceSoftware, String dataDestinationSoftware) throws SQLException, ClassNotFoundException {
int runDataDescriptionKey = -1;
String query = "INSERT INTO run_data_description SET label = ?";
PreparedStatement pstmt = getConn().prepareStatement(query, Statement.NO_GENERATED_KEYS);
try {
pstmt.setString(1, description);
pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
runDataDescriptionKey = rs.getInt(1);
}
query = "INSERT INTO run_data_description_axis_value (run_data_description_id, run_data_description_axis_id, value) values (?,?,?)";
pstmt.setInt(1, runDataDescriptionKey);
// pstmt.setIn
// not done yet
return -1;
} catch (Exception e) {
}
return -1;
}
public SoftwareIdentification getSoftwareIdentification(int i) throws ApolloDatabaseKeyNotFoundException, SQLException,
ClassNotFoundException {
String query = "SELECT developer, name, version, service_type FROM software_identification WHERE " + "id = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, i);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
SoftwareIdentification softwareIdentification = new SoftwareIdentification();
softwareIdentification.setSoftwareDeveloper(rs.getString(1));
softwareIdentification.setSoftwareName(rs.getString(2));
softwareIdentification.setSoftwareVersion(rs.getString(3));
softwareIdentification.setSoftwareType(ApolloSoftwareTypeEnum.fromValue(rs.getString(4)));
return softwareIdentification;
} else {
throw new ApolloDatabaseKeyNotFoundException("No entry found in software_identification where id = " + i);
}
}
public String getUrlForSoftwareIdentification(SoftwareIdentification softwareIdentification) throws SQLException,
ApolloDatabaseKeyNotFoundException, ClassNotFoundException {
String query = "SELECT wsdl_url FROM software_identification WHERE developer = ? and name = ? and version = ? and service_type = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, softwareIdentification.getSoftwareDeveloper());
pstmt.setString(2, softwareIdentification.getSoftwareName());
pstmt.setString(3, softwareIdentification.getSoftwareVersion());
pstmt.setString(4, softwareIdentification.getSoftwareType().toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getString(1);
} else {
throw new ApolloDatabaseKeyNotFoundException("Unable to get wsdl_url from software_identification where developer = "
+ softwareIdentification.getSoftwareDeveloper() + " and name = " + softwareIdentification.getSoftwareName()
+ " and version = " + softwareIdentification.getSoftwareVersion() + " and service_type = "
+ softwareIdentification.getSoftwareType().toString());
}
}
public String getUrlForSoftwareIdentification(int softwareIdentificaitonKey) throws ApolloDatabaseKeyNotFoundException,
SQLException, ClassNotFoundException {
String query = "SELECT wsdl_url FROM software_identification WHERE id = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, softwareIdentificaitonKey);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getString(1);
} else {
throw new ApolloDatabaseKeyNotFoundException(
"Unable to get wsdl_url from software_identification where software_identification.id = "
+ softwareIdentificaitonKey);
}
}
// get files
public int addSimulationRun(RunSimulationMessage runSimulationMessage) throws ApolloDatabaseRecordNotInsertedException,
SQLException, ClassNotFoundException, ApolloDatabaseKeyNotFoundException {
int softwareKey = getSoftwareIdentificationKey(runSimulationMessage.getSimulatorIdentification());
String query = "INSERT INTO run (md5_hash_of_run_message, software_id, requester_id, last_service_to_be_called) VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = getConn().prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, getMd5(runSimulationMessage));
pstmt.setInt(2, softwareKey);
pstmt.setInt(3, 1);
pstmt.setInt(4, 4); // 4 is translator
pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
return rs.getInt(1);
} else {
throw new ApolloDatabaseRecordNotInsertedException("Record not inserted!");
}
}
public int getSimulationRunId(RunSimulationMessage runSimulationMessage) throws ApolloDatabaseKeyNotFoundException,
SQLException, ClassNotFoundException {
int softwareKey = getSoftwareIdentificationKey(runSimulationMessage.getSimulatorIdentification());
String md5Hash = getMd5(runSimulationMessage);
String query = "SELECT id FROM run WHERE md5_hash_of_run_message = ? AND software_id = ? and requester_id = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, md5Hash);
pstmt.setInt(2, softwareKey);
pstmt.setInt(3, 1);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getInt(1);
} else {
throw new ApolloDatabaseKeyNotFoundException("No id found for simulation run where md5_hash_of_run_message = "
+ md5Hash + " and softare_id = " + softwareKey + " and requester_id = 1");
}
}
/**
*
* @param runId
* @param softwareIdentificationKey
* @return The number of rows that were updated (either 1 or 0).
* @throws SQLException
* @throws ClassNotFoundException
*/
public int updateLastServiceToBeCalledForRun(Integer runId, Integer softwareIdentificationKey) throws SQLException,
ClassNotFoundException {
String query = "UPDATE run SET last_service_to_be_called = ? WHERE id = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, softwareIdentificationKey);
pstmt.setInt(2, runId);
return pstmt.executeUpdate();
}
public int updateLastServiceToBeCalledForRun(Integer runId, SoftwareIdentification softwareIdentification)
throws ApolloDatabaseKeyNotFoundException, SQLException, ClassNotFoundException {
int softwareIdentificationKey = getSoftwareIdentificationKey(softwareIdentification);
return updateLastServiceToBeCalledForRun(runId, softwareIdentificationKey);
}
public int getIdOfLastServiceToBeCalledForRun(Integer runId) throws ApolloDatabaseKeyNotFoundException, SQLException,
ClassNotFoundException {
String query = "SELECT last_service_to_be_called FROM run WHERE id = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, runId);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getInt(1);
} else {
throw new ApolloDatabaseKeyNotFoundException("No last_service_to_be_called found for simulation run where id = "
+ runId);
}
}
public SoftwareIdentification getLastServiceToBeCalledForRun(Integer runId) throws ApolloDatabaseKeyNotFoundException,
SQLException, ClassNotFoundException {
int softwareId = getIdOfLastServiceToBeCalledForRun(runId);
String query = "SELECT developer, name, version, service_type FROM software_identification WHERE id = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, softwareId);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String developer = rs.getString("developer");
String name = rs.getString("name");
String version = rs.getString("version");
String type = rs.getString("service_type");
SoftwareIdentification softwareIdentification = new SoftwareIdentification();
softwareIdentification.setSoftwareDeveloper(developer);
softwareIdentification.setSoftwareName(name);
softwareIdentification.setSoftwareVersion(version);
softwareIdentification.setSoftwareType(ApolloSoftwareTypeEnum.valueOf(type));
return softwareIdentification;
} else {
throw new ApolloDatabaseKeyNotFoundException("No software identification found for id = " + softwareId);
}
}
public int getNewSimulationGroupId() throws SQLException, ClassNotFoundException, ApolloDatabaseRecordNotInsertedException {
String query = "INSERT INTO simulation_groups DEFAULT";
PreparedStatement pstmt = getConn().prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
return rs.getInt(1);
} else {
throw new ApolloDatabaseRecordNotInsertedException("Unable to create new simulation group, insert failed.");
}
}
public void addRunIdsToSimulationGroup(int simulationGroupId, List<String> simulationRunIds) throws SQLException,
ClassNotFoundException {
String query = "INSERT INTO simulation_groups_definition (simulation_group_id, run_id) VALUES (?,?)";
PreparedStatement pstmt = getConn().prepareStatement(query);
for (String simulationRunId : simulationRunIds) {
pstmt.setInt(1, simulationGroupId);
pstmt.setInt(2, Integer.valueOf(simulationRunId));
pstmt.execute();
}
}
public int addVisualizationRun(RunVisualizationMessage runVisualizationMessage) throws ApolloDatabaseKeyNotFoundException,
SQLException, ClassNotFoundException, ApolloDatabaseRecordNotInsertedException {
int softwareKey = getSoftwareIdentificationKey(runVisualizationMessage.getVisualizerIdentification());
int simulationGroupId = getNewSimulationGroupId();
addRunIdsToSimulationGroup(simulationGroupId, runVisualizationMessage.getSimulationRunIds());
String query = "INSERT INTO run (md5_hash_of_run_message, software_id, requester_id, last_service_to_be_called, simulation_group_id) VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = getConn().prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, getMd5(runVisualizationMessage));
pstmt.setInt(2, softwareKey);
pstmt.setInt(3, 1);
pstmt.setInt(4, 4); // 4 is translator
pstmt.setInt(5, simulationGroupId);
pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
return rs.getInt(1);
} else {
throw new ApolloDatabaseRecordNotInsertedException("Record not inserted!");
}
}
public void removeRunData(int runId) throws SQLException, ClassNotFoundException {
// need to delete the data content
// find out if there any other runs that reference this data content
String query = "SELECT content_id FROM run_data WHERE run_id = ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, runId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
int content_id = rs.getInt(1);
String innerQuery = "SELECT content_id FROM run_data WHERE run_id <> ?";
PreparedStatement innerPstmt = getConn().prepareStatement(innerQuery);
innerPstmt.setInt(1, runId);
ResultSet innerRs = innerPstmt.executeQuery();
if (!innerRs.next()) {
// content_id is not used by any other run, delete it!
String deleteQuery = "DELETE FROM run_data_content WHERE id = ?";
PreparedStatement deletePstmt = getConn().prepareStatement(deleteQuery);
deletePstmt.setInt(1, content_id);
deletePstmt.execute();
}
}
query = "DELETE FROM run_data WHERE run_id = ?";
pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, runId);
pstmt.execute();
query = "SELECT simulation_group_id FROM run WHERE id = ?";
pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, runId);
rs = pstmt.executeQuery();
if (rs.next()) {
int simulation_group_id = rs.getInt(1);
if (!rs.wasNull()) {
String innerQuery = "DELETE FROM simulation_groups_definition WHERE simulation_group_id = ?";
pstmt = getConn().prepareStatement(innerQuery);
pstmt.setInt(1, simulation_group_id);
pstmt.execute();
innerQuery = "DELETE FROM simulation_groups WHERE id = ?";
pstmt = getConn().prepareStatement(innerQuery);
pstmt.setInt(1, simulation_group_id);
pstmt.execute();
}
}
query = "DELETE FROM time_series WHERE run_id = ?";
pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, runId);
pstmt.execute();
query = "DELETE FROM run WHERE id = ?";
pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, runId);
pstmt.execute();
}
public void createAxisId(String label)
throws ClassNotFoundException, SQLException {
String query = "insert into population_axis (label) values (?)";
PreparedStatement pstmt;
try {
pstmt = getConn().prepareStatement(query);
pstmt.setString(1, label);
pstmt.execute();
} catch (SQLException e) {
throw new SQLException("Error creating axis id for label: " + label
+ ". Specific error was:\n" + e.getMessage());
}
}
public int getAxisId(String label) throws SQLException,
ClassNotFoundException {
Integer id = populationAxisCache.get(label);
if (id == null) {
try {
String query = "Select id from population_axis where label like ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, "%" + label + "%");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
id = rs.getInt(1);
populationAxisCache.put(label, new Integer(id));
// System.out.println(id);
} // end while
} catch (SQLException e) {
throw new SQLException("Error retreiving axis id for label: "
+ label + ". Specific error was:\n" + e.getMessage());
}
try {
if (id == -1) {
String query = "insert into population_axis (label) values (?)";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, label);
}
} catch (SQLException e) {
throw new SQLException("Error creating axis id for label: "
+ label + ". Specific error was:\n" + e.getMessage());
}
}
return id;
}
public Integer getPopulationId(String disease_state)
throws ClassNotFoundException, SQLException {
Integer popId = simulatedPopulationCache.get(disease_state);
if (popId == null) {
try {
String query = "select id from simulated_population where label like ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, disease_state);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
// System.out.println("Internal id is:" + rs.getInt(1));
popId = rs.getInt(1);
simulatedPopulationCache.put(disease_state, popId);
} // end while
} catch (SQLException e) {
throw new SQLException("Error retreiving population id for: "
+ disease_state
+ " from simulated_population. Specific error was:\n"
+ e.getMessage());
}
}
return popId;
}
public int getOrCreatePopulationId(int axisId, String disease_state)
throws ClassNotFoundException, SQLException {
Integer popId = getPopulationId(disease_state);
if (popId == null) {
try {
String query = "INSERT INTO simulated_population (LABEL) VALUES ('"
+ disease_state + "')";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.execute();
} catch (SQLException e) {
throw new SQLException("Error inserting disease state: "
+ disease_state + " into simulated_population."
+ " Specific error was:\n" + e.getMessage());
}
try {
String query = "SELECT ID FROM simulated_population WHERE LABEL like ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, disease_state);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
// System.out.println("Population id is:" +
// rs.getInt(1));
popId = rs.getInt(1);
simulatedPopulationCache.put(disease_state, popId);
} // end while
} catch (SQLException e) {
throw new SQLException(
"Error retreiving ID from simulated_population for label: "
+ disease_state + "."
+ " Specific error was:\n" + e.getMessage());
}
try {
String query = "INSERT INTO simulated_population_axis_value (population_id, axis_id, value) values (?,?,?)";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, popId);
pstmt.setInt(2, axisId);
pstmt.setString(3, disease_state);
pstmt.execute();
} catch (SQLException e) {
throw new SQLException("Error inserting value: "
+ disease_state
+ " into simulated_population_axis_value."
+ " Specific error was:\n" + e.getMessage());
}
}
return popId;
}
public int getOrCreatePopulationId(int diseaseStateAxisId, int locationAxisId,
String disease_state, String location)
throws ClassNotFoundException, SQLException {
int popId = -1;
popId = getPopulationId(disease_state + " in " + location);
if (popId == -1) {
try {
String query = "INSERT INTO simulated_population (LABEL) VALUES ('"
+ disease_state + " in " + location + "')";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.execute();
} catch (SQLException e) {
throw new SQLException("Error inserting disease state: "
+ disease_state + " into simulated_population."
+ " Specific error was:\n" + e.getMessage());
}
try {
String query = "SELECT ID FROM simulated_population WHERE LABEL like ?";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setString(1, disease_state + " in " + location);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
// System.out.println("Population id is:" +
// rs.getInt(1));
popId = rs.getInt(1);
} // end while
} catch (SQLException e) {
throw new SQLException(
"Error retreiving ID from simulated_population for label: "
+ disease_state + "."
+ " Specific error was:\n" + e.getMessage());
}
// there needs to be 2 inserts, one for the disease state, and one for the regionId
// they will have the same population ID but different axis IDs
try {
// disease state
String query = "INSERT INTO simulated_population_axis_value (population_id, axis_id, value) values (?,?,?)";
PreparedStatement pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, popId);
pstmt.setInt(2, diseaseStateAxisId);
pstmt.setString(3, disease_state);
pstmt.execute();
// location
query = "INSERT INTO simulated_population_axis_value (population_id, axis_id, value) values (?,?,?)";
pstmt = getConn().prepareStatement(query);
pstmt.setInt(1, popId);
pstmt.setInt(2, locationAxisId);
pstmt.setString(3, location);
pstmt.execute();
} catch (SQLException e) {
throw new SQLException("Error inserting value: "
+ disease_state
+ " into simulated_population_axis_value."
+ " Specific error was:\n" + e.getMessage());
}
}
return popId;
}
public void insertDiseaseStateTimeSeries(PreparedStatement pstmt,
int runId, int popId, String disease_state, List<Double> ts)
throws SQLException, ClassNotFoundException {
logger.info(
"In insertDiseaseStateTimeSeries, runId={}, popId={}, disease_state={}",
runId, popId, disease_state);
// logger.info("Time Series is:");
try {
for (int i = 0; i < ts.size(); i++) {
// logger.debug("Time Series[{}] is: {}", i, ts.get(i));
pstmt.setInt(1, runId);
pstmt.setInt(2, popId);
pstmt.setInt(3, i);
pstmt.setDouble(4, ts.get(i));
pstmt.addBatch();
}
} catch (SQLException e) {
logger.error(
"Error inserting disease state time series for runId={}, popId={}, disease_state={}",
runId, popId, disease_state);
throw new SQLException(
"Error inserting disease state time series for internal run id: "
+ runId + ", disease state: " + disease_state
+ ". Specific error was:\n" + e.getMessage());
}
}
public void insertDiseaseStateTimeSeriesNegative(PreparedStatement pstmt,
int runId, int popId, String disease_state, List<Double> ts)
throws SQLException, ClassNotFoundException {
logger.info(
"In insertDiseaseStateTimeSeries, runId={}, popId={}, disease_state={}",
runId, popId, disease_state);
// logger.info("Time Series is:");
try {
int counter = 0;
for (int i = -ts.size(); i < 0; i++) {
// logger.debug("Time Series[{}] is: {}", i, ts.get(i));
pstmt.setInt(1, runId);
pstmt.setInt(2, popId);
pstmt.setInt(3, i);
pstmt.setDouble(4, ts.get(counter));
pstmt.addBatch();
counter++;
}
} catch (SQLException e) {
logger.error(
"Error inserting disease state time series for runId={}, popId={}, disease_state={}",
runId, popId, disease_state);
throw new SQLException(
"Error inserting disease state time series for internal run id: "
+ runId + ", disease state: " + disease_state
+ ". Specific error was:\n" + e.getMessage());
}
}
public void awaitRowCountForTimeSeriesTable(int runId,
int totalRowCount) throws SQLException, ClassNotFoundException {
PreparedStatement pstmt = getConn().prepareStatement(
"select count(*) from time_series where run_id = ?");
int actualCount = -1;
for (int sleepSeconds = 0; actualCount != totalRowCount; sleepSeconds = Math.min(sleepSeconds + 1, 10)) {
if (actualCount != -1) {
try {
Thread.sleep(sleepSeconds * 1000);
} catch (InterruptedException e) {
// it is okay to interrupt sleep
}
}
pstmt.setInt(1, runId);
ResultSet rs = pstmt.executeQuery();
rs.next();
actualCount = rs.getInt(1);
rs.close();
}
System.out.printf(
"Confirmed that %d expected rows are in the database for run id %d.\n",
actualCount, runId);
}
}
|
package com.aleggeup.confagrid.service.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.security.SecureRandom;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import com.aleggeup.confagrid.model.User;
import com.aleggeup.confagrid.repository.UserRepository;
import com.aleggeup.confagrid.service.UserService;
@RunWith(MockitoJUnitRunner.class)
public class EmbeddedUserServiceTest {
private static final String USER_NAME = "username";
private static final User TEST_USER = new User("test", "test", null);
private static final Long COUNT = 10L;
private static final String UNENCRYPTED_PASSWORD = "password";
private static final String ENCRYPTED_PASSWORD = "$2a$12$OiHAOiHAOiHAOiHAOiHAOek2Bn3t./pRbHo5UYYCAx.Htp/SiLvay";
@Mock
private UserRepository mockUserRepository;
@Mock
private SecureRandom mockSecureRandom;
private UserService userService;
@Before
public void setUp() {
userService = new EmbeddedUserService(mockUserRepository, mockSecureRandom);
}
@After
public void tearDown() {
Mockito.verifyNoMoreInteractions(mockUserRepository, mockSecureRandom);
}
@Test
public void testSave() {
userService.save(TEST_USER);
Mockito.verify(mockUserRepository).save(TEST_USER);
}
@Test
public void testGetById() {
Mockito.when(mockUserRepository.findOne(USER_NAME)).thenReturn(TEST_USER);
final User user = userService.getById(USER_NAME);
assertEquals(TEST_USER, user);
Mockito.verify(mockUserRepository).findOne(USER_NAME);
}
@Test
public void testContainsKey() {
Mockito.when(mockUserRepository.exists(USER_NAME)).thenReturn(true);
assertTrue(userService.containsKey(USER_NAME));
Mockito.verify(mockUserRepository).exists(USER_NAME);
}
@Test
public void testEncrypt() {
Mockito.doAnswer((Answer<Void>) mock -> {
final byte[] bytes = mock.getArgument(0);
for (int i = 0; i < bytes.length; ++i) {
bytes[i] = 0x42;
}
return null;
}).when(mockSecureRandom).nextBytes(ArgumentMatchers.any());
assertEquals(ENCRYPTED_PASSWORD, userService.encrypt(UNENCRYPTED_PASSWORD));
Mockito.verify(mockSecureRandom).nextBytes(ArgumentMatchers.any());
}
@Test
public void testMatches() {
assertTrue(userService.matches(UNENCRYPTED_PASSWORD, ENCRYPTED_PASSWORD));
}
@Test
public void testCount() {
Mockito.when(mockUserRepository.count()).thenReturn(COUNT);
assertEquals(COUNT, Long.valueOf(userService.count()));
Mockito.verify(mockUserRepository).count();
}
}
|
package koodi.domain;
import javax.persistence.Entity;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public class Question extends BaseModel {
@ManyToOne(targetEntity = QuestionSeries.class)
private QuestionSeries questionSeries;
@OneToMany(fetch=FetchType.EAGER)
private List<AnswerOption> answerOptions;
private Integer orderNumber;
private String title;
@Column(columnDefinition="varchar(10000)")
private String info;
private String programmingLanguage;
@Column(columnDefinition="varchar(10000)")
private String code;
public Integer getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(Integer orderNumber) {
this.orderNumber = orderNumber;
}
public QuestionSeries getQuestionSeries() {
return questionSeries;
}
public String getTitle() {
return title;
}
public String getInfo() {
return info;
}
public String getCode() {
return code;
}
public void setQuestionSeries(QuestionSeries questionSeries) {
this.questionSeries = questionSeries;
}
public void setTitle(String title) {
this.title = title;
}
public void setInfo(String info) {
this.info = info;
}
public void setCode(String code) {
this.code = code;
}
public List<AnswerOption> getAnswerOptions() {
return answerOptions;
}
public String getProgrammingLanguage() {
return programmingLanguage;
}
public void setAnswerOptions(List<AnswerOption> answerOptions) {
this.answerOptions = answerOptions;
}
public void setProgrammingLanguage(String programmingLanguage) {
this.programmingLanguage = programmingLanguage;
}
}
|
package org.ovirt.engine.core.vdsbroker.irsbroker;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.businessentities.AsyncTaskStatus;
import org.ovirt.engine.core.common.businessentities.AsyncTaskStatusEnum;
import org.ovirt.engine.core.common.businessentities.BusinessEntitiesDefinitions;
import org.ovirt.engine.core.common.businessentities.Entities;
import org.ovirt.engine.core.common.businessentities.NonOperationalReason;
import org.ovirt.engine.core.common.businessentities.SpmStatus;
import org.ovirt.engine.core.common.businessentities.SpmStatusResult;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatic;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMap;
import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMapId;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSDomainsData;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VdsProtocol;
import org.ovirt.engine.core.common.businessentities.VdsSpmIdMap;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.errors.EngineError;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.eventqueue.Event;
import org.ovirt.engine.core.common.eventqueue.EventQueue;
import org.ovirt.engine.core.common.eventqueue.EventResult;
import org.ovirt.engine.core.common.eventqueue.EventType;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.vdscommands.ConnectStoragePoolVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.DisconnectStoragePoolVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.GetStoragePoolInfoVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.SpmStartVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.SpmStatusVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.SpmStopVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.VdsIdVDSCommandParametersBase;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.KeyValuePairCompat;
import org.ovirt.engine.core.compat.RefObject;
import org.ovirt.engine.core.compat.TransactionScopeOption;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase;
import org.ovirt.engine.core.di.Injector;
import org.ovirt.engine.core.utils.lock.EngineLock;
import org.ovirt.engine.core.utils.lock.LockManagerFactory;
import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil;
import org.ovirt.engine.core.utils.timer.OnTimerMethodAnnotation;
import org.ovirt.engine.core.utils.timer.SchedulerUtil;
import org.ovirt.engine.core.utils.timer.SchedulerUtilQuartzImpl;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
import org.ovirt.engine.core.vdsbroker.ResourceManager;
import org.ovirt.engine.core.vdsbroker.TransportFactory;
import org.ovirt.engine.core.vdsbroker.jsonrpc.JsonRpcIIrsServer;
import org.ovirt.engine.core.vdsbroker.storage.StoragePoolDomainHelper;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VDSNetworkException;
import org.ovirt.engine.core.vdsbroker.xmlrpc.XmlRpcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IrsProxyData {
private static final Logger log = LoggerFactory.getLogger(IrsProxyData.class);
// TODO the syncObj initial purpose was to lock the IrsBroker creation
// but eventually because the IRS is single threaded and suppose to have
// quite a load of requests,
// In order to avoid unexpected behavior we have used the syncObj to
// lock each request to the IRS
// and by that we caused a serialization of requests to the IRS.
// This lock should be removed as soon as the IrsBroker is turned
// multi threaded
public Object syncObj = new Object();
private final String storagePoolRefreshJobId;
private final String domainRecoverOnHostJobId;
private final HashSet<Guid> triedVdssList = new HashSet<>();
private Guid currentVdsId;
private static Set<VDSStatus> vdsConnectedToPoolStatuses;
static {
vdsConnectedToPoolStatuses = EnumSet.copyOf(StoragePoolDomainHelper.vdsDomainsActiveMonitoringStatus);
vdsConnectedToPoolStatuses.addAll(StoragePoolDomainHelper.vdsDomainsMaintenanceMonitoringStatus);
vdsConnectedToPoolStatuses.add(VDSStatus.NonResponsive);
vdsConnectedToPoolStatuses.add(VDSStatus.PreparingForMaintenance);
}
private Guid preferredHostId;
public Guid getCurrentVdsId() {
return getIrsProxy() != null ? currentVdsId : Guid.Empty;
}
public void setCurrentVdsId(Guid value) {
currentVdsId = (Guid.Empty.equals(value)) ? null : value;
}
private String privatemCurrentIrsHost;
private IIrsServer irsProxy;
private Guid fencedIrs;
private IIrsServer getmIrsProxy() {
return irsProxy;
}
private int privatemIrsPort;
private int getmIrsPort() {
return privatemIrsPort;
}
private void setmIrsPort(int value) {
privatemIrsPort = value;
}
private VdsProtocol privateProtocol;
private VdsProtocol getProtocol() {
return this.privateProtocol;
}
private void setProtocol(VdsProtocol value) {
this.privateProtocol = value;
}
private Version privateVersion;
private Version getVersion() {
return this.privateVersion;
}
private void setVersion(Version version) {
this.privateVersion = version;
}
public Guid getFencedIrs() {
return fencedIrs;
}
public void setFencedIrs(Guid fencedIrs) {
this.fencedIrs = fencedIrs;
}
private Guid _storagePoolId = Guid.Empty;
public IrsProxyData(Guid storagePoolId) {
_storagePoolId = storagePoolId;
int storagePoolRefreshTime = Config.<Integer> getValue(ConfigValues.StoragePoolRefreshTimeInSeconds);
storagePoolRefreshJobId = getSchedulUtil().scheduleAFixedDelayJob(this,
"updatingTimerElapsed", new Class[0], new Object[0], storagePoolRefreshTime,
storagePoolRefreshTime, TimeUnit.SECONDS);
domainRecoverOnHostJobId =
getSchedulUtil().scheduleAFixedDelayJob(this,
"hostsStorageConnectionsAndPoolMetadataRefresh",
new Class[0],
new Object[0],
Config.<Integer>getValue(ConfigValues.HostStorageConnectionAndPoolRefreshTimeInSeconds),
storagePoolRefreshTime,
TimeUnit.SECONDS);
}
protected SchedulerUtil getSchedulUtil() {
return Injector.get(SchedulerUtilQuartzImpl.class);
}
private void updateStoragePoolStatus(Guid poolId, StoragePoolStatus status, AuditLogType auditLogType, EngineError error) {
ResourceManager
.getInstance()
.getEventListener()
.storagePoolStatusChange(poolId, status,
auditLogType,
error);
}
@OnTimerMethodAnnotation("updatingTimerElapsed")
public void updatingTimerElapsed() {
try {
synchronized (syncObj) {
if (!_disposed) {
StoragePool storagePool = DbFacade.getInstance().getStoragePoolDao()
.get(_storagePoolId);
if (storagePool != null) {
boolean poolStatusDeterminedByHostsStatus = FeatureSupported.dataCenterWithoutSpm(storagePool.getCompatibilityVersion());
// when there are no hosts in status up, it means that there shouldn't be domain monitoring
// so all the domains need to move to "unknown" status as otherwise their status won't change.
if (DbFacade.getInstance()
.getVdsDao()
.getAllForStoragePoolAndStatuses(_storagePoolId, StoragePoolDomainHelper.vdsDomainsActiveMonitoringStatus)
.isEmpty()) {
StoragePoolDomainHelper.updateApplicablePoolDomainsStatuses(_storagePoolId,
StoragePoolDomainHelper.storageDomainMonitoredStatus,
StorageDomainStatus.Unknown, "no reporting hosts");
// TODO: need to check if it's fine to skip the update when the status is already NonResponsive (as domains status maybe be not updated.
if (poolStatusDeterminedByHostsStatus && storagePool.getStatus() != StoragePoolStatus.NonResponsive) {
updateStoragePoolStatus(storagePool.getId(), StoragePoolStatus.NonResponsive,
AuditLogType.SYSTEM_CHANGE_STORAGE_POOL_STATUS_NON_RESPONSIVE_NO_REPORTING_HOSTS,
EngineError.ENGINE);
}
} else if (poolStatusDeterminedByHostsStatus && storagePool.getStatus() != StoragePoolStatus.Up) {
updateStoragePoolStatus(storagePool.getId(), StoragePoolStatus.Up,
AuditLogType.SYSTEM_CHANGE_STORAGE_POOL_STATUS_UP_REPORTING_HOSTS,
null);
}
if (storagePool.getStatus() == StoragePoolStatus.Up ||
storagePool.getStatus() == StoragePoolStatus.NonResponsive ||
storagePool.getStatus() == StoragePoolStatus.Contend) {
if (!poolStatusDeterminedByHostsStatus) {
proceedStoragePoolStats(storagePool);
} else {
List<StorageDomain> storageDomains = DbFacade.getInstance().getStorageDomainDao()
.getAllForStoragePool(storagePool.getId());
domainsInMaintenanceCheck(storageDomains, storagePool);
}
}
}
}
}
} catch (Exception ex) {
}
}
private int _errorAttempts;
private static Collection<Guid> getVdsConnectedToPool(Guid storagePoolId) {
// Note - this method is used as it returns only hosts from VIRT supported clusters
// (we use the domain monitoring results only from those clusters hosts).
// every change to it should be inspected carefully.
return Entities.getIds(DbFacade.getInstance().getVdsDao().getAllForStoragePoolAndStatuses(storagePoolId,
vdsConnectedToPoolStatuses));
}
@SuppressWarnings("unchecked")
private void proceedStoragePoolStats(StoragePool storagePool) {
// ugly patch because vdsm doesnt check if host is spm on spm
// operations
VDSReturnValue result = null;
Guid curVdsId = currentVdsId;
if (curVdsId != null) {
result = ResourceManager.getInstance().runVdsCommand(VDSCommandType.SpmStatus,
new SpmStatusVDSCommandParameters(curVdsId, _storagePoolId));
}
if (result == null
|| !result.getSucceeded()
|| (result.getSucceeded() && ((SpmStatusResult) result.getReturnValue()).getSpmStatus() != SpmStatus.SPM)) {
// update pool status to problematic until fence will happen
if (storagePool.getStatus() != StoragePoolStatus.NonResponsive
&& storagePool.getStatus() != StoragePoolStatus.NotOperational) {
if (result != null && result.getVdsError() != null) {
updateStoragePoolStatus(_storagePoolId, StoragePoolStatus.NonResponsive,
AuditLogType.SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC_WITH_ERROR,
result.getVdsError().getCode());
} else {
updateStoragePoolStatus(_storagePoolId, StoragePoolStatus.NonResponsive,
AuditLogType.SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC,
EngineError.ENGINE);
}
}
// if spm status didn't work or not spm and NOT NETWORK
// PROBLEM
// then cause failover with attempts
if (result != null && !(result.getExceptionObject() instanceof VDSNetworkException)) {
HashMap<Guid, AsyncTaskStatus> tasksList =
(HashMap<Guid, AsyncTaskStatus>) ResourceManager
.getInstance()
.runVdsCommand(VDSCommandType.HSMGetAllTasksStatuses,
new VdsIdVDSCommandParametersBase(curVdsId)).getReturnValue();
boolean allTasksFinished = true;
if (tasksList != null) {
for (AsyncTaskStatus taskStatus : tasksList.values()) {
if (AsyncTaskStatusEnum.finished != taskStatus.getStatus()) {
allTasksFinished = false;
break;
}
}
}
if ((tasksList == null) || allTasksFinished) {
nullifyInternalProxies();
} else {
if (_errorAttempts < Config.<Integer> getValue(ConfigValues.SPMFailOverAttempts)) {
_errorAttempts++;
log.warn("failed getting spm status for pool '{}' ({}), attempt number: {}",
_storagePoolId, storagePool.getName(), _errorAttempts);
} else {
nullifyInternalProxies();
_errorAttempts = 0;
}
}
}
} else if (result.getSucceeded()
&& ((SpmStatusResult) result.getReturnValue()).getSpmStatus() == SpmStatus.SPM
&& (storagePool.getStatus() == StoragePoolStatus.NonResponsive || storagePool.getStatus() == StoragePoolStatus.Contend)) {
// if recovered from network exception set back to up
DbFacade.getInstance().getStoragePoolDao().updateStatus(storagePool.getId(), StoragePoolStatus.Up);
storagePool.setStatus(StoragePoolStatus.Up);
ResourceManager.getInstance().getEventListener()
.storagePoolStatusChanged(storagePool.getId(), storagePool.getStatus());
}
List<StorageDomain> domainsInDb = DbFacade.getInstance().getStorageDomainDao()
.getAllForStoragePool(_storagePoolId);
GetStoragePoolInfoVDSCommandParameters tempVar = new GetStoragePoolInfoVDSCommandParameters(
_storagePoolId);
tempVar.setIgnoreFailoverLimit(true);
VDSReturnValue storagePoolInfoResult = ResourceManager.getInstance().runVdsCommand(
VDSCommandType.GetStoragePoolInfo, tempVar);
if (storagePoolInfoResult.getSucceeded()) {
KeyValuePairCompat<StoragePool, List<StorageDomain>> data =
(KeyValuePairCompat<StoragePool, List<StorageDomain>>) storagePoolInfoResult
.getReturnValue();
int masterVersion = data.getKey().getMasterDomainVersion();
HashSet<Guid> domainsInVds = new HashSet<>();
for (StorageDomain domainData : data.getValue()) {
domainsInVds.add(domainData.getId());
proceedStorageDomain(domainData, masterVersion, storagePool);
}
for (final StorageDomain domainInDb : domainsInDb) {
if (domainInDb.getStorageDomainType() != StorageDomainType.Master
&& domainInDb.getStatus() != StorageDomainStatus.Locked
&& !domainInDb.getStorageType().isCinderDomain()
&& !domainsInVds.contains(domainInDb.getId())) {
// domain not attached to pool anymore
DbFacade.getInstance()
.getStoragePoolIsoMapDao()
.remove(new StoragePoolIsoMapId(domainInDb.getId(),
_storagePoolId));
}
}
}
domainsInMaintenanceCheck(domainsInDb, storagePool);
}
private void domainsInMaintenanceCheck(List<StorageDomain> storageDomains, StoragePool pool) {
for (StorageDomain domainInDb : storageDomains) {
if (domainInDb.getStatus() == StorageDomainStatus.PreparingForMaintenance) {
queueDomainMaintenanceCheck(domainInDb, pool);
}
}
}
public void queueDomainMaintenanceCheck(final StorageDomain domain, final StoragePool pool) {
getEventQueue()
.submitEventAsync(new Event(_storagePoolId, domain.getId(), null, EventType.DOMAINFAILOVER, ""),
new Callable<EventResult>() {
@Override
public EventResult call() {
Collection<Guid> vdsConnectedToPool = getVdsConnectedToPool(_storagePoolId);
Set<Guid> vdsDomInMaintenance = _domainsInMaintenance.get(domain.getId());
if (vdsConnectedToPool.isEmpty() ||
(vdsDomInMaintenance != null &&
vdsDomInMaintenance.containsAll(vdsConnectedToPool))) {
log.info("Moving domain '{}' to maintenance", domain.getId());
DbFacade.getInstance().getStoragePoolIsoMapDao().updateStatus(
domain.getStoragePoolIsoMapData().getId(),
StorageDomainStatus.Maintenance);
AuditLogableBase auditLogableBase = new AuditLogableBase();
auditLogableBase.addCustomValue("StorageDomainName", domain.getName());
auditLogableBase.addCustomValue("StoragePoolName", pool.getName());
new AuditLogDirector().log(auditLogableBase, AuditLogType.STORAGE_DOMAIN_MOVED_TO_MAINTENANCE);
}
return null;
}
});
}
private EventQueue getEventQueue() {
return Injector.get(EventQueue.class);
}
public Guid getPreferredHostId() {
return preferredHostId;
}
public void setPreferredHostId(Guid preferredHostId) {
this.preferredHostId = preferredHostId;
}
private void proceedStorageDomain(StorageDomain data, int dataMasterVersion, StoragePool storagePool) {
StorageDomain storage_domain = DbFacade.getInstance().getStorageDomainDao().getForStoragePool(data.getId(), _storagePoolId);
StorageDomainStatic domainFromDb = null;
StoragePoolIsoMap domainPoolMap = null;
if (storage_domain != null) {
domainFromDb = storage_domain.getStorageStaticData();
domainPoolMap = storage_domain.getStoragePoolIsoMapData();
// If the domain is master in the DB
if (domainFromDb.getStorageDomainType() == StorageDomainType.Master && domainPoolMap != null
&& domainPoolMap.getStatus() != StorageDomainStatus.Locked) {
// and the domain is not master in the VDSM
if (!((data.getStorageDomainType() == StorageDomainType.Master) || (data.getStorageDomainType() == StorageDomainType.Unknown))) {
reconstructMasterDomainNotInSync(data.getStoragePoolId(),
domainFromDb.getId(),
"Mismatch between master in DB and VDSM",
MessageFormat.format("Master domain is not in sync between DB and VDSM. "
+ "Domain {0} marked as master in DB and not in the storage",
domainFromDb.getStorageName()));
} // or master in DB and VDSM but there is a version
// mismatch
else if (dataMasterVersion != storagePool.getMasterDomainVersion()) {
reconstructMasterDomainNotInSync(data.getStoragePoolId(),
domainFromDb.getId(),
"Mismatch between master version in DB and VDSM",
MessageFormat.format("Master domain version is not in sync between DB and VDSM. "
+ "Domain {0} marked as master, but the version in DB: {1} and in VDSM: {2}",
domainFromDb.getStorageName(),
storagePool.getMasterDomainVersion(),
dataMasterVersion));
}
}
boolean statusChanged = false;
if (domainPoolMap == null) {
data.setStoragePoolId(_storagePoolId);
DbFacade.getInstance().getStoragePoolIsoMapDao().save(data.getStoragePoolIsoMapData());
statusChanged = true;
} else if (domainPoolMap.getStatus() != StorageDomainStatus.Locked
&& domainPoolMap.getStatus() != data.getStatus()) {
if (domainPoolMap.getStatus() != StorageDomainStatus.Inactive
&& data.getStatus() != StorageDomainStatus.Inactive) {
DbFacade.getInstance().getStoragePoolIsoMapDao().update(data.getStoragePoolIsoMapData());
statusChanged = true;
}
if (data.getStatus() != null && data.getStatus() == StorageDomainStatus.Inactive
&& domainFromDb.getStorageDomainType() == StorageDomainType.Master) {
StoragePool pool = DbFacade.getInstance().getStoragePoolDao()
.get(domainPoolMap.getStoragePoolId());
if (pool != null) {
DbFacade.getInstance().getStoragePoolDao().updateStatus(pool.getId(),
StoragePoolStatus.Maintenance);
pool.setStatus(StoragePoolStatus.Maintenance);
ResourceManager.getInstance().getEventListener()
.storagePoolStatusChanged(pool.getId(), StoragePoolStatus.Maintenance);
}
}
}
// For block domains, synchronize LUN details comprising the storage domain with the DB
if (statusChanged && data.getStatus() == StorageDomainStatus.Active && storage_domain.getStorageType().isBlockDomain()) {
ResourceManager.getInstance().getEventListener().syncLunsInfoForBlockStorageDomain(
data.getId(), getCurrentVdsId());
}
// if status didn't change and still not active no need to
// update dynamic data
if (statusChanged
|| (domainPoolMap.getStatus() != StorageDomainStatus.Inactive && data.getStatus() == StorageDomainStatus.Active)) {
DbFacade.getInstance().getStorageDomainDynamicDao().update(data.getStorageDynamicData());
if (data.getAvailableDiskSize() != null && data.getUsedDiskSize() != null) {
double freePercent = data.getStorageDynamicData().getfreeDiskPercent();
AuditLogType type = AuditLogType.UNASSIGNED;
Integer freeDiskInGB = data.getStorageDynamicData().getAvailableDiskSize();
if (freeDiskInGB != null) {
if (freePercent < domainFromDb.getWarningLowSpaceIndicator()) {
type = AuditLogType.IRS_DISK_SPACE_LOW;
}
if (freeDiskInGB < domainFromDb.getCriticalSpaceActionBlocker()) {
// Note, if both conditions are met, only IRS_DISK_SPACE_LOW_ERROR will be shown
type = AuditLogType.IRS_DISK_SPACE_LOW_ERROR;
}
}
if (type != AuditLogType.UNASSIGNED) {
AuditLogableBase logable = new AuditLogableBase();
logable.setStorageDomain(data);
logable.setStoragePoolId(_storagePoolId);
logable.addCustomValue("DiskSpace", (data.getAvailableDiskSize()).toString());
data.setStorageName(domainFromDb.getStorageName());
new AuditLogDirector().log(logable, type);
}
}
Set<EngineError> alerts = data.getAlerts();
if (alerts != null && !alerts.isEmpty()) {
AuditLogableBase logable = new AuditLogableBase();
logable.setStorageDomain(data);
data.setStorageName(domainFromDb.getStorageName());
logable.setStoragePoolId(_storagePoolId);
for (EngineError alert : alerts) {
switch (alert) {
case VG_METADATA_CRITICALLY_FULL:
new AuditLogDirector().log(logable, AuditLogType.STORAGE_ALERT_VG_METADATA_CRITICALLY_FULL);
break;
case SMALL_VG_METADATA:
new AuditLogDirector().log(logable, AuditLogType.STORAGE_ALERT_SMALL_VG_METADATA);
break;
default:
log.error("Unrecognized alert for domain {}(id = {}): {}",
data.getStorageName(),
data.getId(),
alert);
break;
}
}
}
}
} else {
log.debug("The domain with id '{}' was not found in DB", data.getId());
}
}
/**
* Reconstructs the master domain when the old domain is not in sync.
*
* @param storagePoolId
* The storage pool id.
* @param masterDomainId
* The master domain id.
* @param exceptionMessage
* The message of the exception to throw.
* @param logMessage
* The log message to write in the log.
*/
private void reconstructMasterDomainNotInSync(final Guid storagePoolId,
final Guid masterDomainId,
final String exceptionMessage,
final String logMessage) {
getEventQueue().submitEventSync(new Event(_storagePoolId,
masterDomainId, null, EventType.RECONSTRUCT, "Reconstruct caused by failure to execute spm command"),
new Callable<EventResult>() {
@Override
public EventResult call() {
log.warn(logMessage);
AuditLogableBase logable = new AuditLogableBase(currentVdsId);
logable.setStorageDomainId(masterDomainId);
new AuditLogDirector().log(logable, AuditLogType.SYSTEM_MASTER_DOMAIN_NOT_IN_SYNC);
return ResourceManager.getInstance()
.getEventListener()
.masterDomainNotOperational(masterDomainId, storagePoolId, false, true);
}
});
throw new IRSNoMasterDomainException(exceptionMessage);
}
public HashSet<Guid> getTriedVdssList() {
return triedVdssList;
}
public void init(VDS vds) {
currentVdsId = vds.getId();
setmIrsPort(vds.getPort());
privatemCurrentIrsHost = vds.getHostName();
setProtocol(vds.getProtocol());
setVersion(vds.getVdsGroupCompatibilityVersion());
}
public boolean failover() {
Guid vdsId = currentVdsId;
nullifyInternalProxies();
boolean performFailover = false;
if (vdsId != null) {
try {
VDSReturnValue statusResult = ResourceManager.getInstance().runVdsCommand(VDSCommandType.SpmStatus,
new SpmStatusVDSCommandParameters(vdsId, _storagePoolId));
if (statusResult != null
&& statusResult.getSucceeded()
&& (((SpmStatusResult) statusResult.getReturnValue()).getSpmStatus() == SpmStatus.SPM || ((SpmStatusResult) statusResult
.getReturnValue()).getSpmStatus() == SpmStatus.Contend)) {
performFailover = ResourceManager
.getInstance()
.runVdsCommand(VDSCommandType.SpmStop,
new SpmStopVDSCommandParameters(vdsId, _storagePoolId)).getSucceeded();
} else {
performFailover = true;
}
} catch (Exception ex) {
// try to failover to another host if failed to get spm
// status or stop spm
// (in case currentVdsId has wrong id for some reason)
log.error("Could not get spm status on host '{}' for spmStop: {}", vdsId, ex.getMessage());
log.debug("Exception", ex);
performFailover = true;
}
}
if (performFailover) {
log.info("Irs placed on server '{}' failed. Proceed Failover", vdsId);
triedVdssList.add(vdsId);
return true;
} else {
log.error("IRS failover failed - can't allocate vds server");
return false;
}
}
public IIrsServer getIrsProxy() {
if (getmIrsProxy() == null) {
final StoragePool storagePool = DbFacade.getInstance().getStoragePoolDao().get(_storagePoolId);
// don't try to start spm on uninitialized pool
if (storagePool.getStatus() != StoragePoolStatus.Uninitialized) {
String host =
TransactionSupport.executeInScope(TransactionScopeOption.Suppress,
new TransactionMethod<String>() {
@Override
public String runInTransaction() {
return gethostFromVds();
}
});
if (host != null) {
// Get the values of the timeouts:
int clientTimeOut = Config.<Integer> getValue(ConfigValues.vdsTimeout) * 1000;
int connectionTimeOut = Config.<Integer> getValue(ConfigValues.vdsConnectionTimeout) * 1000;
int heartbeat = Config.<Integer> getValue(ConfigValues.vdsHeartbeatInSeconds) * 1000;
int clientRetries = Config.<Integer> getValue(ConfigValues.vdsRetries);
irsProxy = TransportFactory.createIrsServer(getProtocol(),
getVersion(),
host,
getmIrsPort(),
clientTimeOut,
connectionTimeOut,
clientRetries,
heartbeat);
runStoragePoolUpEvent(storagePool);
}
}
}
return getmIrsProxy();
}
private void runStoragePoolUpEvent(final StoragePool storagePool) {
ThreadPoolUtil.execute(new Runnable() {
@Override
public void run() {
try {
if (isMasterDomainUp()) {
ResourceManager.getInstance()
.getEventListener()
.storagePoolUpEvent(storagePool);
}
} catch (RuntimeException exp) {
log.error("Error in StoragePoolUpEvent: {}", exp.getMessage());
log.debug("Exception", exp);
}
}
private boolean isMasterDomainUp() {
return DbFacade.getInstance().getStorageDomainDao().
getStorageDomains(_storagePoolId, StorageDomainType.Master).stream()
.anyMatch(d -> d.getStatus() == StorageDomainStatus.Active || d.getStatus() == StorageDomainStatus.Unknown);
}
});
}
/**
* Returns True if there are other vdss in pool
*/
public boolean getHasVdssForSpmSelection() {
return (getPrioritizedVdsInPool().size() > 0);
}
private void connectStoragePool(VDS vds, StoragePool storagePool) {
Guid masterDomainId = DbFacade.getInstance().getStorageDomainDao()
.getMasterStorageDomainIdForPool(_storagePoolId);
List<StoragePoolIsoMap> storagePoolIsoMap = DbFacade.getInstance()
.getStoragePoolIsoMapDao().getAllForStoragePool(_storagePoolId);
VDSReturnValue connectResult = ResourceManager.getInstance().runVdsCommand(
VDSCommandType.ConnectStoragePool,
new ConnectStoragePoolVDSCommandParameters(vds, storagePool,
masterDomainId, storagePoolIsoMap));
if (!connectResult.getSucceeded()
&& connectResult.getExceptionObject() instanceof IRSNoMasterDomainException) {
throw connectResult.getExceptionObject();
} else if (!connectResult.getSucceeded()) {
// if connect to pool fails throw exception for
// failover
throw new IRSNonOperationalException("Could not connect host to Data Center(Storage issue)");
}
}
private boolean isStoragePoolMemoryBackend(StoragePool pool) {
return FeatureSupported.storagePoolMemoryBackend(
pool.getCompatibilityVersion());
}
private String gethostFromVds() {
String returnValue = null;
Guid curVdsId = (currentVdsId != null) ? currentVdsId : Guid.Empty;
StoragePool storagePool = DbFacade.getInstance().getStoragePoolDao().get(_storagePoolId);
if (storagePool == null) {
log.info("hostFromVds::Finished elect spm, storage pool '{}' was removed", _storagePoolId);
return null;
}
List<VDS> prioritizedVdsInPool = getPrioritizedVdsInPool();
currentVdsId = null;
// If VDS is in initialize status, wait for it to be up (or until
// configurable timeout is reached)
waitForVdsIfIsInitializing(curVdsId);
// update pool status to problematic while selecting spm
StoragePoolStatus prevStatus = storagePool.getStatus();
if (prevStatus != StoragePoolStatus.NonResponsive) {
try {
ResourceManager
.getInstance()
.getEventListener()
.storagePoolStatusChange(_storagePoolId, StoragePoolStatus.NonResponsive,
AuditLogType.SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC_SEARCHING_NEW_SPM,
EngineError.ENGINE, TransactionScopeOption.RequiresNew);
} catch (RuntimeException ex) {
throw new IRSStoragePoolStatusException(ex);
}
}
VDS selectedVds = null;
SpmStatusResult spmStatus = null;
if (prioritizedVdsInPool != null && prioritizedVdsInPool.size() > 0) {
selectedVds = prioritizedVdsInPool.get(0);
} else if (!Guid.Empty.equals(curVdsId) && !getTriedVdssList().contains(curVdsId)) {
selectedVds = DbFacade.getInstance().getVdsDao().get(curVdsId);
if (selectedVds.getStatus() != VDSStatus.Up
|| selectedVds.getVdsSpmPriority() == BusinessEntitiesDefinitions.HOST_MIN_SPM_PRIORITY) {
selectedVds = null;
}
}
if (selectedVds != null) {
// Stores origin host id in case and will be needed to disconnect from storage pool
Guid selectedVdsId = selectedVds.getId();
Integer selectedVdsSpmId = selectedVds.getVdsSpmId();
triedVdssList.add(selectedVdsId);
if (isStoragePoolMemoryBackend(storagePool)) {
connectStoragePool(selectedVds, storagePool);
}
VDSReturnValue returnValueFromVds = ResourceManager.getInstance().runVdsCommand(
VDSCommandType.SpmStatus,
new SpmStatusVDSCommandParameters(selectedVds.getId(), _storagePoolId));
spmStatus = (SpmStatusResult) returnValueFromVds.getReturnValue();
boolean ignoreSpmStatusResult = returnValueFromVds.getVdsError() != null
&& returnValueFromVds.getVdsError().getCode() == EngineError.InquireNotSupportedError;
if (spmStatus != null || ignoreSpmStatusResult) {
currentVdsId = selectedVds.getId();
boolean performedPoolConnect = false;
log.info(
"hostFromVds::selectedVds - '{}', spmStatus '{}', storage pool '{}', storage pool version '{}'",
selectedVds.getName(),
spmStatus != null ? spmStatus.getSpmStatus() : "unknown",
storagePool.getName(),
storagePool.getCompatibilityVersion());
if (ignoreSpmStatusResult) {
spmStatus = startSpm(storagePool, selectedVds, DEFAULT_PREV_ID, DEFAULT_LVER, DEFAULT_PREV_ID);
} else {
if (spmStatus.getSpmStatus() == SpmStatus.Unknown_Pool) {
connectStoragePool(selectedVds, storagePool);
performedPoolConnect = true;
// refresh spmStatus result
spmStatus = (SpmStatusResult) ResourceManager
.getInstance()
.runVdsCommand(VDSCommandType.SpmStatus,
new SpmStatusVDSCommandParameters(selectedVds.getId(), _storagePoolId))
.getReturnValue();
log.info(
"hostFromVds::Connected host to pool - selectedVds - {}, spmStatus {}, storage pool {}",
selectedVds.getName(),
spmStatus.getSpmStatus(),
storagePool.getName());
}
RefObject<VDS> tempRefObject = new RefObject<>(selectedVds);
spmStatus =
handleSpmStatusResult(curVdsId,
prioritizedVdsInPool,
storagePool,
tempRefObject,
spmStatus);
selectedVds = tempRefObject.argvalue;
}
if (selectedVds != null) {
RefObject<VDS> tempRefObject2 = new RefObject<>(selectedVds);
RefObject<SpmStatusResult> tempRefObject3 = new RefObject<>(spmStatus);
returnValue = handleSelectedVdsForSPM(storagePool, tempRefObject2, tempRefObject3, prevStatus);
selectedVds = tempRefObject2.argvalue;
spmStatus = tempRefObject3.argvalue;
} else {
currentVdsId = null;
}
if (performedPoolConnect && selectedVds == null) {
// if could not start spm on this host and connected to
// pool here
// then disconnect
ResourceManager.getInstance().runVdsCommand(
VDSCommandType.DisconnectStoragePool,
new DisconnectStoragePoolVDSCommandParameters(selectedVdsId, _storagePoolId,
selectedVdsSpmId));
}
} else {
log.info("hostFromVds::selectedVds - '{}', spmStatus returned null!",
selectedVds.getName());
if (returnValueFromVds.getExceptionObject() instanceof IRSNoMasterDomainException) {
throw returnValueFromVds.getExceptionObject();
}
}
}
return returnValue;
}
private List<VDS> getPrioritizedVdsInPool() {
Guid curVdsId = (currentVdsId != null) ? currentVdsId : Guid.Empty;
// Gets a list of the hosts in the storagePool, that are "UP", ordered
// by vds_spm_priority (not including -1) and secondly ordered by RANDOM(), to
// deal with the case that there are several hosts with the same priority.
List<VDS> allVds = DbFacade.getInstance().getVdsDao().getListForSpmSelection(_storagePoolId);
List<VDS> vdsRelevantForSpmSelection = new ArrayList<>();
Guid preferredHost = IrsBrokerCommand.getIrsProxyData(_storagePoolId).getPreferredHostId();
IrsBrokerCommand.getIrsProxyData(_storagePoolId).setPreferredHostId(null);
for (VDS vds : allVds) {
if (!triedVdssList.contains(vds.getId()) && !vds.getId().equals(curVdsId)) {
if (vds.getId().equals(preferredHost)) {
vdsRelevantForSpmSelection.add(0, vds);
}
else {
vdsRelevantForSpmSelection.add(vds);
}
}
}
return vdsRelevantForSpmSelection;
}
private String handleSelectedVdsForSPM(StoragePool storagePool, RefObject<VDS> selectedVds,
RefObject<SpmStatusResult> spmStatus, StoragePoolStatus prevStatus) {
String returnValue = null;
if (spmStatus.argvalue == null || spmStatus.argvalue.getSpmStatus() != SpmStatus.SPM) {
movePoolToProblematicInDB(storagePool);
selectedVds.argvalue = null;
log.info(
"spm start treatment ended and status is not SPM!!! status: '{}' - setting selectedVds to null!",
spmStatus.argvalue != null ? spmStatus.argvalue.getSpmStatus() : null);
} else {
init(selectedVds.argvalue);
storagePool.setLVER(spmStatus.argvalue.getSpmLVER());
storagePool.setSpmVdsId(selectedVds.argvalue.getId());
// if were problemtaic or not operational and succeeded to find
// host move pool to up
if (prevStatus != StoragePoolStatus.NotOperational && prevStatus != StoragePoolStatus.NonResponsive) {
storagePool.setStatus(prevStatus);
} else {
storagePool.setStatus(StoragePoolStatus.Up);
}
DbFacade.getInstance().getStoragePoolDao().update(storagePool);
ResourceManager.getInstance()
.getEventListener()
.storagePoolStatusChanged(storagePool.getId(), storagePool.getStatus());
setFencedIrs(null);
returnValue = selectedVds.argvalue.getHostName();
log.info("Initialize Irs proxy from vds: {}", returnValue);
AuditLogableBase logable = new AuditLogableBase(selectedVds.argvalue.getId());
logable.addCustomValue("ServerIp", returnValue);
new AuditLogDirector().log(logable, AuditLogType.IRS_HOSTED_ON_VDS);
}
return returnValue;
}
/**
* Waits for VDS if is initializing.
*
* @param curVdsId
*/
private void waitForVdsIfIsInitializing(Guid curVdsId) {
if (!Guid.Empty.equals(curVdsId)) {
VDS vds = DbFacade.getInstance().getVdsDao().get(curVdsId);
String vdsName = vds.getName();
if (vds.getStatus() == VDSStatus.Initializing) {
final int DELAY = 5;// 5 Sec
int total = 0;
Integer maxSecToWait = Config.getValue(ConfigValues.WaitForVdsInitInSec);
while (total <= maxSecToWait
&& DbFacade.getInstance().getVdsDynamicDao().get(curVdsId).getStatus() == VDSStatus.Initializing) {
try {
Thread.sleep(DELAY * 1000);
} catch (InterruptedException e) {
log.error("Interrupt exception {}", e.getMessage());
log.debug("Exception", e);
// exit the while block
break;
}
total += DELAY;
log.info("Waiting to Host '{}' to finish initialization for {} Sec.", vdsName, total);
}
}
}
}
private void movePoolToProblematicInDB(StoragePool storagePool) {
updateStoragePoolStatus(storagePool.getId(), StoragePoolStatus.NonResponsive,
AuditLogType.SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC, EngineError.ENGINE);
storagePool.setSpmVdsId(null);
DbFacade.getInstance().getStoragePoolDao().update(storagePool);
}
private boolean wasVdsManuallyFenced(int spmId) {
VdsSpmIdMap map = DbFacade.getInstance().getVdsSpmIdMapDao().get(
_storagePoolId, spmId);
return map != null && map.getId().equals(getFencedIrs());
}
private static final String DEFAULT_LVER = "-1";
private static final int DEFAULT_PREV_ID = -1;
private SpmStatusResult handleSpmStatusResult(Guid curVdsId,
List<VDS> vdsByPool,
final StoragePool storagePool,
RefObject<VDS> selectedVds,
SpmStatusResult spmStatus) {
if (spmStatus.getSpmStatus() == SpmStatus.Free) {
int vdsSpmIdToFence = -1;
boolean startSpm = true;
if (spmStatus.getSpmId() != -1 && !wasVdsManuallyFenced(spmStatus.getSpmId())) {
int spmId = spmStatus.getSpmId();
Guid spmVdsId = Guid.Empty;
VDS spmVds = null;
if (selectedVds.argvalue.getVdsSpmId() == spmId) {
spmVdsId = selectedVds.argvalue.getId();
} else {
for (VDS tempVds : vdsByPool) {
if (tempVds.getVdsSpmId() == spmId) {
log.info("Found spm host '{}', host name: '{}', according to spmId: '{}'.",
tempVds.getId(),
tempVds.getName(),
spmId);
spmVds = tempVds;
break;
}
}
// if the host which is marked as SPM by the storage is
// non operational we want to find it as well
if (spmVds == null) {
List<VDS> nonOperationalVds =
DbFacade.getInstance()
.getVdsDao()
.getAllForStoragePoolAndStatus(_storagePoolId, VDSStatus.NonOperational);
for (VDS tempVds : nonOperationalVds) {
if (tempVds.getVdsSpmId() == spmId) {
spmVds = tempVds;
break;
}
}
}
if (spmVds != null) {
spmVdsId = spmVds.getId();
} else if (!curVdsId.equals(Guid.Empty)) {
VDS currentVds = DbFacade.getInstance().getVdsDao().get(curVdsId);
if (currentVds != null && currentVds.getStatus() == VDSStatus.Up
&& currentVds.getVdsSpmId() != null && currentVds.getVdsSpmId().equals(spmId)) {
spmVdsId = curVdsId;
spmVds = currentVds;
}
}
}
try {
if (!spmVdsId.equals(Guid.Empty)) {
SpmStatusResult destSpmStatus = (SpmStatusResult) ResourceManager
.getInstance()
.runVdsCommand(VDSCommandType.SpmStatus,
new SpmStatusVDSCommandParameters(spmVdsId, _storagePoolId))
.getReturnValue();
log.info("SpmStatus on vds '{}': '{}'", spmVdsId, destSpmStatus == null ? "NULL"
: destSpmStatus.getSpmStatus());
// intentionally unreachable code
if (destSpmStatus != null && destSpmStatus.getSpmStatus() == SpmStatus.SPM) {
if (!spmVdsId.equals(selectedVds.argvalue.getId()) && spmVds != null
&& spmVds.getStatus() == VDSStatus.Up) {
selectedVds.argvalue = spmVds;
startSpm = false;
log.info("Using old spm server: '{}', no start needed", spmVds.getName());
return destSpmStatus;
}
// VDS is non-operational and SPM
else {
log.warn("Host reports to be SPM '{}', but is not up.", spmVdsId);
vdsSpmIdToFence = spmStatus.getSpmId();
}
}
// if the host which is marked as SPM in the storage
// replies
// to SPMStatus with Unknown_Pool we don't need to
// fence it simply assume
// it is not SPM and continue.
else if (destSpmStatus == null
|| (destSpmStatus.getSpmStatus() != SpmStatus.Free && destSpmStatus.getSpmStatus() != SpmStatus.Unknown_Pool)) {
vdsSpmIdToFence = spmStatus.getSpmId();
}
} else {
log.error(
"SPM Init: could not find reported vds or not up - pool: '{}' vds_spm_id: '{}'",
storagePool.getName(), spmStatus.getSpmId());
vdsSpmIdToFence = spmStatus.getSpmId();
}
} catch (Exception ex) {
vdsSpmIdToFence = spmStatus.getSpmId();
}
}
if (startSpm) {
VdsSpmIdMap map = DbFacade.getInstance().getVdsSpmIdMapDao().get(
_storagePoolId, vdsSpmIdToFence);
if (map != null) {
VDS vdsToFenceObject = DbFacade.getInstance().getVdsDao().get(map.getId());
if (vdsToFenceObject != null) {
log.info("SPM selection - vds seems as spm '{}'", vdsToFenceObject.getName());
if (vdsToFenceObject.getStatus() == VDSStatus.NonResponsive) {
log.warn("spm vds is non responsive, stopping spm selection.");
selectedVds.argvalue = null;
return spmStatus;
} else {
// try to stop spm
VDSReturnValue spmStopReturnValue = ResourceManager.getInstance().runVdsCommand(
VDSCommandType.SpmStop,
new SpmStopVDSCommandParameters(vdsToFenceObject.getId(), _storagePoolId));
// if spm stop succeeded no need to fence,
// continue with spm selection
if (spmStopReturnValue != null && spmStopReturnValue.getSucceeded()) {
log.info("spm stop succeeded, continuing with spm selection");
}
// if spm stop failed for any reason we stop spm
// selection
else {
log.warn("spm stop on spm failed, stopping spm selection!");
selectedVds.argvalue = null;
return spmStatus;
}
}
}
}
spmStatus = startSpm(storagePool, selectedVds.argvalue, spmStatus.getSpmId(), spmStatus.getSpmLVER(), vdsSpmIdToFence);
}
}
return spmStatus;
}
private SpmStatusResult startSpm(final StoragePool storagePool, VDS selectedVds, int prevId, String lver, int vdsSpmIdToFence) {
storagePool.setStatus(StoragePoolStatus.Contend);
storagePool.setSpmVdsId(selectedVds.getId());
TransactionSupport.executeInNewTransaction(new TransactionMethod<Object>() {
@Override
public Object runInTransaction() {
DbFacade.getInstance().getStoragePoolDao().update(storagePool);
return null;
}
});
log.info("starting spm on vds '{}', storage pool '{}', prevId '{}', LVER '{}'",
selectedVds.getName(), storagePool.getName(), prevId,
lver);
SpmStatusResult spmStatus = (SpmStatusResult) ResourceManager
.getInstance()
.runVdsCommand(
VDSCommandType.SpmStart,
new SpmStartVDSCommandParameters(selectedVds.getId(),
_storagePoolId,
prevId,
lver,
storagePool
.getRecoveryMode(),
vdsSpmIdToFence != -1,
storagePool.getStoragePoolFormatType())).getReturnValue();
if (spmStatus == null || spmStatus.getSpmStatus() != SpmStatus.SPM) {
ResourceManager
.getInstance()
.getEventListener()
.storagePoolStatusChange(storagePool.getId(),
StoragePoolStatus.NonResponsive,
AuditLogType.SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC,
EngineError.ENGINE,
TransactionScopeOption.RequiresNew);
if (spmStatus != null) {
TransactionSupport.executeInNewTransaction(new TransactionMethod<Object>() {
@Override
public Object runInTransaction() {
StoragePool pool =
DbFacade.getInstance().getStoragePoolDao().get(storagePool.getId());
pool.setSpmVdsId(null);
DbFacade.getInstance().getStoragePoolDao().update(pool);
return null;
}
});
}
throw new IrsSpmStartFailedException();
}
return spmStatus;
}
public String getIsoDirectory() {
String tempVar = privatemCurrentIrsHost;
return String.format("\\\\%1$s\\CD", ((tempVar != null) ? tempVar : gethostFromVds()));
}
public void resetIrs() {
nullifyInternalProxies();
StoragePool storagePool = DbFacade.getInstance().getStoragePoolDao().get(_storagePoolId);
if (storagePool != null) {
storagePool.setSpmVdsId(null);
DbFacade.getInstance().getStoragePoolDao().update(storagePool);
}
}
private void nullifyInternalProxies() {
if (irsProxy != null) {
if (IrsServerWrapper.class.isInstance(irsProxy)) {
XmlRpcUtils.shutDownConnection(((IrsServerWrapper) irsProxy).getHttpClient());
} else {
((JsonRpcIIrsServer) irsProxy).close();
}
}
privatemCurrentIrsHost = null;
irsProxy = null;
currentVdsId = null;
}
private final Map<Guid, HashSet<Guid>> _domainsInProblem = new ConcurrentHashMap<>();
private final Map<Guid, HashSet<Guid>> _domainsInMaintenance = new ConcurrentHashMap<>();
private final Map<Guid, Guid> vdsReportsOnUnseenDomain = new ConcurrentHashMap<>();
private final Map<Guid, Guid> vdsHandeledReportsOnUnseenDomains = new ConcurrentHashMap<>();
private final Map<Guid, String> _timers = new HashMap<>();
public void updateVdsDomainsData(VDS vds,
final ArrayList<VDSDomainsData> data) {
if (!shouldProcessVdsDomainReport(vds)) {
return;
}
StoragePool storagePool =
DbFacade.getInstance().getStoragePoolDao().get(_storagePoolId);
if (storagePool != null
&& (storagePool.getStatus() == StoragePoolStatus.Up
|| storagePool.getStatus() == StoragePoolStatus.NonResponsive)) {
Guid vdsId = vds.getId();
String vdsName = vds.getName();
try {
Set<Guid> monitoredDomains = new HashSet<>();
for (VDSDomainsData tempData : data) {
monitoredDomains.add(tempData.getDomainId());
}
Map<Guid, DomainMonitoringResult> domainsProblematicReportInfo = Collections.emptyMap();
if (StoragePoolDomainHelper.vdsDomainsActiveMonitoringStatus.contains(vds.getStatus())) {
domainsProblematicReportInfo =
handleMonitoredDomainsForHost(vdsId,
vdsName,
data,
monitoredDomains,
storagePool);
}
Set<Guid> domainsInMaintenance = Collections.emptySet();
if (StoragePoolDomainHelper.vdsDomainsMaintenanceMonitoringStatus.contains(vds.getStatus())) {
domainsInMaintenance = handleDomainsInMaintenanceForHost(monitoredDomains);
}
updateDomainInProblem(vdsId, vdsName, domainsProblematicReportInfo, domainsInMaintenance);
} catch (RuntimeException ex) {
log.error("error in updateVdsDomainsData: {}", ex.getMessage());
log.debug("Exception", ex);
}
}
}
private static boolean shouldProcessVdsDomainReport(VDS vds) {
// NOTE - if this condition is ever updated, every place that acts upon the reporting
// should be updated as well, only hosts the we collect the report from should be affected
// from it.
return vds.getVdsGroupSupportsVirtService() &&
(StoragePoolDomainHelper.vdsDomainsActiveMonitoringStatus.contains(vds.getStatus()) ||
StoragePoolDomainHelper.vdsDomainsMaintenanceMonitoringStatus.contains(vds.getStatus()));
}
/**
* The methods inspects which domains status can be changed to Maintenance according to the host
* domains report.
* @param monitoredDomains domains that the host monitors
* @return domains that are not monitored by the host and are in
* @link StorageDomainStatus#Maintenance or @link StorageDomainStatus#PreparingForMaintenance.
*/
private Set<Guid> handleDomainsInMaintenanceForHost(Collection<Guid> monitoredDomains) {
Set<Guid> domainsInMaintenance = new HashSet<>();
Set<Guid> maintInPool = new HashSet<>(
DbFacade.getInstance().getStorageDomainStaticDao().getAllIds(
_storagePoolId, StorageDomainStatus.Maintenance));
maintInPool.addAll(DbFacade.getInstance().getStorageDomainStaticDao().getAllIds(
_storagePoolId, StorageDomainStatus.PreparingForMaintenance));
for (Guid tempDomainId : maintInPool) {
if (!monitoredDomains.contains(tempDomainId)) {
domainsInMaintenance.add(tempDomainId);
}
}
return domainsInMaintenance;
}
/**
* Provides handling for the domains that are monitored by the given host.
* @return map between the domain id and the reason for domains that
* the host reporting is problematic for.
*/
private Map<Guid, DomainMonitoringResult> handleMonitoredDomainsForHost(final Guid vdsId, final String vdsName,
final ArrayList<VDSDomainsData> data, Collection<Guid> monitoredDomains, StoragePool storagePool) {
Map<Guid, DomainMonitoringResult> domainsProblematicReportInfo = new HashMap<>();
// build a list of all domains in pool
// which are in status Active or Unknown
Set<Guid> activeDomainsInPool = new HashSet<>(
DbFacade.getInstance().getStorageDomainStaticDao().getAllIds(
_storagePoolId, StorageDomainStatus.Active));
Set<Guid> unknownDomainsInPool = new HashSet<>(DbFacade.getInstance().getStorageDomainStaticDao().getAllIds(
_storagePoolId, StorageDomainStatus.Unknown));
Set<Guid> inActiveDomainsInPool =
new HashSet<>(DbFacade.getInstance()
.getStorageDomainStaticDao()
.getAllIds(_storagePoolId, StorageDomainStatus.Inactive));
// build a list of all the domains in
// pool (activeDomainsInPool and unknownDomainsInPool) that are not
// visible by the host.
for (Guid tempDomainId : activeDomainsInPool) {
if (!monitoredDomains.contains(tempDomainId)) {
domainsProblematicReportInfo.put(tempDomainId, DomainMonitoringResult.NOT_REPORTED);
}
}
for (Guid tempDomainId : unknownDomainsInPool) {
if (!monitoredDomains.contains(tempDomainId)) {
domainsProblematicReportInfo.put(tempDomainId, DomainMonitoringResult.NOT_REPORTED);
}
}
// build a list of domains that the host
// reports as in problem (code!=0) or (code==0
// && lastChecl >
// ConfigValues.MaxStorageVdsTimeoutCheckSec)
// and are contained in the Active or
// Unknown domains in pool
for (VDSDomainsData tempData : data) {
if (activeDomainsInPool.contains(tempData.getDomainId()) || unknownDomainsInPool.contains(tempData.getDomainId())) {
DomainMonitoringResult domainMonitoringResult = analyzeDomainReport(tempData, storagePool, false);
if (domainMonitoringResult.invalidAndActual()) {
domainsProblematicReportInfo.put(tempData.getDomainId(), domainMonitoringResult);
} else if (domainMonitoringResult.actual() && tempData.getDelay() > Config.<Double> getValue(ConfigValues.MaxStorageVdsDelayCheckSec)) {
logDelayedDomain(vdsId, tempData);
}
}
else if ((inActiveDomainsInPool.contains(tempData.getDomainId()) ||
// in data centers with spm, unknown domains are moving to Active status according to the pool metadata.
(FeatureSupported.dataCenterWithoutSpm(storagePool.getCompatibilityVersion()) && unknownDomainsInPool.contains(tempData.getDomainId())))
&& analyzeDomainReport(tempData, storagePool, false).validAndActual()) {
log.warn("Storage Domain '{}' was reported by Host '{}' as Active in Pool '{}', moving to active status",
getDomainIdTuple(tempData.getDomainId()),
vdsName,
_storagePoolId);
StoragePoolIsoMap map =
DbFacade.getInstance()
.getStoragePoolIsoMapDao()
.get(new StoragePoolIsoMapId(tempData.getDomainId(), _storagePoolId));
map.setStatus(StorageDomainStatus.Active);
DbFacade.getInstance().getStoragePoolIsoMapDao().update(map);
// For block domains, synchronize LUN details comprising the storage domain with the DB
StorageDomain storageDomain = DbFacade.getInstance().getStorageDomainDao().get(tempData.getDomainId());
if (storageDomain.getStorageType().isBlockDomain()) {
ResourceManager.getInstance().getEventListener().syncLunsInfoForBlockStorageDomain(
storageDomain.getId(), vdsId);
}
}
}
return domainsProblematicReportInfo;
}
private void updateDomainInProblem(final Guid vdsId, final String vdsName, final Map<Guid, DomainMonitoringResult> domainsInProblem,
final Set<Guid> domainsInMaintenance) {
getEventQueue().submitEventSync(new Event(_storagePoolId,
null, vdsId, EventType.DOMAINMONITORING, ""),
new Callable<EventResult>() {
@Override
public EventResult call() {
EventResult result = new EventResult(true, EventType.DOMAINMONITORING);
updateProblematicVdsData(vdsId, vdsName, domainsInProblem);
updateMaintenanceVdsData(vdsId, vdsName, domainsInMaintenance);
return result;
}
});
}
private void logDelayedDomain(final Guid vdsId, VDSDomainsData tempData) {
AuditLogableBase logable = new AuditLogableBase();
logable.setVdsId(vdsId);
logable.setStorageDomainId(tempData.getDomainId());
logable.addCustomValue("Delay",
Double.toString(tempData.getDelay()));
new AuditLogDirector().log(logable,
AuditLogType.VDS_DOMAIN_DELAY_INTERVAL);
}
protected List<Guid> obtainDomainsReportedAsProblematic(List<VDSDomainsData> vdsDomainsData, StoragePool storagePool) {
List<Guid> domainsInProblem = new LinkedList<>();
Set<Guid> domainsInPool = new HashSet<>(
DbFacade.getInstance().getStorageDomainStaticDao().getAllIds(
_storagePoolId, StorageDomainStatus.Active));
domainsInPool.addAll(DbFacade.getInstance().getStorageDomainStaticDao().getAllIds(
_storagePoolId, StorageDomainStatus.Unknown));
List<Guid> domainWhichWereSeen = new ArrayList<>();
for (VDSDomainsData vdsDomainData : vdsDomainsData) {
if (domainsInPool.contains(vdsDomainData.getDomainId())) {
if (analyzeDomainReport(vdsDomainData, storagePool, true).invalidAndActual()) {
domainsInProblem.add(vdsDomainData.getDomainId());
}
domainWhichWereSeen.add(vdsDomainData.getDomainId());
}
}
domainsInPool.removeAll(domainWhichWereSeen);
if (domainsInPool.size() > 0) {
for (Guid domainId : domainsInPool) {
log.error("Domain '{}' is not seen by Host", domainId);
}
domainsInProblem.addAll(domainsInPool);
}
return domainsInProblem;
}
private enum DomainMonitoringResult {
PROBLEMATIC(Boolean.FALSE), STORAGE_ACCCESS_ERROR(Boolean.FALSE), OK(Boolean.TRUE), NOT_REPORTED(Boolean.FALSE), NOT_ACTUAL(null);
private Boolean valid;
private DomainMonitoringResult(Boolean valid) {
this.valid = valid;
}
public boolean validAndActual() {
return actual() && valid;
}
public boolean invalidAndActual() {
return actual() && !valid;
}
public boolean actual() {
return this != NOT_ACTUAL;
}
}
private DomainMonitoringResult analyzeDomainReport(VDSDomainsData tempData, StoragePool storagePool, boolean isLog) {
if (!tempData.isActual() &&
FeatureSupported.reportWhetherDomainMonitoringResultIsActual(storagePool.getCompatibilityVersion())) {
log.warn("Domain '{}' report isn't an actual report",
getDomainIdTuple(tempData.getDomainId()));
return DomainMonitoringResult.NOT_ACTUAL;
}
if (tempData.getCode() != 0) {
if (isLog) {
log.error("Domain '{}' was reported with error code '{}'",
getDomainIdTuple(tempData.getDomainId()),
tempData.getCode());
}
if (tempData.getCode() == EngineError.StorageDomainDoesNotExist.getValue()
|| tempData.getCode() == EngineError.StorageException.getValue()) {
return DomainMonitoringResult.STORAGE_ACCCESS_ERROR;
}
return DomainMonitoringResult.PROBLEMATIC;
}
if (tempData.getLastCheck() > Config
.<Double> getValue(ConfigValues.MaxStorageVdsTimeoutCheckSec)) {
if (isLog) {
log.error("Domain '{}' check timeout '{}' is too big",
getDomainIdTuple(tempData.getDomainId()),
tempData.getLastCheck());
}
return DomainMonitoringResult.PROBLEMATIC;
}
return DomainMonitoringResult.OK;
}
private Guid clearVdsReportInfoOnUnseenDomain(Guid vdsId) {
return vdsReportsOnUnseenDomain.remove(vdsId);
}
private void updateMaintenanceVdsData(final Guid vdsId, final String vdsName, Set<Guid> domainsInMaintenance) {
for (Guid domainId : domainsInMaintenance) {
Set<Guid> vdsSet = _domainsInMaintenance.get(domainId);
if (vdsSet == null) {
log.info("Adding domain '{}' to the domains in maintenance cache", domainId);
_domainsInMaintenance.put(domainId, new HashSet<>(Arrays.asList(vdsId)));
} else {
vdsSet.add(vdsId);
}
}
Set<Guid> maintenanceDomainsByHost = new HashSet<>(_domainsInMaintenance.keySet());
maintenanceDomainsByHost.removeAll(domainsInMaintenance);
for (Guid domainId : maintenanceDomainsByHost) {
Set<Guid> vdsForDomain = _domainsInMaintenance.get(domainId);
if (vdsForDomain != null && vdsForDomain.contains(vdsId)) {
vdsForDomain.remove(vdsId);
if (vdsForDomain.isEmpty()) {
log.info("Removing domain '{}' from the domains in maintenance cache", domainId);
_domainsInMaintenance.remove(domainId);
}
}
}
}
private void updateProblematicVdsData(final Guid vdsId, final String vdsName, Map<Guid, DomainMonitoringResult> problematicDomains) {
// for all problematic domains
// update cache of _domainsInProblem
// and _vdssInProblem and add a new
// timer for new domains in problem
boolean newDomainUnreachableByHost = false;
List<Guid> domainsUnreachableByHost = new LinkedList<>();
for (Map.Entry<Guid, DomainMonitoringResult> entry : problematicDomains.entrySet()) {
Guid domainId = entry.getKey();
DomainMonitoringResult domainMonitoringResult = entry.getValue();
HashSet<Guid> hostsReportedDomainAsProblematic = _domainsInProblem.get(domainId);
boolean domainNotFound = domainMonitoringResult == DomainMonitoringResult.STORAGE_ACCCESS_ERROR;
if (domainNotFound) {
domainsUnreachableByHost.add(domainId);
}
if (hostsReportedDomainAsProblematic != null) {
if (!hostsReportedDomainAsProblematic.contains(vdsId) && domainNotFound) {
newDomainUnreachableByHost = true;
}
// existing domains in problem
updateDomainInProblemData(domainId, vdsId, vdsName);
} else {
if (domainNotFound) {
newDomainUnreachableByHost = true;
}
// new domains in problems
addDomainInProblemData(domainId, vdsId, vdsName);
}
}
if (domainsUnreachableByHost.isEmpty()) {
Guid clearedReport = clearVdsReportInfoOnUnseenDomain(vdsId);
if (clearedReport != null)
log.info("Host '{}' no longer storage access problem to any relevant domain " +
" clearing it's report (report id: '{}')",
vdsId,
clearedReport);
} else if (newDomainUnreachableByHost) {
Guid newReportId = Guid.newGuid();
log.info("Host '{}' has reported new storage access problem to the following domains '{}'" +
" marking it for storage connections and pool metadata refresh (report id: '{}')",
vdsId,
StringUtils.join(domainsUnreachableByHost, ","),
newReportId);
vdsReportsOnUnseenDomain.put(vdsId, newReportId);
}
Set<Guid> notReportedDomainsByHost = new HashSet<>(_domainsInProblem.keySet());
notReportedDomainsByHost.removeAll(problematicDomains.keySet());
for (Guid domainId : notReportedDomainsByHost) {
Set<Guid> vdsForDomain = _domainsInProblem.get(domainId);
if (vdsForDomain != null && vdsForDomain.contains(vdsId)) {
domainRecoveredFromProblem(domainId, vdsId, vdsName);
}
}
}
private void domainRecoveredFromProblem(Guid domainId, Guid vdsId, String vdsName) {
String domainIdTuple = getDomainIdTuple(domainId);
log.info("Domain '{}' recovered from problem. vds: '{}'", domainIdTuple, vdsName);
_domainsInProblem.get(domainId).remove(vdsId);
if (_domainsInProblem.get(domainId).size() == 0) {
log.info("Domain '{}' has recovered from problem. No active host in the DC is reporting it as" +
" problematic, so clearing the domain recovery timer.", domainIdTuple);
_domainsInProblem.remove(domainId);
clearTimer(domainId);
}
}
private void addDomainInProblemData(Guid domainId, Guid vdsId, String vdsName) {
_domainsInProblem.put(domainId, new HashSet<>(Arrays.asList(vdsId)));
log.warn("domain '{}' in problem. vds: '{}'", getDomainIdTuple(domainId), vdsName);
Class[] inputType = new Class[] { Guid.class };
Object[] inputParams = new Object[] { domainId };
String jobId = getSchedulUtil().scheduleAOneTimeJob(this, "onTimer", inputType,
inputParams, Config.<Integer>getValue(ConfigValues.StorageDomainFailureTimeoutInMinutes),
TimeUnit.MINUTES);
clearTimer(domainId);
_timers.put(domainId, jobId);
}
@OnTimerMethodAnnotation("onTimer")
public void onTimer(final Guid domainId) {
getEventQueue().submitEventAsync(new Event(_storagePoolId,
domainId, null, EventType.DOMAINFAILOVER, ""),
new Callable<EventResult>() {
@Override
public EventResult call() {
EventResult result = null;
if (_domainsInProblem.containsKey(domainId)) {
log.info("starting processDomainRecovery for domain '{}'.", getDomainIdTuple(domainId));
result = processDomainRecovery(domainId);
}
_timers.remove(domainId);
return result;
}
});
}
private Map<Guid, Guid> procceedReportsThreatmenet() {
if (vdsReportsOnUnseenDomain.isEmpty()) {
if (!vdsHandeledReportsOnUnseenDomains.isEmpty()) {
log.info("No hosts has reported storage access problem to domains, clearing the handled hosts reports map");
vdsHandeledReportsOnUnseenDomains.clear();
}
return Collections.emptyMap();
}
Map<Guid, Guid> reportsToHandle = new HashMap<>();
reportsToHandle.putAll(vdsReportsOnUnseenDomain);
for (Map.Entry<Guid, Guid> entry : vdsHandeledReportsOnUnseenDomains.entrySet()) {
Guid vdsId = entry.getKey();
Guid currentReportId = reportsToHandle.get(vdsId);
if (currentReportId == null) {
log.info("Host '{}' has no longer storage access problem to domains, clearing it from the handled hosts reports map",
vdsId);
vdsHandeledReportsOnUnseenDomains.remove(vdsId);
} else {
Guid handledReportId = entry.getValue();
if (currentReportId.equals(handledReportId)) {
log.debug("Host '{}' storage connections and pool metadata were already refreshed for report '{}', skipping it",
vdsId,
handledReportId);
reportsToHandle.remove(vdsId);
}
}
}
return reportsToHandle;
}
@OnTimerMethodAnnotation("hostsStorageConnectionsAndPoolMetadataRefresh")
public void hostsStorageConnectionsAndPoolMetadataRefresh() {
Map<Guid, Guid> reportsToHandle = procceedReportsThreatmenet();
if (reportsToHandle.isEmpty()) {
return;
}
List<Callable<Void>> connectStorageTasks = new ArrayList<>();
final List<Callable<Void>> refreshStoragePoolTasks = new ArrayList<>();
final StoragePool storagePool = DbFacade.getInstance().getStoragePoolDao().get(_storagePoolId);
final Guid masterDomainId =
DbFacade.getInstance().getStorageDomainDao().getMasterStorageDomainIdForPool(_storagePoolId);
final List<StoragePoolIsoMap> storagePoolIsoMap = DbFacade.getInstance()
.getStoragePoolIsoMapDao().getAllForStoragePool(_storagePoolId);
Map<String, Pair<String, String>> acquiredLocks = new HashMap<>();
try {
for (Map.Entry<Guid, Guid> entry : reportsToHandle.entrySet()) {
Guid vdsId = entry.getKey();
Guid currentReportId = entry.getValue();
vdsHandeledReportsOnUnseenDomains.put(vdsId, currentReportId);
Map<String, Pair<String, String>> lockMap = Collections.singletonMap(vdsId.toString(),
new Pair<>(LockingGroup.VDS_POOL_AND_STORAGE_CONNECTIONS.toString(),
EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED.toString()));
EngineLock engineLock = new EngineLock(lockMap, null);
if (!LockManagerFactory.getLockManager()
.acquireLock(engineLock)
.getFirst()) {
log.info("Failed to acquire lock to refresh storage connection and pool metadata for host '{}', skipping it",
vdsId);
continue;
}
final VDS vds = DbFacade.getInstance().getVdsDao().get(entry.getKey());
if (vds.getStatus() != VDSStatus.Up) {
log.info("Skipping storage connection and pool metadata information for host '{}' as it's no longer in status UP",
vdsId);
LockManagerFactory.getLockManager().releaseLock(engineLock);
continue;
}
acquiredLocks.putAll(lockMap);
connectStorageTasks.add(new Callable<Void>() {
@Override
public Void call() {
ResourceManager.getInstance()
.getEventListener().connectHostToDomainsInActiveOrUnknownStatus(vds);
return null;
}
});
refreshStoragePoolTasks.add(new Callable<Void>() {
@Override
public Void call() {
StoragePoolDomainHelper.refreshHostPoolMetadata(vds, storagePool, masterDomainId, storagePoolIsoMap);
return null;
}
});
}
final Set<String> handledHosts = acquiredLocks.keySet();
log.info("Running storage connections refresh for hosts '{}'", handledHosts);
ThreadPoolUtil.invokeAll(connectStorageTasks);
log.info("Submitting to the event queue pool refresh for hosts '{}'", handledHosts);
getEventQueue().submitEventSync(new Event(_storagePoolId,
null,
null,
EventType.POOLREFRESH,
""),
new Callable<EventResult>() {
@Override
public EventResult call() {
log.info("Running storage pool metadata refresh for hosts '{}'", handledHosts);
ThreadPoolUtil.invokeAll(refreshStoragePoolTasks);
return new EventResult(true, EventType.POOLREFRESH);
}
});
} finally {
if (!acquiredLocks.isEmpty()) {
LockManagerFactory.getLockManager().releaseLock(new EngineLock(acquiredLocks, null));
}
}
}
private void updateDomainInProblemData(Guid domainId, Guid vdsId, String vdsName) {
log.debug("domain '{}' still in problem. vds: '{}'", getDomainIdTuple(domainId), vdsName);
_domainsInProblem.get(domainId).add(vdsId);
}
private EventResult processDomainRecovery(final Guid domainId) {
EventResult result = null;
// build a list of all the hosts in status UP in
// Pool.
List<Guid> vdssInPool = new ArrayList<>();
// Note - this method is used as it returns only hosts from VIRT supported clusters
// (we use the domain monitoring results only from those clusters hosts).
// every change to it should be inspected carefully.
List<VDS> allVds = DbFacade.getInstance().getVdsDao().getAllForStoragePoolAndStatus(_storagePoolId, null);
Map<Guid, VDS> vdsMap = new HashMap<>();
for (VDS tempVDS : allVds) {
vdsMap.put(tempVDS.getId(), tempVDS);
if (tempVDS.getStatus() == VDSStatus.Up) {
vdssInPool.add(tempVDS.getId());
}
}
// build a list of all the hosts that did not report
// on this domain as in problem.
// Mark the above list as hosts we suspect are in
// problem.
Set<Guid> hostsThatReportedDomainAsInProblem = _domainsInProblem.get(domainId);
List<Guid> vdssInProblem = new ArrayList<>();
for (Guid tempVDSId : vdssInPool) {
if (!hostsThatReportedDomainAsInProblem.contains(tempVDSId)) {
vdssInProblem.add(tempVDSId);
}
}
// If not All the hosts in status UP reported on
// this domain as in problem. We assume the problem
// is with the hosts
// that did report on a problem with this domain.
// (and not a problem with the domain itself).
StorageDomainStatic storageDomain = DbFacade.getInstance().getStorageDomainStaticDao().get(domainId);
String domainIdTuple = getDomainIdTuple(domainId);
List<Guid> nonOpVdss = new ArrayList<>();
if (vdssInProblem.size() > 0) {
if (storageDomain.getStorageDomainType() != StorageDomainType.ImportExport
&& storageDomain.getStorageDomainType() != StorageDomainType.ISO) {
// The domain is of type DATA and was
// reported as in problem.
// Moving all the hosts which reported on
// this domain as in problem to non
// operational.
for (final Guid vdsId : _domainsInProblem.get(domainId)) {
VDS vds = vdsMap.get(vdsId);
if (vds == null) {
log.warn(
"vds '{}' reported domain '{}' - as in problem but cannot find vds in db!!",
vdsId,
domainIdTuple);
} else if (vds.getStatus() == VDSStatus.Up) {
log.warn(
"vds '{}' reported domain '{}' as in problem, attempting to move the vds to status NonOperational",
vds.getName(),
domainIdTuple);
final Map<String, String> customLogValues = Collections.singletonMap("StorageDomainNames", storageDomain.getName());
ThreadPoolUtil.execute(new Runnable() {
@Override
public void run() {
ResourceManager
.getInstance()
.getEventListener()
.vdsNonOperational(vdsId, NonOperationalReason.STORAGE_DOMAIN_UNREACHABLE,
true, domainId, customLogValues);
}
});
nonOpVdss.add(vdsId);
} else {
log.warn(
"vds '{}' reported domain '{}' as in problem, vds is in status '{}', no need to move to nonoperational",
vds.getName(),
domainIdTuple,
vds.getStatus());
}
}
} else {
log.warn(
"Storage domain '{}' is not visible to one or more hosts. " +
"Since the domain's type is '{}', hosts status will not be changed to non-operational",
domainIdTuple,
storageDomain.getStorageDomainType());
}
result = new EventResult(true, EventType.VDSSTOARGEPROBLEMS);
} else { // Because all the hosts in status UP
// reported on this domain as in problem
// we assume the problem is with the
// Domain.
if (storageDomain.getStorageDomainType() != StorageDomainType.Master) {
log.error("Domain '{}' was reported by all hosts in status UP as problematic. Moving the domain to NonOperational.",
domainIdTuple);
result = ResourceManager.getInstance()
.getEventListener().storageDomainNotOperational(domainId, _storagePoolId);
} else {
log.warn("Domain '{}' was reported by all hosts in status UP as problematic. Not moving the domain to NonOperational because it is being reconstructed now.",
domainIdTuple);
result = ResourceManager.getInstance()
.getEventListener().masterDomainNotOperational(domainId, _storagePoolId, false, false);
}
}
// clear from cache of _domainsInProblem
clearDomainFromCache(domainId, nonOpVdss);
return result;
}
/**
* clears the time for the given domain
*
* @param domainId
* - the domain to clean the timer for
*/
private void clearTimer(Guid domainId) {
String jobId = _timers.remove(domainId);
if (jobId != null) {
getSchedulUtil().deleteJob(jobId);
}
}
/**
* clears the problematic domain from the vdss that reported on this domain as problematic and from the domains
* in problem
*
* @param domainId
* - the domain to clear cache for.
* @param nonOpVdss - passed vdss that non operational
*/
private void clearDomainFromCache(Guid domainId, List<Guid> nonOpVdss) {
if (domainId != null) {
_domainsInProblem.remove(domainId);
}
removeVdsAsProblematic(nonOpVdss);
removeVdsFromDomainMaintenance(nonOpVdss);
removeVdsFromUnseenDomainsReport(nonOpVdss);
}
private void removeVdsAsProblematic(List<Guid> nonOpVdss) {
Iterator<Map.Entry<Guid, HashSet<Guid>>> iterDomainsInProblem = _domainsInProblem.entrySet().iterator();
while (iterDomainsInProblem.hasNext()) {
Map.Entry<Guid, HashSet<Guid>> entry = iterDomainsInProblem.next();
entry.getValue().removeAll(nonOpVdss);
if (entry.getValue().isEmpty()) {
iterDomainsInProblem.remove();
clearTimer(entry.getKey());
log.info("Domain '{}' has recovered from problem. No active host in the DC is reporting it as poblematic, so clearing the domain recovery timer.",
getDomainIdTuple(entry.getKey()));
}
}
}
private void removeVdsFromUnseenDomainsReport(List<Guid> nonOpVdss) {
log.info("Removing host(s) '{}' from hosts unseen domain report cache", nonOpVdss);
for(Guid id : nonOpVdss) {
clearVdsReportInfoOnUnseenDomain(id);
}
}
private void removeVdsFromDomainMaintenance(List<Guid> nonOpVdss) {
log.info("Removing vds '{}' from the domain in maintenance cache", nonOpVdss);
Iterator<Map.Entry<Guid, HashSet<Guid>>> iterDomainsInProblem = _domainsInMaintenance.entrySet().iterator();
while (iterDomainsInProblem.hasNext()) {
Map.Entry<Guid, HashSet<Guid>> entry = iterDomainsInProblem.next();
entry.getValue().removeAll(nonOpVdss);
if (entry.getValue().isEmpty()) {
iterDomainsInProblem.remove();
}
}
}
/**
* deletes all the jobs for the domains in the pool and clears the problematic entities caches.
*/
public void clearCache() {
log.info("clearing cache for problematic entities in pool '{}'.", _storagePoolId);
// clear lists
_timers.clear();
_domainsInProblem.clear();
}
public void clearPoolTimers() {
log.info("clear domain error-timers for pool '{}'.", _storagePoolId);
for (String jobId : _timers.values()) {
try {
getSchedulUtil().deleteJob(jobId);
} catch (Exception e) {
log.warn("failed deleting job '{}'.", jobId);
}
}
}
/**
* Remove a VDS entry from the cache, clearing the problematic domains for this VDS and their times if they
* need to be cleaned. This is for a case when the VDS is switched to maintenance by the user, since we
* need to clear it's cache data and timers, or else the cache will contain stale data (since the VDS is not
* active anymore, it won't be connected to any of the domains).<br>
*
* @param vdsId The ID of the VDS to remove from the cache.
* @param vdsName The name of the VDS (for logging).
*/
public void clearVdsFromCache(Guid vdsId, String vdsName) {
log.info("Clearing cache of pool: '{}' for problematic entities of VDS: '{}'.",
_storagePoolId, vdsName);
clearDomainFromCache(null, Arrays.asList(vdsId));
}
private boolean _disposed;
public void dispose() {
synchronized (syncObj) {
log.info("IrsProxyData::disposing");
resetIrs();
getSchedulUtil().deleteJob(storagePoolRefreshJobId);
getSchedulUtil().deleteJob(domainRecoverOnHostJobId);
_disposed = true;
}
}
private static String getDomainIdTuple(Guid domainId) {
StorageDomainStatic storage_domain = DbFacade.getInstance().getStorageDomainStaticDao().get(domainId);
if (storage_domain != null) {
return domainId + ":" + storage_domain.getStorageName();
} else {
return domainId.toString();
}
}
}
|
package org.bitrepository.audittrails.store;
import static org.bitrepository.audittrails.store.AuditDatabaseExtractor.POSITION_ACTOR_NAME;
import static org.bitrepository.audittrails.store.AuditDatabaseExtractor.POSITION_AUDIT_TRAIL;
import static org.bitrepository.audittrails.store.AuditDatabaseExtractor.POSITION_CONTRIBUTOR_ID;
import static org.bitrepository.audittrails.store.AuditDatabaseExtractor.POSITION_FILE_ID;
import static org.bitrepository.audittrails.store.AuditDatabaseExtractor.POSITION_INFORMATION;
import static org.bitrepository.audittrails.store.AuditDatabaseExtractor.POSITION_OPERATION;
import static org.bitrepository.audittrails.store.AuditDatabaseExtractor.POSITION_OPERATION_DATE;
import static org.bitrepository.audittrails.store.AuditDatabaseExtractor.POSITION_SEQUENCE_NUMBER;
import static org.bitrepository.audittrails.store.AuditDatabaseExtractor.POSITION_OPERATION_ID;
import static org.bitrepository.audittrails.store.AuditDatabaseExtractor.POSITION_FINGERPRINT;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bitrepository.bitrepositoryelements.AuditTrailEvent;
import org.bitrepository.bitrepositoryelements.FileAction;
import org.bitrepository.common.utils.CalendarUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class to iterate over the set of AuditTrailEvents produced by a resultset.
*/
public class AuditEventIterator {
/** The log.*/
private Logger log = LoggerFactory.getLogger(getClass());
private ResultSet auditResultSet = null;
private Connection conn = null;
private final PreparedStatement ps;
/**
* Constructor
* @param auditResultSet The ResultSet of audit trails from the database
* @param dbConnector The database connection, for looking up foreign keys in the auditResultSet
*/
public AuditEventIterator(PreparedStatement ps) {
this.ps = ps;
}
/**
* Method to explicitly close the ResultSet in the AuditEventIterator
* @throws SQLException in case of a sql error
*/
public void close() throws SQLException {
if(auditResultSet != null) {
auditResultSet.close();
}
if(ps != null) {
ps.close();
}
if(conn != null) {
conn.setAutoCommit(true);
conn.close();
}
}
/**
* Method to return the next AuditTrailEvent in the ResultSet
* When no more AuditTrailEvents are available, null is returned and the internal ResultSet closed.
* @return The next AuditTrailEvent available in the ResultSet, or null if no more events are available.
* @throws SQLException In case of a sql error.
*/
public AuditTrailEvent getNextAuditTrailEvent() {
try {
AuditTrailEvent event = null;
if(auditResultSet == null) {
conn = ps.getConnection();
conn.setAutoCommit(false);
ps.setFetchSize(100);
long tStart = System.currentTimeMillis();
log.debug("Executing query to get AuditTrailEvents resultset");
auditResultSet = ps.executeQuery();
log.debug("Finished executing AuditTrailEvents query, it took: " + (System.currentTimeMillis() - tStart) + "ms");
}
if(auditResultSet.next()) {
event = new AuditTrailEvent();
event.setActionDateTime(CalendarUtils.getFromMillis(auditResultSet.getTimestamp(POSITION_OPERATION_DATE).getTime()));
event.setActionOnFile(FileAction.fromValue(auditResultSet.getString(POSITION_OPERATION)));
event.setAuditTrailInformation(auditResultSet.getString(POSITION_AUDIT_TRAIL));
event.setActorOnFile(auditResultSet.getString(POSITION_ACTOR_NAME));
event.setFileID(auditResultSet.getString(POSITION_FILE_ID));
event.setInfo(auditResultSet.getString(POSITION_INFORMATION));
event.setReportingComponent(auditResultSet.getString(POSITION_CONTRIBUTOR_ID));
event.setSequenceNumber(BigInteger.valueOf(auditResultSet.getLong(POSITION_SEQUENCE_NUMBER)));
event.setOperationID(auditResultSet.getString(POSITION_OPERATION_ID));
event.setCertificateID(auditResultSet.getString(POSITION_FINGERPRINT));
} else {
close();
}
return event;
} catch (Exception e) {
try {
close();
} catch (SQLException e1) {
throw new RuntimeException("Failed to close ResultSet or PreparedStatement", e1);
}
throw new IllegalStateException("Could not extract the wanted audittrails", e);
}
}
}
|
package gov.nih.nci.caadapter.ui.mapping.sdtm;
import gov.nih.nci.caadapter.common.*;
import gov.nih.nci.caadapter.common.csv.CSVMetaParserImpl;
import gov.nih.nci.caadapter.common.csv.CSVMetaResult;
import gov.nih.nci.caadapter.common.util.Config;
import gov.nih.nci.caadapter.common.util.EmptyStringTokenizer;
import gov.nih.nci.caadapter.common.util.GeneralUtilities;
import gov.nih.nci.caadapter.common.validation.ValidatorResult;
import gov.nih.nci.caadapter.common.validation.ValidatorResults;
import gov.nih.nci.caadapter.dataviewer.util.OpenDatabaseConnectionHelper;
import gov.nih.nci.caadapter.sdtm.ParseSDTMXMLFile;
import gov.nih.nci.caadapter.sdtm.SDTMMappingGenerator;
import gov.nih.nci.caadapter.sdtm.SDTMMetadata;
import gov.nih.nci.caadapter.sdtm.meta.QBTableMetaData;
import gov.nih.nci.caadapter.sdtm.meta.QueryBuilderMeta;
import gov.nih.nci.caadapter.ui.common.AbstractMainFrame;
import gov.nih.nci.caadapter.ui.common.ActionConstants;
import gov.nih.nci.caadapter.ui.common.DefaultSettings;
import gov.nih.nci.caadapter.ui.common.MappingFileSynchronizer;
import gov.nih.nci.caadapter.ui.common.actions.TreeCollapseAllAction;
import gov.nih.nci.caadapter.ui.common.actions.TreeExpandAllAction;
import gov.nih.nci.caadapter.ui.common.context.ContextManager;
import gov.nih.nci.caadapter.ui.common.context.MenuConstants;
import gov.nih.nci.caadapter.ui.common.nodeloader.SCMMapSourceNodeLoader;
import gov.nih.nci.caadapter.ui.common.tree.DefaultSourceTreeNode;
import gov.nih.nci.caadapter.ui.common.tree.DefaultTargetTreeNode;
import gov.nih.nci.caadapter.ui.common.tree.TreeDefaultDropTransferHandler;
import gov.nih.nci.caadapter.ui.mapping.AbstractMappingPanel;
import gov.nih.nci.caadapter.ui.mapping.MappingMiddlePanel;
import gov.nih.nci.caadapter.ui.mapping.sdtm.actions.OpenDataViewerHelper;
import gov.nih.nci.caadapter.ui.mapping.sdtm.actions.QBGetPasswordWindow;
import gov.nih.nci.caadapter.ui.mapping.sdtm.actions.QBTransformAction;
import gov.nih.nci.caadapter.ui.mapping.sdtm.actions.SdtmDropTransferHandler;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.awt.dnd.DnDConstants;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
public class Database2SDTMMappingPanel extends AbstractMappingPanel {
private static final String LOGID = "$RCSfile: Database2SDTMMappingPanel.java,v $";
public static String RCSID = "$Header: /share/content/gforge/caadapter/caadapter/components/userInterface/src/gov/nih/nci/caadapter/ui/mapping/sdtm/Database2SDTMMappingPanel.java,v 1.20 2007-09-13 14:41:38 jayannah Exp $";
private static final String SELECT_SCS = "Open SCS file...";
private static final String SELECT_TARGET = "Open SDTM definition file...";
private SdtmDropTransferHandler sdtmTargetTreeDropTransferHandler = null;
static ArrayList<String> _retArray = null;
private String defineXMLLocation = null;
private SDTMMappingGenerator sdtmMappingGenerator = null;
private static String OPENDB = "Choose Database";
private boolean connectDB = false;
private JButton openTargetButton = null;
private AbstractMainFrame _mainFrame = null;
private Hashtable connectionParameters = null;
private JButton _dbCon = null;
private JButton openSCSButton = null;
private boolean openDBmap = false;
private Hashtable sqlQueries = null;
private JButton transformBut = null;
private JButton _commonBut = null;
private boolean isDataBase = false;
private boolean connectException = false;
public JButton get_dbCon() {
return _dbCon;
}
public JButton getOpenSCSButton() {
return openSCSButton;
}
public JButton getTransFormBut() {
return transformBut;
}
public static Hashtable getDomainFieldsList() {
return domainFieldsList;
}
private static Hashtable domainFieldsList = null;
public Database2SDTMMappingPanel(AbstractMainFrame mf) {
this.setBorder(BorderFactory.createEmptyBorder());
this.setLayout(new BorderLayout());
this.add(getCenterPanel(false), BorderLayout.CENTER);
fileSynchronizer = new MappingFileSynchronizer(this);
this._mainFrame = mf;
}
public Database2SDTMMappingPanel(AbstractMainFrame mf, String _conn) {
this.setBorder(BorderFactory.createEmptyBorder());
this.setLayout(new BorderLayout());
this._mainFrame = mf;
try {
this.add(getCenterPanel(false), BorderLayout.CENTER);
} catch (Exception e) {
//e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
fileSynchronizer = new MappingFileSynchronizer(this);
}
public Hashtable getSqlQueries() {
return sqlQueries;
}
public Database2SDTMMappingPanel(AbstractMainFrame mf, String _conn, boolean openDatabaseMap) {
this.setBorder(BorderFactory.createEmptyBorder());
this.setLayout(new BorderLayout());
this._mainFrame = mf;
this.openDBmap = true;
this.add(getCenterPanel(false), BorderLayout.CENTER);
fileSynchronizer = new MappingFileSynchronizer(this);
sqlQueries = new Hashtable();
openDBmap = openDatabaseMap;
}
public Hashtable getConnectionParameters() throws SQLException {
try {
connectionParameters.put("connection", DBConnector.getConnection());
} catch (Exception e) {
try {
connectionParameters.put("connection", DBConnector.getDBConnection(connectionParameters.get("URL").toString(), connectionParameters.get("Driver").toString(), connectionParameters.get("UserID").toString(), connectionParameters.get("PWD").toString()));
} catch (Exception e1) {
// e1.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
JOptionPane.showMessageDialog(this, e1.getMessage().toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
return connectionParameters;
}
public SDTMMappingGenerator getSDTMappingGenerator() {
return sdtmMappingGenerator;
}
public JButton get_commonBut() {
return _commonBut;
}
public AbstractMainFrame get_mainFrame() {
return _mainFrame;
}
public JButton getTransformBut() {
return transformBut;
}
public JButton getOpenTargetButton() {
return openTargetButton;
}
protected JPanel getTopLevelLeftPanel() {
JPanel topCenterPanel = new JPanel(new BorderLayout());
topCenterPanel.setBorder(BorderFactory.createEmptyBorder());
JSplitPane centerSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
DefaultSettings.setDefaultFeatureForJSplitPane(centerSplitPane);
// construct source panel
sourceButtonPanel = new JPanel(new BorderLayout());
sourceButtonPanel.setBorder(BorderFactory.createEmptyBorder());
sourceLocationPanel = new JPanel(new BorderLayout(2, 0));
sourceLocationPanel.setBorder(BorderFactory.createEmptyBorder());
sourceTreeCollapseAllAction = new TreeCollapseAllAction(sTree);
sourceTreeExpandAllAction = new TreeExpandAllAction(sTree);
JToolBar sourceTreeToolBar = new JToolBar("Source Tree Tool Bar");
sourceTreeToolBar.setFloatable(false);
sourceTreeToolBar.add(sourceTreeExpandAllAction);
sourceTreeToolBar.add(sourceTreeCollapseAllAction);
sourceLocationPanel.add(sourceTreeToolBar, BorderLayout.WEST);
sourceLocationArea.setEditable(false);
sourceLocationArea.setPreferredSize(new Dimension((int) (Config.FRAME_DEFAULT_WIDTH / 10), 24));
sourceLocationPanel.add(sourceLocationArea, BorderLayout.CENTER);
openSCSButton = new JButton(SELECT_SCS);
sourceLocationPanel.add(openSCSButton, BorderLayout.EAST);
openSCSButton.setMnemonic('O');
openSCSButton.setToolTipText("Select SCS file...");
openSCSButton.addActionListener(this);
sourceButtonPanel.add(sourceLocationPanel, BorderLayout.NORTH);
// sourceScrollPane = DefaultSettings.createScrollPaneWithDefaultFeatures();
sourceScrollPane.setSize(new Dimension((int) (Config.FRAME_DEFAULT_WIDTH / 4), (int) (Config.FRAME_DEFAULT_HEIGHT / 1.5)));
sourceButtonPanel.add(sourceScrollPane, BorderLayout.CENTER);
// construct target panel
targetButtonPanel = new JPanel(new BorderLayout());
targetButtonPanel.setBorder(BorderFactory.createEmptyBorder());
targetLocationPanel = new JPanel(new BorderLayout(2, 0));
targetLocationPanel.setBorder(BorderFactory.createEmptyBorder());
targetTreeCollapseAllAction = new TreeCollapseAllAction(tTree);
targetTreeExpandAllAction = new TreeExpandAllAction(tTree);
JToolBar targetTreeToolBar = new JToolBar("Target Tree Tool Bar");
targetTreeToolBar.setFloatable(false);
targetTreeToolBar.add(targetTreeExpandAllAction);
targetTreeToolBar.add(targetTreeCollapseAllAction);
targetLocationPanel.add(targetTreeToolBar, BorderLayout.WEST);
targetLocationArea.setEditable(false);
targetLocationArea.setPreferredSize(new Dimension((int) (Config.FRAME_DEFAULT_WIDTH / 10), 24));
targetLocationPanel.add(targetLocationArea, BorderLayout.CENTER);
openTargetButton = new JButton(SELECT_TARGET);
targetLocationPanel.add(openTargetButton, BorderLayout.EAST);
openTargetButton.setMnemonic('T');
openTargetButton.setToolTipText("Open Target Structure file");
openTargetButton.addActionListener(this);
targetButtonPanel.add(targetLocationPanel, BorderLayout.NORTH);
// targetScrollPane = DefaultSettings.createScrollPaneWithDefaultFeatures();
targetButtonPanel.add(targetScrollPane, BorderLayout.CENTER);
targetButtonPanel.setPreferredSize(new Dimension((int) (Config.FRAME_DEFAULT_WIDTH / 5), (int) (Config.FRAME_DEFAULT_HEIGHT / 1.5)));
// construct middle panel
//JPanel centerFunctionPanel = new JPanel(new BorderLayout(2, 0));
JPanel centerFunctionPanel = new JPanel(new BorderLayout());
//JPanel centerFunctionPanel = new JPanel(new FlowLayout());
JPanel middleContainerPanel = new JPanel(new BorderLayout());
JLabel placeHolderLabel = new JLabel();
placeHolderLabel.setPreferredSize(new Dimension((int) (Config.FRAME_DEFAULT_WIDTH / 3.5), 24));
middlePanel = new MappingMiddlePanel(this);
middlePanel.setKind("SDTM");
sdtmMappingGenerator = new SDTMMappingGenerator();
sdtmMappingGenerator.set_sdtmMappingGeneratorReference(sdtmMappingGenerator);
middlePanel.setSize(new Dimension((int) (Config.FRAME_DEFAULT_WIDTH / 3), (int) (Config.FRAME_DEFAULT_HEIGHT / 1.5)));
_dbCon = new JButton("Choose Database");
_dbCon.setActionCommand("Choose Database");
_commonBut = new JButton("Data Viewer");
_commonBut.setActionCommand("dataview");
_commonBut.addActionListener(this);
transformBut = new JButton("Transform");
transformBut.setActionCommand("transform");
transformBut.addActionListener(this);
if (!openDBmap) {
_commonBut.setEnabled(false);
transformBut.setEnabled(false);
}
JPanel westpanel = new JPanel(new FlowLayout());
westpanel.add(_dbCon);
westpanel.add(_commonBut);
//westpanel.add(transformBut);
_dbCon.setPreferredSize(new Dimension(135, 19));
transformBut.setPreferredSize(new Dimension(100, 19));
_commonBut.setPreferredSize(new Dimension(110, 19));
//_dbCon.setBounds(2,2,2,2);
//centerFunctionPanel.add(westpanel, BorderLayout.CENTER);
// centerFunctionPanel.add(_dbCon);
// centerFunctionPanel.add(_commonBut);
// centerFunctionPanel.add(transformBut);
_dbCon.addActionListener(this);
westpanel.setPreferredSize(new Dimension((int) (Config.FRAME_DEFAULT_WIDTH / 3.5), 24));
//centerFunctionPanel.add(placeHolderLabel, BorderLayout.EAST);
middleContainerPanel.add(westpanel, BorderLayout.NORTH);
// middleContainerPanel.add(placeHolderLabel, BorderLayout.NORTH);
middleContainerPanel.add(middlePanel, BorderLayout.CENTER);
JSplitPane rightSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
DefaultSettings.setDefaultFeatureForJSplitPane(rightSplitPane);
rightSplitPane.setDividerLocation(0.5);
rightSplitPane.setLeftComponent(middleContainerPanel);
rightSplitPane.setRightComponent(targetButtonPanel);
centerSplitPane.setLeftComponent(sourceButtonPanel);
centerSplitPane.setRightComponent(rightSplitPane);
topCenterPanel.add(centerSplitPane, BorderLayout.CENTER);
topCenterPanel.setPreferredSize(new Dimension((int) (Config.FRAME_DEFAULT_WIDTH * 0.8), (int) (Config.FRAME_DEFAULT_HEIGHT / 1.5)));
if (openDBmap) {
_dbCon.setEnabled(false);
openTargetButton.setEnabled(false);
openSCSButton.setEnabled(false);
}
return topCenterPanel;
}
public boolean isConnectDB() {
return connectDB;
}
public boolean isOpenDBmap() {
return openDBmap;
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
try {
boolean everythingGood = true;
if (SELECT_SCS.equals(command)) {
_dbCon.setEnabled(false);
File file = DefaultSettings.getUserInputOfFileFromGUI(this, ".scs", "Open SCS file ...", false, false);
if (file != null) {
everythingGood = processOpenSourceTree(file, true, true);
openSCSButton.setEnabled(false);
} else {
openSCSButton.setEnabled(true);
_dbCon.setEnabled(true);
}
} else if (SELECT_TARGET.equals(command)) {
File file = DefaultSettings.getUserInputOfFileFromGUI(this, ".xml", "Open SDTM Structure file ...", false, false);
if (file != null) {
buildTargetTree(null, file, true);
openTargetButton.setEnabled(false);
} else {
openTargetButton.setEnabled(true);
}
} else if (OPENDB.equalsIgnoreCase(command)) {
isDataBase = true;
final Dialog _queryWaitDialog = new Dialog(_mainFrame);
new Thread(new Runnable() {
public void run() {
try {
connectDB = true;
openSCSButton.setEnabled(false);
OpenDatabaseConnectionHelper _openDatabaseConnectionHelper = new OpenDatabaseConnectionHelper(_mainFrame);
if (!_openDatabaseConnectionHelper.isCancelled()) {
connectionParameters = _openDatabaseConnectionHelper.getDatabaseConnectionInfo();
processOpenSourceTree(null, true, true);
_dbCon.setEnabled(connectException);
} else {
_dbCon.setEnabled(true);
openSCSButton.setEnabled(true);
}
_queryWaitDialog.dispose();
} catch (Exception e) {
_queryWaitDialog.dispose();
JOptionPane.showMessageDialog(_mainFrame, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}).start();
_queryWaitDialog.setTitle("Connection in Progress");
_queryWaitDialog.setSize(350, 100);
_queryWaitDialog.setLocationRelativeTo(null);
_queryWaitDialog.setLayout(new BorderLayout());
LineBorder lineBorder = (LineBorder) BorderFactory.createLineBorder(Color.black);
JPanel _waitLabel = new JPanel();
_waitLabel.setBorder(lineBorder);
_waitLabel.add(new JLabel(" Connecting to database, Please wait ..."));
_queryWaitDialog.add(new JLabel(" "), BorderLayout.NORTH);
_queryWaitDialog.add(_waitLabel, BorderLayout.CENTER);
_queryWaitDialog.setVisible(true);
_dbCon.setEnabled(false);
} else if (command.equalsIgnoreCase("Transform")) {
try {
new QBTransformAction(_mainFrame, this, (Connection) connectionParameters.get("connection"));
} catch (Exception e1) {
JOptionPane.showMessageDialog(this, e1.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
} else if (command.equalsIgnoreCase("dataview")) {
/**
* open the helper to bypass another window
*/
new OpenDataViewerHelper(_mainFrame, this, getSaveFile(), transformBut, false).launchQueryBuilder();
} else if (!everythingGood) {
Message msg = MessageResources.getMessage("GEN3", new Object[0]);
JOptionPane.showMessageDialog(this, msg.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
DefaultSettings.reportThrowableToLogAndUI(this, e1, "", this, false, false);
}
}
public boolean openDataBaseMapFileFromOpenMapFile(String params) {
boolean retVal = false;
try {
QBGetPasswordWindow getPass = new QBGetPasswordWindow(_mainFrame, params, this.getSaveFile().toString());
if (getPass.isResult()) {
String pass = getPass.getPassword();
EmptyStringTokenizer empt = new EmptyStringTokenizer(params, "~");
connectDB = true;
connectionParameters = new Hashtable();
connectionParameters.put("URL", empt.getTokenAt(0));
connectionParameters.put("UserID", empt.getTokenAt(2));
connectionParameters.put("PWD", pass);
connectionParameters.put("SCHEMA", empt.getTokenAt(3));
connectionParameters.put("Driver", empt.getTokenAt(1));
try {
connectionParameters.put("connection", DBConnector.getDBConnection(empt.getTokenAt(0), empt.getTokenAt(1), empt.getTokenAt(2), pass));
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage().toString(), "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
processOpenSourceTree(null, true, true);
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return retVal;
}
public void openDataBaseMapFile(String params) {
try {
QBGetPasswordWindow getPass = new QBGetPasswordWindow(_mainFrame, params, this.getSaveFile().toString());
String pass = getPass.getPassword();
EmptyStringTokenizer empt = new EmptyStringTokenizer(params, "~");
connectDB = true;
connectionParameters = new Hashtable();
connectionParameters.put("URL", empt.getTokenAt(0));
connectionParameters.put("UserID", empt.getTokenAt(2));
connectionParameters.put("PWD", pass);
connectionParameters.put("SCHEMA", empt.getTokenAt(3));
connectionParameters.put("Driver", empt.getTokenAt(1));
try {
connectionParameters.put("connection", DBConnector.getDBConnection(empt.getTokenAt(0), empt.getTokenAt(1), empt.getTokenAt(2), pass));
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage().toString(), "Error", JOptionPane.ERROR_MESSAGE);
return;
}
processOpenSourceTree(null, true, true);
} catch (Exception e) {
e.printStackTrace();
}
}
protected TreeNode loadSourceTreeData(Object metaInfo, File absoluteFile) throws Exception {
if (!connectDB) {
TreeNode node = new DefaultMutableTreeNode("SCS Model");
// build source tree end
SCMMapSourceNodeLoader scmMapSourceNodeLoader = new SCMMapSourceNodeLoader();
node = scmMapSourceNodeLoader.loadData(metaInfo);
return node;
} else {
TreeNode node = new DefaultMutableTreeNode("Data Model");
return createSourceNodes(node, "");
}
}
protected void buildSourceTree(Object metaInfo, File file, boolean isToResetGraph) throws Exception {
super.buildSourceTree(metaInfo, file, isToResetGraph);
if (connectDB) {
sTree.setCellRenderer(new SourceRenderer());
ToolTipManager.sharedInstance().registerComponent(sTree);
}
sTree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) sTree.getLastSelectedPathComponent();
if (node == null)
return;
}
});
}
public TreeNode createSourceNodes(TreeNode nodes, String flavor) {
ArrayList ary = null;
try {
ary = DBConnector.getSchemaCollection(connectionParameters);
} catch (Exception e) {
JOptionPane.showMessageDialog(_mainFrame, " " + e.getMessage().toString() + " ", "Could not connect to Database : " + connectionParameters.get("URL").toString(), JOptionPane.ERROR_MESSAGE);
connectException = true;
openSCSButton.setEnabled(true);
}
DefaultMutableTreeNode pNode = null;
DefaultSourceTreeNode tableNode = null;
if (ary != null) {
for (int k = 0; k < ary.size(); k++) {
if (ary.get(k) instanceof String) {
String _tmpStr = ary.get(k).toString();
String _str1 = _tmpStr.substring(3, _tmpStr.length());
pNode = new DefaultMutableTreeNode(_str1);
((DefaultMutableTreeNode) nodes).add(pNode);
} else if (ary.get(k) instanceof QBTableMetaData) {
tableNode = new DefaultSourceTreeNode(ary.get(k));
if (pNode != null)
pNode.add(tableNode);
} else if (ary.get(k) instanceof QueryBuilderMeta) {
if (tableNode != null) {
tableNode.add(new DefaultSourceTreeNode(ary.get(k)));
}
}
}
}
return nodes;
}
public static ArrayList getDefaultTargetTreeNodeList() {
return defaultTargetTreeNodeList;
}
private static ArrayList defaultTargetTreeNodeList;
@SuppressWarnings("unchecked")
public static void createTargetNodes(TreeNode nodes, File SDTMXmlFile) {
defaultTargetTreeNodeList = new ArrayList();
ParseSDTMXMLFile _parseSDTMFile = new ParseSDTMXMLFile(SDTMXmlFile.getAbsolutePath().toString());
_retArray = _parseSDTMFile.getSDTMStructure();
domainFieldsList = new Hashtable();
DefaultMutableTreeNode pNode = null;
String domainString = "";
StringBuffer fieldsString = null;
String _tempHolder;
domainFieldsList = new Hashtable();
for (int k = 0; k < _retArray.size(); k++) {
if (_retArray.get(k).startsWith("KEY")) {
if (fieldsString != null)
domainFieldsList.put(domainString, fieldsString.toString().substring(0, fieldsString.toString().lastIndexOf(',')));
fieldsString = new StringBuffer();
EmptyStringTokenizer _str = new EmptyStringTokenizer(_retArray.get(k), ",");
pNode = new DefaultMutableTreeNode(_str.getTokenAt(1).substring(0, 2));
((DefaultMutableTreeNode) nodes).add(pNode);
defaultTargetTreeNodeList.add(pNode);
domainString = pNode.toString();
} else {
EmptyStringTokenizer _str = new EmptyStringTokenizer(_retArray.get(k), ",");
_tempHolder = _str.getTokenAt(1);
pNode.add(new DefaultTargetTreeNode(new SDTMMetadata(pNode.toString(), _tempHolder, _str.getTokenAt(2), _str.getTokenAt(3), _str.getTokenAt(4))));
fieldsString.append(_tempHolder.substring(0, _tempHolder.indexOf('&')) + ",");
}
}
//System.out.println("wait");
}
protected TreeNode loadTargetTreeData(Object metaInfo, File file) throws Exception {
String fileName = file.getAbsolutePath();
sdtmMappingGenerator.setScsDefineXMLFIle(fileName);
TreeNode targetNodes = new DefaultMutableTreeNode("SDTM Data Structure");
setDefineXMLLocation(fileName);
createTargetNodes(targetNodes, file);
return targetNodes;
}
protected void buildTargetTree(Object metaInfo, File absoluteFile, boolean isToResetGraph) throws Exception {
super.buildTargetTree(metaInfo, absoluteFile, isToResetGraph);
//instantiate the "DropTransferHandler"
tTree.setCellRenderer(new TargetRenderer());
ToolTipManager.sharedInstance().registerComponent(tTree);
sdtmTargetTreeDropTransferHandler = new SdtmDropTransferHandler(tTree, getMappingDataManager(), DnDConstants.ACTION_LINK, sdtmMappingGenerator);
}
/**
* Called by actionPerformed() and overridable by descendant classes.
*
* @param file
* @throws Exception
*/
protected boolean processOpenSourceTree(File file, boolean isToResetGraph, boolean supressReportIssuesToUI) throws Exception {
MetaObject metaInfo = null;
BaseResult returnResult = null;
MetaParser parser = null;
if (!connectDB) {
parser = new CSVMetaParserImpl();
returnResult = parser.parse(new FileReader(file));
ValidatorResults validatorResults = returnResult.getValidatorResults();
if (validatorResults != null && validatorResults.hasFatal()) {
Message msg = validatorResults.getMessages(ValidatorResult.Level.FATAL).get(0);
DefaultSettings.reportThrowableToLogAndUI(this, null, msg.toString(), this, true, supressReportIssuesToUI);
return false;
}
metaInfo = ((CSVMetaResult) returnResult).getCsvMeta();
((CSVMetaResult) returnResult).getCsvMeta().getRootSegment();
sdtmMappingGenerator.setScsSDTMFile(file.getAbsolutePath());
}
buildSourceTree(metaInfo, file, isToResetGraph);
return true;
}
/**
* Called by actionPerformed() and overridable by descendant classes.
*
* @param file
* @throws Exception
*/
protected boolean processOpenTargetTree(File file, boolean isToResetGraph, boolean supressReportIssuesToUI) throws Exception {
buildTargetTree(null, file, isToResetGraph);
return true;
}
/**
* Called by actionPerformed() and overridable by descendant classes.
*
* @param file
* @throws Exception changed from protected to pulic by sean
*/
public ValidatorResults processOpenMapFile(File file) throws Exception {
new OpenSDTMMapFile(this, file.toString());
return null;
}
public Map getMenuItems(String menu_name) {
Action action = null;
ContextManager contextManager = ContextManager.getContextManager();
Map<String, Action> actionMap = contextManager.getClientMenuActions(MenuConstants.DB_TO_SDTM, menu_name);
if (MenuConstants.FILE_MENU_NAME.equals(menu_name)) {
JRootPane rootPane = this.getRootPane();
if (rootPane != null) {//rootpane is not null implies this panel is fully displayed;
//on the flip side, if it is null, it implies it is under certain construction.
contextManager.enableAction(ActionConstants.NEW_O2DB_MAP_FILE, false);
//contextManager.enableAction(ActionConstants.OPEN_MAP_FILE, true);
}
}
//since the action depends on the panel instance,
//the old action instance should be removed
if (actionMap != null)
contextManager.removeClientMenuAction(MenuConstants.CSV_SPEC, menu_name, "");
// if (actionMap==null)
action = new gov.nih.nci.caadapter.ui.mapping.sdtm.actions.SaveSdtmAction(this, sdtmMappingGenerator);
contextManager.addClientMenuAction(MenuConstants.DB_TO_SDTM, MenuConstants.FILE_MENU_NAME, ActionConstants.SAVE, action);
contextManager.addClientMenuAction(MenuConstants.DB_TO_SDTM, MenuConstants.TOOLBAR_MENU_NAME, ActionConstants.SAVE, action);
action.setEnabled(false);
action = new gov.nih.nci.caadapter.ui.mapping.sdtm.actions.SaveAsSdtmAction(this, sdtmMappingGenerator);
contextManager.addClientMenuAction(MenuConstants.DB_TO_SDTM, MenuConstants.FILE_MENU_NAME, ActionConstants.SAVE_AS, action);
contextManager.addClientMenuAction(MenuConstants.DB_TO_SDTM, MenuConstants.TOOLBAR_MENU_NAME, ActionConstants.SAVE_AS, action);
action.setEnabled(false);
action = new gov.nih.nci.caadapter.ui.mapping.mms.actions.AnotateAction(this);
contextManager.addClientMenuAction(MenuConstants.DB_TO_SDTM, MenuConstants.FILE_MENU_NAME, ActionConstants.ANOTATE, action);
action.setEnabled(true);
action = new gov.nih.nci.caadapter.ui.mapping.hl7.actions.ValidateMapAction(this);
contextManager.addClientMenuAction(MenuConstants.DB_TO_SDTM, MenuConstants.FILE_MENU_NAME, ActionConstants.VALIDATE, action);
contextManager.addClientMenuAction(MenuConstants.DB_TO_SDTM, MenuConstants.TOOLBAR_MENU_NAME, ActionConstants.VALIDATE, action);
action.setEnabled(true);
action = new gov.nih.nci.caadapter.ui.mapping.sdtm.actions.SDTMCloseAction(this);
contextManager.addClientMenuAction(MenuConstants.DB_TO_SDTM, MenuConstants.FILE_MENU_NAME, ActionConstants.CLOSE, action);
action.setEnabled(true);
action = new gov.nih.nci.caadapter.ui.mapping.sdtm.actions.GenerateSDTMReportAction(this);
contextManager.addClientMenuAction(MenuConstants.DB_TO_SDTM, MenuConstants.REPORT_MENU_NAME, ActionConstants.GENERATE_REPORT, action);
contextManager.addClientMenuAction(MenuConstants.DB_TO_SDTM, MenuConstants.TOOLBAR_MENU_NAME, ActionConstants.GENERATE_REPORT, action);
action.setEnabled(true);
action = new gov.nih.nci.caadapter.ui.mapping.hl7.actions.RefreshMapAction(this);
contextManager.addClientMenuAction(MenuConstants.DB_TO_SDTM, MenuConstants.TOOLBAR_MENU_NAME, ActionConstants.REFRESH, action);
action.setEnabled(true);
actionMap = contextManager.getClientMenuActions(MenuConstants.DB_TO_SDTM, menu_name);
return actionMap;
}
/**
* return the open action inherited with this client.
*/
public Action getDefaultOpenAction() {
ContextManager contextManager = ContextManager.getContextManager();
return contextManager.getDefinedAction(ActionConstants.OPEN_CSV2SDTM_MAP_FILE_TXT);
}
/**
* Explicitly reload information from the internal given file.
*
* @throws Exception
*/
public void reload() throws Exception {
//processOpenMapFile(getSaveFile());
processOpenSourceTree(getSaveFile(), false, true);
}
protected TreeDefaultDropTransferHandler getTargetTreeDropTransferHandler() {
return this.sdtmTargetTreeDropTransferHandler;
}
/**
* Reload the file specified in the parameter.
*
* @param changedFileMap
*/
public void reload(Map<MappingFileSynchronizer.FILE_TYPE, File> changedFileMap) {
/**
* Design rationale: 1) if the changedFileMap is null, simply return; 2)
* if the getSaveFile() method does not return null, it implies current
* panel associates with a mapping file, just reload the whole mapping
* file so as to refresh those mapping relationship; 3) if the
* getSaveFile() returns null, just reload source and/or target file
* within the changedFileMap, and ignore the checking of
* MappingFileSynchronizer.FILE_TYPE.Mapping_File item in the map;
*/
if (changedFileMap == null) {
return;
}
File existMapFile = getSaveFile();
try {
if (existMapFile != null) {
if (existMapFile.exists()) {
processOpenMapFile(existMapFile);
} else {// exist map file does not exist anymore
JOptionPane.showMessageDialog(this, existMapFile.getAbsolutePath() + " does not exist or is not accessible anymore", "File Error", JOptionPane.ERROR_MESSAGE);
return;
}
} else {// exist map file does not exist, simply reload source
// and/or target file
Iterator it = changedFileMap.keySet().iterator();
while (it.hasNext()) {
MappingFileSynchronizer.FILE_TYPE key = (MappingFileSynchronizer.FILE_TYPE) it.next();
File file = changedFileMap.get(key);
if (GeneralUtilities.areEqual(MappingFileSynchronizer.FILE_TYPE.Source_File, key)) {
processOpenSourceTree(file, true, true);
} else if (GeneralUtilities.areEqual(MappingFileSynchronizer.FILE_TYPE.Target_File, key)) {
processOpenTargetTree(file, true, true);
}
}// end of while
}// end of else
} catch (Exception e) {
DefaultSettings.reportThrowableToLogAndUI(this, e, "", this, false, false);
}
}
public String getDefineXMLLocation() {
return defineXMLLocation;
}
public void setDefineXMLLocation(String defineXMLLocation) {
this.defineXMLLocation = defineXMLLocation;
}
public TreeNode getTargetNodes() {
if (tTree != null)
return tTree.getRootTreeNode();
else
return null;
}
public TreeNode getSourceNodes() {
if (sTree != null)
return sTree.getRootTreeNode();
else
return null;
}
public SDTMMappingGenerator getSdtmMappingGenerator() {
return sdtmMappingGenerator;
}
/**
* Returns an ImageIcon, or null if the path was invalid.
*/
protected static ImageIcon createImageIcon(String path) {
//java.net.URL imgURL = Database2SDTMMappingPanel.class.getResource(path);
java.net.URL imgURL = DefaultSettings.class.getClassLoader().getResource("images/" + path);
if (imgURL != null) {
//System.out.println("class.getResource is "+imgURL.toString());
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + imgURL.toString() + " & " + path);
return null;
}
}
private class SourceRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
ImageIcon tutorialIcon;
try {
String _tmpStr = (String) ((DefaultMutableTreeNode) value).getUserObject();
if (_tmpStr.equalsIgnoreCase("Data Model")) {
tutorialIcon = createImageIcon("database.png");
setIcon(tutorialIcon);
setToolTipText("Data model");
} else {
tutorialIcon = createImageIcon("schema.png");
setIcon(tutorialIcon);
setToolTipText("Schema");
}
return this;
} catch (Exception e) {
//continue;
}
try {
QBTableMetaData qbTableMetaData = (QBTableMetaData) ((DefaultSourceTreeNode) value).getUserObject();
if (qbTableMetaData.getType().equalsIgnoreCase("TABLE")) {
tutorialIcon = createImageIcon("table.png");
setIcon(tutorialIcon);
setToolTipText("Table");
} else if (qbTableMetaData.getType().equalsIgnoreCase("VIEW")) {
tutorialIcon = createImageIcon("view.png");
setIcon(tutorialIcon);
setToolTipText("View");
}
} catch (ClassCastException e) {
try {
QueryBuilderMeta queryBuilderMeta = (QueryBuilderMeta) ((DefaultSourceTreeNode) value).getUserObject();
setToolTipText("Column ; Type= " + queryBuilderMeta.getTypeName() + " ; Size= " + queryBuilderMeta.getColumnSize());
tutorialIcon = createImageIcon("column.png");
setIcon(tutorialIcon);
} catch (Exception ee) {
try {
//String queryBuilderMeta = (String) ((DefaultSourceTreeNode) value).getUserObject();
tutorialIcon = createImageIcon("load.gif");
setIcon(tutorialIcon);
} catch (Exception e1) {
setToolTipText(null);
}
}
}
return this;
}
}
private class TargetRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
ImageIcon tutorialIcon;
try {
String _tmpStr = (String) ((DefaultMutableTreeNode) value).getUserObject();
if (!_tmpStr.equalsIgnoreCase("SDTM Data Structure")) {
tutorialIcon = createImageIcon("book.png");
setIcon(tutorialIcon);
setToolTipText(_tmpStr);
} else {
tutorialIcon = createImageIcon("house.png");
setIcon(tutorialIcon);
setToolTipText("SDTM Root");
}
} catch (Exception e) {
SDTMMetadata sdtmMetadata = (SDTMMetadata) ((DefaultTargetTreeNode) value).getUserObject();
setToolTipText(sdtmMetadata.getName() + "; isMandatory " + sdtmMetadata.getMandatory());
tutorialIcon = createImageIcon("blue.png");
setIcon(tutorialIcon);
}
return this;
}
}
}
/**
* Change History
* $Log: not supported by cvs2svn $
* Revision 1.19 2007/09/13 13:51:41 jayannah
* Changes made to ensure that flow is correct, the save , reopen etc
*
* Revision 1.18 2007/09/11 15:31:42 jayannah
* made changes to pass the instance of the entire panel when the data viewer is opened
*
* Revision 1.17 2007/08/31 21:22:27 jayannah
* commented sysouts
*
* Revision 1.16 2007/08/29 21:26:52 jayannah
* fixed bugs to gracelfully cancel during times when database open is cancelled by the user and proper enabling and disabling of the buttons
*
* Revision 1.15 2007/08/29 21:01:00 jayannah
* Made sure that the buttons on the mapping panel are correctly disabled and enables depending on the which map file is opened
*
* Revision 1.14 2007/08/29 14:46:48 jayannah
* enabled the buttons for SCS file and Choose database if the user cancels during choosing a SCS file
*
* Revision 1.13 2007/08/22 14:27:06 jayannah
* show transform button
*
* Revision 1.12 2007/08/17 20:12:05 jayannah
* added a new image for QBAddButtons
* Reduced the height for viewing the 3 buttons in the center panel
*
* Revision 1.11 2007/08/17 15:55:52 jayannah
* Reformatted, the source file and enabled the button when the user cancelled the action
*
* Revision 1.10 2007/08/16 19:39:45 jayannah
* Reformatted and added the Comments and the log tags for all the files
*
*/
|
package gov.nih.nci.caadapter.ui.mapping.sdtm.actions;
import gov.nih.nci.caadapter.common.util.EmptyStringTokenizer;
import gov.nih.nci.caadapter.dataviewer.util.GetConnectionSingleton;
import gov.nih.nci.caadapter.dataviewer.util.QBParseMappingFile;
import gov.nih.nci.caadapter.sdtm.ParseSDTMXMLFile;
import gov.nih.nci.caadapter.sdtm.SDTMMetadata;
import gov.nih.nci.caadapter.sdtm.util.CSVMapFileReader;
import gov.nih.nci.caadapter.ui.common.AbstractMainFrame;
import gov.nih.nci.caadapter.ui.common.CaadapterFileFilter;
import gov.nih.nci.caadapter.ui.common.tree.DefaultTargetTreeNode;
import gov.nih.nci.caadapter.ui.mapping.sdtm.Database2SDTMMappingPanel;
import gov.nih.nci.caadapter.ui.mapping.sdtm.RDSFixedLenghtInput;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.prefs.Preferences;
public class QBTransformAction
{
JFileChooser directoryLoc, saveXLSLocation;
File directory;
private Connection con;
Preferences prefs;
HashMap fixedLengthRecords;
boolean fixedLengthIndicator = false;
public QBTransformAction(AbstractMainFrame _mainFrame, Database2SDTMMappingPanel mappingPanel, Connection _con, Preferences _prefs) throws Exception
{
//this(_mainFrame, mappingPanel, "");
this.con = _con;
directoryLoc = new JFileChooser(System.getProperty("user.dir"));
directoryLoc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = directoryLoc.showOpenDialog(_mainFrame);
this.prefs = _prefs;
if (prefs.get("FIXED_LENGTH_VAR", "NULL").equalsIgnoreCase("Fixed"))
{
fixedLengthIndicator = true;
CSVMapFileReader csvMapFileReader = new CSVMapFileReader(new File(mappingPanel.getSaveFile().getAbsolutePath()));
//Prepare the list here and keep it ready so that number of blanks corresponding to the
//value set by the user will be applied appropriately
RDSFixedLenghtInput rdsFixedLenghtInput = new RDSFixedLenghtInput(_mainFrame, csvMapFileReader.getTargetKeyList());
fixedLengthRecords = rdsFixedLenghtInput.getUserValues();
}
if (returnVal == JFileChooser.APPROVE_OPTION)
{
directory = directoryLoc.getSelectedFile();
try
{
processTransform1(mappingPanel.getSaveFile().getAbsolutePath(), mappingPanel.getDefineXMLLocation(), directory.getAbsolutePath().toString());
} catch (Exception e)
{
throw e;
} finally
{
GetConnectionSingleton.closeConnection();
}
}
}
public QBTransformAction(AbstractMainFrame _mainFrame, Database2SDTMMappingPanel mappingPanel, String newway)
{
CaadapterFileFilter filter = new CaadapterFileFilter();
filter.addExtension("xls");
filter.setDescription("xls");
saveXLSLocation = new JFileChooser(System.getProperty("user.dir"));
saveXLSLocation.setFileFilter(filter);
int returnVal = saveXLSLocation.showSaveDialog(_mainFrame);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
String xlsFileName = saveXLSLocation.getSelectedFile().toString();
if (!xlsFileName.endsWith(".xls"))
{
xlsFileName = xlsFileName + ".xls";
}
System.out.println(xlsFileName);
try
{
processTransform1(mappingPanel.getSaveFile().getAbsolutePath(), mappingPanel.getDefineXMLLocation(), directory.getAbsolutePath().toString());
} catch (Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String args[]) throws Exception
{
// new QBTransformAction().processTransform1("c:\\d2.map", "c:\\define.xml", "c:\\save.xls");
}
public static Connection getConnection() throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "hr", "hr");
}
public static Hashtable getAllFieldsForDomains(File SDTMXmlFile)
{
ParseSDTMXMLFile _parseSDTMFile = new ParseSDTMXMLFile(SDTMXmlFile.getAbsolutePath().toString());
ArrayList _retArray = _parseSDTMFile.getSDTMStructure();
Hashtable domainFieldsList = new Hashtable();
DefaultMutableTreeNode pNode = null;
String domainString = "";
ArrayList fieldsString = null;
String _tempHolder;
domainFieldsList = new Hashtable();
for (int k = 0; k < _retArray.size(); k++)
{
if (_retArray.get(k).toString().startsWith("KEY"))
{
if (fieldsString != null)
domainFieldsList.put(domainString, fieldsString);
fieldsString = new ArrayList();
EmptyStringTokenizer _str = new EmptyStringTokenizer(_retArray.get(k).toString(), ",");
pNode = new DefaultMutableTreeNode(_str.getTokenAt(1).substring(0, 2));
domainString = pNode.toString();
} else
{
EmptyStringTokenizer _str = new EmptyStringTokenizer(_retArray.get(k).toString(), ",");
_tempHolder = _str.getTokenAt(1);
pNode.add(new DefaultTargetTreeNode(new SDTMMetadata(pNode.toString(), _tempHolder, _str.getTokenAt(2), _str.getTokenAt(3), _str.getTokenAt(4))));
if (!_tempHolder.startsWith(domainString))
_tempHolder = domainString + "." + _tempHolder;
fieldsString.add(_tempHolder.substring(0, _tempHolder.indexOf('&')));
}
}
return domainFieldsList;
}
public void processTransform1(String savedMapFile, String defineXML, String xlsFile) throws Exception
{
try
{
QBParseMappingFile qb = new QBParseMappingFile(new File(savedMapFile));
Hashtable tempTable = getAllFieldsForDomains(new File(defineXML));
Iterator _iter = qb.getHashSQLfromMappings().keySet().iterator();
while (_iter.hasNext())
{
//get the domain name
String domainName = _iter.next().toString();
//create a file with domain name
FileWriter fstream = new FileWriter(xlsFile + "\\" + domainName + ".csv");
BufferedWriter out = new BufferedWriter(fstream);
//get the query and fire it
String query = qb.getHashSQLfromMappings().get(domainName);
ResultSet rs = con.createStatement().executeQuery(query);
//get all the columns for the 'domainName'
ArrayList columns = qb.getHashTableTransform().get(domainName);
out.write(tempTable.get(domainName).toString().substring(1, tempTable.get(domainName).toString().indexOf(']')));
ArrayList domainHeader = (ArrayList) tempTable.get(domainName);
//compute the number of commas for each mapped columnvalue and set if the retrieved value is
int rsIncrementer = 1;
while (rs.next())
{// each row begins here
try
{
// if(rsIncrementer == 5000)
// break;
int sizeOfEachRow = ((ArrayList) tempTable.get(domainName)).size();
ArrayList _tempArray = new ArrayList(sizeOfEachRow + 1);
for (int j = 0; j < (sizeOfEachRow + 1); j++)
{
_tempArray.add(" ");//add empty buffer
}
for (int i = 0; i < columns.size(); i++)
{
EmptyStringTokenizer emt = new EmptyStringTokenizer(columns.get(i).toString(), "~");
EmptyStringTokenizer getColumn = new EmptyStringTokenizer(emt.nextToken(), ".");
String _dataStr = rs.getString(getColumn.getTokenAt(1) + "_" + getColumn.getTokenAt(2));
String empt1 = emt.nextToken().toString();
int position = (new Integer(((ArrayList) tempTable.get(domainName)).indexOf(empt1)));
if (fixedLengthRecords.containsKey(empt1))
{
try
{
_tempArray = implementFixedRec(position, _dataStr, _tempArray, new Integer(fixedLengthRecords.get(empt1).toString()).intValue());
} catch (Exception e)
{
String runTimePrp = System.getProperty("debug", "false");
if (new Boolean(runTimePrp))
System.out.println("Problem for target field \"" + empt1 + "\" at position \"" + position + "\" and date was \"" + _dataStr + "\"");
}
} else
{
_tempArray.remove(position);
try
{
_tempArray.add(position, _dataStr);
} catch (Exception e)
{
System.out.println("error at " + position);
}
}
}
out.write("\n" + _tempArray.toString().substring(1, _tempArray.toString().indexOf(']')));
rsIncrementer++;
} catch (Exception e)
{
e.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
continue;
}
}// result set
out.close();
}
} catch (SQLException e)
{
System.out.println(e.getLocalizedMessage());
}
}
private ArrayList implementFixedRec(int position, String srcData, ArrayList _tempArray, int fixedsize) throws Exception
{
StringBuffer _setSize;
int finalSize = fixedsize - srcData.length();
_setSize = new StringBuffer();
_setSize.append(srcData);
for (int i = 0; i < finalSize; i++)
{
_setSize.append(" ");
}
_tempArray.add(position - 1, _setSize.toString());
return _tempArray;
}
}
|
package gov.nih.nci.cagrid.bdt.service;
import java.rmi.RemoteException;
import javax.naming.InitialContext;
import org.apache.axis.MessageContext;
import org.globus.wsrf.Constants;
import org.globus.wsrf.ResourceHome;
public abstract class BulkDataHandlerImplBase {
public BulkDataHandlerImplBase() throws RemoteException {
}
public ResourceHome getResourceHome(String resourceKey) throws Exception {
MessageContext ctx = MessageContext.getCurrentContext();
ResourceHome resourceHome = null;
String servicePath = ctx.getTargetService();
String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/" + resourceKey;
try {
javax.naming.Context initialContext = new InitialContext();
resourceHome = (ResourceHome) initialContext.lookup(jndiName);
} catch (Exception e) {
throw new Exception("Unable to instantiate resource home. : " + resourceKey, e);
}
return resourceHome;
}
}
|
package org.jboss.as.clustering.infinispan;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.LinkedHashSet;
import java.util.Set;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.manager.impl.AbstractDelegatingEmbeddedCacheManager;
import org.wildfly.clustering.infinispan.spi.CacheContainer;
import org.wildfly.clustering.service.SubGroupServiceNameFactory;
/**
* EmbeddedCacheManager decorator that overrides the default cache semantics of a cache manager.
* @author Paul Ferraro
*/
public class DefaultCacheContainer extends AbstractDelegatingEmbeddedCacheManager implements CacheContainer {
private final String name;
private final BatcherFactory batcherFactory;
private final String defaultCacheName;
public DefaultCacheContainer(String name, EmbeddedCacheManager container, String defaultCacheName) {
this(name, container, defaultCacheName, new InfinispanBatcherFactory());
}
public DefaultCacheContainer(String name, EmbeddedCacheManager container, String defaultCacheName, BatcherFactory batcherFactory) {
super(container);
this.name = name;
this.defaultCacheName = defaultCacheName;
this.batcherFactory = batcherFactory;
}
@Override
public String getName() {
return this.name;
}
@Override
public void start() {
// No-op. Lifecycle is managed by container
}
@Override
public void stop() {
// No-op. Lifecycle is managed by container
}
@Override
public String getDefaultCacheName() {
return this.defaultCacheName;
}
@Override
public Configuration defineConfiguration(String cacheName, Configuration configuration) {
return this.cm.defineConfiguration(this.getCacheName(cacheName), configuration);
}
@Override
public Configuration defineConfiguration(String cacheName, String templateCacheName, Configuration configurationOverride) {
return this.cm.defineConfiguration(this.getCacheName(cacheName), this.getCacheName(templateCacheName), configurationOverride);
}
@Override
public void undefineConfiguration(String cacheName) {
this.cm.undefineConfiguration(this.getCacheName(cacheName));
}
@Override
public Configuration getDefaultCacheConfiguration() {
return this.cm.getCacheConfiguration(this.defaultCacheName);
}
@Override
public Configuration getCacheConfiguration(String name) {
return this.cm.getCacheConfiguration(this.getCacheName(name));
}
/**
* {@inheritDoc}
* @see org.infinispan.manager.CacheContainer#getCache()
*/
@Override
public <K, V> Cache<K, V> getCache() {
return this.getCache(this.defaultCacheName);
}
@Override
public <K, V> Cache<K, V> getCache(String cacheName) {
return this.getCache(cacheName, cacheName);
}
@Override
public <K, V> Cache<K, V> getCache(String cacheName, String configurationName) {
Cache<K, V> cache;
if (System.getSecurityManager() == null) {
cache = this.getCacheInternal(cacheName, configurationName);
} else {
cache = AccessController.doPrivileged(new PrivilegedAction<Cache<K, V>>() {
@Override
public Cache<K, V> run() {
return getCacheInternal(cacheName, configurationName);
}
});
}
return (cache != null) ? new DefaultCache<>(this, this.batcherFactory, cache.getAdvancedCache()) : null;
}
private <K, V> Cache<K, V> getCacheInternal(String cacheName, String configurationName) {
return cm.<K, V>getCache(this.getCacheName(cacheName), this.getCacheName(configurationName));
}
@Override
public <K, V> Cache<K, V> getCache(String cacheName, boolean createIfAbsent) {
return this.getCache(cacheName, cacheName, createIfAbsent);
}
@Override
public <K, V> Cache<K, V> getCache(String cacheName, String configurationTemplate, boolean createIfAbsent) {
boolean cacheExists = this.cacheExists(cacheName);
return (cacheExists || createIfAbsent) ? this.getCache(cacheName, configurationTemplate) : null;
}
/**
* {@inheritDoc}
* @see org.infinispan.manager.EmbeddedCacheManager#isDefaultRunning()
*/
@Override
public boolean isDefaultRunning() {
return this.cm.isRunning(this.defaultCacheName);
}
/**
* {@inheritDoc}
* @see org.infinispan.manager.EmbeddedCacheManager#isRunning(String)
*/
@Override
public boolean isRunning(String cacheName) {
return this.cm.isRunning(this.getCacheName(cacheName));
}
/**
* {@inheritDoc}
* @see org.infinispan.manager.EmbeddedCacheManager#cacheExists(java.lang.String)
*/
@Override
public boolean cacheExists(String cacheName) {
return this.cm.cacheExists(this.getCacheName(cacheName));
}
/**
* {@inheritDoc}
* @see org.infinispan.manager.EmbeddedCacheManager#removeCache(java.lang.String)
*/
@Override
public void removeCache(String cacheName) {
this.cm.removeCache(this.getCacheName(cacheName));
}
@Override
public EmbeddedCacheManager startCaches(String... names) {
Set<String> cacheNames = new LinkedHashSet<>();
for (String name: names) {
cacheNames.add(this.getCacheName(name));
}
this.cm.startCaches(cacheNames.toArray(new String[cacheNames.size()]));
return this;
}
@Override
public void addCacheDependency(String from, String to) {
this.cm.addCacheDependency(this.getCacheName(from), this.getCacheName(to));
}
private String getCacheName(String name) {
return ((name == null) || name.equals(SubGroupServiceNameFactory.DEFAULT_SUB_GROUP)) ? this.defaultCacheName : name;
}
/**
* {@inheritDoc}
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.toString().hashCode();
}
/**
* {@inheritDoc}
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.cm.getCacheManagerConfiguration().globalJmxStatistics().cacheManagerName();
}
}
|
package org.phenotips.ontology.internal;
import org.phenotips.ontology.OntologyService;
import org.phenotips.ontology.OntologyTerm;
import org.xwiki.cache.Cache;
import org.xwiki.cache.CacheException;
import org.xwiki.cache.CacheManager;
import org.xwiki.cache.config.CacheConfiguration;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.component.util.ReflectionUtils;
import org.xwiki.configuration.ConfigurationSource;
import org.xwiki.test.mockito.MockitoComponentMockingRule;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.internal.matchers.CapturingMatcher;
import net.sf.json.JSONArray;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for the {@link GeneNomenclature} component.
*
* @version $Id$
*/
public class GeneNomenclatureTest
{
@Rule
public MockitoComponentMockingRule<OntologyService> mocker =
new MockitoComponentMockingRule<OntologyService>(GeneNomenclature.class);
private ConfigurationSource configuration;
@Mock
private CloseableHttpClient client;
@Mock
private CloseableHttpResponse response;
@Mock
private HttpEntity responseEntity;
@Mock
private Cache<OntologyTerm> cache;
@Mock
private OntologyTerm term;
private OntologyTerm emptyMarker;
@Before
public void setUp() throws ComponentLookupException, CacheException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException
{
MockitoAnnotations.initMocks(this);
when(this.mocker.<CacheManager>getInstance(CacheManager.class).<OntologyTerm>createNewLocalCache(
any(CacheConfiguration.class))).thenReturn(this.cache);
this.configuration = this.mocker.getInstance(ConfigurationSource.class, "xwikiproperties");
when(this.configuration.getProperty("phenotips.ontologies.hgnc.serviceURL", "http:
ReflectionUtils.setFieldValue(this.mocker.getComponentUnderTest(), "client", this.client);
Field em = ReflectionUtils.getField(GeneNomenclature.class, "EMPTY_MARKER");
em.setAccessible(true);
this.emptyMarker = (OntologyTerm) em.get(null);
}
@Test
public void checkURLConfigurable() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException, InitializationException
{
when(this.configuration.getProperty("phenotips.ontologies.hgnc.serviceURL", "http://rest.genenames.org/"))
.thenReturn("https://proxy/genenames/");
URI expectedURI = new URI("https://proxy/genenames/fetch/symbol/BRCA1");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("BRCA1.json"));
// Since the component was already initialized in setUp() with the default URL, re-initialize it
// with the new configuration mock
((Initializable) this.mocker.getComponentUnderTest()).initialize();
OntologyTerm result = this.mocker.getComponentUnderTest().getTerm("BRCA1");
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertNotNull(result);
Assert.assertEquals("BRCA1", result.get("symbol"));
Assert.assertEquals("breast cancer 1, early onset", result.getName());
JSONArray aliases = (JSONArray) result.get("alias_symbol");
Assert.assertArrayEquals(new String[] { "RNF53", "BRCC1", "PPP1R53" }, aliases.toArray());
verify(this.cache).set("BRCA1", result);
}
@Test
public void getTermFetchesFromRemoteServer() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI = new URI("http://rest.genenames.org/fetch/symbol/BRCA1");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("BRCA1.json"));
OntologyTerm result = this.mocker.getComponentUnderTest().getTerm("BRCA1");
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertNotNull(result);
Assert.assertEquals("BRCA1", result.get("symbol"));
Assert.assertEquals("breast cancer 1, early onset", result.getName());
JSONArray aliases = (JSONArray) result.get("alias_symbol");
Assert.assertArrayEquals(new String[] { "RNF53", "BRCC1", "PPP1R53" }, aliases.toArray());
verify(this.cache).set("BRCA1", result);
}
@Test
public void getTermUsesCache() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.cache.get("BRCA1")).thenReturn(this.term);
OntologyTerm result = this.mocker.getComponentUnderTest().getTerm("BRCA1");
verify(this.client, never()).execute(any(HttpUriRequest.class));
Assert.assertSame(this.term, result);
}
@Test
public void getTermWithInvalidTermReturnsNull() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI = new URI("http://rest.genenames.org/fetch/symbol/NOTHING");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("NOTHING.json"));
OntologyTerm result = this.mocker.getComponentUnderTest().getTerm("NOTHING");
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertNull(result);
verify(this.cache).set("NOTHING", this.emptyMarker);
}
@Test
public void getTermWithEmptyMarkerInCacheReturnsNull() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.cache.get("NOTHING")).thenReturn(this.emptyMarker);
OntologyTerm result = this.mocker.getComponentUnderTest().getTerm("NOTHING");
verify(this.client, never()).execute(any(HttpUriRequest.class));
Assert.assertNull(result);
}
@Test
public void getTermWithExceptionReturnsNull() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenThrow(new IOException());
OntologyTerm result = this.mocker.getComponentUnderTest().getTerm("ERROR");
Assert.assertNull(result);
}
@Test
public void getTermsFetchesFromRemoteServer() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI1 = new URI("http://rest.genenames.org/fetch/symbol/BRCA1");
URI expectedURI2 = new URI("http://rest.genenames.org/fetch/symbol/NOTHING");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("BRCA1.json"),
ClassLoader.getSystemResourceAsStream("NOTHING.json"));
Set<OntologyTerm> result = this.mocker.getComponentUnderTest().getTerms(Arrays.asList("BRCA1", "NOTHING"));
List<HttpUriRequest> calledURIs = reqCapture.getAllValues();
Assert.assertEquals(expectedURI1, calledURIs.get(0).getURI());
Assert.assertEquals(expectedURI2, calledURIs.get(1).getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertEquals(1, result.size());
Assert.assertEquals("BRCA1", result.iterator().next().getId());
}
@Test
public void getStringDistanceIsFlat() throws ComponentLookupException
{
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance("A", "B"));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance("A", "A"));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance("A", null));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance(null, "B"));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance((String) null, null));
}
@Test
public void getTermDistanceIsFlat() throws ComponentLookupException
{
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance(this.term, this.term));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance(this.term, mock(OntologyTerm.class)));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance(this.term, null));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance(null, this.term));
Assert.assertEquals(-1, this.mocker.getComponentUnderTest().getDistance((OntologyTerm) null, null));
}
@Test
public void getSizeFetchesFromRemoteServer() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI = new URI("http://rest.genenames.org/info");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("info.json"));
long result = this.mocker.getComponentUnderTest().size();
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertEquals(40045, result);
}
@Test
public void getSizeWithErrorReturnsNegative1() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenThrow(new IOException());
long result = this.mocker.getComponentUnderTest().size();
Assert.assertEquals(-1, result);
}
@Test
public void getVersionFetchesFromRemoteServer() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI = new URI("http://rest.genenames.org/info");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("info.json"));
String result = this.mocker.getComponentUnderTest().getVersion();
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertEquals("2014-09-01T04:42:14.649Z", result);
}
@Test
public void getVersionWithErrorReturnsEmptyString() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenThrow(new IOException());
String result = this.mocker.getComponentUnderTest().getVersion();
Assert.assertEquals("", result);
}
@Test
public void reindexInvalidatesCache() throws ComponentLookupException
{
Assert.assertEquals(0, this.mocker.getComponentUnderTest().reindex(null));
Mockito.verify(this.cache).removeAll();
Mockito.verifyNoMoreInteractions(this.client);
}
@Test
public void checkReturnedTermsBehavior() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("BRCA1.json"));
OntologyTerm result = this.mocker.getComponentUnderTest().getTerm("BRCA1");
Assert.assertEquals("BRCA1", result.get("symbol"));
Assert.assertEquals("breast cancer 1, early onset", result.getName());
Assert.assertEquals("", result.getDescription());
Assert.assertEquals(-1, result.getDistanceTo(null));
Assert.assertEquals(-1, result.getDistanceTo(result));
Assert.assertEquals(-1, result.getDistanceTo(mock(OntologyTerm.class)));
Assert.assertEquals(this.mocker.getComponentUnderTest(), result.getOntology());
Assert.assertTrue(result.getParents().isEmpty());
Assert.assertTrue(result.getAncestors().isEmpty());
Assert.assertEquals(1, result.getAncestorsAndSelf().size());
Assert.assertTrue(result.getAncestorsAndSelf().contains(result));
Assert.assertEquals("BRCA1", result.getId());
Assert.assertEquals("HGNC:BRCA1", result.toString());
}
@Test
public void searchFetchesFromRemoteServer() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI = new URI("http://rest.genenames.org/search/"
+ "+status%3A%28Approved%29+AND+%28+symbol%3A%28brcA*%29+alias_symbol%3A%28brcA*%29%29");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("brca.json"));
Map<String, Object> search = new LinkedHashMap<>();
search.put("status", "Approved");
Map<String, String> subquery = new LinkedHashMap<>();
subquery.put("symbol", "brcA*");
subquery.put("alias_symbol", "brcA*");
search.put("AND", subquery);
Map<String, String> queryOptions = new LinkedHashMap<>();
queryOptions.put("start", "3");
queryOptions.put("rows", "2");
Set<OntologyTerm> result = this.mocker.getComponentUnderTest().search(search, queryOptions);
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertEquals(2, result.size());
Iterator<OntologyTerm> terms = result.iterator();
Assert.assertEquals("BRCA1", terms.next().getId());
Assert.assertEquals("BRCA1P1", terms.next().getId());
}
@Test
public void searchWithErrorReturnsEmptySet() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenThrow(new IOException());
Set<OntologyTerm> result = this.mocker.getComponentUnderTest().search(new HashMap<String, Object>());
Assert.assertTrue(result.isEmpty());
}
@Test
public void searchIgnoresBadOptions() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("brca.json"));
this.responseEntity.getContent().mark(5000);
Map<String, Object> search = new LinkedHashMap<>();
search.put("status", "Approved");
Map<String, String> queryOptions = new LinkedHashMap<>();
queryOptions.put("start", "three");
queryOptions.put("rows", "");
Assert.assertEquals(6, this.mocker.getComponentUnderTest().search(search, queryOptions).size());
this.responseEntity.getContent().reset();
queryOptions.put("start", "2");
queryOptions.put("rows", "100");
Assert.assertEquals(4, this.mocker.getComponentUnderTest().search(search, queryOptions).size());
this.responseEntity.getContent().reset();
queryOptions.put("start", "-2");
queryOptions.put("rows", "-3");
Assert.assertEquals(6, this.mocker.getComponentUnderTest().search(search, queryOptions).size());
}
@Test
public void countFetchesFromRemoteServer() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
URI expectedURI = new URI("http://rest.genenames.org/search/"
+ "+status%3A%28Approved%29+AND+%28+symbol%3A%28brcA*%29+alias_symbol%3A%28brcA*%29%29");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("brca.json"));
Map<String, Object> search = new LinkedHashMap<>();
search.put("status", "Approved");
Map<String, String> subquery = new LinkedHashMap<>();
subquery.put("symbol", "brcA*");
subquery.put("alias_symbol", "brcA*");
search.put("AND", subquery);
long result = this.mocker.getComponentUnderTest().count(search);
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
Assert.assertEquals(6, result);
}
@Test
public void countWithExceptionReturnsZero() throws ComponentLookupException, URISyntaxException,
ClientProtocolException, IOException
{
when(this.client.execute(any(HttpUriRequest.class))).thenThrow(new IOException());
long result = this.mocker.getComponentUnderTest().count(new HashMap<String, Object>());
Assert.assertEquals(0, result);
}
@Test
public void testQueryBuilder() throws URISyntaxException, ClientProtocolException, IOException,
ComponentLookupException
{
URI expectedURI = new URI("http://rest.genenames.org/search/+status%3A%28Approved%29"
+ "+AND+locus_type%3A%28RNA%2C%5C+cluster+RNA%2C%5C+micro*+%29"
+ "+%28+symbol%3A%28br%5C%3AcA*%29+alias_symbol%3A%28br%5C%5EcA*%29%29"
+ "+AND+%28+locus_group%3A%28non%5C-coding%5C+RNA%29%29+-%28+symbol%3A%28M*%29%29");
CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
when(this.response.getEntity()).thenReturn(this.responseEntity);
when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("NOTHING.json"));
Map<String, Object> search = new LinkedHashMap<>();
search.put("status", "Approved");
search.put("locus_type", Arrays.asList("RNA, cluster", "RNA, micro*"));
search.put("hgnc_id", Collections.emptyList());
Map<String, String> subquery = new LinkedHashMap<>();
subquery.put("symbol", "br:cA*");
subquery.put("alias_symbol", "br^cA*");
search.put("OR", subquery);
subquery = new LinkedHashMap<>();
subquery.put("locus_group", "non-coding RNA");
search.put("AND", subquery);
subquery = new LinkedHashMap<>();
subquery.put("symbol", "M*");
search.put("NOT", subquery);
subquery = new LinkedHashMap<>();
subquery.put("what", "where");
search.put("DISCARD", subquery);
this.mocker.getComponentUnderTest().search(search);
Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
}
@Test
public void getAliases() throws ComponentLookupException
{
Set<String> aliases = this.mocker.getComponentUnderTest().getAliases();
Assert.assertTrue(aliases.contains("hgnc"));
Assert.assertTrue(aliases.contains("HGNC"));
}
@Test
public void getDefaultOntologyLocation() throws ComponentLookupException
{
String location = this.mocker.getComponentUnderTest().getDefaultOntologyLocation();
Assert.assertEquals("http://rest.genenames.org/", location);
}
}
|
package soot.jimple.infoflow;
import heros.FlowFunction;
import heros.FlowFunctions;
import heros.InterproceduralCFG;
import heros.flowfunc.Identity;
import heros.solver.PathEdge;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import soot.Local;
import soot.NullType;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.infoflow.data.Abstraction;
import soot.jimple.infoflow.data.AbstractionWithPath;
import soot.jimple.infoflow.data.AccessPath;
import soot.jimple.infoflow.heros.InfoflowSolver;
import soot.jimple.infoflow.source.DefaultSourceSinkManager;
import soot.jimple.infoflow.source.ISourceSinkManager;
import soot.jimple.infoflow.util.BaseSelector;
import soot.jimple.internal.JInstanceFieldRef;
import soot.jimple.internal.JimpleLocal;
import soot.jimple.toolkits.ide.icfg.JimpleBasedBiDiICFG;
public class InfoflowProblem extends AbstractInfoflowProblem {
InfoflowSolver bSolver;
private final static boolean DEBUG = false;
final ISourceSinkManager sourceSinkManager;
Abstraction zeroValue = null;
/**
* Computes the taints produced by a taint wrapper object
* @param iStmt The call statement the taint wrapper shall check for well-
* known methods that introduce black-box taint propagation
* @param callArgs The actual parameters with which the method in invoked
* @param source The taint source
* @return The taints computed by the wrapper
*/
private Set<Abstraction> computeWrapperTaints
(final Stmt iStmt,
final List<Value> callArgs,
Abstraction source) {
Set<Abstraction> res = new HashSet<Abstraction>();
if(taintWrapper == null || !taintWrapper.supportsTaintWrappingForClass(iStmt.getInvokeExpr().getMethod().getDeclaringClass()))
return Collections.emptySet();
int taintedPos = -1;
for(int i=0; i< callArgs.size(); i++){
if(source.getAccessPath().isLocal() && callArgs.get(i).equals(source.getAccessPath().getPlainValue())){
taintedPos = i;
break;
}
}
Value taintedBase = null;
if(iStmt.getInvokeExpr() instanceof InstanceInvokeExpr){
InstanceInvokeExpr iiExpr = (InstanceInvokeExpr) iStmt.getInvokeExpr();
if(iiExpr.getBase().equals(source.getAccessPath().getPlainValue())){
if(source.getAccessPath().isLocal()){
taintedBase = iiExpr.getBase();
}
else if(source.getAccessPath().isInstanceFieldRef()){
// The taint refers to the actual type of the field, not the formal type,
// so we must check whether we have the tainted field at all
SootClass callerClass = interproceduralCFG().getMethodOf(iStmt).getDeclaringClass();
if (callerClass.getFields().contains(source.getAccessPath().getFirstField()))
taintedBase = new JInstanceFieldRef(iiExpr.getBase(),
callerClass.getFieldByName(source.getAccessPath().getFirstField().getName()).makeRef());
}
}
}
Set<AccessPath> vals = taintWrapper.getTaintsForMethod(iStmt, taintedPos, taintedBase);
if(vals != null) {
for (AccessPath val : vals) {
Abstraction newAbs = source.deriveNewAbstraction(val, iStmt);
if (pathTracking == PathTrackingMethod.ForwardTracking)
((AbstractionWithPath) newAbs).addPathElement(iStmt);
res.add(newAbs);
// If the taint wrapper taints the base object (new taint), this must be propagated
// backwards as there might be aliases for the base object
if(taintedBase == null && iStmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iiExpr = (InstanceInvokeExpr) iStmt.getInvokeExpr();
if ((iiExpr.getBase().equals(newAbs.getAccessPath().getPlainValue())
|| newAbs.getAccessPath().isStaticFieldRef())){
Abstraction bwAbs = source.deriveNewAbstraction(val,iStmt, false);
for (Unit predUnit : interproceduralCFG().getPredsOf(iStmt))
bSolver.processEdge(new PathEdge<Unit, Abstraction, SootMethod>(bwAbs, predUnit, bwAbs));
}
}
}
}
// For the moment, we don't implement static taints on wrappers. Pass it on
// not to break anything
if(source.getAccessPath().isStaticFieldRef())
res.add(source);
return res;
}
/**
* Checks whether a taint wrapper is exclusive for a specific invocation statement
* @param iStmt The call statement the taint wrapper shall check for well-
* known methods that introduce black-box taint propagation
* @param callArgs The actual parameters with which the method in invoked
* @param source The taint source
* @return True if the wrapper is exclusive, otherwise false
*/
private boolean isWrapperExclusive
(final Stmt iStmt,
final List<Value> callArgs,
Abstraction source) {
if(taintWrapper == null || !taintWrapper.supportsTaintWrappingForClass(iStmt.getInvokeExpr().getMethod().getDeclaringClass()))
return false;
int taintedPos = -1;
for(int i=0; i< callArgs.size(); i++){
if(source.getAccessPath().isLocal() && callArgs.get(i).equals(source.getAccessPath().getPlainValue())){
taintedPos = i;
break;
}
}
Value taintedBase = null;
if(iStmt.getInvokeExpr() instanceof InstanceInvokeExpr){
InstanceInvokeExpr iiExpr = (InstanceInvokeExpr) iStmt.getInvokeExpr();
if(iiExpr.getBase().equals(source.getAccessPath().getPlainValue())){
if(source.getAccessPath().isLocal()){
taintedBase = iiExpr.getBase();
}else if(source.getAccessPath().isInstanceFieldRef()){
// The taint refers to the actual type of the field, not the formal type,
// so we must check whether we have the tainted field at all
SootClass callerClass = interproceduralCFG().getMethodOf(iStmt).getDeclaringClass();
if (callerClass.getFields().contains(source.getAccessPath().getFirstField()))
taintedBase = new JInstanceFieldRef(iiExpr.getBase(),
callerClass.getFieldByName(source.getAccessPath().getFirstField().getName()).makeRef());
}
}
if(source.getAccessPath().isStaticFieldRef()){
//TODO
}
}
return taintWrapper.isExclusive(iStmt, taintedPos, taintedBase);
}
@Override
public FlowFunctions<Unit, Abstraction, SootMethod> createFlowFunctionsFactory() {
return new FlowFunctions<Unit, Abstraction, SootMethod>() {
/**
* Creates a new taint abstraction for the given value
* @param src The source statement from which the taint originated
* @param targetValue The target value that shall now be tainted
* @param source The incoming taint abstraction from the source
* @param taintSet The taint set to which to add all newly produced
* taints
*/
private void addTaintViaStmt
(final Unit src,
final Value targetValue,
Abstraction source,
Set<Abstraction> taintSet,
boolean cutFirstField) {
taintSet.add(source);
Abstraction newAbs = source.deriveNewAbstraction(targetValue, cutFirstField, src);
if (pathTracking == PathTrackingMethod.ForwardTracking)
((AbstractionWithPath) newAbs).addPathElement(src);
taintSet.add(newAbs);
//only heap-objects
if (triggerInaktiveTaintOrReverseFlow(targetValue, source)) {
// call backwards-check:
Abstraction bwAbs = newAbs.deriveInactiveAbstraction();
for (Unit predUnit : interproceduralCFG().getPredsOf(src)){
bSolver.processEdge(new PathEdge<Unit, Abstraction, SootMethod>(bwAbs, predUnit, bwAbs));
}
}
}
@Override
public FlowFunction<Abstraction> getNormalFlowFunction(final Unit src, final Unit dest) {
// If we compute flows on parameters, we create the initial
// flow fact here
if (src instanceof IdentityStmt) {
final IdentityStmt is = (IdentityStmt) src;
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
Set<Abstraction> res = new HashSet<Abstraction>();
boolean addOriginal = true;
if (is.getRightOp() instanceof CaughtExceptionRef) {
if (source.getExceptionThrown()) {
res.add(source.deriveNewAbstractionOnCatch(is.getLeftOp(), is));
addOriginal = false;
}
}
if (addOriginal)
res.add(source);
if (sourceSinkManager.isSource(is, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
res.add(new AbstractionWithPath(is.getLeftOp(),
is.getRightOp(),
is, false, true, is).addPathElement(is));
else
res.add(new Abstraction(is.getLeftOp(),
is.getRightOp(), is, false, true, is));
}
return res;
}
};
}
// taint is propagated with assignStmt
else if (src instanceof AssignStmt) {
final AssignStmt assignStmt = (AssignStmt) src;
Value right = assignStmt.getRightOp();
Value left = assignStmt.getLeftOp();
final Value leftValue = BaseSelector.selectBase(left, false);
final Set<Value> rightVals = BaseSelector.selectBaseList(right, true);
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
boolean addLeftValue = false;
boolean cutFirstField = false;
Set<Abstraction> res = new HashSet<Abstraction>();
// shortcuts:
// on NormalFlow taint cannot be created
if (source.equals(zeroValue)) {
return Collections.emptySet();
}
Abstraction newSource;
if (!source.isAbstractionActive() && (src.equals(source.getActivationUnit()) || src.equals(source.getActivationUnitOnCurrentLevel()))){
newSource = source.getActiveCopy(false);
}else{
newSource = source;
}
for (Value rightValue : rightVals) {
// check if static variable is tainted (same name, same class)
//y = X.f && X.f tainted --> y, X.f tainted
if (newSource.getAccessPath().isStaticFieldRef()) {
if (rightValue instanceof StaticFieldRef) {
StaticFieldRef rightRef = (StaticFieldRef) rightValue;
if (newSource.getAccessPath().getFirstField().equals(rightRef.getField())) {
addLeftValue = true; //TODO: check all fields --> create Testcase for this!
cutFirstField = true;
}
}
} else {
// if both are fields, we have to compare their fieldName via equals and their bases
//y = x.f && x tainted --> y, x tainted
//y = x.f && x.f tainted --> y, x tainted
if (rightValue instanceof InstanceFieldRef) {
InstanceFieldRef rightRef = (InstanceFieldRef) rightValue;
Local rightBase = (Local) rightRef.getBase();
Local sourceBase = newSource.getAccessPath().getPlainLocal();
if (rightBase.equals(sourceBase)) {
if (newSource.getAccessPath().isInstanceFieldRef()) {
if (rightRef.getField().equals(newSource.getAccessPath().getFirstField())) {
addLeftValue = true;
cutFirstField = true;
}
} else {
addLeftValue = true;
}
}
}
// indirect taint propagation:
// if rightvalue is local and source is instancefield of this local:
// y = x && x.f tainted --> y.f, x.f tainted
// y.g = x && x.f tainted --> y.g.f, x.f tainted
if (rightValue instanceof Local && newSource.getAccessPath().isInstanceFieldRef()) {
Local base = newSource.getAccessPath().getPlainLocal();
if (rightValue.equals(base)) {
if (leftValue instanceof Local) {
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(((AbstractionWithPath) newSource.deriveNewAbstraction
(newSource.getAccessPath().copyWithNewValue(leftValue), assignStmt)).addPathElement(src));
else
res.add(newSource.deriveNewAbstraction(newSource.getAccessPath().copyWithNewValue(leftValue), assignStmt));
} else {
// access path length = 1 - taint entire value if left is field reference
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(((AbstractionWithPath) newSource.deriveNewAbstraction(leftValue, assignStmt))
.addPathElement(src));
else
res.add(newSource.deriveNewAbstraction(leftValue, assignStmt));
}
}
}
if (rightValue instanceof ArrayRef) {
//y = x[i] && x tainted -> x, y tainted
Local rightBase = (Local) ((ArrayRef) rightValue).getBase();
if (rightBase.equals(newSource.getAccessPath().getPlainValue())) {
addLeftValue = true;
}
}
// generic case, is true for Locals, ArrayRefs that are equal etc..
//y = x && x tainted --> y, x tainted
if (rightValue.equals(newSource.getAccessPath().getPlainValue())) {
addLeftValue = true;
}
}
}
// if one of them is true -> add leftValue
if (addLeftValue) {
if (sourceSinkManager.isSink(assignStmt, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(leftValue, assignStmt,
newSource.getSource(),
newSource.getSourceContext(),
((AbstractionWithPath) newSource).getPropagationPathAsString(interproceduralCFG()),
assignStmt.toString());
else
results.addResult(leftValue, assignStmt,
newSource.getSource(), newSource.getSourceContext());
}
if(triggerInaktiveTaintOrReverseFlow(leftValue, newSource) || newSource.isAbstractionActive()) {
SootMethod sm = interproceduralCFG().getMethodOf(src);
addTaintViaStmt(src, leftValue, newSource, res, cutFirstField);
}
return res;
}
//if leftvalue contains the tainted value -> it is overwritten - remove taint:
//but not for arrayRefs:
// x[i] = y --> taint is preserved since we do not distinguish between elements of collections
//because we do not use a MUST-Alias analysis, we cannot delete aliases of taints
if(((AssignStmt)src).getLeftOp() instanceof ArrayRef){
return Collections.singleton(newSource);
}
if(newSource.getAccessPath().isInstanceFieldRef()){
//x.f = y && x.f tainted --> no taint propagated
if (leftValue instanceof InstanceFieldRef) {
InstanceFieldRef leftRef = (InstanceFieldRef) leftValue;
if (leftRef.getBase().equals(newSource.getAccessPath().getPlainValue())) {
if (leftRef.getField().equals(newSource.getAccessPath().getFirstField())) {
if(newSource.isAbstractionActive()){
return Collections.emptySet();
}else{
//start backward:
for (Value rightValue : rightVals) {
Abstraction newAbs = newSource.deriveNewAbstraction(rightValue, true, src);
if (triggerInaktiveTaintOrReverseFlow(rightValue, newAbs)) {
Abstraction bwAbs = newAbs.deriveInactiveAbstraction();
// for (Unit predUnit : interproceduralCFG().getPredsOf(src))
// bSolver.processEdge(new PathEdge<Unit, Abstraction, SootMethod>(bwAbs, predUnit, bwAbs));
}
}
}
}
}
//x = y && x.f tainted -> no taint propagated
}else if (leftValue instanceof Local){
if (leftValue.equals(newSource.getAccessPath().getPlainValue())) {
if(newSource.isAbstractionActive()){
return Collections.emptySet();
}else{
//start backward:
for (Value rightValue : rightVals) {
Abstraction newAbs = newSource.deriveNewAbstraction(rightValue, false, src);
if (triggerInaktiveTaintOrReverseFlow(rightValue, newAbs)) {
Abstraction bwAbs = newAbs.deriveInactiveAbstraction();
// for (Unit predUnit : interproceduralCFG().getPredsOf(src))
// bSolver.processEdge(new PathEdge<Unit, Abstraction, SootMethod>(bwAbs, predUnit, bwAbs));
}
}
}
}
}
}else if(newSource.getAccessPath().isStaticFieldRef()){
//X.f = y && X.f tainted -> no taint propagated
if(leftValue instanceof StaticFieldRef && ((StaticFieldRef)leftValue).getField().equals(newSource.getAccessPath().getFirstField())){
if(newSource.isAbstractionActive()){
return Collections.emptySet();
}else{
//start backward:
for (Value rightValue : rightVals) {
Abstraction newAbs = newSource.deriveNewAbstraction(rightValue, false, src);
if (triggerInaktiveTaintOrReverseFlow(rightValue, newAbs)) {
Abstraction bwAbs = newAbs.deriveInactiveAbstraction();
// for (Unit predUnit : interproceduralCFG().getPredsOf(src))
// bSolver.processEdge(new PathEdge<Unit, Abstraction, SootMethod>(bwAbs, predUnit, bwAbs));
}
}
}
}
}
//when the fields of an object are tainted, but the base object is overwritten then the fields should not be tainted any more
//x = y && x.f tainted -> no taint propagated
if(newSource.getAccessPath().isLocal() && leftValue.equals(newSource.getAccessPath().getPlainValue())){
if(newSource.isAbstractionActive()){
return Collections.emptySet();
}
}
//nothing applies: z = y && x tainted -> taint is preserved
return Collections.singleton(newSource);
}
};
}
// for unbalanced problems, return statements correspond to
// normal flows, not return flows, because there is no return
// site we could jump to
else if (src instanceof ReturnStmt) {
final ReturnStmt returnStmt = (ReturnStmt) src;
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (returnStmt.getOp().equals(source.getAccessPath().getPlainValue()) && sourceSinkManager.isSink(returnStmt, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(returnStmt.getOp(), returnStmt,
source.getSource(),
source.getSourceContext(),
((AbstractionWithPath) source).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(returnStmt) + ": " + returnStmt.toString());
else
results.addResult(returnStmt.getOp(), returnStmt,
source.getSource(), source.getSourceContext());
}
return Collections.singleton(source);
}
};
}
else if (src instanceof ThrowStmt) {
final ThrowStmt throwStmt = (ThrowStmt) src;
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (throwStmt.getOp().equals(source.getAccessPath().getPlainLocal()))
return Collections.singleton(source.deriveNewAbstractionOnThrow());
return Collections.singleton(source);
}
};
}
return Identity.v();
}
@Override
public FlowFunction<Abstraction> getCallFlowFunction(final Unit src, final SootMethod dest) {
final Stmt stmt = (Stmt) src;
final InvokeExpr ie = stmt.getInvokeExpr();
final List<Value> callArgs = ie.getArgs();
final List<Value> paramLocals = new ArrayList<Value>();
for (int i = 0; i < dest.getParameterCount(); i++) {
paramLocals.add(dest.getActiveBody().getParameterLocal(i));
}
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (source.equals(zeroValue)) {
return Collections.singleton(source);
}
if(isWrapperExclusive(stmt, callArgs, source)) {
//taint is propagated in CallToReturnFunction, so we do not need any taint here:
return Collections.emptySet();
}
//if we do not have to look into sinks:
if (!inspectSinks && sourceSinkManager.isSink(stmt, interproceduralCFG())) {
return Collections.emptySet();
}
Abstraction newSource = source;
Set<Abstraction> res = new HashSet<Abstraction>();
// check if whole object is tainted (happens with strings, for example:)
if (!dest.isStatic() && ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) ie;
// this might be enough because every call must happen with a local variable which is tainted itself:
if (vie.getBase().equals(newSource.getAccessPath().getPlainValue())) {
Abstraction abs = newSource.deriveNewAbstraction(newSource.getAccessPath().copyWithNewValue
(dest.getActiveBody().getThisLocal()));
if (pathTracking == PathTrackingMethod.ForwardTracking)
((AbstractionWithPath) abs).addPathElement(stmt);
//add new callArgs:
assert abs != newSource; // our source abstraction must be immutable
abs.setAbstractionFromCallEdge(abs.clone());
res.add(abs);
}
}
//special treatment for clinit methods - no param mapping possible
if(!dest.getName().equals("<clinit>")) {
assert dest.getParameterCount() == callArgs.size();
// check if param is tainted:
for (int i = 0; i < callArgs.size(); i++) {
if (callArgs.get(i).equals(newSource.getAccessPath().getPlainLocal()) &&
(triggerInaktiveTaintOrReverseFlow(callArgs.get(i), newSource) || newSource.isAbstractionActive())) {
Abstraction abs = newSource.deriveNewAbstraction(newSource.getAccessPath().copyWithNewValue
(paramLocals.get(i)), stmt);
if (pathTracking == PathTrackingMethod.ForwardTracking)
((AbstractionWithPath) abs).addPathElement(stmt);
assert abs != newSource; // our source abstraction must be immutable
abs.setAbstractionFromCallEdge(abs.clone());
res.add(abs);
}
}
}
// staticfieldRefs must be analyzed even if they are not part of the params:
if (newSource.getAccessPath().isStaticFieldRef()) {
Abstraction abs;
abs = newSource.clone();
assert (abs.equals(newSource) && abs.hashCode() == newSource.hashCode());
assert abs != newSource; // our source abstraction must be immutable
abs.setAbstractionFromCallEdge(abs.clone());
res.add(abs);
}
return res;
}
};
}
@Override
public FlowFunction<Abstraction> getReturnFlowFunction(final Unit callSite, final SootMethod callee, final Unit exitStmt, final Unit retSite) {
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
if (source.equals(zeroValue)) {
return Collections.emptySet();
}
Abstraction newSource;
if(!source.isAbstractionActive()){
if(callSite.equals(source.getActivationUnit()) || callSite.equals(source.getActivationUnitOnCurrentLevel()) ){
newSource = source.getActiveCopy(true);
}else{
newSource = source.cloneUsePredAbstractionOfCG();
}
}else{
newSource = source.cloneUsePredAbstractionOfCG();
}
//if abstraction is not active and activeStmt was in this method, it will not get activated = it can be removed:
if(!newSource.isAbstractionActive() && newSource.getActivationUnit() != null && interproceduralCFG().getMethodOf(newSource.getActivationUnit()).equals(callee)){
return Collections.emptySet();
}
Set<Abstraction> res = new HashSet<Abstraction>();
// if we have a returnStmt we have to look at the returned value:
if (exitStmt instanceof ReturnStmt) {
ReturnStmt returnStmt = (ReturnStmt) exitStmt;
Value retLocal = returnStmt.getOp();
if (callSite instanceof DefinitionStmt) {
DefinitionStmt defnStmt = (DefinitionStmt) callSite;
Value leftOp = defnStmt.getLeftOp();
if (retLocal.equals(newSource.getAccessPath().getPlainLocal()) &&
(triggerInaktiveTaintOrReverseFlow(leftOp, newSource) || newSource.isAbstractionActive())) {
Abstraction abs = newSource.deriveNewAbstraction(newSource.getAccessPath().copyWithNewValue(leftOp), callSite);
if (pathTracking == PathTrackingMethod.ForwardTracking)
((AbstractionWithPath) abs).addPathElement(exitStmt);
assert abs != newSource; // our source abstraction must be immutable
res.add(abs);
//call backwards-solver:
if(triggerInaktiveTaintOrReverseFlow(leftOp, abs) && abs.isAbstractionActive()){
Abstraction bwAbs = newSource.deriveNewAbstraction(newSource.getAccessPath().copyWithNewValue(leftOp), callSite, false);
bwAbs = bwAbs.getAbstractionWithNewActivationUnitOnCurrentLevel(callSite);
for (Unit predUnit : interproceduralCFG().getPredsOf(callSite))
bSolver.processEdge(new PathEdge<Unit, Abstraction, SootMethod>(bwAbs, predUnit, bwAbs));
}
}
}
// Check whether this return is treated as a sink
assert returnStmt.getOp() == null
|| returnStmt.getOp() instanceof Local
|| returnStmt.getOp() instanceof Constant;
if (returnStmt.getOp() != null
&& newSource.getAccessPath().isLocal()
&& newSource.getAccessPath().getPlainValue().equals(returnStmt.getOp())
&& sourceSinkManager.isSink(returnStmt, interproceduralCFG())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(returnStmt.getOp(), returnStmt,
newSource.getSource(),
newSource.getSourceContext(),
((AbstractionWithPath) newSource).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(returnStmt) + ": " + returnStmt.toString());
else
results.addResult(returnStmt.getOp(), returnStmt,
newSource.getSource(), newSource.getSourceContext());
}
}
// easy: static
if (newSource.getAccessPath().isStaticFieldRef() && newSource.isAbstractionActive()) {
Abstraction abs = newSource.clone();
assert (abs.equals(newSource) && abs.hashCode() == newSource.hashCode());
res.add(abs);
// call backwards-check:
Abstraction bwAbs = newSource.deriveInactiveAbstraction();
bwAbs = bwAbs.getAbstractionWithNewActivationUnitOnCurrentLevel(callSite);
for (Unit predUnit : interproceduralCFG().getPredsOf(callSite))
bSolver.processEdge(new PathEdge<Unit, Abstraction, SootMethod>(bwAbs, predUnit, bwAbs));
}
// checks: this/params/fields
// check one of the call params are tainted (not if simple type)
Value sourceBase = newSource.getAccessPath().getPlainLocal();
Value originalCallArg = null;
for (int i = 0; i < callee.getParameterCount(); i++) {
if (callee.getActiveBody().getParameterLocal(i).equals(sourceBase)) {
if (callSite instanceof Stmt) {
Stmt iStmt = (Stmt) callSite;
originalCallArg = iStmt.getInvokeExpr().getArg(i);
//either the param is a fieldref (not possible in jimple?) or an array Or one of its fields is tainted/all fields are tainted
if (triggerInaktiveTaintOrReverseFlow(originalCallArg, newSource)) {
Abstraction abs = newSource.deriveNewAbstraction(newSource.getAccessPath().copyWithNewValue(originalCallArg), callSite);
if (pathTracking == PathTrackingMethod.ForwardTracking)
abs = ((AbstractionWithPath) abs).addPathElement(exitStmt);
res.add(abs);
if(triggerInaktiveTaintOrReverseFlow(originalCallArg, abs) && abs.isAbstractionActive()){
// call backwards-check:
Abstraction bwAbs = abs.deriveInactiveAbstraction();
bwAbs = bwAbs.getAbstractionWithNewActivationUnitOnCurrentLevel(callSite);
SootMethod sm = interproceduralCFG().getMethodOf(callSite);
for (Unit predUnit : interproceduralCFG().getPredsOf(callSite))
bSolver.processEdge(new PathEdge<Unit, Abstraction, SootMethod>(bwAbs, predUnit, bwAbs));
}
}
}
}
}
Local thisL = null;
if (!callee.isStatic()) {
thisL = callee.getActiveBody().getThisLocal();
}
if (thisL != null) {
if (thisL.equals(sourceBase)) {
boolean param = false;
// check if it is not one of the params (then we have already fixed it)
for (int i = 0; i < callee.getParameterCount(); i++) {
if (callee.getActiveBody().getParameterLocal(i).equals(sourceBase)) {
param = true;
break;
}
}
if (!param) {
if (callSite instanceof Stmt) {
Stmt stmt = (Stmt) callSite;
if (stmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iIExpr = (InstanceInvokeExpr) stmt.getInvokeExpr();
Abstraction abs = newSource.deriveNewAbstraction(newSource.getAccessPath().copyWithNewValue(iIExpr.getBase()));
if (pathTracking == PathTrackingMethod.ForwardTracking)
((AbstractionWithPath) abs).addPathElement(stmt);
res.add(abs);
if(triggerInaktiveTaintOrReverseFlow(iIExpr.getBase(), abs) && abs.isAbstractionActive()){
Abstraction bwAbs = abs.deriveInactiveAbstraction();
bwAbs = bwAbs.getAbstractionWithNewActivationUnitOnCurrentLevel(callSite);
for (Unit predUnit : interproceduralCFG().getPredsOf(callSite))
bSolver.processEdge(new PathEdge<Unit, Abstraction, SootMethod>(bwAbs, predUnit, bwAbs));
}
}
}
}
}
}
return res;
}
};
}
@Override
public FlowFunction<Abstraction> getCallToReturnFlowFunction(final Unit call, final Unit returnSite) {
// special treatment for native methods:
if (call instanceof Stmt) {
final Stmt iStmt = (Stmt) call;
final List<Value> callArgs = iStmt.getInvokeExpr().getArgs();
return new FlowFunction<Abstraction>() {
@Override
public Set<Abstraction> computeTargets(Abstraction source) {
if (stopAfterFirstFlow && !results.isEmpty())
return Collections.emptySet();
Abstraction newSource;
//check inactive elements:
if (!source.isAbstractionActive() && (call.equals(source.getActivationUnit()))|| call.equals(source.getActivationUnitOnCurrentLevel())){
newSource = source.getActiveCopy(false);
}else{
newSource = source;
}
Set<Abstraction> res = new HashSet<Abstraction>();
res.addAll(computeWrapperTaints(iStmt, callArgs, newSource));
// We can only pass on a taint if it is neither a parameter nor the
// base object of the current call
boolean passOn = true;
//we only can remove the taint if we step into the call/return edges
// if(!interproceduralCFG().getCalleesOfCallAt(call).isEmpty()){
if (iStmt.getInvokeExpr() instanceof InstanceInvokeExpr)
if (((InstanceInvokeExpr) iStmt.getInvokeExpr()).getBase().equals
(newSource.getAccessPath().getPlainLocal()))
passOn = false;
if (passOn)
for (int i = 0; i < callArgs.size(); i++)
if (callArgs.get(i).equals(newSource.getAccessPath().getPlainLocal()) && isTransferableValue(callArgs.get(i))) {
passOn = false;
break;
}
//static variables are always propagated if they are not overwritten. So if we have at least one call/return edge pair,
//we can be sure that the value does not get "lost" if we do not pass it on:
if(newSource.getAccessPath().isStaticFieldRef()){
passOn = false;
}
if (passOn)
res.add(newSource);
if (iStmt.getInvokeExpr().getMethod().isNative()) {
if (callArgs.contains(newSource.getAccessPath().getPlainValue())) {
// java uses call by value, but fields of complex objects can be changed (and tainted), so use this conservative approach:
res.addAll(ncHandler.getTaintedValues(iStmt, newSource, callArgs));
}
}
if (iStmt instanceof AssignStmt) {
final AssignStmt stmt = (AssignStmt) iStmt;
if (sourceSinkManager.isSource(stmt, interproceduralCFG())) {
if (DEBUG)
System.out.println("Found source: " + stmt.getInvokeExpr().getMethod());
if (pathTracking == PathTrackingMethod.ForwardTracking)
res.add(new AbstractionWithPath(stmt.getLeftOp(),
stmt.getInvokeExpr(),
stmt, false, true, iStmt).addPathElement(call));
else
res.add(new Abstraction(stmt.getLeftOp(),
stmt.getInvokeExpr(), stmt, false, true, iStmt));
res.remove(zeroValue);
}
}
// if we have called a sink we have to store the path from the source - in case one of the params is tainted!
if (sourceSinkManager.isSink(iStmt, interproceduralCFG())) {
boolean taintedParam = false;
for (int i = 0; i < callArgs.size(); i++) {
if (callArgs.get(i).equals(newSource.getAccessPath().getPlainLocal())) {
taintedParam = true;
break;
}
}
if (taintedParam) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(iStmt.getInvokeExpr(), iStmt,
newSource.getSource(),
newSource.getSourceContext(),
((AbstractionWithPath) newSource).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(call) + ": " + call.toString());
else
results.addResult(iStmt.getInvokeExpr(), iStmt,
newSource.getSource(), newSource.getSourceContext());
}
// if the base object which executes the method is tainted the sink is reached, too.
if (iStmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) iStmt.getInvokeExpr();
if (vie.getBase().equals(newSource.getAccessPath().getPlainValue())) {
if (pathTracking != PathTrackingMethod.NoTracking)
results.addResult(iStmt.getInvokeExpr(), iStmt,
newSource.getSource(),
newSource.getSourceContext(),
((AbstractionWithPath) newSource).getPropagationPathAsString(interproceduralCFG()),
interproceduralCFG().getMethodOf(call) + ": " + call.toString());
else
results.addResult(iStmt.getInvokeExpr(), iStmt,
newSource.getSource(), newSource.getSourceContext());
}
}
}
return res;
}
};
}
return Identity.v();
}
};
}
public InfoflowProblem(List<String> sourceList, List<String> sinkList) {
super(new JimpleBasedBiDiICFG());
this.sourceSinkManager = new DefaultSourceSinkManager(sourceList, sinkList);
}
public InfoflowProblem(ISourceSinkManager sourceSinkManager) {
super(new JimpleBasedBiDiICFG());
this.sourceSinkManager = sourceSinkManager;
}
public InfoflowProblem(InterproceduralCFG<Unit, SootMethod> icfg, List<String> sourceList, List<String> sinkList) {
super(icfg);
this.sourceSinkManager = new DefaultSourceSinkManager(sourceList, sinkList);
}
public InfoflowProblem(InterproceduralCFG<Unit, SootMethod> icfg, ISourceSinkManager sourceSinkManager) {
super(icfg);
this.sourceSinkManager = sourceSinkManager;
}
public InfoflowProblem(ISourceSinkManager mySourceSinkManager, Set<Unit> analysisSeeds) {
super(new JimpleBasedBiDiICFG());
this.sourceSinkManager = mySourceSinkManager;
this.initialSeeds.addAll(analysisSeeds);
}
@Override
public Abstraction createZeroValue() {
if (zeroValue == null) {
zeroValue = this.pathTracking == PathTrackingMethod.NoTracking ?
new Abstraction(new JimpleLocal("zero", NullType.v()), null, null, false, true, null) :
new AbstractionWithPath(new JimpleLocal("zero", NullType.v()), null, null, false, true, null);
}
return zeroValue;
}
public void setBackwardSolver(InfoflowSolver backwardSolver){
bSolver = backwardSolver;
}
@Override
public boolean autoAddZero() {
return false;
}
}
|
package soot.jimple.infoflow;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Value;
import soot.jimple.InvokeExpr;
import soot.jimple.Stmt;
/**
* Class for collecting information flow results
*
* @author Steven Arzt
*/
public class InfoflowResults {
/**
* Class for modeling information flowing out of a specific source
* @author Steven Arzt
*/
public class SourceInfo {
private final Value source;
private final Stmt context;
private final List<String> path;
public SourceInfo(Value source, Stmt context) {
this.source = source;
this.context = context;
this.path = null;
}
public SourceInfo(Value source, Stmt context, List<String> path) {
this.source = source;
this.context = context;
this.path = path;
}
public Value getSource() {
return this.source;
}
public Stmt getContext() {
return this.context;
}
public List<String> getPath() {
return this.path;
}
@Override
public int hashCode() {
return 31 * this.source.hashCode()
+ 7 * this.context.hashCode();
}
@Override
public boolean equals(Object o) {
if (super.equals(o))
return true;
if (o == null || !(o instanceof SourceInfo))
return false;
SourceInfo si = (SourceInfo) o;
return this.source.equals(si.source)
&& this.context.equals(si.context);
}
}
/**
* Class for modeling information flowing into a specific source
* @author Steven Arzt
*/
public class SinkInfo {
private final Value sink;
private final Stmt context;
public SinkInfo(Value sink, Stmt context) {
this.sink = sink;
this.context = context;
}
public Value getSink() {
return this.sink;
}
public Stmt getContext() {
return this.context;
}
@Override
public String toString() {
return this.context.toString();
}
@Override
public int hashCode() {
return 31 * this.sink.hashCode()
+ 7 * this.context.hashCode();
}
@Override
public boolean equals(Object o) {
if (super.equals(o))
return true;
if (o == null || !(o instanceof SinkInfo))
return false;
SinkInfo si = (SinkInfo) o;
return this.sink.equals(si.sink)
&& this.context.equals(si.context);
}
}
private final Map<SinkInfo, Set<SourceInfo>> results = new HashMap<SinkInfo, Set<SourceInfo>>();
public InfoflowResults() {
}
/**
* Gets the number of entries in this result object
* @return The number of entries in this result object
*/
public int size() {
return this.results.size();
}
/**
* Gets whether this result object is empty, i.e. contains no information
* flows
* @return True if this result object is empty, otherwise false.
*/
public boolean isEmpty() {
return this.results.isEmpty();
}
/**
* Checks whether this result object contains a sink that exactly matches the
* given value.
* @param sink The sink to check for
* @return True if this result contains the given value as a sink, otherwise
* false.
*/
public boolean containsSink(Value sink) {
for (SinkInfo si : this.results.keySet())
if (si.getSink().equals(sink))
return true;
return false;
}
/**
* Checks whether this result object contains a sink with the given method
* signature
* @param sinkSignature The method signature to check for
* @return True if there is a sink with the given method signature in this
* result object, otherwise false.
*/
public boolean containsSinkMethod(String sinkSignature) {
return !findSinkByMethodSignature(sinkSignature).isEmpty();
}
public void addResult(Value sink, Stmt sinkStmt, Value source, Stmt sourceStmt) {
this.addResult(new SinkInfo(sink, sinkStmt), new SourceInfo(source, sourceStmt));
}
public void addResult(Value sink, Stmt sinkStmt, Value source,
Stmt sourceStmt, List<String> propagationPath) {
this.addResult(new SinkInfo(sink, sinkStmt), new SourceInfo(source, sourceStmt, propagationPath));
}
public void addResult(Value sink, Stmt sinkContext, Value source,
Stmt sourceStmt, List<String> propagationPath, String stmt) {
List<String> newPropPath = new ArrayList<String>(propagationPath);
newPropPath.add(stmt);
this.addResult(new SinkInfo(sink, sinkContext),
new SourceInfo(source, sourceStmt, newPropPath));
}
public void addResult(SinkInfo sink, SourceInfo source) {
Set<SourceInfo> sourceInfo = this.results.get(sink);
if (sourceInfo == null) {
sourceInfo = new HashSet<SourceInfo>();
this.results.put(sink, sourceInfo);
}
sourceInfo.add(source);
}
/**
* Gets all results in this object as a hash map.
* @return All results in this object as a hash map.
*/
public Map<SinkInfo, Set<SourceInfo>> getResults() {
return this.results;
}
/**
* Checks whether there is a path between the given source and sink.
* @param sink The sink to which there may be a path
* @param source The source from which there may be a path
* @return True if there is a path between the given source and sink, false
* otherwise
*/
public boolean isPathBetween(Value sink, Value source) {
Set<SourceInfo> sources = this.results.get(sink);
if (sources == null)
return false;
for (SourceInfo src : sources)
if (src.source.equals(source))
return true;
return false;
}
/**
* Checks whether there is a path between the given source and sink.
* @param sink The sink to which there may be a path
* @param source The source from which there may be a path
* @return True if there is a path between the given source and sink, false
* otherwise
*/
public boolean isPathBetween(String sink, String source) {
for (SinkInfo si : this.results.keySet())
if (si.getSink().toString().equals(sink)) {
Set<SourceInfo> sources = this.results.get(si);
for (SourceInfo src : sources)
if (src.source.toString().equals(source))
return true;
}
return false;
}
/**
* Checks whether there is an information flow between the two
* given methods (specified by their respective Soot signatures).
* @param sinkSignature The sink to which there may be a path
* @param sourceSignature The source from which there may be a path
* @return True if there is a path between the given source and sink, false
* otherwise
*/
public boolean isPathBetweenMethods(String sinkSignature, String sourceSignature) {
List<SinkInfo> sinkVals = findSinkByMethodSignature(sinkSignature);
for (SinkInfo si : sinkVals) {
Set<SourceInfo> sources = this.results.get(si);
if (sources == null)
return false;
for (SourceInfo src : sources)
if (src.source instanceof InvokeExpr) {
InvokeExpr expr = (InvokeExpr) src.source;
if (expr.getMethod().getSignature().equals(sourceSignature))
return true;
}
}
return false;
}
/**
* Finds the entry for a sink method with the given signature
* @param sinkSignature The sink's method signature to look for
* @return The key of the entry with the given method signature if such an
* entry has been found, otherwise null.
*/
private List<SinkInfo> findSinkByMethodSignature(String sinkSignature) {
List<SinkInfo> sinkVals = new ArrayList<SinkInfo>();
for (SinkInfo si : this.results.keySet())
if (si.getSink() instanceof InvokeExpr) {
InvokeExpr expr = (InvokeExpr) si.getSink();
if (expr.getMethod().getSignature().equals(sinkSignature))
sinkVals.add(si);
}
return sinkVals;
}
/**
* Prints all results stored in this object to the standard output
*/
public void printResults() {
for (SinkInfo sink : this.results.keySet()) {
System.out.println("Found a flow to sink " + sink + " from the following sources:");
for (SourceInfo source : this.results.get(sink))
System.out.println("\t- " + source.getSource());
}
}
}
|
package org.mustbe.consulo.csharp.lang.psi.impl.source.resolve.type;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mustbe.consulo.csharp.lang.psi.CSharpMethodDeclaration;
import org.mustbe.consulo.csharp.lang.psi.CSharpReferenceExpression;
import org.mustbe.consulo.csharp.lang.psi.impl.CSharpTypeUtil;
import org.mustbe.consulo.csharp.lang.psi.impl.msil.CSharpTransform;
import org.mustbe.consulo.dotnet.DotNetTypes;
import org.mustbe.consulo.dotnet.resolve.DotNetGenericExtractor;
import org.mustbe.consulo.dotnet.resolve.DotNetPsiSearcher;
import org.mustbe.consulo.dotnet.resolve.DotNetTypeRef;
import org.mustbe.consulo.dotnet.resolve.DotNetTypeResolveResult;
import com.intellij.psi.PsiElement;
/**
* @author VISTALL
* @since 20.10.14
*/
public class CSharpReferenceTypeRef implements DotNetTypeRef
{
public static class Result implements DotNetTypeResolveResult
{
protected final PsiElement myElement;
public Result(PsiElement element)
{
myElement = element;
}
@Nullable
@Override
public PsiElement getElement()
{
return myElement;
}
@NotNull
@Override
public DotNetGenericExtractor getGenericExtractor()
{
return DotNetGenericExtractor.EMPTY;
}
@Override
public boolean isNullable()
{
PsiElement element = getElement();
return element == null || CSharpTypeUtil.isElementIsNullable(element);
}
}
public static class LambdaResult extends Result implements CSharpLambdaResolveResult
{
private final PsiElement myScope;
public LambdaResult(PsiElement scope, PsiElement element)
{
super(element);
myScope = scope;
}
@Nullable
@Override
public PsiElement getElement()
{
return DotNetPsiSearcher.getInstance(myScope.getProject()).findType(DotNetTypes.System.MulticastDelegate,
myScope.getResolveScope(), DotNetPsiSearcher.TypeResoleKind.UNKNOWN, CSharpTransform.INSTANCE);
}
@NotNull
@Override
public DotNetTypeRef getReturnTypeRef()
{
return ((CSharpMethodDeclaration)myElement).getReturnTypeRef();
}
@NotNull
@Override
public DotNetTypeRef[] getParameterTypeRefs()
{
return ((CSharpMethodDeclaration)myElement).getParameterTypeRefs();
}
@NotNull
@Override
public PsiElement getTarget()
{
return myElement;
}
}
private final CSharpReferenceExpression myReferenceExpression;
public CSharpReferenceTypeRef(CSharpReferenceExpression referenceExpression)
{
myReferenceExpression = referenceExpression;
}
@NotNull
@Override
public String getPresentableText()
{
return myReferenceExpression.getReferenceName();
}
@NotNull
@Override
public String getQualifiedText()
{
return myReferenceExpression.getText();
}
@NotNull
@Override
public DotNetTypeResolveResult resolve(@NotNull PsiElement scope)
{
PsiElement resolve = myReferenceExpression.resolve();
if(resolve instanceof CSharpMethodDeclaration && ((CSharpMethodDeclaration) resolve).isDelegate())
{
return new LambdaResult(scope, resolve);
}
return new Result(resolve);
}
}
|
package org.ihtsdo.buildcloud.service.execution.database.map;
import org.ihtsdo.buildcloud.service.execution.RF2Constants;
import org.ihtsdo.buildcloud.service.execution.database.DatabasePopulatorException;
import org.ihtsdo.buildcloud.service.execution.database.RF2TableDAO;
import org.ihtsdo.buildcloud.service.execution.database.RF2TableResults;
import org.ihtsdo.buildcloud.service.execution.transform.UUIDGenerator;
import org.ihtsdo.buildcloud.service.file.FileUtils;
import org.ihtsdo.snomed.util.rf2.schema.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RF2TableDAOTreeMapImpl implements RF2TableDAO {
private final SchemaFactory schemaFactory;
private TableSchema tableSchema;
private DataType idType;
private Map<Key, String> table;
private Set<Key> dirtyKeys;
private final UUIDGenerator uuidGenerator;
private static final Pattern REFSET_ID_AND_REFERENCED_COMPONENT_ID_PATTERN = Pattern.compile("[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t([^\t]*\t[^\t]*)(\t.*)?");
private static final Pattern REFSET_ID_REFERENCED_COMPONENT_ID_AND_TARGET_ID_PATTERN = Pattern.compile("[^\t]*\t[^\t]*\t[^\t]*\t[^\t]*\t([^\t]*\t[^\t]*\t[^\t]*)(\t.*)?");
private static final Logger LOGGER = LoggerFactory.getLogger(RF2TableDAOTreeMapImpl.class);
public RF2TableDAOTreeMapImpl(UUIDGenerator uuidGenerator) {
this.uuidGenerator = uuidGenerator;
schemaFactory = new SchemaFactory();
table = new TreeMap<>();
}
@Override
public TableSchema createTable(String rf2FilePath, InputStream rf2InputStream, boolean workbenchDataFixesRequired) throws SQLException, IOException, FileRecognitionException, ParseException, DatabasePopulatorException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(rf2InputStream, RF2Constants.UTF_8))) {
// Build Schema
String rf2Filename = FileUtils.getFilenameFromPath(rf2FilePath);
String headerLine = getHeader(rf2FilePath, reader);
tableSchema = schemaFactory.createSchemaBean(rf2Filename);
idType = tableSchema.getFields().get(0).getType();
schemaFactory.populateExtendedRefsetAdditionalFieldNames(tableSchema, headerLine);
// Insert Data
insertData(reader, tableSchema, true, workbenchDataFixesRequired);
return tableSchema;
}
}
@Override
public void appendData(TableSchema tableSchema, InputStream rf2InputStream, boolean workbenchDataFixesRequired) throws IOException, SQLException, ParseException, DatabasePopulatorException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(rf2InputStream, RF2Constants.UTF_8))) {
reader.readLine(); // Discard header line
insertData(reader, tableSchema, false, workbenchDataFixesRequired);
}
}
@Override
public RF2TableResults selectAllOrdered(TableSchema tableSchema) throws SQLException {
return new RF2TableResultsMapImpl(table);
}
@Override
public RF2TableResults selectNone(TableSchema tableSchema) throws SQLException {
return new RF2TableResultsMapImpl(new TreeMap<Key, String>());
}
@Override
public void closeConnection() throws SQLException {
table = null;
}
@Override
public void discardAlreadyPublishedDeltaStates(InputStream previousSnapshotFileStream, String currentSnapshotFileName, String effectiveTime) throws IOException, DatabasePopulatorException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(previousSnapshotFileStream, RF2Constants.UTF_8))) {
getHeader(currentSnapshotFileName, reader);
String line;
String value;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(RF2Constants.COLUMN_SEPARATOR, 3);
Key key = getKey(parts[0], effectiveTime);
if ((value = table.get(key)) != null) {
if (value.equals(parts[2])) {
// Fields after second column
LOGGER.debug("Removing already published Delta state in {} : {}", currentSnapshotFileName, line);
table.remove(key);
}
}
}
}
}
@Override
public void reconcileRefsetMemberIds(InputStream previousSnapshotFileStream, String currentSnapshotFileName, String effectiveTime) throws IOException, DatabasePopulatorException {
try (BufferedReader prevSnapshotReader = new BufferedReader(new InputStreamReader(previousSnapshotFileStream, RF2Constants.UTF_8))) {
getHeader("previous to " + currentSnapshotFileName, prevSnapshotReader);
String line;
String[] parts;
while ((line = prevSnapshotReader.readLine()) != null) {
String compositeKey = getCompositeKey(tableSchema, line);
Key matcherKey = new StringKey(compositeKey);
String newValues = table.get(matcherKey);
if (newValues != null) {
parts = line.split(RF2Constants.COLUMN_SEPARATOR, 3);
replaceDirtyKey(matcherKey, parts[0], effectiveTime);
}
}
}
}
@Override
public void generateNewMemberIds(String effectiveTime) throws DatabasePopulatorException {
if (!dirtyKeys.isEmpty()) {
LOGGER.info("{} dirty refset ids remain. Generating UUIDs for new members.", dirtyKeys.size());
while (dirtyKeys.iterator().hasNext()) {
Key remainingDirtyKey = dirtyKeys.iterator().next();
String newKey = uuidGenerator.uuid();
replaceDirtyKey(remainingDirtyKey, newKey, effectiveTime);
}
} else {
LOGGER.info("No dirty refset ids remain. No new members.", dirtyKeys.size());
}
}
private void replaceDirtyKey(Key existingDirtyKey, String newKeyUUID, String effectiveTime) throws DatabasePopulatorException {
String existingData = table.remove(existingDirtyKey);
if (existingData != null) {
table.put(new UUIDKey(newKeyUUID, effectiveTime), existingData);
if (!dirtyKeys.remove(existingDirtyKey)) {
throw new DatabasePopulatorException("Failed to remove dirty key " + existingDirtyKey + "'");
}
} else {
throw new DatabasePopulatorException("No match found when replacing dirty key '" + existingDirtyKey + "'");
}
}
public Map<Key, String> getTable() {
return table;
}
private String getHeader(String rf2FilePath, BufferedReader reader) throws IOException, DatabasePopulatorException {
String headerLine = reader.readLine();
if (headerLine == null) throw new DatabasePopulatorException("RF2 file " + rf2FilePath + " is empty.");
return headerLine;
}
private void insertData(BufferedReader reader, TableSchema tableSchema, boolean deltaData, boolean workbenchDataFixesRequired) throws IOException, DatabasePopulatorException {
String line;
String[] parts;
Key key;
dirtyKeys = new LinkedHashSet<>();
while ((line = reader.readLine()) != null) {
parts = line.split(RF2Constants.COLUMN_SEPARATOR, 3);
if (workbenchDataFixesRequired && deltaData && tableSchema.getComponentType() == ComponentType.REFSET) {
// Key id = refsetId (5th field) and referencedComponentId (6th field)
String compositeKey = getCompositeKey(tableSchema, line);
key = new StringKey(compositeKey);
if (!dirtyKeys.contains(key)) {
dirtyKeys.add(key);
} else {
LOGGER.info(RF2Constants.DATA_PROBLEM + "Duplicate refset member found. Rows are logically equivalent, the first will be discarded: [{}], [{}].", table.get(key), parts[2]);
}
} else {
key = getKey(parts[0], parts[1]);
}
table.put(key, parts[2]);
}
}
private String getCompositeKey(TableSchema tableSchema, String line) throws DatabasePopulatorException {
Pattern compKeyPattern;
List<Field> fields = tableSchema.getFields();
if (fields.size() >= 7 && ("mapTarget".equals(fields.get(6).getName()) || "targetComponentId".equals(fields.get(6).getName()))) {
// Simple Map or Association
compKeyPattern = REFSET_ID_REFERENCED_COMPONENT_ID_AND_TARGET_ID_PATTERN;
} else {
// Simple RefSet
compKeyPattern = REFSET_ID_AND_REFERENCED_COMPONENT_ID_PATTERN;
}
Matcher matcher = compKeyPattern.matcher(line);
if (matcher.matches()) {
return matcher.group(1);
} else {
throw new DatabasePopulatorException("No composite key match in line '" + line + "'");
}
}
private Key getKey(String part0, String part1) {
Key key;
if (idType == DataType.SCTID) {
key = new SCTIDKey(part0, part1);
} else {
key = new UUIDKey(part0, part1);
}
return key;
}
@Override
public void resolveEmptyValueId(final InputStream previousSnapshotFileStream, final String effectiveTime) throws IOException {
//check whether there are any empty value id
List<Key> emptyValueKeys = new ArrayList<>();
for (Key key : table.keySet()) {
String value = table.get(key);
String[] data = value.split(RF2Constants.COLUMN_SEPARATOR, -1);
if (RF2Constants.EMPTY_SPACE.equals(data[data.length - 1])) {
emptyValueKeys.add(key);
}
}
LOGGER.info("Total number of rows with empty value id found:" + emptyValueKeys.size());
if (emptyValueKeys.size() < 1) {
//no empty value id is found.
return;
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(previousSnapshotFileStream, RF2Constants.UTF_8))) {
String line;
line = reader.readLine();
if (line == null) {
throw new IOException("Privious attribute value snapshot file has no data");
}
while ((line = reader.readLine()) != null) {
String[] parts = line.split(RF2Constants.COLUMN_SEPARATOR, -1);
Key key = getKey(parts[0], effectiveTime);
if (emptyValueKeys.contains(key)) {
String value = table.get(key);
boolean isPreviousActive = RF2Constants.BOOLEAN_TRUE.equals(parts[2]);
//check data in delta file has got empty value id and with inactive flag
String[] data = value.split(RF2Constants.COLUMN_SEPARATOR, -1);
boolean isCurrentActive = RF2Constants.BOOLEAN_TRUE.equals(data[0]);
if (!isCurrentActive) {
if (isPreviousActive) {
//add previous value id
table.put(key, value + parts[6]);
} else {
//remove line from table and dirty key set
table.remove(key);
dirtyKeys.remove(key);
}
}
emptyValueKeys.remove(key);
}
}
}
//remove any rows with empty value id as not existing in previous file
if (emptyValueKeys.size() > 0) {
LOGGER.info("Found total number of rows with empty value id but member id doesn't exist in previous snapshot file:" + emptyValueKeys.size());
}
for (Key k : emptyValueKeys) {
table.remove(k);
dirtyKeys.remove(k);
}
}
}
|
package de.wwu.md2.framework.ui.generator;
import java.io.InputStream;
import java.util.Collection;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.xtext.builder.EclipseResourceFileSystemAccess2;
import org.eclipse.xtext.generator.OutputConfiguration;
import com.google.common.collect.Sets;
import de.wwu.md2.framework.generator.IExtendedFileSystemAccess;
public class ExtendedEclipseResourceFileSystemAccess2
extends EclipseResourceFileSystemAccess2 implements IExtendedFileSystemAccess {
private IFileCallback callBack;
private IProject project;
@Override
public void setPostProcessor(IFileCallback callBack) {
this.callBack = callBack;
super.setPostProcessor(callBack);
}
@Override
public void setProject(IProject project) {
this.project = project;
super.setProject(project);
}
@Override
public void generateFileFromInputStream(InputStream inputStream, String targetFileName) {
generateFileFromInputStream(inputStream, targetFileName, DEFAULT_OUTPUT);
}
/**
* Generates a file from an input stream.
*
* @param inputStream Any input stream that should be written to the given file.
* @param targetFileName File name and path of the new resource.
* @param outputConfiguration Output configuration.
*/
public void generateFileFromInputStream(InputStream inputStream, String targetFileName, String outputConfiguration) {
if (getMonitor().isCanceled())
throw new OperationCanceledException();
OutputConfiguration outputConfig = getOutputConfig(outputConfiguration);
// check output folder exists
IContainer folder = getContainer(outputConfig);
if (!folder.exists()) {
if (outputConfig.isCreateOutputDirectory()) {
try {
createContainer(folder);
} catch (CoreException e) {
throw new RuntimeException(e);
}
} else {
return;
}
}
// copy file
IFile file = getFile(targetFileName, outputConfiguration);
if (file.exists()) {
if (outputConfig.isOverrideExistingResources()) {
try {
file.setContents(inputStream, true, true, getMonitor());
if (file.isDerived() != outputConfig.isSetDerivedProperty()) {
file.setDerived(outputConfig.isSetDerivedProperty(), getMonitor());
}
} catch (CoreException e) {
throw new RuntimeException(e);
}
callBack.afterFileUpdate(file);
}
} else {
try {
ensureParentExists(file);
file.create(inputStream, true, getMonitor());
if (outputConfig.isSetDerivedProperty()) {
file.setDerived(true, getMonitor());
}
} catch (CoreException e) {
throw new RuntimeException(e);
}
callBack.afterFileCreation(file);
}
}
@Override
public Collection<String> copyFileFromProject(String fileName, String targetFolderName) {
OutputConfiguration outputConfiguration = getOutputConfig(DEFAULT_OUTPUT);
IResource sourceResource = project.findMember(new Path(fileName));
IPath outputPath = new Path(outputConfiguration.getOutputDirectory() + "/"
+ targetFolderName.replaceAll("^/", ""));
// Check of sourceResource exists
if (sourceResource == null) return null;
// check output folder exists
IContainer folder = getContainer(outputConfiguration);
if (!folder.exists()) {
if (outputConfiguration.isCreateOutputDirectory()) {
try {
createContainer(folder);
} catch (CoreException e) {
throw new RuntimeException(e);
}
} else {
return null;
}
}
// ensure target folder exists
IFolder outputFolder = project.getFolder(outputPath.removeLastSegments(1));
if (!outputFolder.exists()) {
try {
createContainer(outputFolder);
} catch (CoreException e) {
throw new RuntimeException(e);
}
}
// copy
try {
sourceResource.copy(outputPath.makeRelativeTo(project.getFullPath()), true, getMonitor());
return getAllFileNames(sourceResource);
} catch (CoreException e) {
throw new RuntimeException(e);
}
}
/**
* Collect all file names of the files in a folder (recursive).
* @return
*/
private Collection<String> getAllFileNames(IResource resource) {
Collection<String> fileNames = Sets.newHashSet();
if(resource.getType() == IResource.FILE) {
fileNames.add(((IFile)resource).getName());
} else if(resource.getType() == IResource.FOLDER) {
try {
for(IResource res : ((IFolder)resource).members()) {
if(res.getType() == IResource.FILE) {
fileNames.add(((IFile)res).getName());
} else if(res.getType() == IResource.FOLDER) {
fileNames.addAll(getAllFileNames(res));
}
}
} catch (CoreException e) {
e.printStackTrace();
}
}
return fileNames;
}
@Override
public void deleteDirectory(String directoryName) {
deleteDirectory(directoryName, DEFAULT_OUTPUT);
}
/**
* Deletes the specified directory.
*
* @param directoryName Directory to delete.
* @param outputConfiguration Output configuration.
*/
public void deleteDirectory(String directoryName, String outputConfiguration) {
if (getMonitor().isCanceled())
throw new OperationCanceledException();
OutputConfiguration outputConfig = getOutputConfig(outputConfiguration);
try {
directoryName = directoryName.replaceAll("^/", "");
IContainer folder = getContainer(outputConfig);
IResource toDelete = folder;
if(!directoryName.isEmpty()) {
toDelete = folder.findMember(directoryName);
}
toDelete.delete(IResource.KEEP_HISTORY, getMonitor());
} catch (CoreException e) {
throw new RuntimeException(e);
}
}
}
|
package som.vmobjects;
import static som.interpreter.TruffleCompiler.transferToInterpreterAndInvalidate;
import java.lang.reflect.Field;
import java.util.Arrays;
import som.interpreter.objectstorage.ObjectLayout;
import som.interpreter.objectstorage.StorageLocation;
import som.interpreter.objectstorage.StorageLocation.AbstractObjectStorageLocation;
import som.interpreter.objectstorage.StorageLocation.GeneralizeStorageLocationException;
import som.interpreter.objectstorage.StorageLocation.UninitalizedStorageLocationException;
import som.vm.constants.Nil;
import com.oracle.truffle.api.CompilerAsserts;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.nodes.ExplodeLoop;
import com.oracle.truffle.api.nodes.NodeUtil;
import com.oracle.truffle.api.nodes.NodeUtil.FieldOffsetProvider;
public class SObject extends SAbstractObject {
@CompilationFinal protected SClass clazz;
public static final int NUM_PRIMITIVE_FIELDS = 5;
public static final int NUM_OBJECT_FIELDS = 5;
@SuppressWarnings("unused") private long primField1;
@SuppressWarnings("unused") private long primField2;
@SuppressWarnings("unused") private long primField3;
@SuppressWarnings("unused") private long primField4;
@SuppressWarnings("unused") private long primField5;
@SuppressWarnings("unused") private Object field1;
@SuppressWarnings("unused") private Object field2;
@SuppressWarnings("unused") private Object field3;
@SuppressWarnings("unused") private Object field4;
@SuppressWarnings("unused") private Object field5;
@SuppressWarnings("unused") @CompilationFinal private long[] extensionPrimFields;
@SuppressWarnings("unused") @CompilationFinal private Object[] extensionObjFields;
// we manage the layout entirely in the class, but need to keep a copy here
// to know in case the layout changed that we can update the instances lazily
@CompilationFinal private ObjectLayout objectLayout;
private int primitiveUsedMap;
private final int numberOfFields;
protected SObject(final SClass instanceClass) {
numberOfFields = instanceClass.getNumberOfInstanceFields();
clazz = instanceClass;
setLayoutInitially(instanceClass.getLayoutForInstances());
}
protected SObject(final int numFields) {
numberOfFields = numFields;
setLayoutInitially(new ObjectLayout(numFields, null));
}
private void setLayoutInitially(final ObjectLayout layout) {
field1 = field2 = field3 = field4 = field5 = Nil.nilObject;
objectLayout = layout;
assert objectLayout.getNumberOfFields() == numberOfFields;
extensionPrimFields = getExtendedPrimStorage();
extensionObjFields = getExtendedObjectStorage();
}
public final int getNumberOfFields() {
return numberOfFields;
}
public final ObjectLayout getObjectLayout() {
// TODO: should I really remove it, or should I update the layout?
// assert clazz.getLayoutForInstances() == objectLayout;
return objectLayout;
}
public final long[] getExtendedPrimFields() {
return extensionPrimFields;
}
public final Object[] getExtensionObjFields() {
return extensionObjFields;
}
public final void setClass(final SClass value) {
transferToInterpreterAndInvalidate("SObject.setClass");
// Set the class of this object by writing to the field with class index
assert value != null;
clazz = value;
setLayoutInitially(value.getLayoutForInstances());
}
private long[] getExtendedPrimStorage() {
return new long[objectLayout.getNumberOfUsedExtendedPrimStorageLocations()];
}
private Object[] getExtendedObjectStorage() {
Object[] storage = new Object[objectLayout.getNumberOfUsedExtendedObjectStorageLocations()];
Arrays.fill(storage, Nil.nilObject);
return storage;
}
@ExplodeLoop
private Object[] readAllFields() {
Object[] fieldValues = new Object[numberOfFields];
for (int i = 0; i < numberOfFields; i++) {
if (isFieldSet(i)) {
fieldValues[i] = getField(i);
} else {
fieldValues[i] = null;
}
}
return fieldValues;
}
@ExplodeLoop
private void setAllFields(final Object[] fieldValues) {
field1 = field2 = field3 = field4 = field5 = null;
primField1 = primField2 = primField3 = primField4 = primField5 = Long.MIN_VALUE;
assert fieldValues.length == numberOfFields;
for (int i = 0; i < numberOfFields; i++) {
if (fieldValues[i] != null) {
setField(i, fieldValues[i]);
} else if (getLocation(i) instanceof AbstractObjectStorageLocation) {
setField(i, Nil.nilObject);
}
}
}
public final boolean updateLayoutToMatchClass() {
ObjectLayout layoutAtClass = clazz.getLayoutForInstances();
assert layoutAtClass.getNumberOfFields() == numberOfFields;
if (objectLayout != layoutAtClass) {
setLayoutAndTransferFields(layoutAtClass);
return true;
} else {
return false;
}
}
private void setLayoutAndTransferFields(final ObjectLayout layout) {
CompilerDirectives.transferToInterpreterAndInvalidate();
Object[] fieldValues = readAllFields();
objectLayout = layout;
primitiveUsedMap = 0;
extensionPrimFields = getExtendedPrimStorage();
extensionObjFields = getExtendedObjectStorage();
setAllFields(fieldValues);
}
protected final void updateLayoutWithInitializedField(final long index, final Class<?> type) {
ObjectLayout layout = clazz.updateInstanceLayoutWithInitializedField(index, type);
assert objectLayout != layout;
assert layout.getNumberOfFields() == numberOfFields;
setLayoutAndTransferFields(layout);
}
protected final void updateLayoutWithGeneralizedField(final long index) {
ObjectLayout layout = clazz.updateInstanceLayoutWithGeneralizedField(index);
assert objectLayout != layout;
assert layout.getNumberOfFields() == numberOfFields;
setLayoutAndTransferFields(layout);
}
@Override
public final SClass getSOMClass() {
return CompilerDirectives.unsafeCast(clazz, SClass.class, true, true);
}
public final long getFieldIndex(final SSymbol fieldName) {
return clazz.lookupFieldIndex(fieldName);
}
public static final SObject create(final SClass instanceClass) {
return new SObject(instanceClass);
}
public static SObject create(final int numFields) {
return new SObject(numFields);
}
private static final long FIRST_OBJECT_FIELD_OFFSET = getFirstObjectFieldOffset();
private static final long FIRST_PRIM_FIELD_OFFSET = getFirstPrimFieldOffset();
private static final long OBJECT_FIELD_LENGTH = getObjectFieldLength();
private static final long PRIM_FIELD_LENGTH = getPrimFieldLength();
public static long getObjectFieldOffset(final int fieldIndex) {
assert 0 <= fieldIndex && fieldIndex < NUM_OBJECT_FIELDS;
return FIRST_OBJECT_FIELD_OFFSET + fieldIndex * OBJECT_FIELD_LENGTH;
}
public static long getPrimitiveFieldOffset(final int fieldIndex) {
assert 0 <= fieldIndex && fieldIndex < NUM_PRIMITIVE_FIELDS;
return FIRST_PRIM_FIELD_OFFSET + fieldIndex * PRIM_FIELD_LENGTH;
}
public static int getPrimitiveFieldMask(final int fieldIndex) {
assert 0 <= fieldIndex && fieldIndex < 32; // this limits the number of object fields for the moment...
return 1 << fieldIndex;
}
public final boolean isPrimitiveSet(final int mask) {
return (primitiveUsedMap & mask) != 0;
}
public final void markPrimAsSet(final int mask) {
primitiveUsedMap |= mask;
}
private StorageLocation getLocation(final long index) {
StorageLocation location = objectLayout.getStorageLocation(index);
assert location != null;
return location;
}
public final boolean isFieldSet(final long index) {
StorageLocation location = getLocation(index);
return location.isSet(this, true);
}
public final Object getField(final long index) {
StorageLocation location = getLocation(index);
return location.read(this, true);
}
public final void setField(final long index, final Object value) {
StorageLocation location = getLocation(index);
try {
location.write(this, value);
} catch (UninitalizedStorageLocationException e) {
updateLayoutWithInitializedField(index, value.getClass());
setFieldAfterLayoutChange(index, value);
} catch (GeneralizeStorageLocationException e) {
updateLayoutWithGeneralizedField(index);
setFieldAfterLayoutChange(index, value);
}
}
private void setFieldAfterLayoutChange(final long index, final Object value) {
CompilerAsserts.neverPartOfCompilation("SObject.setFieldAfterLayoutChange(..)");
StorageLocation location = getLocation(index);
try {
location.write(this, value);
} catch (GeneralizeStorageLocationException
| UninitalizedStorageLocationException e) {
throw new RuntimeException("This should not happen, we just prepared this field for the new value.");
}
}
private static long getFirstObjectFieldOffset() {
CompilerAsserts.neverPartOfCompilation("SObject.getFirstObjectFieldOffset()");
try {
final FieldOffsetProvider fieldOffsetProvider = getFieldOffsetProvider();
final Field firstField = SObject.class.getDeclaredField("field1");
return fieldOffsetProvider.objectFieldOffset(firstField);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private static long getFirstPrimFieldOffset() {
CompilerAsserts.neverPartOfCompilation("SObject.getFirstPrimFieldOffset()");
try {
final FieldOffsetProvider fieldOffsetProvider = getFieldOffsetProvider();
final Field firstField = SObject.class.getDeclaredField("primField1");
return fieldOffsetProvider.objectFieldOffset(firstField);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private static FieldOffsetProvider getFieldOffsetProvider()
throws NoSuchFieldException, IllegalAccessException {
final Field fieldOffsetProviderField =
NodeUtil.class.getDeclaredField("unsafeFieldOffsetProvider");
fieldOffsetProviderField.setAccessible(true);
final FieldOffsetProvider fieldOffsetProvider =
(FieldOffsetProvider) fieldOffsetProviderField.get(null);
return fieldOffsetProvider;
}
private static long getObjectFieldLength() {
CompilerAsserts.neverPartOfCompilation("getObjectFieldLength()");
try {
return getFieldDistance("field1", "field2");
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private static long getPrimFieldLength() {
CompilerAsserts.neverPartOfCompilation("getPrimFieldLength()");
try {
return getFieldDistance("primField1", "primField2");
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private static long getFieldDistance(final String field1, final String field2) throws NoSuchFieldException,
IllegalAccessException {
final FieldOffsetProvider fieldOffsetProvider = getFieldOffsetProvider();
final Field firstField = SObject.class.getDeclaredField(field1);
final Field secondField = SObject.class.getDeclaredField(field2);
return fieldOffsetProvider.objectFieldOffset(secondField) - fieldOffsetProvider.objectFieldOffset(firstField);
}
}
|
package org.pentaho.reporting.designer.core.editor.report;
import java.applet.Applet;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.Window;
import java.awt.dnd.DropTarget;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.ImageObserver;
import java.awt.print.PageFormat;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import javax.swing.JComponent;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.pentaho.reporting.designer.core.Messages;
import org.pentaho.reporting.designer.core.ReportDesignerBoot;
import org.pentaho.reporting.designer.core.ReportDesignerContext;
import org.pentaho.reporting.designer.core.editor.ContextMenuUtility;
import org.pentaho.reporting.designer.core.editor.ReportRenderContext;
import org.pentaho.reporting.designer.core.editor.ZoomModel;
import org.pentaho.reporting.designer.core.editor.ZoomModelListener;
import org.pentaho.reporting.designer.core.editor.report.drag.CompoundDragOperation;
import org.pentaho.reporting.designer.core.editor.report.drag.MouseDragOperation;
import org.pentaho.reporting.designer.core.editor.report.drag.MoveDragOperation;
import org.pentaho.reporting.designer.core.editor.report.drag.ResizeBottomDragOperation;
import org.pentaho.reporting.designer.core.editor.report.drag.ResizeLeftDragOperation;
import org.pentaho.reporting.designer.core.editor.report.drag.ResizeRightDragOperation;
import org.pentaho.reporting.designer.core.editor.report.drag.ResizeTopDragOperation;
import org.pentaho.reporting.designer.core.editor.report.layouting.AbstractElementRenderer;
import org.pentaho.reporting.designer.core.editor.report.layouting.ElementRenderer;
import org.pentaho.reporting.designer.core.editor.report.snapping.EmptySnapModel;
import org.pentaho.reporting.designer.core.editor.report.snapping.FullSnapModel;
import org.pentaho.reporting.designer.core.editor.report.snapping.SnapToPositionModel;
import org.pentaho.reporting.designer.core.model.CachedLayoutData;
import org.pentaho.reporting.designer.core.model.HorizontalPositionsModel;
import org.pentaho.reporting.designer.core.model.ModelUtility;
import org.pentaho.reporting.designer.core.model.lineal.GuideLine;
import org.pentaho.reporting.designer.core.model.lineal.LinealModel;
import org.pentaho.reporting.designer.core.model.lineal.LinealModelEvent;
import org.pentaho.reporting.designer.core.model.lineal.LinealModelListener;
import org.pentaho.reporting.designer.core.model.selection.ReportSelectionEvent;
import org.pentaho.reporting.designer.core.model.selection.ReportSelectionListener;
import org.pentaho.reporting.designer.core.model.selection.ReportSelectionModel;
import org.pentaho.reporting.designer.core.settings.SettingsListener;
import org.pentaho.reporting.designer.core.settings.WorkspaceSettings;
import org.pentaho.reporting.designer.core.util.BreakPositionsList;
import org.pentaho.reporting.designer.core.util.exceptions.UncaughtExceptionsModel;
import org.pentaho.reporting.designer.core.util.undo.AttributeEditUndoEntry;
import org.pentaho.reporting.designer.core.util.undo.CompoundUndoEntry;
import org.pentaho.reporting.designer.core.util.undo.MassElementStyleUndoEntry;
import org.pentaho.reporting.designer.core.util.undo.MassElementStyleUndoEntryBuilder;
import org.pentaho.reporting.designer.core.util.undo.UndoEntry;
import org.pentaho.reporting.engine.classic.core.AttributeNames;
import org.pentaho.reporting.engine.classic.core.Band;
import org.pentaho.reporting.engine.classic.core.Element;
import org.pentaho.reporting.engine.classic.core.PageDefinition;
import org.pentaho.reporting.engine.classic.core.ReportElement;
import org.pentaho.reporting.engine.classic.core.RootLevelBand;
import org.pentaho.reporting.engine.classic.core.Section;
import org.pentaho.reporting.engine.classic.core.event.ReportModelEvent;
import org.pentaho.reporting.engine.classic.core.event.ReportModelListener;
import org.pentaho.reporting.engine.classic.core.style.ElementStyleKeys;
import org.pentaho.reporting.engine.classic.core.style.ResolverStyleSheet;
import org.pentaho.reporting.engine.classic.core.style.resolver.SimpleStyleResolver;
import org.pentaho.reporting.engine.classic.core.util.PageFormatFactory;
import org.pentaho.reporting.engine.classic.core.util.geom.StrictBounds;
import org.pentaho.reporting.engine.classic.core.util.geom.StrictGeomUtility;
import org.pentaho.reporting.libraries.base.util.DebugLog;
import org.pentaho.reporting.libraries.designtime.swing.ColorUtility;
/**
* Base class to handle rendering & dnd events of elements rendered inside sub-reports
*
* @author Thomas Morgner
*/
public abstract class AbstractRenderComponent extends JComponent
implements ReportElementEditorContext, CellEditorListener
{
protected class AsyncChangeNotifier implements Runnable
{
public void run()
{
final AbstractElementRenderer elementRenderer = (AbstractElementRenderer) getElementRenderer();
elementRenderer.fireChangeEvent();
}
}
protected class RequestFocusHandler extends MouseAdapter implements PropertyChangeListener
{
/**
* Invoked when the mouse has been clicked on a component.
*/
public void mouseClicked(final MouseEvent e)
{
requestFocusInWindow();
setFocused(true);
SwingUtilities.invokeLater(new AsyncChangeNotifier());
}
/**
* This method gets called when a bound property is changed.
*
* @param evt A PropertyChangeEvent object describing the event source and the property that has changed.
*/
public void propertyChange(final PropertyChangeEvent evt)
{
final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
final boolean oldFocused = isFocused();
final boolean focused = (owner == AbstractRenderComponent.this);
if (oldFocused != focused)
{
setFocused(focused);
repaint();
}
SwingUtilities.invokeLater(new AsyncChangeNotifier());
}
}
protected class RootBandChangeHandler implements SettingsListener, ReportModelListener
{
protected RootBandChangeHandler()
{
updateGridSettings();
}
public void nodeChanged(final ReportModelEvent event)
{
final Object element = event.getElement();
if (element instanceof ReportElement == false)
{
return;
}
final ReportElement reportElement = (ReportElement) element;
final Section band = getElementRenderer().getElement();
if (ModelUtility.isDescendant(band, reportElement))
{
getElementRenderer().invalidateLayout();
AbstractRenderComponent.this.revalidate();
AbstractRenderComponent.this.repaint();
return;
}
if (reportElement instanceof Section)
{
final Section section = (Section) reportElement;
if (ModelUtility.isDescendant(section, band))
{
getElementRenderer().invalidateLayout();
AbstractRenderComponent.this.revalidate();
AbstractRenderComponent.this.repaint();
}
}
}
public void settingsChanged()
{
updateGridSettings();
// this is cheap, just repaint and we will be happy
AbstractRenderComponent.this.revalidate();
AbstractRenderComponent.this.repaint();
}
}
protected class MouseSelectionHandler extends MouseAdapter implements MouseMotionListener
{
private Point2D normalizedSelectionRectangleOrigin;
private Point selectionRectangleOrigin;
private Point selectionRectangleTarget;
private boolean clearSelectionOnDrag;
private HashSet<Element> newlySelectedElements;
protected MouseSelectionHandler()
{
newlySelectedElements = new HashSet<Element>();
}
/**
* Invoked when a mouse button has been released on a component.
*/
public void mouseReleased(final MouseEvent e)
{
getDesignerContext().setSelectionWaiting(false);
normalizedSelectionRectangleOrigin = null;
selectionRectangleOrigin = null;
selectionRectangleTarget = null;
newlySelectedElements.clear();
repaint();
}
/**
* Invoked when a mouse button is pressed on a component and then dragged. <code>MOUSE_DRAGGED</code> events will
* continue to be delivered to the component where the drag originated until the mouse button is released
* (regardless of whether the mouse position is within the bounds of the component).
* <p/>
* Due to platform-dependent Drag&Drop implementations, <code>MOUSE_DRAGGED</code> events may not be delivered
* during a native Drag&Drop operation.
*/
public void mouseDragged(final MouseEvent e)
{
if (getDesignerContext().isSelectionWaiting() == false)
{
return;
}
// Check to see if this mouse handler should handle this mouse event (Mouse Operation Handler vs the Mouse Selection Handler)
if (isMouseOperationInProgress())
{
return;
}
if (normalizedSelectionRectangleOrigin == null)
{
return;
}
final Point2D normalizedSelectionRectangleTarget = normalize(e.getPoint());
normalizedSelectionRectangleTarget.setLocation(Math.max(0, normalizedSelectionRectangleTarget.getX()), Math.max(0, normalizedSelectionRectangleTarget
.getY()));
final ElementRenderer rendererRoot = getElementRenderer();
final ReportRenderContext renderContext = getRenderContext();
if (clearSelectionOnDrag)
{
final ReportSelectionModel selectionModel = renderContext.getSelectionModel();
selectionModel.clearSelection();
clearSelectionOnDrag = false;
}
selectionRectangleTarget = e.getPoint();
// Calculate the bounding box for the selection
final double y1 = Math.min(normalizedSelectionRectangleOrigin.getY(), normalizedSelectionRectangleTarget.getY());
final double x1 = Math.min(normalizedSelectionRectangleOrigin.getX(), normalizedSelectionRectangleTarget.getX());
final double y2 = Math.max(normalizedSelectionRectangleOrigin.getY(), normalizedSelectionRectangleTarget.getY());
final double x2 = Math.max(normalizedSelectionRectangleOrigin.getX(), normalizedSelectionRectangleTarget.getX());
final Element[] allNodes = rendererRoot.getElementsAt(x1, y1, x2 - x1, y2 - y1);
final ReportSelectionModel selectionModel = renderContext.getSelectionModel();
// Convert between points to micro-points (1 point X 100K is a micro-point)
final StrictBounds rect1 = StrictGeomUtility.createBounds(x1, y1, x2 - x1, y2 - y1);
final StrictBounds rect2 = new StrictBounds();
for (int i = allNodes.length - 1; i >= 0; i -= 1)
{
final Element element = allNodes[i];
if (element instanceof RootLevelBand)
{
continue;
}
final CachedLayoutData data = ModelUtility.getCachedLayoutData(element);
rect2.setRect(data.getX(), data.getY(), data.getWidth(), data.getHeight());
// Checking if the bounding box intersects an element
if (StrictBounds.intersects(rect1, rect2))
{
if (selectionModel.add(element))
{
newlySelectedElements.add(element);
}
}
}
// second step, check which previously added elements are no longer selected by the rectangle.
for (Iterator<Element> visualReportElementIterator = newlySelectedElements.iterator(); visualReportElementIterator.hasNext(); )
{
final Element element = visualReportElementIterator.next();
final CachedLayoutData data = ModelUtility.getCachedLayoutData(element);
rect2.setRect(data.getX(), data.getY(), data.getWidth(), data.getHeight());
if (StrictBounds.intersects(rect1, rect2) == false)
{
selectionModel.remove(element);
visualReportElementIterator.remove();
}
}
AbstractRenderComponent.this.repaint();
}
public Point getSelectionRectangleOrigin()
{
return selectionRectangleOrigin;
}
public Point getSelectionRectangleTarget()
{
return selectionRectangleTarget;
}
/**
* Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
*/
public void mouseMoved(final MouseEvent e)
{
}
/**
* Invoked when a mouse button has been pressed on a component.
*/
public void mousePressed(final MouseEvent e)
{
if (isMouseOperationPossible())
{
return;
}
if (getDesignerContext().isSelectionWaiting() == false)
{
return;
}
newlySelectedElements.clear();
normalizedSelectionRectangleOrigin = normalize(e.getPoint());
normalizedSelectionRectangleOrigin.setLocation(Math.max(0,
normalizedSelectionRectangleOrigin.getX()), Math.max(0, normalizedSelectionRectangleOrigin.getY()));
selectionRectangleOrigin = e.getPoint();
if (e.isShiftDown() == false)
{
clearSelectionOnDrag = true;
}
final ReportRenderContext renderContext = getRenderContext();
final ElementRenderer rendererRoot = getElementRenderer();
final ReportSelectionModel selectionModel = renderContext.getSelectionModel();
final Element[] allNodes = rendererRoot.getElementsAt
(normalizedSelectionRectangleOrigin.getX(), normalizedSelectionRectangleOrigin.getY());
for (int i = allNodes.length - 1; i >= 0; i -= 1)
{
final Element element = allNodes[i];
if (element instanceof RootLevelBand)
{
continue;
}
if (!e.isShiftDown())
{
if (!selectionModel.isSelected(element))
{
selectionModel.clearSelection();
selectionModel.add(element);
return;
}
}
}
}
/**
* Invoked when the mouse has been clicked on a component.
*/
public void mouseClicked(final MouseEvent e)
{
final Point2D point = normalize(e.getPoint());
if (point.getX() < 0 || point.getY() < 0)
{
return; // we do not handle that one ..
}
final ReportSelectionModel selectionModel = getRenderContext().getSelectionModel();
final ElementRenderer rendererRoot = getElementRenderer();
// Sorted list of all elements that intersect the point we are seeking
final Element[] allNodes = rendererRoot.getElementsAt(point.getX(), point.getY());
for (int i = allNodes.length - 1; i >= 0; i -= 1)
{
// Check if element is null due to structural helper node like (SectionRenderBox)
final Element element = allNodes[i];
if (element instanceof RootLevelBand)
{
continue;
}
if (e.isShiftDown())
{
// toggle selection ..
if (selectionModel.isSelected(element))
{
selectionModel.remove(element);
}
else
{
selectionModel.add(element);
}
}
else
{
if (!selectionModel.isSelected(element))
{
selectionModel.clearSelection();
selectionModel.add(element);
}
}
return;
}
// No element found, clear the selection.
if (e.isShiftDown() == false)
{
selectionModel.clearSelection();
}
//PRD-4466 select band (update tree) and allow insert menu to be enbaled
if(rendererRoot.getElement() instanceof RootLevelBand){
selectionModel.add(rendererRoot.getElement());
}
}
}
protected class SelectionModelListener implements ReportSelectionListener
{
protected SelectionModelListener()
{
}
public void selectionAdded(final ReportSelectionEvent event)
{
final Object element = event.getElement();
if (element instanceof Element == false)
{
return;
}
final Element velement = (Element) element;
ReportElement parentSearch = velement;
final Section rootBand = getElementRenderer().getElement();
final ZoomModel zoomModel = getRenderContext().getZoomModel();
while (parentSearch != null)
{
if (parentSearch == rootBand)
{
final SelectionOverlayInformation renderer = new SelectionOverlayInformation(velement);
renderer.validate(zoomModel.getZoomAsPercentage());
velement.setAttribute(ReportDesignerBoot.DESIGNER_NAMESPACE, ReportDesignerBoot.SELECTION_OVERLAY_INFORMATION, renderer, false);
AbstractRenderComponent.this.repaint();
return;
}
parentSearch = parentSearch.getParentSection();
}
}
public void selectionRemoved(final ReportSelectionEvent event)
{
final Object element = event.getElement();
if (element instanceof Element)
{
final Element e = (Element) element;
final Object o = e.getAttribute(ReportDesignerBoot.DESIGNER_NAMESPACE, ReportDesignerBoot.SELECTION_OVERLAY_INFORMATION);
e.setAttribute(ReportDesignerBoot.DESIGNER_NAMESPACE, ReportDesignerBoot.SELECTION_OVERLAY_INFORMATION, null, false);
if (o != null)
{
AbstractRenderComponent.this.repaint();
}
}
AbstractRenderComponent.this.repaint();
}
public void leadSelectionChanged(final ReportSelectionEvent event)
{
if (event.getModel().getSelectionCount() != 1)
{
return;
}
final Object raw = event.getElement();
if (raw instanceof Element == false)
{
return;
}
Element e = (Element) raw;
while (e != null && e instanceof RootLevelBand == false)
{
e = e.getParent();
}
if (e == getRootBand())
{
setFocused(true);
repaint();
SwingUtilities.invokeLater(new AsyncChangeNotifier());
}
else
{
setFocused(false);
repaint();
SwingUtilities.invokeLater(new AsyncChangeNotifier());
}
}
}
protected static final class RepaintHandler implements LinealModelListener, ZoomModelListener, ChangeListener
{
private AbstractRenderComponent component;
private RepaintHandler(final AbstractRenderComponent component)
{
this.component = component;
}
public void stateChanged(final ChangeEvent e)
{
// this is cheap, just repaint and we will be happy
component.revalidate();
component.repaint();
}
public void modelChanged(final LinealModelEvent event)
{
component.revalidate();
component.repaint();
}
public void zoomFactorChanged()
{
component.revalidate();
component.repaint();
component.stopCellEditing();
}
}
protected class SettingsUpdateHandler implements SettingsListener
{
protected SettingsUpdateHandler()
{
}
public void settingsChanged()
{
updateGridSettings();
revalidate();
repaint();
}
}
protected class KeyboardElementMoveHandler extends KeyAdapter
{
public KeyboardElementMoveHandler()
{
}
public void keyReleased(final KeyEvent e)
{
if (e.isShiftDown() == false && getDesignerContext().isSelectionWaiting())
{
if (currentIndicator == SelectionOverlayInformation.InRangeIndicator.NOT_IN_RANGE)
{
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
else if (currentIndicator == SelectionOverlayInformation.InRangeIndicator.MOVE)
{
setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
getDesignerContext().setSelectionWaiting(false);
}
}
public void keyPressed(final KeyEvent keyEvent)
{
// move all selected components 1px
final Element[] visualElements = getRenderContext().getSelectionModel().getSelectedVisualElements();
if (visualElements.length == 0)
{
return;
}
// if any element's X or Y is == 0, then do not move anything
// PRD-1442
final int keyCode = keyEvent.getKeyCode();
if (keyCode != KeyEvent.VK_UP && keyCode != KeyEvent.VK_DOWN &&
keyCode != KeyEvent.VK_LEFT && keyCode != KeyEvent.VK_RIGHT)
{
return;
}
if (keyEvent.isShiftDown() || keyEvent.isAltDown() || keyEvent.isControlDown())
{
return;
}
keyEvent.consume();
for (int i = 0; i < visualElements.length; i++)
{
final Element element = visualElements[i];
if (element instanceof RootLevelBand)
{
continue;
}
final double elementX = element.getStyle().getDoubleStyleProperty(ElementStyleKeys.POS_X, 0);
final double elementY = element.getStyle().getDoubleStyleProperty(ElementStyleKeys.POS_Y, 0);
// check if we can't move, one of the elements in the group is already at the minimum position
if (keyCode == KeyEvent.VK_UP && elementY == 0)
{
return;
}
else if (keyCode == KeyEvent.VK_LEFT && elementX == 0)
{
return;
}
}
final MassElementStyleUndoEntryBuilder builder = new MassElementStyleUndoEntryBuilder(visualElements);
final MoveDragOperation mop = new MoveDragOperation(visualElements, new Point(), EmptySnapModel.INSTANCE, EmptySnapModel.INSTANCE);
if (keyCode == KeyEvent.VK_UP)
{
mop.update(new Point(0, -1), 1);
}
else if (keyCode == KeyEvent.VK_DOWN)
{
mop.update(new Point(0, 1), 1);
}
else if (keyCode == KeyEvent.VK_LEFT)
{
mop.update(new Point(-1, 0), 1);
}
else
{
mop.update(new Point(1, 0), 1);
}
final MassElementStyleUndoEntry massElementStyleUndoEntry = builder.finish();
getRenderContext().getUndo().addChange(Messages.getString("AbstractRenderComponent.MoveUndoName"), massElementStyleUndoEntry);
mop.finish();
}
}
/**
* When you double-click on an element, you can edit it inside
* the canvas editor area.
*/
protected class MouseEditorActionHandler extends MouseAdapter
{
private MouseEditorActionHandler()
{
}
/**
* Invoked when the mouse has been clicked on a component.
*/
public void mouseClicked(final MouseEvent e)
{
if (stopCellEditing() == false)
{
return;
}
if (e.isPopupTrigger())
{
final Point2D point = normalize(e.getPoint());
if (point.getX() < 0 || point.getY() < 0)
{
return; // we do not handle that one ..
}
showElementPopup(e, point);
return;
}
// ReportElementInlineEditor ...
if (e.getClickCount() >= 2 && (e.getButton() == MouseEvent.BUTTON1))
{
final Point2D point = normalize(e.getPoint());
if (point.getX() < 0 || point.getY() < 0)
{
return; // we do not handle that one ..
}
final Element element = getElementForLocation(point, true);
if (element == null)
{
return;
}
final String typeName = element.getElementTypeName();
ReportElementEditor elementEditor = ReportElementEditorRegistry.getInstance().getPlugin(typeName);
if (elementEditor == null)
{
elementEditor = ReportElementEditorRegistry.getInstance().getPlugin(null);
if (elementEditor == null)
{
return;
}
}
final ReportElementInlineEditor inlineEditor = elementEditor.createInlineEditor();
if (inlineEditor == null)
{
return;
}
installEditor(inlineEditor, element);
}
}
/**
* Invoked when a mouse button has been released on a component.
*/
public void mouseReleased(final MouseEvent e)
{
if (stopCellEditing() == false)
{
return;
}
if (e.isPopupTrigger())
{
final Point2D point = normalize(e.getPoint());
if (point.getX() < 0 || point.getY() < 0)
{
return; // we do not handle that one ..
}
showElementPopup(e, point);
}
}
/**
* Invoked when a mouse button has been pressed on a component.
*/
public void mousePressed(final MouseEvent e)
{
if (stopCellEditing() == false)
{
return;
}
if (e.isPopupTrigger())
{
final Point2D point = normalize(e.getPoint());
if (point.getX() < 0 || point.getY() < 0)
{
return; // we do not handle that one ..
}
showElementPopup(e, point);
}
}
protected void showElementPopup(final MouseEvent e, final Point2D normalizedPoint)
{
Element element = getElementForLocation(normalizedPoint, true);
if (element == null)
{
element = (Element) findRootBandForPosition(normalizedPoint);
}
if (element == null)
{
return;
}
final JPopupMenu pop = ContextMenuUtility.getMenu(getDesignerContext(), element);
if (pop == null)
{
return;
}
pop.show(AbstractRenderComponent.this, e.getX(), e.getY());
}
}
private class MouseOperationHandler extends MouseAdapter implements MouseMotionListener
{
private SelectionOverlayInformation currentRenderer;
private Point2D lastPoint;
private MouseOperationHandler()
{
}
/**
* Invoked when a mouse button is pressed on a component and then dragged. <code>MOUSE_DRAGGED</code> events will continue to be delivered to the component
* where the drag originated until the mouse button is released (regardless of whether the mouse position is within the bounds of the component).
* <p/>
* Due to platform-dependent Drag&Drop implementations, <code>MOUSE_DRAGGED</code> events may not be delivered during a native Drag&Drop operation.
*/
public void mouseDragged(final MouseEvent e)
{
if (lastPoint == null)
{
return;
}
final Point2D normalizedPoint = normalize(e.getPoint());
updateElements(normalizedPoint, e.isAltDown(), e.isControlDown());
}
/**
* Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
*/
public void mouseMoved(final MouseEvent e)
{
final Point point1 = e.getPoint();
updateCursor(point1);
}
private void updateCursor(final Point rawPoint)
{
final boolean selectionMode = getDesignerContext().isSelectionWaiting();
if (selectionMode)
{
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
currentIndicator = SelectionOverlayInformation.InRangeIndicator.NOT_IN_RANGE;
return;
}
currentIndicator = SelectionOverlayInformation.InRangeIndicator.NOT_IN_RANGE;
final Point2D normalizedPoint = normalize(rawPoint);
if (currentRenderer != null)
{
currentIndicator = currentRenderer.getMouseInRangeIndicator(normalizedPoint);
if (currentIndicator == SelectionOverlayInformation.InRangeIndicator.NOT_IN_RANGE)
{
currentRenderer = null;
currentIndicator = SelectionOverlayInformation.InRangeIndicator.NOT_IN_RANGE;
}
if (currentIndicator == SelectionOverlayInformation.InRangeIndicator.MOVE)
{
currentRenderer = null;
currentIndicator = SelectionOverlayInformation.InRangeIndicator.NOT_IN_RANGE;
}
}
final Element[] renderers = getRenderContext().getSelectionModel().getSelectedVisualElements();
for (int i = 0; i < renderers.length; i++)
{
final Element e = renderers[i];
final Object o = e.getAttribute(ReportDesignerBoot.DESIGNER_NAMESPACE, "selection-overlay-information"); // NON-NLS
if (o instanceof SelectionOverlayInformation == false)
{
continue;
}
if (isLocalElement(e) == false)
{
continue;
}
final SelectionOverlayInformation renderer = (SelectionOverlayInformation) o;
final SelectionOverlayInformation.InRangeIndicator indicator = renderer.getMouseInRangeIndicator(normalizedPoint);
if (indicator == SelectionOverlayInformation.InRangeIndicator.NOT_IN_RANGE)
{
continue;
}
// a resize-handle wins over a ordinary move selection
if (currentIndicator == SelectionOverlayInformation.InRangeIndicator.MOVE
|| currentIndicator == SelectionOverlayInformation.InRangeIndicator.NOT_IN_RANGE)
{
currentIndicator = indicator;
currentRenderer = renderer;
}
else
{
break;
}
}
updateCursorForIndicator();
}
/**
* Invoked when a mouse button has been pressed on a component.
*/
public void mousePressed(final MouseEvent e)
{
lastPoint = normalize(e.getPoint());
updateCursor(e.getPoint());
initializeDragOperation(lastPoint, currentIndicator);
}
/**
* Invoked when a mouse button has been released on a component.
*/
public void mouseReleased(final MouseEvent e)
{
if (lastPoint == null)
{
return;
}
if (lastPoint.equals(normalize(e.getPoint())) == false)
{
// only fire a drag operation if we moved the mouse
finishDragOperation();
}
}
/**
* Invoked when the mouse enters a component.
*/
public void mouseEntered(final MouseEvent e)
{
updateCursor(e.getPoint());
}
/**
* Invoked when the mouse has been clicked on a component.
*/
public void mouseClicked(final MouseEvent e)
{
updateCursor(e.getPoint());
}
}
protected class CellEditorRemover implements PropertyChangeListener
{
private KeyboardFocusManager focusManager;
public CellEditorRemover(final KeyboardFocusManager fm)
{
this.focusManager = fm;
}
public void propertyChange(final PropertyChangeEvent ev)
{
if (!isEditing() || isTerminateEditOnFocusLost() == false)
{
return;
}
Component c = focusManager.getPermanentFocusOwner();
while (c != null)
{
if (c == AbstractRenderComponent.this)
{
// focus remains inside the table
return;
}
else if ((c instanceof Window) || (c instanceof Applet && c.getParent() == null))
{
if (c == SwingUtilities.getRoot(AbstractRenderComponent.this))
{
if (!getCellEditor().stopCellEditing())
{
getCellEditor().cancelCellEditing();
}
}
break;
}
c = c.getParent();
}
}
}
private class DragAbortReportModelListener implements ReportModelListener
{
private DragAbortReportModelListener()
{
}
public void nodeChanged(final ReportModelEvent event)
{
if (event.isNodeAddedEvent() || event.isNodeDeleteEvent())
{
finishDragOperation();
}
}
}
private class SelectionStateHandler implements PropertyChangeListener
{
/**
* This method gets called when a bound property is changed.
*
* @param evt A PropertyChangeEvent object describing the event source
* and the property that has changed.
*/
public void propertyChange(final PropertyChangeEvent evt)
{
if (getDesignerContext().isSelectionWaiting())
{
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
else
{
updateCursorForIndicator();
}
}
}
protected class SelectionRectangleOverlayRenderer implements OverlayRenderer
{
public SelectionRectangleOverlayRenderer()
{
}
public void validate(final ReportRenderContext context, final double zoomFactor)
{
}
public void draw(final Graphics2D graphics, final Rectangle2D bounds, final ImageObserver obs)
{
paintSelectionRectangle(graphics);
}
}
private static final BasicStroke SELECTION_STROKE = new BasicStroke(0.5f);
private CellEditorRemover editorRemover;
private RepaintHandler repaintHandler;
private SettingsUpdateHandler settingsUpdateHandler;
private ReportDesignerContext designerContext;
private ReportRenderContext renderContext;
private boolean showLeftBorder;
private boolean showTopBorder;
private double gridSize;
private int gridDivisions;
private boolean terminateEditOnFocusLost;
private Component editorComponent;
private ReportElementInlineEditor inlineEditor;
private MouseDragOperation operation;
private MassElementStyleUndoEntryBuilder undoEntryBuilder;
private FullSnapModel horizontalSnapModel;
private FullSnapModel verticalSnapModel;
private LinealModel verticalLinealModel;
private LinealModel horizontalLinealModel;
private HorizontalPositionsModel horizontalPositionsModel;
private boolean focused;
private SelectionOverlayInformation.InRangeIndicator currentIndicator;
private SelectionStateHandler selectionStateHandler;
private ArrayList<Object> oldValues = new ArrayList<Object>();
private MouseSelectionHandler selectionHandler;
private RequestFocusHandler focusHandler;
private SelectionModelListener selectionModelListener;
private RootBandChangeHandler changeHandler;
private SimpleStyleResolver styleResolver;
private ResolverStyleSheet resolvedStyle;
protected AbstractRenderComponent(final ReportDesignerContext designerContext,
final ReportRenderContext renderContext)
{
if (renderContext == null)
{
throw new NullPointerException();
}
if (designerContext == null)
{
throw new NullPointerException();
}
setDoubleBuffered(true);
setOpaque(false);
setFocusable(true);
setFocusCycleRoot(true);
setFocusTraversalKeysEnabled(false);
setLayout(null);
this.showLeftBorder = true;
this.showTopBorder = false;
this.repaintHandler = new RepaintHandler(this);
this.designerContext = designerContext;
this.renderContext = renderContext;
this.settingsUpdateHandler = new SettingsUpdateHandler();
this.horizontalSnapModel = new FullSnapModel();
this.verticalSnapModel = new FullSnapModel();
this.terminateEditOnFocusLost = true;
gridSize = WorkspaceSettings.getInstance().getGridSize();
gridDivisions = WorkspaceSettings.getInstance().getGridDivisions();
WorkspaceSettings.getInstance().addSettingsListener(settingsUpdateHandler);
new DropTarget(this, new BandDndHandler(this));
renderContext.getZoomModel().addZoomModelListener(repaintHandler);
renderContext.getReportDefinition().addReportModelListener(new DragAbortReportModelListener());
addMouseListener(new MouseEditorActionHandler());
addKeyListener(new KeyboardElementMoveHandler());
selectionStateHandler = new SelectionStateHandler();
designerContext.addPropertyChangeListener(ReportDesignerContext.SELECTION_WAITING_PROPERTY, selectionStateHandler);
focusHandler = new RequestFocusHandler();
addMouseListener(focusHandler);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("permanentFocusOwner", focusHandler); // NON-NLS
this.selectionHandler = new MouseSelectionHandler();
addMouseListener(selectionHandler);
addMouseMotionListener(selectionHandler);
this.changeHandler = new RootBandChangeHandler();
this.selectionModelListener = new SelectionModelListener();
renderContext.getSelectionModel().addReportSelectionListener(selectionModelListener);
new DropTarget(this, new BandDndHandler(this));
installMouseOperationHandler();
styleResolver = new SimpleStyleResolver(true);
resolvedStyle = new ResolverStyleSheet();
renderContext.getReportDefinition().addReportModelListener(changeHandler);
}
/**
* Abstract method to retrieve the element renderer
*
* @return ElementRenderer
*/
protected abstract ElementRenderer getElementRenderer();
/**
* Abstract method to return the default element
*
* @return Element
*/
public abstract Element getDefaultElement();
public Band getRootBand()
{
return (Band) getElementRenderer().getElement();
}
public boolean isTerminateEditOnFocusLost()
{
return terminateEditOnFocusLost;
}
public void setTerminateEditOnFocusLost(final boolean terminateEditOnFocusLost)
{
this.terminateEditOnFocusLost = terminateEditOnFocusLost;
}
protected abstract boolean isLocalElement(ReportElement e);
protected void installMouseOperationHandler()
{
// must be added *after* the selection handler
final MouseOperationHandler operationHandler = new MouseOperationHandler();
addMouseListener(operationHandler);
addMouseMotionListener(operationHandler);
}
protected boolean isFocused()
{
return focused;
}
protected void setFocused(final boolean focused)
{
this.focused = focused;
}
public boolean isShowLeftBorder()
{
return showLeftBorder;
}
public void setShowLeftBorder(final boolean showLeftBorder)
{
this.showLeftBorder = showLeftBorder;
}
public boolean isShowTopBorder()
{
return showTopBorder;
}
public void setShowTopBorder(final boolean showTopBorder)
{
this.showTopBorder = showTopBorder;
}
protected double getLeftBorder()
{
if (renderContext == null)
{
return 0;
}
if (showLeftBorder == false)
{
return 0;
}
final PageDefinition pageDefinition = renderContext.getPageDefinition();
final PageFormat pageFormat = pageDefinition.getPageFormat(0);
final PageFormatFactory pageFormatFactory = PageFormatFactory.getInstance();
return pageFormatFactory.getLeftBorder(pageFormat.getPaper());
}
protected double getTopBorder()
{
if (renderContext == null)
{
return 0;
}
if (showTopBorder == false)
{
return 0;
}
final PageDefinition pageDefinition = renderContext.getPageDefinition();
final PageFormat pageFormat = pageDefinition.getPageFormat(0);
final PageFormatFactory pageFormatFactory = PageFormatFactory.getInstance();
return pageFormatFactory.getTopBorder(pageFormat.getPaper());
}
public Point2D normalize(final Point2D e)
{
final double topBorder = getTopBorder();
final double leftBorder = getLeftBorder();
final float scaleFactor = getRenderContext().getZoomModel().getZoomAsPercentage();
final double x = (e.getX() / scaleFactor) - leftBorder;
final double y = (e.getY() / scaleFactor) - topBorder;
final Point2D o = getOffset();
o.setLocation(x, y + o.getY());
return o;
}
protected Point2D getOffset()
{
final StrictBounds bounds = getElementRenderer().getRootElementBounds();
return new Point2D.Double(StrictGeomUtility.toExternalValue(bounds.getX()),
StrictGeomUtility.toExternalValue(bounds.getY()));
}
public ReportRenderContext getRenderContext()
{
return renderContext;
}
public ReportDesignerContext getDesignerContext()
{
return designerContext;
}
protected void paintComponent(final Graphics g)
{
final Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(new Color(224, 224, 224));
g2.fillRect(0, 0, getWidth(), getHeight());
final int leftBorder = (int) getLeftBorder();
final int topBorder = (int) getTopBorder();
final float scaleFactor = getRenderContext().getZoomModel().getZoomAsPercentage();
// draw the page area ..
final PageDefinition pageDefinition = getRenderContext().getPageDefinition();
final Rectangle2D.Double area = new Rectangle2D.Double(0, 0, pageDefinition.getWidth() * scaleFactor, getHeight());
g2.translate(leftBorder * scaleFactor, topBorder * scaleFactor);
g2.clip(area);
g2.setColor(Color.WHITE);
g2.fill(area);
// draw the grid (unscaled, but translated)
final Point2D offset = getOffset();
if (offset.getX() != 0)
{
// The blackout area is for inline sub-reports and is the area where the subreport is not interested in
// (so we can clip out). The blackout area is only visible in the sub-report.
final Rectangle2D.Double blackoutArea = new Rectangle2D.Double(0, 0, offset.getX() * scaleFactor, getHeight());
g2.setColor(Color.LIGHT_GRAY);
g2.fill(blackoutArea);
}
paintGrid(g2);
paintElementAlignment(g2);
g2.dispose();
final Graphics2D logicalPageAreaG2 = (Graphics2D) g.create();
// draw the renderable content ...
logicalPageAreaG2.translate(leftBorder * scaleFactor, topBorder * scaleFactor);
logicalPageAreaG2.clip(area);
logicalPageAreaG2.scale(scaleFactor, scaleFactor);
try
{
final ElementRenderer rendererRoot = getElementRenderer();
if (rendererRoot != null)
{
if (rendererRoot.draw(logicalPageAreaG2) == false)
{
rendererRoot.handleError(designerContext, renderContext);
logicalPageAreaG2.scale(1f/scaleFactor, 1f/scaleFactor);
logicalPageAreaG2.setPaint(Color.WHITE);
logicalPageAreaG2.fill(area);
}
}
}
catch (Exception e)
{
// ignore for now..
UncaughtExceptionsModel.getInstance().addException(e);
}
logicalPageAreaG2.dispose();
final OverlayRenderer[] renderers = new OverlayRenderer[4];
renderers[0] = new OverlappingElementOverlayRenderer(getDefaultElement()); // displays the red border for warning
renderers[1] = new SelectionOverlayRenderer(getDefaultElement());
renderers[2] = new GuidelineOverlayRenderer(horizontalLinealModel, verticalLinealModel);
renderers[3] = new SelectionRectangleOverlayRenderer(); // blue box when you shift and drag the region to select multiple elements
for (int i = 0; i < renderers.length; i++)
{
final OverlayRenderer renderer = renderers[i];
final Graphics2D selectionG2 = (Graphics2D) g.create();
// TODO: Check if this is a no-op due to negative offset
selectionG2.translate(0, -offset.getY() * scaleFactor);
renderer.validate(getRenderContext(), scaleFactor);
renderer.draw(selectionG2, new Rectangle2D.Double(getLeftBorder(), getTopBorder(), getWidth(), getHeight()), this);
selectionG2.dispose();
}
}
protected void paintSelectionRectangle(final Graphics2D g2)
{
final Point origin = selectionHandler.getSelectionRectangleOrigin();
final Point target = selectionHandler.getSelectionRectangleTarget();
if (origin == null || target == null)
{
return;
}
g2.setColor(Color.BLUE);
g2.setStroke(SELECTION_STROKE);
final double y1 = Math.min(origin.getY(), target.getY());
final double x1 = Math.min(origin.getX(), target.getX());
final double y2 = Math.max(origin.getY(), target.getY());
final double x2 = Math.max(origin.getX(), target.getX());
g2.draw(new Rectangle2D.Double(x1, y1, x2 - x1, y2 - y1));
}
protected void paintGrid(final Graphics2D g2d)
{
if (WorkspaceSettings.getInstance().isShowGrid())
{
final float scaleFactor = getRenderContext().getZoomModel().getZoomAsPercentage();
final double gridSize = getGridSize() * scaleFactor;
if (gridSize < 1)
{
return;
}
final int gridDivisions = Math.max(1, getGridDivisions());
final Color primaryColor = WorkspaceSettings.getInstance().getGridColor();
final Color secondaryColor = ColorUtility.convertToBrighter(primaryColor);
// draw vertical lines
g2d.setStroke(new BasicStroke(.1f));
int horizontalLineCount = 0;
final Line2D.Double line = new Line2D.Double();
final double gridHeight = getHeight();
final double gridWidth = getWidth();
for (double w = gridSize; w < gridWidth; w += gridSize)
{
if (horizontalLineCount % gridDivisions == gridDivisions - 1)
{
g2d.setColor(primaryColor);
}
else
{
g2d.setColor(secondaryColor);
}
horizontalLineCount++;
line.setLine(w, 0, w, gridHeight);
g2d.draw(line);
}
// draw horizontal lines
int verticalLineCount = 0;
for (double h = gridSize; h < gridHeight; h += gridSize)
{
if (verticalLineCount % gridDivisions == gridDivisions - 1)
{
g2d.setColor(primaryColor);
}
else
{
g2d.setColor(secondaryColor);
}
verticalLineCount++;
line.setLine(0, h, gridWidth, h);
g2d.draw(line);
}
}
}
protected void paintElementAlignment(final Graphics2D g2d)
{
if (WorkspaceSettings.getInstance().isShowElementAlignmentHints())
{
final float scaleFactor = getRenderContext().getZoomModel().getZoomAsPercentage();
g2d.setColor(WorkspaceSettings.getInstance().getAlignmentHintColor());
g2d.setStroke(new BasicStroke(.2f));
final double gridHeight = getHeight();
final double gridWidth = getWidth();
final long[] hPositions;
if (getHorizontalPositionsModel() == null)
{
final BreakPositionsList horizontalPositions = getHorizontalEdgePositions();
hPositions = horizontalPositions.getKeys();
}
else
{
hPositions = getHorizontalPositionsModel().getBreaks();
}
final Line2D.Double line = new Line2D.Double();
for (int i = 0; i < hPositions.length; i++)
{
final double position = StrictGeomUtility.toExternalValue(hPositions[i]);
final double x = position * scaleFactor;
line.setLine(x, 0, x, gridHeight);
g2d.draw(line);
}
final Point2D offset = getOffset();
final BreakPositionsList verticalPositions = getVerticalEdgePositions();
final long[] vPositions = verticalPositions.getKeys();
for (int i = 0; i < vPositions.length; i++)
{
final double position = StrictGeomUtility.toExternalValue(vPositions[i]) - offset.getY();
final double y2 = position * scaleFactor;
line.setLine(0, y2, gridWidth, y2);
g2d.draw(line);
}
}
}
protected void updateGridSettings()
{
gridSize = WorkspaceSettings.getInstance().getGridSize();
gridDivisions = WorkspaceSettings.getInstance().getGridDivisions();
}
public double getGridSize()
{
return gridSize;
}
public int getGridDivisions()
{
return gridDivisions;
}
public Element getElementForLocation(final Point2D point, final boolean onlySelected)
{
final ElementRenderer rendererRoot = getElementRenderer();
final Element[] allNodes = rendererRoot.getElementsAt(point.getX(), point.getY());
for (int i = allNodes.length - 1; i >= 0; i -= 1)
{
final Element element = allNodes[i];
if (ModelUtility.isHideInLayoutGui(element) == true)
{
continue;
}
styleResolver.resolve(element, resolvedStyle);
if (resolvedStyle.getBooleanStyleProperty(ElementStyleKeys.VISIBLE) == false)
{
continue;
}
if (onlySelected == false || getRenderContext().getSelectionModel().isSelected(element))
{
return element;
}
}
return null;
}
protected RootLevelBand findRootBandForPosition(final Point2D point)
{
if (getElementRenderer() == null)
{
return null;
}
final Element[] elementsAt = getElementRenderer().getElementsAt(point.getX(), point.getY());
for (int i = elementsAt.length - 1; i >= 0; i -= 1)
{
final Element element = elementsAt[i];
if (element instanceof RootLevelBand)
{
return (RootLevelBand) element;
}
}
final Section section = getElementRenderer().getElement();
if (section instanceof RootLevelBand)
{
return (RootLevelBand) section;
}
return null;
}
public void dispose()
{
WorkspaceSettings.getInstance().removeSettingsListener(settingsUpdateHandler);
if (this.verticalLinealModel != null)
{
this.verticalLinealModel.removeLinealModelListener(repaintHandler);
}
if (this.horizontalLinealModel != null)
{
this.horizontalLinealModel.removeLinealModelListener(repaintHandler);
}
if (getElementRenderer() != null)
{
getElementRenderer().removeChangeListener(repaintHandler);
}
designerContext.removePropertyChangeListener(ReportDesignerContext.SELECTION_WAITING_PROPERTY, selectionStateHandler);
KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("permanentFocusOwner", focusHandler); // NON-NLS
final ReportRenderContext renderContext = getRenderContext();
renderContext.getReportDefinition().removeReportModelListener(changeHandler);
renderContext.getSelectionModel().removeReportSelectionListener(selectionModelListener);
getElementRenderer().dispose();
}
protected void removeEditor()
{
if (editorRemover != null)
{
KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener
("permanentFocusOwner", editorRemover); // NON-NLS
editorRemover = null;
}
if (editorComponent == null)
{
inlineEditor = null;
return;
}
remove(editorComponent);
inlineEditor.removeCellEditorListener(this);
editorComponent = null;
inlineEditor = null;
}
protected ReportElementInlineEditor getCellEditor()
{
return inlineEditor;
}
protected boolean installEditor(final ReportElementInlineEditor inlineEditor, final Element element)
{
if (inlineEditor == null)
{
throw new NullPointerException();
}
this.inlineEditor = inlineEditor;
final CachedLayoutData data = ModelUtility.getCachedLayoutData(element);
if (data == null)
{
removeEditor();
return false;
}
final Component editorComponent = inlineEditor.getElementCellEditorComponent(this, element);
if (editorComponent == null)
{
removeEditor();
return false;
}
if (editorRemover == null)
{
final KeyboardFocusManager fm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
editorRemover = new CellEditorRemover(fm);
fm.addPropertyChangeListener("permanentFocusOwner", editorRemover); // NON-NLS
}
this.editorComponent = editorComponent;
final float zoomFactor = getRenderContext().getZoomModel().getZoomAsPercentage();
final int x = (int) ((getLeftBorder() + StrictGeomUtility.toExternalValue(data.getX())) * zoomFactor);
final int y = (int) ((getTopBorder() + StrictGeomUtility.toExternalValue(data.getY())) * zoomFactor);
final int width = (int) (StrictGeomUtility.toExternalValue(data.getWidth()) * zoomFactor);
final int height = (int) (StrictGeomUtility.toExternalValue(data.getHeight()) * zoomFactor);
editorComponent.setBounds(x, y, width, height);
add(editorComponent);
editorComponent.validate();
inlineEditor.addCellEditorListener(this);
final Element[] visualElements = getRenderContext().getSelectionModel().getSelectedVisualElements();
if (visualElements.length > 0)
{
oldValues = new ArrayList<Object>();
for (int i = 0; i < visualElements.length; i++)
{
final Object attribute = visualElements[i].getAttribute(AttributeNames.Core.NAMESPACE, AttributeNames.Core.VALUE);
oldValues.add(attribute);
}
}
return true;
}
protected boolean isEditing()
{
return inlineEditor != null;
}
public void editingStopped(final ChangeEvent e)
{
final Element[] visualElements = getRenderContext().getSelectionModel().getSelectedVisualElements();
if (visualElements.length > 0)
{
final ArrayList<UndoEntry> undos = new ArrayList<UndoEntry>();
for (int i = 0; i < visualElements.length; i++)
{
final Object attribute = visualElements[i].getAttribute(AttributeNames.Core.NAMESPACE, AttributeNames.Core.VALUE);
undos.add(new AttributeEditUndoEntry(visualElements[i].getObjectID(), AttributeNames.Core.NAMESPACE, AttributeNames.Core.VALUE, oldValues.get(i),
attribute));
}
getRenderContext().getUndo().addChange(Messages.getString("AbstractRenderComponent.InlineEditUndoName"),
new CompoundUndoEntry((UndoEntry[]) undos.toArray(new UndoEntry[undos.size()])));
}
removeEditor();
}
public void editingCanceled(final ChangeEvent e)
{
operation = null;
undoEntryBuilder = null;
removeEditor();
}
public JComponent getRepresentationContainer()
{
return this;
}
public LinealModel getVerticalLinealModel()
{
return verticalLinealModel;
}
public LinealModel getHorizontalLinealModel()
{
return horizontalLinealModel;
}
public HorizontalPositionsModel getHorizontalPositionsModel()
{
return horizontalPositionsModel;
}
protected void updateElements(final Point2D normalizedPoint, final boolean snapToGrid, final boolean snapToElements)
{
if (operation != null)
{
horizontalSnapModel.setEnableElements(snapToElements || WorkspaceSettings.getInstance().isSnapToElements());
horizontalSnapModel.setEnableGrid(snapToGrid || WorkspaceSettings.getInstance().isSnapToGrid());
horizontalSnapModel.setEnableGuides(true);
verticalSnapModel.setEnableElements(snapToElements || WorkspaceSettings.getInstance().isSnapToElements());
verticalSnapModel.setEnableGrid(snapToGrid || WorkspaceSettings.getInstance().isSnapToGrid());
verticalSnapModel.setEnableGuides(true);
operation.update(normalizedPoint, getRenderContext().getZoomModel().getZoomAsPercentage());
}
}
/**
* Returns the break positions for inner-band drag-operations (snap to element).
*
* @return the edge positions of all elements.
*/
protected BreakPositionsList getHorizontalEdgePositions()
{
return getElementRenderer().getHorizontalEdgePositions();
}
/**
* Returns the break positions for inner-band drag-operations (snap to element).
*
* @return the edge positions of all elements.
*/
protected BreakPositionsList getVerticalEdgePositions()
{
return getElementRenderer().getVerticalEdgePositions();
}
protected void initializeDragOperation(final Point2D originPoint,
final SelectionOverlayInformation.InRangeIndicator currentIndicator)
{
final Element[] visualElements = getRenderContext().getSelectionModel().getSelectedVisualElements();
if (visualElements.length == 0)
{
return;
}
horizontalSnapModel.getGridModel().setGridSize(StrictGeomUtility.toInternalValue(getGridSize()));
verticalSnapModel.getGridModel().setGridSize(StrictGeomUtility.toInternalValue(getGridSize()));
horizontalSnapModel.setEnableGrid(WorkspaceSettings.getInstance().isSnapToGrid());
verticalSnapModel.setEnableGrid(WorkspaceSettings.getInstance().isSnapToGrid());
final SnapToPositionModel horizontalGuildesPositions = horizontalSnapModel.getGuidesModel();
horizontalGuildesPositions.clear();
final GuideLine[] hlines = horizontalLinealModel.getGuideLines();
for (int i = 0; i < hlines.length; i++)
{
final GuideLine guideLine = hlines[i];
if (guideLine.isActive())
{
horizontalGuildesPositions.add(StrictGeomUtility.toInternalValue(guideLine.getPosition()), null);
}
}
final SnapToPositionModel verticalGuidesPositions = verticalSnapModel.getGuidesModel();
verticalGuidesPositions.clear();
final GuideLine[] vlines = verticalLinealModel.getGuideLines();
for (int i = 0; i < vlines.length; i++)
{
final GuideLine guideLine = vlines[i];
if (guideLine.isActive())
{
verticalGuidesPositions.add(StrictGeomUtility.toInternalValue(guideLine.getPosition()), null);
}
}
final SnapToPositionModel hElementModel = horizontalSnapModel.getElementModel();
hElementModel.clear();
final BreakPositionsList horizontalPositions = getHorizontalEdgePositions();
final long[] horizontalKeys;
if (horizontalPositionsModel == null)
{
horizontalKeys = horizontalPositions.getKeys();
}
else
{
horizontalKeys = horizontalPositionsModel.getBreaks();
}
for (int i = 0; i < horizontalKeys.length; i++)
{
final long key = horizontalKeys[i];
hElementModel.add(key, horizontalPositions.getOwner(key));
}
final SnapToPositionModel vElementModel = verticalSnapModel.getElementModel();
vElementModel.clear();
final BreakPositionsList verticalPositions = getVerticalEdgePositions();
final long[] verticalKeys = verticalPositions.getKeys();
for (int i = 0; i < verticalKeys.length; i++)
{
final long key = verticalKeys[i];
vElementModel.add(key, verticalPositions.getOwner(key));
}
switch (currentIndicator)
{
case MOVE:
operation = new MoveDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel);
break;
case BOTTOM_CENTER:
operation = new ResizeBottomDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel);
break;
case MIDDLE_RIGHT:
operation = new ResizeRightDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel);
break;
case MIDDLE_LEFT:
operation = new ResizeLeftDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel);
break;
case TOP_CENTER:
operation = new ResizeTopDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel);
break;
case BOTTOM_LEFT:
{
final CompoundDragOperation op = new CompoundDragOperation();
op.add(new ResizeLeftDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel));
op.add(new ResizeBottomDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel));
operation = op;
break;
}
case BOTTOM_RIGHT:
{
final CompoundDragOperation op = new CompoundDragOperation();
op.add(new ResizeRightDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel));
op.add(new ResizeBottomDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel));
operation = op;
break;
}
case TOP_LEFT:
{
final CompoundDragOperation op = new CompoundDragOperation();
op.add(new ResizeLeftDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel));
op.add(new ResizeTopDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel));
operation = op;
break;
}
case TOP_RIGHT:
{
final CompoundDragOperation op = new CompoundDragOperation();
op.add(new ResizeRightDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel));
op.add(new ResizeTopDragOperation(visualElements, originPoint, horizontalSnapModel, verticalSnapModel));
operation = op;
break;
}
default:
}
if (operation != null)
{
undoEntryBuilder = new MassElementStyleUndoEntryBuilder(visualElements);
}
}
protected void finishDragOperation()
{
if (operation != null)
{
operation.finish();
final MassElementStyleUndoEntry undoEntry = undoEntryBuilder.finish();
getRenderContext().getUndo().addChange(Messages.getString("AbstractRenderComponent.ResizeUndoName"), undoEntry);
}
operation = null;
undoEntryBuilder = null;
repaint();
}
protected boolean isMouseOperationInProgress()
{
return operation != null;
}
protected boolean isMouseOperationPossible()
{
return currentIndicator != null && currentIndicator != SelectionOverlayInformation.InRangeIndicator.NOT_IN_RANGE;
}
protected void installLineals(final LinealModel horizontalLinealModel,
final HorizontalPositionsModel horizontalPositionsModel)
{
final LinealModel verticalLinealModel;
final ElementRenderer elementRenderer = getElementRenderer();
if (elementRenderer != null)
{
verticalLinealModel = elementRenderer.getVerticalLinealModel();
}
else
{
verticalLinealModel = null;
}
if (this.verticalLinealModel != null)
{
this.verticalLinealModel.removeLinealModelListener(repaintHandler);
}
if (this.horizontalLinealModel != null)
{
this.horizontalLinealModel.removeLinealModelListener(repaintHandler);
}
this.horizontalPositionsModel = horizontalPositionsModel;
this.verticalLinealModel = verticalLinealModel;
this.horizontalLinealModel = horizontalLinealModel;
if (this.verticalLinealModel != null)
{
this.verticalLinealModel.addLinealModelListener(repaintHandler);
}
if (this.horizontalLinealModel != null)
{
this.horizontalLinealModel.addLinealModelListener(repaintHandler);
}
if (elementRenderer != null)
{
elementRenderer.removeChangeListener(repaintHandler);
elementRenderer.addChangeListener(repaintHandler);
}
}
public Dimension getMinimumSize()
{
return getPreferredSize();
}
public Dimension getPreferredSize()
{
final ElementRenderer rendererRoot = getElementRenderer();
if (rendererRoot == null)
{
return new Dimension(0, 0);
}
final float zoom = getRenderContext().getZoomModel().getZoomAsPercentage();
try
{
final Rectangle2D bounds = rendererRoot.getBounds();
final int leftBorder;
if (isShowLeftBorder())
{
leftBorder = (int) getLeftBorder();
}
else
{
leftBorder = 0;
}
final int topBorder;
if (isShowTopBorder())
{
topBorder = (int) getTopBorder();
}
else
{
topBorder = 0;
}
return new Dimension((int) (zoom * (leftBorder + bounds.getWidth())), (int) (zoom * (topBorder + bounds.getHeight())));
}
catch (Exception e)
{
UncaughtExceptionsModel.getInstance().addException(e);
return new Dimension(0, (int) (zoom * rendererRoot.getVisualHeight()));
}
}
public void removeNotify()
{
KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener
("permanentFocusOwner", editorRemover); // NON-NLS
editorRemover = null;
super.removeNotify();
}
protected boolean stopCellEditing()
{
if (isEditing() == false)
{
return true;
}
final ReportElementInlineEditor elementInlineEditor = getCellEditor();
if (elementInlineEditor == null)
{
return true;
}
return elementInlineEditor.stopCellEditing();
}
protected void updateCursorForIndicator()
{
if (currentIndicator == null)
{
setCursor(Cursor.getDefaultCursor());
return;
}
switch (currentIndicator)
{
case NOT_IN_RANGE:
setCursor(Cursor.getDefaultCursor());
break;
case MOVE:
setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
break;
case BOTTOM_CENTER:
setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));
break;
case BOTTOM_LEFT:
setCursor(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR));
break;
case BOTTOM_RIGHT:
setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
break;
case MIDDLE_LEFT:
setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
break;
case MIDDLE_RIGHT:
setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
break;
case TOP_LEFT:
setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR));
break;
case TOP_CENTER:
setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
break;
case TOP_RIGHT:
setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR));
break;
}
}
}
|
package som.vmobjects;
import som.vm.constants.Classes;
public final class SSymbol extends SAbstractObject {
private final String string;
private final int numberOfSignatureArguments;
public SSymbol(final String value) {
string = value;
numberOfSignatureArguments = determineNumberOfSignatureArguments();
}
@Override
public SClass getSOMClass() {
assert Classes.symbolClass != null;
return Classes.symbolClass;
}
@Override
public boolean isValue() {
return true;
}
public String getString() {
// Get the string associated to this symbol
return string;
}
private int determineNumberOfSignatureArguments() {
// Check for binary signature
if (isBinarySignature()) {
return 2;
} else {
// Count the colons in the signature string
int numberOfColons = 0;
// Iterate through every character in the signature string
for (char c : string.toCharArray()) {
if (c == ':') { numberOfColons++; }
}
// The number of arguments is equal to the number of colons plus one
return numberOfColons + 1;
}
}
@Override
public String toString() {
return "#" + string;
}
/**
* @return number of arguments, including receiver
*/
public int getNumberOfSignatureArguments() {
return numberOfSignatureArguments;
}
private boolean isBinarySignature() {
// Check the individual characters of the string
for (char c : string.toCharArray()) {
if (c != '~' && c != '&' && c != '|' && c != '*' && c != '/' && c != '@'
&& c != '+' && c != '-' && c != '=' && c != '>' && c != '<'
&& c != ',' && c != '%' && c != '\\') { return false; }
}
return true;
}
}
|
package com.cronutils;
import com.cronutils.model.Cron;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import org.junit.Test;
import org.threeten.bp.ZonedDateTime;
import static org.junit.Assert.assertEquals;
public class Issue223Test {
/**
* Issue #223: for dayOfWeek value == 3 && division of day, nextExecution do not return correct results
*/
@Test
public void testEveryWednesdayOfEveryDayNextExecution() {
CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX);
CronParser parser = new CronParser(cronDefinition);
Cron myCron = parser.parse("* * * * 3");
ZonedDateTime time = ZonedDateTime.parse("2017-09-05T11:31:55.407-05:00");
assertEquals(ZonedDateTime.parse("2017-09-06T00:00-05:00"), ExecutionTime.forCron(myCron).nextExecution(time).get());
myCron = parser.parse("* * */1 * 3");
time = ZonedDateTime.parse("2017-09-05T11:31:55.407-05:00");
assertEquals(ZonedDateTime.parse("2017-09-06T00:00-05:00"), ExecutionTime.forCron(myCron).nextExecution(time).get());
}
}
|
package com.bignerdranch.expandablerecyclerview;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import com.bignerdranch.expandablerecyclerview.model.ParentListItem;
import com.bignerdranch.expandablerecyclerview.model.ParentWrapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* RecyclerView.Adapter implementation that
* adds the ability to expand and collapse list items.
*
* Changes should be notified through:
* {@link #notifyParentItemInserted(int)}
* {@link #notifyParentItemRemoved(int)}
* {@link #notifyParentItemChanged(int)}
* {@link #notifyParentItemRangeInserted(int, int)}
* {@link #notifyChildItemInserted(int, int)}
* {@link #notifyChildItemRemoved(int, int)}
* {@link #notifyChildItemChanged(int, int)}
* methods and not the notify methods of RecyclerView.Adapter.
*
* @author Ryan Brooks
* @version 1.0
* @since 5/27/2015
*/
public abstract class ExpandableRecyclerAdapter<PVH extends ParentViewHolder, CVH extends ChildViewHolder>
extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements ParentViewHolder.ParentListItemExpandCollapseListener {
private static final String EXPANDED_STATE_MAP = "ExpandableRecyclerAdapter.ExpandedStateMap";
/** Default ViewType for parent rows */
public static final int TYPE_PARENT = 0;
/** Default ViewType for children rows */
public static final int TYPE_CHILD = 1;
/** Start of user-defined view types */
public static final int TYPE_FIRST_USER = 2;
/**
* A {@link List} of all currently expanded {@link ParentListItem} objects
* and their children, in order. Changes to this list should be made through the add/remove methods
* available in {@link ExpandableRecyclerAdapter}
*/
protected List<Object> mItemList;
private List<? extends ParentListItem> mParentItemList;
private ExpandCollapseListener mExpandCollapseListener;
private List<RecyclerView> mAttachedRecyclerViewPool;
/**
* Allows objects to register themselves as expand/collapse listeners to be
* notified of change events.
* <p>
* Implement this in your {@link android.app.Activity} or {@link android.app.Fragment}
* to receive these callbacks.
*/
public interface ExpandCollapseListener {
/**
* Called when a list item is expanded.
*
* @param position The index of the item in the list being expanded
*/
void onListItemExpanded(int position);
/**
* Called when a list item is collapsed.
*
* @param position The index of the item in the list being collapsed
*/
void onListItemCollapsed(int position);
}
/**
* Primary constructor. Sets up {@link #mParentItemList} and {@link #mItemList}.
*
* Changes to {@link #mParentItemList} should be made through add/remove methods in
* {@link ExpandableRecyclerAdapter}
*
* @param parentItemList List of all {@link ParentListItem} objects to be
* displayed in the RecyclerView that this
* adapter is linked to
*/
public ExpandableRecyclerAdapter(@NonNull List<? extends ParentListItem> parentItemList) {
super();
mParentItemList = parentItemList;
mItemList = ExpandableRecyclerAdapterHelper.generateParentChildItemList(parentItemList);
mAttachedRecyclerViewPool = new ArrayList<>();
}
/**
* Implementation of Adapter.onCreateViewHolder(ViewGroup, int)
* that determines if the list item is a parent or a child and calls through
* to the appropriate implementation of either {@link #onCreateParentViewHolder(ViewGroup, int)}
* or {@link #onCreateChildViewHolder(ViewGroup, int)}.
*
* @param viewGroup The {@link ViewGroup} into which the new {@link android.view.View}
* will be added after it is bound to an adapter position.
* @param viewType The view type of the new {@code android.view.View}.
* @return A new RecyclerView.ViewHolder
* that holds a {@code android.view.View} of the given view type.
*/
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (isParentViewType(viewType)) {
PVH pvh = onCreateParentViewHolder(viewGroup, viewType);
pvh.setParentListItemExpandCollapseListener(this);
pvh.mExpandableAdapter = this;
return pvh;
} else {
CVH cvh = onCreateChildViewHolder(viewGroup, viewType);
cvh.mExpandableAdapter = this;
return cvh;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Object listItem = getListItem(position);
if (listItem instanceof ParentWrapper) {
PVH parentViewHolder = (PVH) holder;
if (parentViewHolder.shouldItemViewClickToggleExpansion()) {
parentViewHolder.setMainItemClickToExpand();
}
ParentWrapper parentWrapper = (ParentWrapper) listItem;
parentViewHolder.setExpanded(parentWrapper.isExpanded());
parentViewHolder.mParentWrapper = parentWrapper;
onBindParentViewHolder(parentViewHolder, getNearestParentPosition(position), parentWrapper.getParentListItem());
} else if (listItem == null) {
throw new IllegalStateException("Incorrect ViewHolder found");
} else {
CVH childViewHolder = (CVH) holder;
childViewHolder.mChildListItem = listItem;
onBindChildViewHolder(childViewHolder, getNearestParentPosition(position), getChildPosition(position), listItem);
}
}
/**
* Callback called from {@link #onCreateViewHolder(ViewGroup, int)} when
* the list item created is a parent.
*
* @param parentViewGroup The {@link ViewGroup} in the list for which a {@link PVH}
* is being created
* @return A {@code PVH} corresponding to the {@link ParentListItem} with
* the {@code ViewGroup} parentViewGroup
*/
public abstract PVH onCreateParentViewHolder(ViewGroup parentViewGroup, int viewType);
/**
* Callback called from {@link #onCreateViewHolder(ViewGroup, int)} when
* the list item created is a child.
*
* @param childViewGroup The {@link ViewGroup} in the list for which a {@link CVH}
* is being created
* @return A {@code CVH} corresponding to the child list item with the
* {@code ViewGroup} childViewGroup
*/
public abstract CVH onCreateChildViewHolder(ViewGroup childViewGroup, int viewType);
/**
* Callback called from onBindViewHolder(RecyclerView.ViewHolder, int)
* when the list item bound to is a parent.
* <p>
* Bind data to the {@link PVH} here.
*
* @param parentViewHolder The {@code PVH} to bind data to
* @param parentPosition The position of the Parent item to bind
* @param parentListItem The {@link ParentListItem} which holds the data to
* be bound to the {@code PVH}
*/
public abstract void onBindParentViewHolder(PVH parentViewHolder, int parentPosition, ParentListItem parentListItem);
/**
* Callback called from onBindViewHolder(RecyclerView.ViewHolder, int)
* when the list item bound to is a child.
* <p>
* Bind data to the {@link CVH} here.
*
* @param childViewHolder The {@code CVH} to bind data to
* @param parentPosition The position of the Parent item that contains the child to bind
* @param childPosition The position of the Child item to bind
* @param childListItem The child list item which holds that data to be
* bound to the {@code CVH}
*/
public abstract void onBindChildViewHolder(CVH childViewHolder, int parentPosition, int childPosition, Object childListItem);
/**
* Gets the number of parent and child objects currently expanded.
*
* @return The size of {@link #mItemList}
*/
@Override
public int getItemCount() {
return mItemList.size();
}
@Override
public int getItemViewType(int position) {
Object listItem = getListItem(position);
if (listItem instanceof ParentWrapper) {
return getParentItemViewType(getNearestParentPosition(position));
} else if (listItem == null) {
throw new IllegalStateException("Null object added");
} else {
return getChildItemViewType(getNearestParentPosition(position), getChildPosition(position));
}
}
/**
* Return the view type of the parent item at {@code parentPosition} for the purposes
* of view recycling.
* <p>
* The default implementation of this method returns {@link #TYPE_PARENT}, making the assumption of
* a single view type for the parent items in this adapter. Unlike ListView adapters, types need not
* be contiguous. Consider using id resources to uniquely identify item view types.
* <p>
* If you are overriding this method make sure to override {@link #isParentViewType(int)} as well.
* <p>
* Start your defined viewtypes at {@link #TYPE_FIRST_USER}
*
* @param parentPosition The index of the parent to query
* @return integer value identifying the type of the view needed to represent the item at
* {@code parentPosition}. Type codes need not be contiguous.
*/
public int getParentItemViewType(int parentPosition) {
return TYPE_PARENT;
}
/**
* Return the view type of the child item at {@code parentPosition} contained within the parent
* at {@code parentPosition} for the purposes of view recycling.
* <p>
* The default implementation of this method returns {@link #TYPE_CHILD}, making the assumption of
* a single view type for the child items in this adapter. Unlike ListView adapters, types need not
* be contiguous. Consider using id resources to uniquely identify item view types.
* <p>
* Start your defined viewtypes at {@link #TYPE_FIRST_USER}
*
* @param parentPosition The index of the parent continaing the child to query
* @param childPosition The index of the child within the parent to query
* @return integer value identifying the type of the view needed to represent the item at
* {@code parentPosition}. Type codes need not be contiguous.
*/
public int getChildItemViewType(int parentPosition, int childPosition) {
return TYPE_CHILD;
}
/**
* Used to determine whether a viewType is that of a parent or not, for ViewHolder creation purposes.
* <p>
* Only override if {@link #getParentItemViewType(int)} is being overriden
*
* @param viewType the viewType identifier in question
* @return whether the given viewType belongs to a parent view
*/
public boolean isParentViewType(int viewType) {
return viewType == TYPE_PARENT;
}
/**
* Gets the list of ParentItems that is backing this adapter.
* Changes can be made to the list and the adapter notified via the
* {@link #notifyParentItemInserted(int)}
* {@link #notifyParentItemRemoved(int)}
* {@link #notifyParentItemChanged(int)}
* {@link #notifyParentItemRangeInserted(int, int)}
* {@link #notifyChildItemInserted(int, int)}
* {@link #notifyChildItemRemoved(int, int)}
* {@link #notifyChildItemChanged(int, int)}
* methods.
*
*
* @return The list of ParentListItems that this adapter represents
*/
public List<? extends ParentListItem> getParentItemList() {
return mParentItemList;
}
/**
* Implementation of {@link com.bignerdranch.expandablerecyclerview.ParentViewHolder.ParentListItemExpandCollapseListener#onParentListItemExpanded(int)}.
* <p>
* Called when a {@link ParentListItem} is triggered to expand.
*
* @param position The index of the item in the list being expanded
*/
@Override
public void onParentListItemExpanded(int position) {
Object listItem = getListItem(position);
if (listItem instanceof ParentWrapper) {
expandParentListItem((ParentWrapper) listItem, position, true);
}
}
/**
* Implementation of {@link com.bignerdranch.expandablerecyclerview.ParentViewHolder.ParentListItemExpandCollapseListener#onParentListItemCollapsed(int)}.
* <p>
* Called when a {@link ParentListItem} is triggered to collapse.
*
* @param position The index of the item in the list being collapsed
*/
@Override
public void onParentListItemCollapsed(int position) {
Object listItem = getListItem(position);
if (listItem instanceof ParentWrapper) {
collapseParentListItem((ParentWrapper) listItem, position, true);
}
}
/**
* Implementation of Adapter#onAttachedToRecyclerView(RecyclerView).
* <p>
* Called when this {@link ExpandableRecyclerAdapter} is attached to a RecyclerView.
*
* @param recyclerView The {@code RecyclerView} this {@code ExpandableRecyclerAdapter}
* is being attached to
*/
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
mAttachedRecyclerViewPool.add(recyclerView);
}
/**
* Implementation of Adapter.onDetachedFromRecyclerView(RecyclerView)
* <p>
* Called when this ExpandableRecyclerAdapter is detached from a RecyclerView.
*
* @param recyclerView The {@code RecyclerView} this {@code ExpandableRecyclerAdapter}
* is being detached from
*/
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
mAttachedRecyclerViewPool.remove(recyclerView);
}
public void setExpandCollapseListener(ExpandCollapseListener expandCollapseListener) {
mExpandCollapseListener = expandCollapseListener;
}
// region Programmatic Expansion/Collapsing
/**
* Expands the parent with the specified index in the list of parents.
*
* @param parentIndex The index of the parent to expand
*/
public void expandParent(int parentIndex) {
int parentWrapperIndex = getParentWrapperIndex(parentIndex);
Object listItem = getListItem(parentWrapperIndex);
ParentWrapper parentWrapper;
if (listItem instanceof ParentWrapper) {
parentWrapper = (ParentWrapper) listItem;
} else {
return;
}
expandViews(parentWrapper, parentWrapperIndex);
}
/**
* Expands the parent associated with a specified {@link ParentListItem} in
* the list of parents.
*
* @param parentListItem The {@code ParentListItem} of the parent to expand
*/
public void expandParent(ParentListItem parentListItem) {
ParentWrapper parentWrapper = getParentWrapper(parentListItem);
int parentWrapperIndex = mItemList.indexOf(parentWrapper);
if (parentWrapperIndex == -1) {
return;
}
expandViews(parentWrapper, parentWrapperIndex);
}
/**
* Expands all parents in a range of indices in the list of parents.
*
* @param startParentIndex The index at which to to start expanding parents
* @param parentCount The number of parents to expand
*/
public void expandParentRange(int startParentIndex, int parentCount) {
int endParentIndex = startParentIndex + parentCount;
for (int i = startParentIndex; i < endParentIndex; i++) {
expandParent(i);
}
}
/**
* Expands all parents in the list.
*/
public void expandAllParents() {
for (ParentListItem parentListItem : mParentItemList) {
expandParent(parentListItem);
}
}
/**
* Collapses the parent with the specified index in the list of parents.
*
* @param parentIndex The index of the parent to collapse
*/
public void collapseParent(int parentIndex) {
int parentWrapperIndex = getParentWrapperIndex(parentIndex);
Object listItem = getListItem(parentWrapperIndex);
ParentWrapper parentWrapper;
if (listItem instanceof ParentWrapper) {
parentWrapper = (ParentWrapper) listItem;
} else {
return;
}
collapseViews(parentWrapper, parentWrapperIndex);
}
/**
* Collapses the parent associated with a specified {@link ParentListItem} in
* the list of parents.
*
* @param parentListItem The {@code ParentListItem} of the parent to collapse
*/
public void collapseParent(ParentListItem parentListItem) {
ParentWrapper parentWrapper = getParentWrapper(parentListItem);
int parentWrapperIndex = mItemList.indexOf(parentWrapper);
if (parentWrapperIndex == -1) {
return;
}
collapseViews(parentWrapper, parentWrapperIndex);
}
/**
* Collapses all parents in a range of indices in the list of parents.
*
* @param startParentIndex The index at which to to start collapsing parents
* @param parentCount The number of parents to collapse
*/
public void collapseParentRange(int startParentIndex, int parentCount) {
int endParentIndex = startParentIndex + parentCount;
for (int i = startParentIndex; i < endParentIndex; i++) {
collapseParent(i);
}
}
/**
* Collapses all parents in the list.
*/
public void collapseAllParents() {
for (ParentListItem parentListItem : mParentItemList) {
collapseParent(parentListItem);
}
}
/**
* Stores the expanded state map across state loss.
* <p>
* Should be called from {@link Activity#onSaveInstanceState(Bundle)} in
* the {@link Activity} that hosts the RecyclerView that this
* {@link ExpandableRecyclerAdapter} is attached to.
* <p>
* This will make sure to add the expanded state map as an extra to the
* instance state bundle to be used in {@link #onRestoreInstanceState(Bundle)}.
*
* @param savedInstanceState The {@code Bundle} into which to store the
* expanded state map
*/
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable(EXPANDED_STATE_MAP, generateExpandedStateMap());
}
/**
* Fetches the expandable state map from the saved instance state {@link Bundle}
* and restores the expanded states of all of the list items.
* <p>
* Should be called from {@link Activity#onRestoreInstanceState(Bundle)} in
* the {@link Activity} that hosts the RecyclerView that this
* {@link ExpandableRecyclerAdapter} is attached to.
* <p>
* Assumes that the list of parent list items is the same as when the saved
* instance state was stored.
*
* @param savedInstanceState The {@code Bundle} from which the expanded
* state map is loaded
*/
public void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState == null
|| !savedInstanceState.containsKey(EXPANDED_STATE_MAP)) {
return;
}
HashMap<Integer, Boolean> expandedStateMap = (HashMap<Integer, Boolean>) savedInstanceState.getSerializable(EXPANDED_STATE_MAP);
if (expandedStateMap == null) {
return;
}
List<Object> parentWrapperList = new ArrayList<>();
ParentListItem parentListItem;
ParentWrapper parentWrapper;
int parentListItemCount = mParentItemList.size();
for (int i = 0; i < parentListItemCount; i++) {
parentListItem = mParentItemList.get(i);
parentWrapper = new ParentWrapper(parentListItem);
parentWrapperList.add(parentWrapper);
if (expandedStateMap.containsKey(i)) {
boolean expanded = expandedStateMap.get(i);
if (expanded) {
parentWrapper.setExpanded(true);
int childListItemCount = parentWrapper.getChildItemList().size();
for (int j = 0; j < childListItemCount; j++) {
parentWrapperList.add(parentWrapper.getChildItemList().get(j));
}
}
}
}
mItemList = parentWrapperList;
notifyDataSetChanged();
}
/**
* Gets the list item held at the specified adapter position.
*
* @param position The index of the list item to return
* @return The list item at the specified position
*/
protected Object getListItem(int position) {
boolean indexInRange = position >= 0 && position < mItemList.size();
if (indexInRange) {
return mItemList.get(position);
} else {
return null;
}
}
/**
* Calls through to the ParentViewHolder to expand views for each
* RecyclerView the specified parent is a child of.
*
* These calls to the ParentViewHolder are made so that animations can be
* triggered at the ViewHolder level.
*
* @param parentIndex The index of the parent to expand
*/
private void expandViews(ParentWrapper parentWrapper, int parentIndex) {
PVH viewHolder;
for (RecyclerView recyclerView : mAttachedRecyclerViewPool) {
viewHolder = (PVH) recyclerView.findViewHolderForAdapterPosition(parentIndex);
if (viewHolder != null && !viewHolder.isExpanded()) {
viewHolder.setExpanded(true);
viewHolder.onExpansionToggled(false);
}
}
expandParentListItem(parentWrapper, parentIndex, false);
}
/**
* Calls through to the ParentViewHolder to collapse views for each
* RecyclerView a specified parent is a child of.
*
* These calls to the ParentViewHolder are made so that animations can be
* triggered at the ViewHolder level.
*
* @param parentIndex The index of the parent to collapse
*/
private void collapseViews(ParentWrapper parentWrapper, int parentIndex) {
PVH viewHolder;
for (RecyclerView recyclerView : mAttachedRecyclerViewPool) {
viewHolder = (PVH) recyclerView.findViewHolderForAdapterPosition(parentIndex);
if (viewHolder != null && viewHolder.isExpanded()) {
viewHolder.setExpanded(false);
viewHolder.onExpansionToggled(true);
}
}
collapseParentListItem(parentWrapper, parentIndex, false);
}
/**
* Expands a specified parent item. Calls through to the
* ExpandCollapseListener and adds children of the specified parent to the
* total list of items.
*
* @param parentWrapper The ParentWrapper of the parent to expand
* @param parentIndex The index of the parent to expand
* @param expansionTriggeredByListItemClick true if expansion was triggered
* by a click event, false otherwise.
*/
private void expandParentListItem(ParentWrapper parentWrapper, int parentIndex, boolean expansionTriggeredByListItemClick) {
if (!parentWrapper.isExpanded()) {
parentWrapper.setExpanded(true);
List<?> childItemList = parentWrapper.getChildItemList();
if (childItemList != null) {
int childListItemCount = childItemList.size();
for (int i = 0; i < childListItemCount; i++) {
mItemList.add(parentIndex + i + 1, childItemList.get(i));
}
notifyItemRangeInserted(parentIndex + 1, childListItemCount);
}
if (expansionTriggeredByListItemClick && mExpandCollapseListener != null) {
mExpandCollapseListener.onListItemExpanded(getNearestParentPosition(parentIndex));
}
}
}
/**
* Collapses a specified parent item. Calls through to the
* ExpandCollapseListener and adds children of the specified parent to the
* total list of items.
*
* @param parentWrapper The ParentWrapper of the parent to collapse
* @param parentIndex The index of the parent to collapse
* @param collapseTriggeredByListItemClick true if expansion was triggered
* by a click event, false otherwise.
*/
private void collapseParentListItem(ParentWrapper parentWrapper, int parentIndex, boolean collapseTriggeredByListItemClick) {
if (parentWrapper.isExpanded()) {
parentWrapper.setExpanded(false);
List<?> childItemList = parentWrapper.getChildItemList();
if (childItemList != null) {
int childListItemCount = childItemList.size();
for (int i = childListItemCount - 1; i >= 0; i
mItemList.remove(parentIndex + i + 1);
}
notifyItemRangeRemoved(parentIndex + 1, childListItemCount);
}
if (collapseTriggeredByListItemClick && mExpandCollapseListener != null) {
mExpandCollapseListener.onListItemCollapsed(getNearestParentPosition(parentIndex));
}
}
}
/**
* Given the index relative to the entire RecyclerView, returns the nearest
* ParentPosition without going past the given index.
*
* If it is the index of a parent item, will return the corresponding parent position.
* If it is the index of a child item within the RV, will return the position of that childs parent.
*/
int getNearestParentPosition(int fullPosition) {
if (fullPosition == 0) {
return 0;
}
int parentCount = -1;
for (int i = 0; i <= fullPosition; i++) {
Object listItem = getListItem(i);
if (listItem instanceof ParentWrapper) {
parentCount++;
}
}
return parentCount;
}
/**
* Given the index relative to the entire RecyclerView for a child item,
* returns the child position within the child list of the parent.
*/
int getChildPosition(int fullPosition) {
if (fullPosition == 0) {
return 0;
}
int childCount = 0;
for (int i = 0; i < fullPosition; i++) {
Object listItem = getListItem(i);
if (listItem instanceof ParentWrapper) {
childCount = 0;
} else {
childCount++;
}
}
return childCount;
}
// endregion
// region Data Manipulation
/**
* Notify any registered observers that the ParentListItem reflected at {@code parentPosition}
* has been newly inserted. The ParentListItem previously at {@code parentPosition} is now at
* position {@code parentPosition + 1}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.
*
* @param parentPosition Position of the newly inserted ParentListItem in the data set, relative
* to list of ParentListItems only.
*
* @see #notifyParentItemRangeInserted(int, int)
*/
public void notifyParentItemInserted(int parentPosition) {
ParentListItem parentListItem = mParentItemList.get(parentPosition);
int wrapperIndex;
if (parentPosition < mParentItemList.size() - 1) {
wrapperIndex = getParentWrapperIndex(parentPosition);
} else {
wrapperIndex = mItemList.size();
}
int sizeChanged = addParentWrapper(wrapperIndex, parentListItem);
notifyItemRangeInserted(wrapperIndex, sizeChanged);
}
/**
* Notify any registered observers that the currently reflected {@code itemCount}
* ParentListItems starting at {@code parentPositionStart} have been newly inserted.
* The ParentListItems previously located at {@code parentPositionStart} and beyond
* can now be found starting at position {@code parentPositionStart + itemCount}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPositionStart Position of the first ParentListItem that was inserted, relative
* to list of ParentListItems only.
* @param itemCount Number of items inserted
*
* @see #notifyParentItemInserted(int)
*/
public void notifyParentItemRangeInserted(int parentPositionStart, int itemCount) {
int initialWrapperIndex;
if (parentPositionStart < mParentItemList.size() - itemCount) {
initialWrapperIndex = getParentWrapperIndex(parentPositionStart);
} else {
initialWrapperIndex = mItemList.size();
}
int sizeChanged = 0;
int wrapperIndex = initialWrapperIndex;
int changed;
int parentPositionEnd = parentPositionStart + itemCount;
for (int i = parentPositionStart; i < parentPositionEnd; i++) {
ParentListItem parentListItem = mParentItemList.get(i);
changed = addParentWrapper(wrapperIndex, parentListItem);
wrapperIndex += changed;
sizeChanged += changed;
}
notifyItemRangeInserted(initialWrapperIndex, sizeChanged);
}
private int addParentWrapper(int wrapperIndex, ParentListItem parentListItem) {
int sizeChanged = 1;
ParentWrapper parentWrapper = new ParentWrapper(parentListItem);
mItemList.add(wrapperIndex, parentWrapper);
if (parentWrapper.isInitiallyExpanded()) {
parentWrapper.setExpanded(true);
List<?> childItemList = parentWrapper.getChildItemList();
mItemList.addAll(wrapperIndex + sizeChanged, childItemList);
sizeChanged += childItemList.size();
}
return sizeChanged;
}
/**
* Notify any registered observers that the ParentListItem previously located at {@code parentPosition}
* has been removed from the data set. The ParentListItems previously located at and after
* {@code parentPosition} may now be found at {@code oldPosition - 1}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPosition Position of the ParentListItem that has now been removed, relative
* to list of ParentListItems only.
*/
public void notifyParentItemRemoved(int parentPosition) {
int wrapperIndex = getParentWrapperIndex(parentPosition);
int sizeChanged = removeParentWrapper(wrapperIndex);
notifyItemRangeRemoved(wrapperIndex, sizeChanged);
}
/**
* Notify any registered observers that the {@code itemCount} ParentListItems previously located
* at {@code parentPositionStart} have been removed from the data set. The ParentListItems
* previously located at and after {@code parentPositionStart + itemCount} may now be found at
* {@code oldPosition - itemCount}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPositionStart The previous position of the first ParentListItem that was
* removed, relative to list of ParentListItems only.
* @param itemCount Number of ParentListItems removed from the data set
*/
public void notifyParentItemRangeRemoved(int parentPositionStart, int itemCount) {
int sizeChanged = 0;
int wrapperIndex = getParentWrapperIndex(parentPositionStart);
for (int i = 0; i < itemCount; i++) {
sizeChanged += removeParentWrapper(wrapperIndex);
}
notifyItemRangeRemoved(wrapperIndex, sizeChanged);
}
private int removeParentWrapper(int parentWrapperIndex) {
int sizeChanged = 1;
ParentWrapper parentWrapper = (ParentWrapper) mItemList.remove(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
int childListSize = parentWrapper.getChildItemList().size();
for (int i = 0; i < childListSize; i++) {
mItemList.remove(parentWrapperIndex);
sizeChanged++;
}
}
return sizeChanged;
}
/**
* Notify any registered observers that the ParentListItem at {@code parentPosition} has changed.
* This will also trigger an item changed for children of the ParentList specified.
* <p>
* This is an item change event, not a structural change event. It indicates that any
* reflection of the data at {@code parentPosition} is out of date and should be updated.
* The ParentListItem at {@code parentPosition} retains the same identity. This means
* the number of children must stay the same.
*
* @param parentPosition Position of the item that has changed
*/
public void notifyParentItemChanged(int parentPosition) {
ParentListItem parentListItem = mParentItemList.get(parentPosition);
int wrapperIndex = getParentWrapperIndex(parentPosition);
int sizeChanged = changeParentWrapper(wrapperIndex, parentListItem);
notifyItemRangeChanged(wrapperIndex, sizeChanged);
}
/**
* Notify any registered observers that the {@code itemCount} ParentListItems starting
* at {@code parentPositionStart} have changed. This will also trigger an item changed
* for children of the ParentList specified.
* <p>
* This is an item change event, not a structural change event. It indicates that any
* reflection of the data in the given position range is out of date and should be updated.
* The ParentListItems in the given range retain the same identity. This means
* the number of children must stay the same.
*
* @param parentPositionStart Position of the item that has changed
* @param itemCount Number of ParentListItems changed in the dataset
*/
public void notifyParentItemRangeChanged(int parentPositionStart, int itemCount) {
int initialWrapperIndex = getParentWrapperIndex(parentPositionStart);
int wrapperIndex = initialWrapperIndex;
int sizeChanged = 0;
int changed;
ParentListItem parentListItem;
for (int j = 0; j < itemCount; j++) {
parentListItem = mParentItemList.get(parentPositionStart);
changed = changeParentWrapper(wrapperIndex, parentListItem);
sizeChanged += changed;
wrapperIndex += changed;
parentPositionStart++;
}
notifyItemRangeChanged(initialWrapperIndex, sizeChanged);
}
private int changeParentWrapper(int wrapperIndex, ParentListItem parentListItem) {
ParentWrapper parentWrapper = (ParentWrapper) mItemList.get(wrapperIndex);
parentWrapper.setParentListItem(parentListItem);
int sizeChanged = 1;
if (parentWrapper.isExpanded()) {
List<?> childItems = parentWrapper.getChildItemList();
int childListSize = childItems.size();
Object child;
for (int i = 0; i < childListSize; i++) {
child = childItems.get(i);
mItemList.set(wrapperIndex + i + 1, child);
sizeChanged++;
}
}
return sizeChanged;
}
/**
* Notify any registered observers that the ParentListItem and it's child list items reflected at
* {@code fromParentPosition} has been moved to {@code toParentPosition}.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param fromParentPosition Previous position of the ParentListItem, relative to list of
* ParentListItems only.
* @param toParentPosition New position of the ParentListItem, relative to list of
* ParentListItems only.
*/
public void notifyParentItemMoved(int fromParentPosition, int toParentPosition) {
int fromWrapperIndex = getParentWrapperIndex(fromParentPosition);
ParentWrapper fromParentWrapper = (ParentWrapper) mItemList.get(fromWrapperIndex);
// If the parent is collapsed we can take advantage of notifyItemMoved otherwise
// we are forced to do a "manual" move by removing and then adding the parent + children
// (no notifyItemRangeMovedAvailable)
boolean isCollapsed = !fromParentWrapper.isExpanded();
boolean isExpandedNoChildren = !isCollapsed && (fromParentWrapper.getChildItemList().size() == 0);
if (isCollapsed || isExpandedNoChildren) {
int toWrapperIndex = getParentWrapperIndex(toParentPosition);
ParentWrapper toParentWrapper = (ParentWrapper) mItemList.get(toWrapperIndex);
mItemList.remove(fromWrapperIndex);
int childOffset = 0;
if (toParentWrapper.isExpanded()) {
childOffset = toParentWrapper.getChildItemList().size();
}
mItemList.add(toWrapperIndex + childOffset, fromParentWrapper);
notifyItemMoved(fromWrapperIndex, toWrapperIndex + childOffset);
} else {
// Remove the parent and children
int sizeChanged = 0;
int childListSize = fromParentWrapper.getChildItemList().size();
for (int i = 0; i < childListSize + 1; i++) {
mItemList.remove(fromWrapperIndex);
sizeChanged++;
}
notifyItemRangeRemoved(fromWrapperIndex, sizeChanged);
// Add the parent and children at new position
int toWrapperIndex = getParentWrapperIndex(toParentPosition);
int childOffset = 0;
if (toWrapperIndex != -1) {
ParentWrapper toParentWrapper = (ParentWrapper) mItemList.get(toWrapperIndex);
if (toParentWrapper.isExpanded()) {
childOffset = toParentWrapper.getChildItemList().size();
}
} else {
toWrapperIndex = mItemList.size();
}
mItemList.add(toWrapperIndex + childOffset, fromParentWrapper);
List<?> childItemList = fromParentWrapper.getChildItemList();
sizeChanged = childItemList.size() + 1;
mItemList.addAll(toWrapperIndex + childOffset + 1, childItemList);
notifyItemRangeInserted(toWrapperIndex + childOffset, sizeChanged);
}
}
/**
* Notify any registered observers that the ParentListItem reflected at {@code parentPosition}
* has a child list item that has been newly inserted at {@code childPosition}.
* The child list item previously at {@code childPosition} is now at
* position {@code childPosition + 1}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.
*
* @param parentPosition Position of the ParentListItem which has been added a child, relative
* to list of ParentListItems only.
* @param childPosition Position of the child object that has been inserted, relative to children
* of the ParentListItem specified by {@code parentPosition} only.
*
*/
public void notifyChildItemInserted(int parentPosition, int childPosition) {
int parentWrapperIndex = getParentWrapperIndex(parentPosition);
ParentWrapper parentWrapper = (ParentWrapper) mItemList.get(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
ParentListItem parentListItem = mParentItemList.get(parentPosition);
Object child = parentListItem.getChildItemList().get(childPosition);
mItemList.add(parentWrapperIndex + childPosition + 1, child);
notifyItemInserted(parentWrapperIndex + childPosition + 1);
}
}
/**
* Notify any registered observers that the ParentListItem reflected at {@code parentPosition}
* has {@code itemCount} child list items that have been newly inserted at {@code childPositionStart}.
* The child list item previously at {@code childPositionStart} and beyond are now at
* position {@code childPositionStart + itemCount}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.
*
* @param parentPosition Position of the ParentListItem which has been added a child, relative
* to list of ParentListItems only.
* @param childPositionStart Position of the first child object that has been inserted,
* relative to children of the ParentListItem specified by
* {@code parentPosition} only.
* @param itemCount number of children inserted
*
*/
public void notifyChildItemRangeInserted(int parentPosition, int childPositionStart, int itemCount) {
int parentWrapperIndex = getParentWrapperIndex(parentPosition);
ParentWrapper parentWrapper = (ParentWrapper) mItemList.get(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
ParentListItem parentListItem = mParentItemList.get(parentPosition);
List<?> childList = parentListItem.getChildItemList();
Object child;
for (int i = 0; i < itemCount; i++) {
child = childList.get(childPositionStart + i);
mItemList.add(parentWrapperIndex + childPositionStart + i + 1, child);
}
notifyItemRangeInserted(parentWrapperIndex + childPositionStart + 1, itemCount);
}
}
/**
* Notify any registered observers that the ParentListItem located at {@code parentPosition}
* has a child list item that has been removed from the data set, previously located at {@code childPosition}.
* The child list item previously located at and after {@code childPosition} may
* now be found at {@code childPosition - 1}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPosition Position of the ParentListItem which has a child removed from, relative
* to list of ParentListItems only.
* @param childPosition Position of the child object that has been removed, relative to children
* of the ParentListItem specified by {@code parentPosition} only.
*/
public void notifyChildItemRemoved(int parentPosition, int childPosition) {
int parentWrapperIndex = getParentWrapperIndex(parentPosition);
ParentWrapper parentWrapper = (ParentWrapper) mItemList.get(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
mItemList.remove(parentWrapperIndex + childPosition + 1);
notifyItemRemoved(parentWrapperIndex + childPosition + 1);
}
}
/**
* Notify any registered observers that the ParentListItem located at {@code parentPosition}
* has {@code itemCount} child list items that have been removed from the data set, previously
* located at {@code childPositionStart} onwards. The child list item previously located at and
* after {@code childPositionStart} may now be found at {@code childPositionStart - itemCount}.
* <p>
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.
*
* @param parentPosition Position of the ParentListItem which has a child removed from, relative
* to list of ParentListItems only.
* @param childPositionStart Position of the first child object that has been removed, relative
* to children of the ParentListItem specified by
* {@code parentPosition} only.
* @param itemCount number of children removed
*/
public void notifyChildItemRangeRemoved(int parentPosition, int childPositionStart, int itemCount) {
int parentWrapperIndex = getParentWrapperIndex(parentPosition);
ParentWrapper parentWrapper = (ParentWrapper) mItemList.get(parentWrapperIndex);
if (parentWrapper.isExpanded()) {
for (int i = 0; i < itemCount; i++) {
mItemList.remove(parentWrapperIndex + childPositionStart + 1);
}
notifyItemRangeRemoved(parentWrapperIndex + childPositionStart + 1, itemCount);
}
}
/**
* Notify any registered observers that the ParentListItem at {@code parentPosition} has
* a child located at {@code childPosition} that has changed.
* <p>
* This is an item change event, not a structural change event. It indicates that any
* reflection of the data at {@code childPosition} is out of date and should be updated.
* The ParentListItem at {@code childPosition} retains the same identity.
*
* @param parentPosition Position of the ParentListItem who has a child that has changed
* @param childPosition Position of the child that has changed
*/
public void notifyChildItemChanged(int parentPosition, int childPosition) {
ParentListItem parentListItem = mParentItemList.get(parentPosition);
int parentWrapperIndex = getParentWrapperIndex(parentPosition);
ParentWrapper parentWrapper = (ParentWrapper) mItemList.get(parentWrapperIndex);
parentWrapper.setParentListItem(parentListItem);
if (parentWrapper.isExpanded()) {
int listChildPosition = parentWrapperIndex + childPosition + 1;
Object child = parentWrapper.getChildItemList().get(childPosition);
mItemList.set(listChildPosition, child);
notifyItemChanged(listChildPosition);
}
}
/**
* Notify any registered observers that the ParentListItem at {@code parentPosition} has
* {@code itemCount} child Objects starting at {@code childPositionStart} that have changed.
* <p>
* This is an item change event, not a structural change event. It indicates that any
* The ParentListItem at {@code childPositionStart} retains the same identity.
* reflection of the set of {@code itemCount} child objects starting at {@code childPositionStart}
* are out of date and should be updated.
*
* @param parentPosition Position of the ParentListItem who has a child that has changed
* @param childPositionStart Position of the first child object that has changed
* @param itemCount number of child objects changed
*/
public void notifyChildItemRangeChanged(int parentPosition, int childPositionStart, int itemCount) {
ParentListItem parentListItem = mParentItemList.get(parentPosition);
int parentWrapperIndex = getParentWrapperIndex(parentPosition);
ParentWrapper parentWrapper = (ParentWrapper) mItemList.get(parentWrapperIndex);
parentWrapper.setParentListItem(parentListItem);
if (parentWrapper.isExpanded()) {
int listChildPosition = parentWrapperIndex + childPositionStart + 1;
for (int i = 0; i < itemCount; i++) {
Object child = parentWrapper.getChildItemList().get(childPositionStart + i);
mItemList.set(listChildPosition + i, child);
}
notifyItemRangeChanged(listChildPosition, itemCount);
}
}
/**
* Notify any registered observers that the child list item contained within the ParentListItem
* at {@code parentPosition} has moved from {@code fromChildPosition} to {@code toChildPosition}.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param parentPosition Position of the ParentListItem who has a child that has moved
* @param fromChildPosition Previous position of the child list item
* @param toChildPosition New position of the child list item
*/
public void notifyChildItemMoved(int parentPosition, int fromChildPosition, int toChildPosition) {
ParentListItem parentListItem = mParentItemList.get(parentPosition);
int parentWrapperIndex = getParentWrapperIndex(parentPosition);
ParentWrapper parentWrapper = (ParentWrapper) mItemList.get(parentWrapperIndex);
parentWrapper.setParentListItem(parentListItem);
if (parentWrapper.isExpanded()) {
Object fromChild = mItemList.remove(parentWrapperIndex + 1 + fromChildPosition);
mItemList.add(parentWrapperIndex + 1 + toChildPosition, fromChild);
notifyItemMoved(parentWrapperIndex + 1 + fromChildPosition, parentWrapperIndex + 1 + toChildPosition);
}
}
// endregion
/**
* Generates a HashMap used to store expanded state for items in the list
* on configuration change or whenever onResume is called.
*
* @return A HashMap containing the expanded state of all parent list items
*/
private HashMap<Integer, Boolean> generateExpandedStateMap() {
HashMap<Integer, Boolean> parentListItemHashMap = new HashMap<>();
int childCount = 0;
Object listItem;
ParentWrapper parentWrapper;
int listItemCount = mItemList.size();
for (int i = 0; i < listItemCount; i++) {
if (mItemList.get(i) != null) {
listItem = getListItem(i);
if (listItem instanceof ParentWrapper) {
parentWrapper = (ParentWrapper) listItem;
parentListItemHashMap.put(i - childCount, parentWrapper.isExpanded());
} else {
childCount++;
}
}
}
return parentListItemHashMap;
}
/**
* Gets the index of a ParentWrapper within the helper item list based on
* the index of the ParentWrapper.
*
* @param parentIndex The index of the parent in the list of parent items
* @return The index of the parent in the list of all views in the adapter
*/
private int getParentWrapperIndex(int parentIndex) {
int parentCount = 0;
int listItemCount = mItemList.size();
for (int i = 0; i < listItemCount; i++) {
if (mItemList.get(i) instanceof ParentWrapper) {
parentCount++;
if (parentCount > parentIndex) {
return i;
}
}
}
return -1;
}
/**
* Gets the ParentWrapper for a specified ParentListItem from the list of
* parents.
*
* @param parentListItem A ParentListItem in the list of parents
* @return If the parent exists on the list, returns its ParentWrapper.
* Otherwise, returns null.
*/
private ParentWrapper getParentWrapper(ParentListItem parentListItem) {
int listItemCount = mItemList.size();
for (int i = 0; i < listItemCount; i++) {
Object listItem = mItemList.get(i);
if (listItem instanceof ParentWrapper) {
if (((ParentWrapper) listItem).getParentListItem().equals(parentListItem)) {
return (ParentWrapper) listItem;
}
}
}
return null;
}
}
|
package com.cronutils;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Optional;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class Issue363Test {
//@Test
public void quartzNextExecutionTime() {
String cronExpression = "* 1 * * * ?";
ZonedDateTime now = ZonedDateTime.of(2019, 1, 1, 0, 1, 0, 0, ZoneOffset.UTC);
CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
Optional<ZonedDateTime> nextExecution = ExecutionTime.forCron(parser.parse(cronExpression)).nextExecution(now);
assertTrue(nextExecution.isPresent());
ZonedDateTime expectedTime = ZonedDateTime.of(2019, 1, 1, 1, 1, 0, 0, ZoneOffset.UTC);
assertEquals(expectedTime, nextExecution.get());
}
}
|
package io.quarkus.lambda.deployment;
import static java.util.stream.Collectors.toList;
import java.util.List;
import java.util.function.Consumer;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.Type;
import org.jboss.protean.gizmo.ClassCreator;
import org.jboss.protean.gizmo.ClassOutput;
import org.jboss.protean.gizmo.MethodCreator;
import org.jboss.protean.gizmo.MethodDescriptor;
import org.objectweb.asm.Opcodes;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.GeneratedClassBuildItem;
import io.quarkus.deployment.builditem.substrate.ReflectiveClassBuildItem;
import io.quarkus.deployment.builditem.substrate.ReflectiveMethodBuildItem;
import io.quarkus.lambda.runtime.LambdaServlet;
import io.quarkus.undertow.ServletBuildItem;
public final class LambdaProcessor {
private static final DotName REQUEST_HANDLER = DotName.createSimple(RequestHandler.class.getName());
@BuildStep
public void servlets(CombinedIndexBuildItem combinedIndexBuildItem, BuildProducer<ServletBuildItem> servletProducer,
Consumer<GeneratedClassBuildItem> classConsumer,
BuildProducer<ReflectiveMethodBuildItem> reflectiveMethods,
BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {
final ClassOutput classOutput = (name, data) -> classConsumer.accept(new GeneratedClassBuildItem(true, name, data));
for (ClassInfo info : combinedIndexBuildItem.getIndex().getAllKnownImplementors(REQUEST_HANDLER)) {
final DotName name = info.name();
final String lambda = name.toString();
final String mapping = name.local();
final String servletName = name.toString() + "Lambda";
servletProducer.produce(ServletBuildItem.builder(mapping, servletName)
.setLoadOnStartup(1)
.addMapping("/" + mapping)
.build());
try (final ClassCreator creator = new ClassCreator(classOutput, servletName, null, LambdaServlet.class.getName())) {
try (MethodCreator ctor = creator.getMethodCreator("<init>", "void")) {
ctor.setModifiers(Opcodes.ACC_PUBLIC);
ctor.invokeSpecialMethod(MethodDescriptor.ofConstructor(LambdaServlet.class, Class.class), ctor.getThis(),
ctor.loadClass(lambda));
ctor.returnValue(null);
}
}
final List<MethodInfo> list = info.methods().stream()
.filter(methodInfo -> methodInfo.name().equals("handleRequest"))
.collect(toList());
final MethodInfo methodInfo = list.get(0);
reflectiveMethods.produce(new ReflectiveMethodBuildItem(methodInfo));
final Type firstParam = methodInfo.parameters().get(0).asClassType();
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, true, firstParam.name().toString()));
}
}
}
|
package org.ethereum.trie;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.spongycastle.util.encoders.Hex;
import java.io.IOException;
import static org.junit.Assert.*;
public class TrieTest {
private static String LONG_STRING = "1234567890abcdefghijklmnopqrstuvwxxzABCEFGHIJKLMNOPQRSTUVWXYZ";
private static String ROOT_HASH_EMPTY = "";
private static String c = "c";
private static String ca = "ca";
private static String cat = "cat";
private static String dog = "dog";
private static String doge = "doge";
private static String test = "test";
private static String dude = "dude";
private MockDB mockDb = new MockDB();
// ROOT: [ '\x16', A ]
// A: [ '', '', '', '', B, '', '', '', C, '', '', '', '', '', '', '', '' ]
// B: [ '\x00\x6f', D ]
// D: [ '', '', '', '', '', '', E, '', '', '', '', '', '', '', '', '', 'verb' ]
// E: [ '\x17', F ]
// F: [ '', '', '', '', '', '', G, '', '', '', '', '', '', '', '', '', 'puppy' ]
// G: [ '\x35', 'coin' ]
// C: [ '\x20\x6f\x72\x73\x65', 'stallion' ]
@After
public void closeMockDb() throws IOException {
mockDb.close();
}
@Test
public void testEmptyKey() {
Trie trie = new Trie(mockDb);
trie.update("", dog);
assertEquals(dog, new String(trie.get("")));
}
@Test
public void testInsertShortString() {
Trie trie = new Trie(mockDb);
trie.update(cat, dog);
assertEquals(dog, new String(trie.get(cat)));
}
@Test
public void testInsertLongString() {
Trie trie = new Trie(mockDb);
trie.update(cat, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(cat)));
}
@Test
public void testInsertMultipleItems1() {
Trie trie = new Trie(mockDb);
trie.update(ca, dude);
assertEquals(dude, new String(trie.get(ca)));
trie.update(cat, dog);
assertEquals(dog, new String(trie.get(cat)));
trie.update(dog, test);
assertEquals(test, new String(trie.get(dog)));
trie.update(doge, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(doge)));
trie.update(test, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(test)));
// Test if everything is still there
assertEquals(dude, new String(trie.get(ca)));
assertEquals(dog, new String(trie.get(cat)));
assertEquals(test, new String(trie.get(dog)));
assertEquals(LONG_STRING, new String(trie.get(doge)));
assertEquals(LONG_STRING, new String(trie.get(test)));
}
@Test
public void testInsertMultipleItems2() {
Trie trie = new Trie(mockDb);
trie.update(cat, dog);
assertEquals(dog, new String(trie.get(cat)));
trie.update(ca, dude);
assertEquals(dude, new String(trie.get(ca)));
trie.update(doge, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(doge)));
trie.update(dog, test);
assertEquals(test, new String(trie.get(dog)));
trie.update(test, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(test)));
// Test if everything is still there
assertEquals(dog, new String(trie.get(cat)));
assertEquals(dude, new String(trie.get(ca)));
assertEquals(LONG_STRING, new String(trie.get(doge)));
assertEquals(test, new String(trie.get(dog)));
assertEquals(LONG_STRING, new String(trie.get(test)));
}
@Test
public void testUpdateShortToShortString() {
Trie trie = new Trie(mockDb);
trie.update(cat, dog);
assertEquals(dog, new String(trie.get(cat)));
trie.update(cat, dog+"1");
assertEquals(dog+"1", new String(trie.get(cat)));
}
@Test
public void testUpdateLongToLongString() {
Trie trie = new Trie(mockDb);
trie.update(cat, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(cat)));
trie.update(cat, LONG_STRING+"1");
assertEquals(LONG_STRING+"1", new String(trie.get(cat)));
}
@Test
public void testUpdateShortToLongString() {
Trie trie = new Trie(mockDb);
trie.update(cat, dog);
assertEquals(dog, new String(trie.get(cat)));
trie.update(cat, LONG_STRING+"1");
assertEquals(LONG_STRING+"1", new String(trie.get(cat)));
}
@Test
public void testUpdateLongToShortString() {
Trie trie = new Trie(mockDb);
trie.update(cat, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(cat)));
trie.update(cat, dog+"1");
assertEquals(dog+"1", new String(trie.get(cat)));
}
@Test
public void testDeleteShortString1() {
String ROOT_HASH_BEFORE = "a9539c810cc2e8fa20785bdd78ec36cc1dab4b41f0d531e80a5e5fd25c3037ee";
String ROOT_HASH_AFTER = "fc5120b4a711bca1f5bb54769525b11b3fb9a8d6ac0b8bf08cbb248770521758";
Trie trie = new Trie(mockDb);
trie.update(cat, dog);
assertEquals(dog, new String(trie.get(cat)));
trie.update(ca, dude);
assertEquals(dude, new String(trie.get(ca)));
assertEquals(ROOT_HASH_BEFORE, Hex.toHexString(trie.getRootHash()));
trie.delete(ca);
assertEquals("", new String(trie.get(ca)));
assertEquals(ROOT_HASH_AFTER, Hex.toHexString(trie.getRootHash()));
}
@Test
public void testDeleteShortString2() {
String ROOT_HASH_BEFORE = "a9539c810cc2e8fa20785bdd78ec36cc1dab4b41f0d531e80a5e5fd25c3037ee";
String ROOT_HASH_AFTER = "b25e1b5be78dbadf6c4e817c6d170bbb47e9916f8f6cc4607c5f3819ce98497b";
Trie trie = new Trie(mockDb);
trie.update(ca, dude);
assertEquals(dude, new String(trie.get(ca)));
trie.update(cat, dog);
assertEquals(dog, new String(trie.get(cat)));
assertEquals(ROOT_HASH_BEFORE, Hex.toHexString(trie.getRootHash()));
trie.delete(cat);
assertEquals("", new String(trie.get(cat)));
assertEquals(ROOT_HASH_AFTER, Hex.toHexString(trie.getRootHash()));
}
@Test
public void testDeleteShortString3() {
String ROOT_HASH_BEFORE = "778ab82a7e8236ea2ff7bb9cfa46688e7241c1fd445bf2941416881a6ee192eb";
String ROOT_HASH_AFTER = "05875807b8f3e735188d2479add82f96dee4db5aff00dc63f07a7e27d0deab65";
Trie trie = new Trie(mockDb);
trie.update(cat, dude);
assertEquals(dude, new String(trie.get(cat)));
trie.update(dog, test);
assertEquals(test, new String(trie.get(dog)));
assertEquals(ROOT_HASH_BEFORE, Hex.toHexString(trie.getRootHash()));
trie.delete(dog);
assertEquals("", new String(trie.get(dog)));
assertEquals(ROOT_HASH_AFTER, Hex.toHexString(trie.getRootHash()));
}
@Test
public void testDeleteLongString1() {
String ROOT_HASH_BEFORE = "318961a1c8f3724286e8e80d312352f01450bc4892c165cc7614e1c2e5a0012a";
String ROOT_HASH_AFTER = "63356ecf33b083e244122fca7a9b128cc7620d438d5d62e4f8b5168f1fb0527b";
Trie trie = new Trie(mockDb);
trie.update(cat, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(cat)));
trie.update(dog, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(dog)));
assertEquals(ROOT_HASH_BEFORE, Hex.toHexString(trie.getRootHash()));
trie.delete(dog);
assertEquals("", new String(trie.get(dog)));
assertEquals(ROOT_HASH_AFTER, Hex.toHexString(trie.getRootHash()));
}
@Test
public void testDeleteLongString2() {
String ROOT_HASH_BEFORE = "e020de34ca26f8d373ff2c0a8ac3a4cb9032bfa7a194c68330b7ac3584a1d388";
String ROOT_HASH_AFTER = "334511f0c4897677b782d13a6fa1e58e18de6b24879d57ced430bad5ac831cb2";
Trie trie = new Trie(mockDb);
trie.update(ca, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(ca)));
trie.update(cat, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(cat)));
assertEquals(ROOT_HASH_BEFORE, Hex.toHexString(trie.getRootHash()));
trie.delete(cat);
assertEquals("", new String(trie.get(cat)));
assertEquals(ROOT_HASH_AFTER, Hex.toHexString(trie.getRootHash()));
}
@Test
public void testDeleteLongString3() {
String ROOT_HASH_BEFORE = "e020de34ca26f8d373ff2c0a8ac3a4cb9032bfa7a194c68330b7ac3584a1d388";
String ROOT_HASH_AFTER = "63356ecf33b083e244122fca7a9b128cc7620d438d5d62e4f8b5168f1fb0527b";
Trie trie = new Trie(mockDb);
trie.update(cat, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(cat)));
trie.update(ca, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(ca)));
assertEquals(ROOT_HASH_BEFORE, Hex.toHexString(trie.getRootHash()));
trie.delete(ca);
assertEquals("", new String(trie.get(ca)));
assertEquals(ROOT_HASH_AFTER, Hex.toHexString(trie.getRootHash()));
}
@Test
public void testDeleteMultipleItems1() {
String ROOT_HASH_BEFORE = "3a784eddf1936515f0313b073f99e3bd65c38689021d24855f62a9601ea41717";
String ROOT_HASH_AFTER1 = "60a2e75cfa153c4af2783bd6cb48fd6bed84c6381bc2c8f02792c046b46c0653";
String ROOT_HASH_AFTER2 = "a84739b4762ddf15e3acc4e6957e5ab2bbfaaef00fe9d436a7369c6f058ec90d";
Trie trie = new Trie(mockDb);
trie.update(cat, dog);
assertEquals(dog, new String(trie.get(cat)));
trie.update(ca, dude);
assertEquals(dude, new String(trie.get(ca)));
trie.update(doge, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(doge)));
trie.update(dog, test);
assertEquals(test, new String(trie.get(dog)));
trie.update(test, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(test)));
assertEquals(ROOT_HASH_BEFORE, Hex.toHexString(trie.getRootHash()));
trie.delete(dog);
assertEquals("", new String(trie.get(dog)));
assertEquals(ROOT_HASH_AFTER1, Hex.toHexString(trie.getRootHash()));
trie.delete(test);
assertEquals("", new String(trie.get(test)));
assertEquals(ROOT_HASH_AFTER2, Hex.toHexString(trie.getRootHash()));
}
@Test
public void testDeleteMultipleItems2() {
String ROOT_HASH_BEFORE = "cf1ed2b6c4b6558f70ef0ecf76bfbee96af785cb5d5e7bfc37f9804ad8d0fb56";
String ROOT_HASH_AFTER1 = "f586af4a476ba853fca8cea1fbde27cd17d537d18f64269fe09b02aa7fe55a9e";
String ROOT_HASH_AFTER2 = "c59fdc16a80b11cc2f7a8b107bb0c954c0d8059e49c760ec3660eea64053ac91";
Trie trie = new Trie(mockDb);
trie.update(c, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(c)));
trie.update(ca, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(ca)));
trie.update(cat, LONG_STRING);
assertEquals(LONG_STRING, new String(trie.get(cat)));
assertEquals(ROOT_HASH_BEFORE, Hex.toHexString(trie.getRootHash()));
trie.delete(ca);
assertEquals("", new String(trie.get(ca)));
assertEquals(ROOT_HASH_AFTER1, Hex.toHexString(trie.getRootHash()));
trie.delete(cat);
assertEquals("", new String(trie.get(cat)));
assertEquals(ROOT_HASH_AFTER2, Hex.toHexString(trie.getRootHash()));
}
@Test
public void testDeleteAll() {
String ROOT_HASH_BEFORE = "a84739b4762ddf15e3acc4e6957e5ab2bbfaaef00fe9d436a7369c6f058ec90d";
Trie trie = new Trie(mockDb);
assertEquals(ROOT_HASH_EMPTY, Hex.toHexString(trie.getRootHash()));
trie.update(ca, dude);
trie.update(cat, dog);
trie.update(doge, LONG_STRING);
assertEquals(ROOT_HASH_BEFORE, Hex.toHexString(trie.getRootHash()));
trie.delete(ca);
trie.delete(cat);
trie.delete(doge);
assertEquals(ROOT_HASH_EMPTY, Hex.toHexString(trie.getRootHash()));
}
@Test
public void testTrieCmp() {
Trie trie1 = new Trie(mockDb);
Trie trie2 = new Trie(mockDb);
trie1.update(doge, LONG_STRING);
trie2.update(doge, LONG_STRING);
assertTrue("Expected tries to be equal", trie1.cmp(trie2));
assertEquals(Hex.toHexString(trie1.getRootHash()), Hex.toHexString(trie2.getRootHash()));
trie1.update(dog, LONG_STRING);
trie2.update(cat, LONG_STRING);
assertFalse("Expected tries not to be equal", trie1.cmp(trie2));
assertNotEquals(Hex.toHexString(trie1.getRootHash()), Hex.toHexString(trie2.getRootHash()));
}
@Test
public void testTrieSync() {
Trie trie = new Trie(mockDb);
trie.update(dog, LONG_STRING);
assertEquals("Expected no data in database", mockDb.getAddedItems(), 0);
trie.sync();
assertNotEquals("Expected data to be persisted", mockDb.getAddedItems(), 0);
}
@Test
public void TestTrieDirtyTracking() {
Trie trie = new Trie(mockDb);
trie.update(dog, LONG_STRING);
assertTrue("Expected trie to be dirty", trie.getCache().isDirty());
trie.sync();
assertFalse("Expected trie not to be dirty", trie.getCache().isDirty());
trie.update(test, LONG_STRING);
trie.getCache().undo();
assertFalse("Expected trie not to be dirty", trie.getCache().isDirty());
}
@Test
public void TestTrieReset() {
Trie trie = new Trie(mockDb);
trie.update(cat, LONG_STRING);
assertNotEquals("Expected cached nodes", 0, trie.getCache().getNodes().size());
trie.getCache().undo();
assertEquals("Expected no nodes after undo", 0, trie.getCache().getNodes().size());
}
@Test
public void testTrieCopy() {
Trie trie = new Trie(mockDb);
trie.update("doe", "reindeer");
Trie trie2 = trie.copy();
assertFalse(trie.equals(trie2)); // avoid possibility that its just a reference copy
assertEquals(Hex.toHexString(trie.getRootHash()), Hex.toHexString(trie2.getRootHash()));
assertTrue(trie.cmp(trie2));
}
@Test
public void testTrieUndo() {
Trie trie = new Trie(mockDb);
trie.update("doe", "reindeer");
assertEquals("11a0327cfcc5b7689b6b6d727e1f5f8846c1137caaa9fc871ba31b7cce1b703e", Hex.toHexString(trie.getRootHash()));
trie.sync();
trie.update("dog", "puppy");
assertEquals("05ae693aac2107336a79309e0c60b24a7aac6aa3edecaef593921500d33c63c4", Hex.toHexString(trie.getRootHash()));
trie.undo();
assertEquals("11a0327cfcc5b7689b6b6d727e1f5f8846c1137caaa9fc871ba31b7cce1b703e", Hex.toHexString(trie.getRootHash()));
}
@Test
public void testSingleItem() {
Trie trie = new Trie(mockDb);
trie.update("A", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
assertEquals("d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab", Hex.toHexString(trie.getRootHash()));
}
@Test
public void testDogs() {
Trie trie = new Trie(mockDb);
trie.update("doe", "reindeer");
assertEquals("11a0327cfcc5b7689b6b6d727e1f5f8846c1137caaa9fc871ba31b7cce1b703e", Hex.toHexString(trie.getRootHash()));
trie.update("dog", "puppy");
assertEquals("05ae693aac2107336a79309e0c60b24a7aac6aa3edecaef593921500d33c63c4", Hex.toHexString(trie.getRootHash()));
trie.update("dogglesworth", "cat");
assertEquals("8aad789dff2f538bca5d8ea56e8abe10f4c7ba3a5dea95fea4cd6e7c3a1168d3", Hex.toHexString(trie.getRootHash()));
}
@Test
public void testPuppy() {
Trie trie = new Trie(mockDb);
trie.update("do", "verb");
trie.update("horse", "stallion");
trie.update("doge", "coin");
trie.update("dog", "puppy");
assertEquals("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84", Hex.toHexString(trie.getRootHash()));
}
@Test
public void testEmptyValues() {
Trie trie = new Trie(mockDb);
trie.update("do", "verb");
trie.update("ether", "wookiedoo");
trie.update("horse", "stallion");
trie.update("shaman", "horse");
trie.update("doge", "coin");
trie.update("ether", "");
trie.update("dog", "puppy");
trie.update("shaman", "");
assertEquals("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84", Hex.toHexString(trie.getRootHash()));
}
@Test
public void testFoo() {
Trie trie = new Trie(mockDb);
trie.update("foo", "bar");
trie.update("food", "bat");
trie.update("food", "bass");
assertEquals("17beaa1648bafa633cda809c90c04af50fc8aed3cb40d16efbddee6fdf63c4c3", Hex.toHexString(trie.getRootHash()));
}
@Test
public void testSmallValues() {
Trie trie = new Trie(mockDb);
trie.update("be", "e");
trie.update("dog", "puppy");
trie.update("bed", "d");
assertEquals("3f67c7a47520f79faa29255d2d3c084a7a6df0453116ed7232ff10277a8be68b", Hex.toHexString(trie.getRootHash()));
}
@Test
public void testTesty() {
Trie trie = new Trie(mockDb);
trie.update("test", "test");
assertEquals("85d106d4edff3b7a4889e91251d0a87d7c17a1dda648ebdba8c6060825be23b8", Hex.toHexString(trie.getRootHash()));
trie.update("te", "testy");
assertEquals("8452568af70d8d140f58d941338542f645fcca50094b20f3c3d8c3df49337928", Hex.toHexString(trie.getRootHash()));
}
@Test
public void testGetFromRootNode() {
Trie trie1 = new Trie(mockDb);
trie1.update(cat, LONG_STRING);
trie1.sync();
Trie trie2 = new Trie(mockDb);
trie2.setRoot(trie1.getRootHash());
assertEquals(LONG_STRING, new String(trie2.get(cat)));
}
/*
0x7645b9fbf1b51e6b980801fafe6bbc22d2ebe218 0x517eaccda568f3fa24915fed8add49d3b743b3764c0bc495b19a47c54dbc3d62 0x 0x1
0x0000000000000000000000000000000000000000000000000000000000000010 0x947e70f9460402290a3e487dae01f610a1a8218fda
0x0000000000000000000000000000000000000000000000000000000000000014 0x40
0x0000000000000000000000000000000000000000000000000000000000000016 0x94412e0c4f0102f3f0ac63f0a125bce36ca75d4e0d
0x0000000000000000000000000000000000000000000000000000000000000017 0x01
*/
@Test
public void storageHashCalc_1(){
byte[] key1 = Hex.decode("0000000000000000000000000000000000000000000000000000000000000010");
byte[] key2 = Hex.decode("0000000000000000000000000000000000000000000000000000000000000014");
byte[] key3 = Hex.decode("0000000000000000000000000000000000000000000000000000000000000016");
byte[] key4 = Hex.decode("0000000000000000000000000000000000000000000000000000000000000017");
byte[] val1 = Hex.decode("947e70f9460402290a3e487dae01f610a1a8218fda");
byte[] val2 = Hex.decode("40");
byte[] val3 = Hex.decode("94412e0c4f0102f3f0ac63f0a125bce36ca75d4e0d");
byte[] val4 = Hex.decode("01");
Trie storage = new Trie(new org.ethereum.trie.MockDB());
storage.update(key1, val1);
storage.update(key2, val2);
storage.update(key3, val3);
storage.update(key4, val4);
String hash = Hex.toHexString(storage.getRootHash());
System.out.println(hash);
Assert.assertEquals("517eaccda568f3fa24915fed8add49d3b743b3764c0bc495b19a47c54dbc3d62", hash);
}
}
|
package org.mariadb.jdbc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Properties;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
public class MultiTest extends BaseTest {
/**
* Tables initialisation.
*/
@BeforeClass()
public static void initClass() throws SQLException {
createTable("MultiTestt1", "id int, test varchar(100)");
createTable("MultiTestt2", "id int, test varchar(100)");
createTable("MultiTestt3", "message text");
createTable("MultiTestt4", "id int, test varchar(100), PRIMARY KEY (`id`)");
createTable("MultiTestt5", "id int, test varchar(100)");
createTable("MultiTestt6", "id int, test varchar(100)");
createTable("MultiTestt7", "id int, test varchar(100)");
createTable("MultiTestt8", "id int, test varchar(100)");
createTable("MultiTestt10", "id int");
createTable("MultiTestreWriteDuplicateTestTable",
"id int, name varchar(100), PRIMARY KEY (`id`)");
createTable("MultiTesttselect1", "LAST_UPDATE_DATETIME TIMESTAMP , nn int");
createTable("MultiTesttselect2", "nn int");
createTable("MultiTesttselect3", "LAST_UPDATE_DATETIME TIMESTAMP , nn int");
createTable("MultiTesttselect4", "nn int");
createTable("MultiTestt3_dupp",
"col1 int, pkey int NOT NULL, col2 int, col3 int, col4 int, PRIMARY KEY "
+ "(`pkey`)");
createTable("MultiTesttest_table",
"col1 VARCHAR(32), col2 VARCHAR(32), col3 VARCHAR(32), col4 VARCHAR(32), "
+ "col5 VARCHAR(32)");
createTable("MultiTesttest_table2",
"col1 VARCHAR(32), col2 VARCHAR(32), col3 VARCHAR(32), col4 VARCHAR(32), "
+ "col5 VARCHAR(32)");
createTable("MultiTestValues", "col1 VARCHAR(32), col2 VARCHAR(32)");
createTable("MultiTestprepsemi", "id int not null primary key auto_increment, text text");
createTable("MultiTestA", "data varchar(10)");
createTable("testMultiGeneratedKey", "id int not null primary key auto_increment, text text");
if (testSingleHost) {
Statement st = sharedConnection.createStatement();
st.execute("insert into MultiTestt1 values(1,'a'),(2,'a')");
st.execute("insert into MultiTestt2 values(1,'a'),(2,'a')");
st.execute("insert into MultiTestt5 values(1,'a'),(2,'a'),(2,'b')");
}
}
@Test
public void rewriteSelectQuery() throws Throwable {
Statement st = sharedConnection.createStatement();
st.execute("INSERT INTO MultiTesttselect2 VALUES (1)");
PreparedStatement ps = sharedConnection
.prepareStatement("/*CLIENT*/ insert into MultiTesttselect1 "
+ "(LAST_UPDATE_DATETIME, nn) select ?, nn from MultiTesttselect2");
ps.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
ps.executeUpdate();
ResultSet rs = st.executeQuery("SELECT * FROM MultiTesttselect1");
assertTrue(rs.next());
assertEquals(rs.getInt(2), 1);
}
@Test
public void rewriteParsingDoubleSlash() throws Throwable {
parsingDoubleSlash(sharedConnection);
try (Connection conn = setConnection("&rewriteBatchedStatements=true")) {
parsingDoubleSlash(conn);
Statement stmt = conn.createStatement();
stmt.execute("CREATE TEMPORARY TABLE rewriteSlash(t varchar(50))");
stmt.addBatch("insert into rewriteSlash values ('\\\\')");
stmt.executeBatch();
ResultSet rs = stmt.executeQuery("SELECT * FROM rewriteSlash");
assertTrue(rs.next());
assertEquals(rs.getString(1), "\\");
}
}
private void parsingDoubleSlash(Connection conn) throws SQLException {
try (PreparedStatement p = conn.prepareStatement("SELECT '\\\\', ?")) {
p.setString(1, "\\\\");
ResultSet rs = p.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getString(1), "\\");
assertEquals(rs.getString(2), "\\\\");
}
}
@Test
public void rewriteSelectQueryServerPrepared() throws Throwable {
Statement st = sharedConnection.createStatement();
st.execute("INSERT INTO MultiTesttselect4 VALUES (1)");
PreparedStatement ps = sharedConnection
.prepareStatement("insert into MultiTesttselect3 (LAST_UPDATE_DATETIME,"
+ " nn) select ?, nn from MultiTesttselect4");
ps.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
ps.executeUpdate();
ResultSet rs = st.executeQuery("SELECT * FROM MultiTesttselect3");
assertTrue(rs.next());
assertEquals(rs.getInt(2), 1);
}
@Test
public void basicTest() throws SQLException {
try (Connection connection = setConnection("&allowMultiQueries=true")) {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from MultiTestt1;select * from MultiTestt2;");
int count = 0;
while (rs.next()) {
count++;
}
assertTrue(count > 0);
assertTrue(statement.getMoreResults());
rs = statement.getResultSet();
count = 0;
while (rs.next()) {
count++;
}
assertTrue(count > 0);
assertFalse(statement.getMoreResults());
}
}
@Test
public void updateTest() throws SQLException {
try (Connection connection = setConnection("&allowMultiQueries=true")) {
Statement statement = connection.createStatement();
statement.execute("update MultiTestt5 set test='a " + System.currentTimeMillis()
+ "' where id = 2;select * from MultiTestt2;update MultiTestt5 set test='a2 " + System
.currentTimeMillis()
+ "' where id = 1;");
assertNull(statement.getResultSet());
assertEquals(2, statement.getUpdateCount());
assertTrue(statement.getMoreResults());
assertEquals(-1, statement.getUpdateCount());
ResultSet rs = statement.getResultSet();
int count = 0;
while (rs.next()) {
count++;
}
assertTrue(count > 0);
assertFalse(statement.getMoreResults());
assertEquals(1, statement.getUpdateCount());
assertNull(statement.getResultSet());
assertFalse(statement.getMoreResults());
assertEquals(-1, statement.getUpdateCount());
}
}
@Test
public void updateTest2() throws SQLException {
try (Connection connection = setConnection("&allowMultiQueries=true")) {
Statement statement = connection.createStatement();
statement.execute(
"select * from MultiTestt2;update MultiTestt5 set test='a " + System.currentTimeMillis()
+ "' where id = 2;");
ResultSet rs = statement.getResultSet();
int count = 0;
while (rs.next()) {
count++;
}
assertTrue(count == 2);
statement.getMoreResults();
int updateNb = statement.getUpdateCount();
assertEquals(2, updateNb);
}
}
@Test
public void selectTest() throws SQLException {
try (Connection connection = setConnection("&allowMultiQueries=true")) {
Statement statement = connection.createStatement();
statement.execute("select * from MultiTestt2;select * from MultiTestt1;");
ResultSet rs = statement.getResultSet();
int count = 0;
while (rs.next()) {
count++;
}
assertTrue(count > 0);
rs = statement.executeQuery("select * from MultiTestt1");
count = 0;
while (rs.next()) {
count++;
}
assertTrue(count > 0);
}
}
@Test
public void setMaxRowsMulti() throws Exception {
try (Connection connection = setConnection("&allowMultiQueries=true")) {
Statement st = connection.createStatement();
assertEquals(0, st.getMaxRows());
st.setMaxRows(1);
assertEquals(1, st.getMaxRows());
/* Check 3 rows are returned if maxRows is limited to 3, in every result set in batch */
/* Check first result set for at most 3 rows*/
ResultSet rs = st.executeQuery("select 1 union select 2;select 1 union select 2");
int cnt = 0;
while (rs.next()) {
cnt++;
}
rs.close();
assertEquals(1, cnt);
/* Check second result set for at most 3 rows*/
assertTrue(st.getMoreResults());
rs = st.getResultSet();
cnt = 0;
while (rs.next()) {
cnt++;
}
rs.close();
assertEquals(1, cnt);
}
}
/**
* Conj-99: rewriteBatchedStatements parameter.
*
* @throws SQLException exception
*/
@Test
public void rewriteBatchedStatementsDisabledInsertionTest() throws SQLException {
verifyInsertBehaviorBasedOnRewriteBatchedStatements(Boolean.FALSE, 3000);
}
/**
* Conj-206: rewriteBatchedStatements parameter take care of max_allowed_size.
*
* @throws SQLException exception
*/
@Test
public void rewriteBatchedMaxAllowedSizeTest() throws SQLException {
createTable("MultiTestt6", "id int, test varchar(10000)");
Assume.assumeTrue(checkMaxAllowedPacketMore8m("rewriteBatchedMaxAllowedSizeTest"));
Statement st = sharedConnection.createStatement();
ResultSet rs = st.executeQuery("select @@max_allowed_packet");
if (rs.next()) {
long maxAllowedPacket = rs.getInt(1);
Assume.assumeTrue(maxAllowedPacket < 512 * 1024 * 1024L);
int totalInsertCommands = (int) Math.ceil(maxAllowedPacket / 10050);
verifyInsertBehaviorBasedOnRewriteBatchedStatements(Boolean.TRUE, totalInsertCommands);
} else {
fail();
}
}
@Test
public void rewriteBatchedWithoutParam() throws SQLException {
try (Connection connection = setConnection("&rewriteBatchedStatements=true")) {
PreparedStatement preparedStatement = connection
.prepareStatement("INSERT INTO MultiTestt10 VALUES (1)");
for (int i = 0; i < 100; i++) {
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
ResultSet rs = connection.createStatement().executeQuery("SELECT COUNT(*) FROM MultiTestt10");
assertTrue(rs.next());
assertEquals(100, rs.getInt(1));
}
}
/**
* CONJ-329 error for rewrite without parameter.
*
* @throws SQLException if exception occur
*/
@Test
public void rewriteStatementWithoutParameter() throws SQLException {
try (Connection connection = setConnection("&rewriteBatchedStatements=true")) {
try (PreparedStatement statement = connection.prepareStatement("SELECT 1")) {
statement.executeQuery();
}
}
}
/**
* CONJ-330 - correction using execute...() for rewriteBatchedStatements
*
* @throws SQLException if exception occur
*/
@Test
public void rewriteMonoQueryStatementWithParameter() throws SQLException {
try (Connection connection = setConnection("&rewriteBatchedStatements=true")) {
String failingQuery1 = "SELECT (1=? AND 2=2)";
String failingQuery2 = "SELECT (1=?) AND 2=2";
String workingQuery = "SELECT 1=? AND (2=2)";
try (PreparedStatement statement = connection.prepareStatement(failingQuery1)) {
checkResult(statement);
}
try (PreparedStatement statement = connection.prepareStatement(failingQuery2)) {
checkResult(statement);
}
try (PreparedStatement statement = connection.prepareStatement(workingQuery)) {
checkResult(statement);
}
}
}
private void checkResult(PreparedStatement statement) throws SQLException {
statement.setInt(1, 1);
statement.executeQuery();
ResultSet rs = statement.executeQuery();
assertTrue(rs.next());
assertTrue(rs.getBoolean(1));
}
@Test
public void testServerPrepareMeta() throws Throwable {
try (Connection connection = setConnection("&rewriteBatchedStatements=true")) {
createTable("insertSelectTable1", "tt int");
createTable("insertSelectTable2", "tt int");
Statement stmt = connection.createStatement();
stmt.execute("INSERT INTO insertSelectTable2(tt) VALUES (1),(2),(1)");
PreparedStatement ps = connection.prepareStatement(
"INSERT INTO insertSelectTable1 "
+ "SELECT a1.tt FROM insertSelectTable2 a1 "
+ "WHERE a1.tt = ? ");
ps.setInt(1, 1);
ps.addBatch();
ps.setInt(1, 2);
ps.addBatch();
ps.executeBatch();
ResultSet rs = stmt.executeQuery("SELECT count(*) FROM insertSelectTable1");
assertTrue(rs.next());
assertEquals(3, rs.getInt(1));
}
}
private void verifyInsertBehaviorBasedOnRewriteBatchedStatements(Boolean rewriteBatchedStatements,
int totalInsertCommands) throws SQLException {
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", rewriteBatchedStatements.toString());
props.setProperty("allowMultiQueries", "true");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
verifyInsertCount(tmpConnection, 0);
Statement statement = tmpConnection.createStatement();
for (int i = 0; i < totalInsertCommands; i++) {
statement.addBatch("INSERT INTO MultiTestt6 VALUES (" + i + ", 'testValue" + i + "')");
}
int[] updateCounts = statement.executeBatch();
assertEquals(totalInsertCommands, updateCounts.length);
int totalUpdates = 0;
for (int updateCount : updateCounts) {
assertEquals(1, updateCount);
totalUpdates += updateCount;
}
assertEquals(totalInsertCommands, totalUpdates);
verifyInsertCount(tmpConnection, totalInsertCommands);
}
}
private void verifyInsertCount(Connection tmpConnection, int insertCount) throws SQLException {
assertEquals(insertCount, retrieveSessionVariableFromServer(tmpConnection, "Com_insert"));
}
private int retrieveSessionVariableFromServer(Connection tmpConnection, String variable)
throws SQLException {
Statement statement = tmpConnection.createStatement();
try (ResultSet resultSet = statement.executeQuery("SHOW STATUS LIKE '" + variable + "'")) {
if (resultSet.next()) {
return resultSet.getInt(2);
}
}
throw new SQLException("Unable to retrieve, variable value from Server " + variable);
}
/**
* Conj-141 : Batch Statement Rewrite: Support for ON DUPLICATE KEY.
*
* @throws SQLException exception
*/
@Test
public void rewriteBatchedStatementsWithQueryFirstAndLAst() throws SQLException {
try (Connection connection = setConnection("&rewriteBatchedStatements=true")) {
PreparedStatement sqlInsert = connection
.prepareStatement("INSERT INTO MultiTestt3_dupp(col1, pkey,col2,"
+ "col3,col4) VALUES (9, ?, 5, ?, 8) ON DUPLICATE KEY UPDATE pkey=pkey+10");
sqlInsert.setInt(1, 1);
sqlInsert.setInt(2, 2);
sqlInsert.addBatch();
sqlInsert.setInt(1, 2);
sqlInsert.setInt(2, 5);
sqlInsert.addBatch();
sqlInsert.setInt(1, 7);
sqlInsert.setInt(2, 6);
sqlInsert.addBatch();
sqlInsert.executeBatch();
}
}
/**
* Conj-142: Using a semicolon in a string with "rewriteBatchedStatements=true" fails.
*
* @throws SQLException exception
*/
@Test
public void rewriteBatchedStatementsSemicolon() throws SQLException {
// set the rewrite batch statements parameter
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("allowMultiQueries", "true");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
final int currentInsert = retrieveSessionVariableFromServer(tmpConnection, "Com_insert");
PreparedStatement sqlInsert = tmpConnection.prepareStatement(
"INSERT INTO MultiTestt3 (message) VALUES (?)");
sqlInsert.setString(1, "aa");
sqlInsert.addBatch();
sqlInsert.setString(1, "b;b");
sqlInsert.addBatch();
sqlInsert.setString(1, ";ccccccc");
sqlInsert.addBatch();
sqlInsert.setString(1, "ddddddddddddddd;");
sqlInsert.addBatch();
sqlInsert.setString(1, ";eeeeeee;;eeeeeeeeee;eeeeeeeeee;");
sqlInsert.addBatch();
int[] updateCounts = sqlInsert.executeBatch();
// rewrite should be ok, so the above should be executed in 1 command updating 5 rows
assertEquals(5, updateCounts.length);
assertEquals(Statement.SUCCESS_NO_INFO, updateCounts[0]);
assertEquals(Statement.SUCCESS_NO_INFO, updateCounts[1]);
assertEquals(Statement.SUCCESS_NO_INFO, updateCounts[2]);
assertEquals(Statement.SUCCESS_NO_INFO, updateCounts[3]);
assertEquals(Statement.SUCCESS_NO_INFO, updateCounts[4]);
assertEquals(1,
retrieveSessionVariableFromServer(tmpConnection, "Com_insert") - currentInsert);
int[] realUpdateCount = ((ClientSidePreparedStatement) sqlInsert).getServerUpdateCounts();
assertEquals(1, realUpdateCount.length);
assertEquals(5, realUpdateCount[0]);
final int secondCurrentInsert = retrieveSessionVariableFromServer(tmpConnection,
"Com_insert");
// rewrite for multiple statements isn't possible, so use allowMutipleQueries
sqlInsert = tmpConnection.prepareStatement("INSERT INTO MultiTestt3 (message) VALUES (?); "
+ "INSERT INTO MultiTestt3 (message) VALUES ('multiple')");
sqlInsert.setString(1, "aa");
sqlInsert.addBatch();
sqlInsert.setString(1, "b;b");
sqlInsert.addBatch();
try {
updateCounts = sqlInsert.executeBatch();
assertEquals(4, updateCounts.length);
assertEquals(1, updateCounts[0]);
assertEquals(1, updateCounts[1]);
assertEquals(1, updateCounts[2]);
assertEquals(1, updateCounts[3]);
assertEquals(4,
retrieveSessionVariableFromServer(tmpConnection, "Com_insert") - secondCurrentInsert);
} catch (BatchUpdateException bue) {
if ((sharedOptions().useBulkStmts && isMariadbServer() && minVersion(10, 2))) {
assertTrue(bue.getMessage().contains("You have an error in your SQL syntax"));
} else {
fail(bue.getMessage());
}
}
}
}
private PreparedStatement prepareStatementBatch(Connection tmpConnection, int size)
throws SQLException {
PreparedStatement preparedStatement = tmpConnection
.prepareStatement("INSERT INTO MultiTestt7 VALUES (?, ?)");
for (int i = 0; i < size; i++) {
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "testValue" + i);
preparedStatement.addBatch();
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "testSecn" + i);
preparedStatement.addBatch();
}
return preparedStatement;
}
/**
* Conj-215: Batched statements with rewriteBatchedStatements that end with a semicolon fails.
*
* @throws SQLException exception
*/
@Test
public void semicolonTest() throws SQLException {
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("allowMultiQueries", "true");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
Statement sqlInsert = tmpConnection.createStatement();
verifyInsertCount(tmpConnection, 0);
for (int i = 0; i < 100; i++) {
sqlInsert
.addBatch("insert into MultiTestprepsemi (text) values ('This is a test" + i + "');");
}
sqlInsert.executeBatch();
verifyInsertCount(tmpConnection, 100);
for (int i = 0; i < 100; i++) {
sqlInsert
.addBatch("insert into MultiTestprepsemi (text) values ('This is a test" + i + "')");
}
sqlInsert.executeBatch();
verifyInsertCount(tmpConnection, 200);
}
}
/**
* Conj-99: rewriteBatchedStatements parameter.
*
* @throws SQLException exception
*/
@Test
public void rewriteBatchedStatementsUpdateTest() throws SQLException {
// set the rewrite batch statements parameter
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("allowMultiQueries", "true");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
tmpConnection.setClientInfo(props);
verifyUpdateCount(tmpConnection, 0);
int cycles = 1000;
prepareStatementBatch(tmpConnection, cycles).executeBatch(); // populate the table
PreparedStatement preparedStatement = tmpConnection.prepareStatement(
"UPDATE MultiTestt7 SET test = ? WHERE id = ?");
for (int i = 0; i < cycles; i++) {
preparedStatement.setString(1, "updated testValue" + i);
preparedStatement.setInt(2, i);
preparedStatement.addBatch();
}
int[] updateCounts = preparedStatement.executeBatch();
assertEquals(cycles, updateCounts.length);
for (int updateCount : updateCounts) {
assertTrue(updateCount == 2
|| updateCount == Statement.SUCCESS_NO_INFO); //2 rows updated by update.
}
verifyUpdateCount(tmpConnection, cycles); //1000 update commande launched
}
}
/**
* Conj-152: rewriteBatchedStatements and multiple executeBatch check.
*
* @throws SQLException exception
*/
@Test
public void testMultipleExecuteBatch() throws SQLException {
// set the rewrite batch statements parameter
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("allowMultiQueries", "true");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
tmpConnection.setClientInfo(props);
verifyUpdateCount(tmpConnection, 0);
tmpConnection.createStatement().execute("insert into MultiTestt8 values(1,'a'),(2,'a')");
PreparedStatement preparedStatement = tmpConnection.prepareStatement(
"UPDATE MultiTestt8 SET test = ? WHERE id = ?");
preparedStatement.setString(1, "executebatch");
preparedStatement.setInt(2, 1);
preparedStatement.addBatch();
preparedStatement.setString(1, "executebatch2");
preparedStatement.setInt(2, 3);
preparedStatement.addBatch();
int[] updateCounts = preparedStatement.executeBatch();
assertEquals(2, updateCounts.length);
preparedStatement.setString(1, "executebatch3");
preparedStatement.setInt(2, 1);
preparedStatement.addBatch();
updateCounts = preparedStatement.executeBatch();
assertEquals(1, updateCounts.length);
}
}
@Test
public void rewriteBatchedStatementsInsertWithDuplicateRecordsTest() throws SQLException {
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("allowMultiQueries", "true");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
verifyInsertCount(tmpConnection, 0);
Statement statement = tmpConnection.createStatement();
for (int i = 0; i < 100; i++) {
int newId = i % 20; //to create duplicate id's
String roleTxt = "VAMPIRE" + newId;
statement.addBatch("INSERT IGNORE INTO MultiTestreWriteDuplicateTestTable VALUES (" + newId
+ ", '" + roleTxt + "')");
}
int[] updateCounts = statement.executeBatch();
assertEquals(100, updateCounts.length);
for (int i = 0; i < updateCounts.length; i++) {
assertEquals((i < 20) ? 1 : 0, updateCounts[i]);
}
verifyInsertCount(tmpConnection, 100);
verifyUpdateCount(tmpConnection, 0);
}
}
@Test
public void updateCountTest() throws SQLException {
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("allowMultiQueries", "true");
props.setProperty("useBulkStmts", "false");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
PreparedStatement sqlInsert = tmpConnection.prepareStatement(
"INSERT IGNORE INTO MultiTestt4 (id,test) VALUES (?,?)");
sqlInsert.setInt(1, 1);
sqlInsert.setString(2, "value1");
sqlInsert.addBatch();
sqlInsert.setInt(1, 1);
sqlInsert.setString(2, "valuenull");
sqlInsert.addBatch();
sqlInsert.setInt(1, 2);
sqlInsert.setString(2, "value2");
sqlInsert.addBatch();
sqlInsert.setInt(1, 3);
sqlInsert.setString(2, "value2");
sqlInsert.addBatch();
int[] insertCounts = sqlInsert.executeBatch();
//Insert in prepare statement, cannot know the number og each one
assertEquals(4, insertCounts.length);
assertEquals(Statement.SUCCESS_NO_INFO, insertCounts[0]);
assertEquals(Statement.SUCCESS_NO_INFO, insertCounts[1]);
assertEquals(Statement.SUCCESS_NO_INFO, insertCounts[2]);
assertEquals(Statement.SUCCESS_NO_INFO, insertCounts[3]);
PreparedStatement sqlUpdate = tmpConnection.prepareStatement(
"UPDATE MultiTestt4 SET test = ? WHERE test = ?");
sqlUpdate.setString(1, "value1 - updated");
sqlUpdate.setString(2, "value1");
sqlUpdate.addBatch();
sqlUpdate.setString(1, "value3 - updated");
sqlUpdate.setString(2, "value3");
sqlUpdate.addBatch();
sqlUpdate.setString(1, "value2 - updated");
sqlUpdate.setString(2, "value2");
sqlUpdate.addBatch();
int[] updateCounts = sqlUpdate.executeBatch();
assertEquals(3, updateCounts.length);
assertEquals(1, updateCounts[0]);
assertEquals(0, updateCounts[1]);
assertEquals(2, updateCounts[2]);
}
}
private void verifyUpdateCount(Connection tmpConnection, int updateCount) throws SQLException {
assertEquals(updateCount, retrieveSessionVariableFromServer(tmpConnection, "Com_update"));
}
@Test
public void testInsertWithLeadingConstantValue() throws Exception {
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("allowMultiQueries", "true");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
PreparedStatement insertStmt = tmpConnection
.prepareStatement("INSERT INTO MultiTesttest_table (col1, col2,"
+ " col3, col4, col5) values('some value', ?, 'other value', ?, 'third value')");
insertStmt.setString(1, "a1");
insertStmt.setString(2, "a2");
insertStmt.addBatch();
insertStmt.setString(1, "b1");
insertStmt.setString(2, "b2");
insertStmt.addBatch();
insertStmt.executeBatch();
}
}
@Test
public void testInsertWithoutFirstContent() throws Exception {
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("allowMultiQueries", "true");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
PreparedStatement insertStmt = tmpConnection
.prepareStatement("INSERT INTO MultiTesttest_table2 "
+ "(col2, col3, col4, col5) values(?, 'other value', ?, 'third value')");
insertStmt.setString(1, "a1");
insertStmt.setString(2, "a2");
insertStmt.addBatch();
insertStmt.setString(1, "b1");
insertStmt.setString(2, "b2");
insertStmt.addBatch();
insertStmt.executeBatch();
}
}
@Test
public void testduplicate() throws Exception {
createTable("SOME_TABLE",
"ID INT(11) not null, FOO INT(11), PRIMARY KEY (ID), UNIQUE INDEX `FOO` (`FOO`)");
String sql = "insert into `SOME_TABLE` (`ID`, `FOO`) values (?, ?) "
+ "on duplicate key update `SOME_TABLE`.`FOO` = ?";
PreparedStatement st = sharedConnection.prepareStatement(sql);
st.setInt(1, 1);
st.setInt(2, 1);
st.setInt(3, 1);
st.addBatch();
st.setInt(1, 2);
st.setInt(2, 1);
st.setInt(3, 2);
st.addBatch();
st.executeBatch();
sql = "/*CLIENT*/" + sql;
st = sharedConnection.prepareStatement(sql);
st.setInt(1, 4);
st.setInt(2, 4);
st.setInt(3, 5);
st.addBatch();
st.setInt(1, 5);
st.setInt(2, 4);
st.setInt(3, 8);
st.addBatch();
st.executeBatch();
}
@Test
public void valuesWithoutSpace() throws Exception {
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("allowMultiQueries", "true");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
PreparedStatement insertStmt = tmpConnection
.prepareStatement("INSERT INTO MultiTestValues (col1, col2)VALUES (?, ?)");
insertStmt.setString(1, "a");
insertStmt.setString(2, "b");
insertStmt.addBatch();
insertStmt.setString(1, "c");
insertStmt.setString(2, "d");
insertStmt.addBatch();
insertStmt.executeBatch();
}
}
/**
* Conj-208 : Rewritten batch inserts can fail without a space before the VALUES clause.
*
* @throws Exception exception
*/
@Test
public void valuesWithoutSpacewithoutRewrite() throws Exception {
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", "true");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
PreparedStatement insertStmt = tmpConnection
.prepareStatement("INSERT INTO MultiTestValues (col1, col2)VALUES (?, ?)");
insertStmt.setString(1, "a");
insertStmt.setString(2, "b");
insertStmt.addBatch();
insertStmt.setString(1, "c");
insertStmt.setString(2, "d");
insertStmt.addBatch();
insertStmt.executeBatch();
}
}
@Test
public void continueOnBatchError() throws SQLException {
for (int i = 0; i < 16; i++) {
continueOnBatchError(i % 16 < 8, i % 8 < 4, i % 4 < 2, i % 2 == 0);
}
}
private void continueOnBatchError(boolean continueBatch, boolean serverPrepare,
boolean rewrite, boolean batchMulti) throws SQLException {
System.out.println("continueBatch:" + continueBatch
+ " serverPrepare:" + serverPrepare
+ " rewrite:" + rewrite
+ " batchMulti:" + batchMulti);
createTable("MultiTestt9", "id int not null primary key, test varchar(10)");
Assume.assumeTrue(!batchMulti || !sharedIsAurora());
try (Connection connection = setBlankConnection(
"&useServerPrepStmts=" + serverPrepare
+ "&useBatchMultiSend=" + batchMulti
+ "&continueBatchOnError=" + continueBatch
+ "&rewriteBatchedStatements=" + rewrite)) {
PreparedStatement pstmt = connection
.prepareStatement("INSERT INTO MultiTestt9 (id, test) VALUES (?, ?)");
for (int i = 0; i < 10; i++) {
pstmt.setInt(1, (i == 5) ? 0 : i);
pstmt.setString(2, String.valueOf(i));
pstmt.addBatch();
}
try {
pstmt.executeBatch();
fail("Must have thrown SQLException");
} catch (BatchUpdateException e) {
int[] updateCount = e.getUpdateCounts();
assertEquals(10, updateCount.length);
if (rewrite) {
//rewrite exception is all or nothing
assertEquals(Statement.EXECUTE_FAILED, updateCount[0]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[1]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[2]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[3]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[4]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[5]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[6]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[7]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[8]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[9]);
} else {
assertEquals(1, updateCount[0]);
assertEquals(1, updateCount[1]);
assertEquals(1, updateCount[2]);
assertEquals(1, updateCount[3]);
assertEquals(1, updateCount[4]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[5]);
if (continueBatch) {
assertEquals(1, updateCount[6]);
assertEquals(1, updateCount[7]);
assertEquals(1, updateCount[8]);
assertEquals(1, updateCount[9]);
} else {
if (batchMulti) {
//send in batch, so continue will be handle, but send packet is executed.
assertEquals(1, updateCount[6]);
assertEquals(1, updateCount[7]);
assertEquals(1, updateCount[8]);
assertEquals(1, updateCount[9]);
} else {
assertEquals(Statement.EXECUTE_FAILED, updateCount[6]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[7]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[8]);
assertEquals(Statement.EXECUTE_FAILED, updateCount[9]);
}
}
}
ResultSet rs = connection.createStatement().executeQuery("SELECT * FROM MultiTestt9");
//check result
if (!rewrite) {
checkNextData(0, rs);
checkNextData(1, rs);
checkNextData(2, rs);
checkNextData(3, rs);
checkNextData(4, rs);
if (continueBatch || batchMulti) {
checkNextData(6, rs);
checkNextData(7, rs);
checkNextData(8, rs);
checkNextData(9, rs);
}
}
assertFalse(rs.next());
}
}
}
private void checkNextData(int value, ResultSet rs) throws SQLException {
assertTrue(rs.next());
assertEquals(value, rs.getInt(1));
assertEquals(String.valueOf(value), rs.getString(2));
}
@Test
public void testCloseStatementWithoutQuery() throws SQLException {
final Statement statement = sharedConnection.createStatement();
// Make sure it is a streaming statement:
statement.setFetchSize(Integer.MIN_VALUE);
for (int count = 1; count <= 10; count++) {
statement.close();
}
}
@Test
public void testClosePrepareStatementWithoutQuery() throws SQLException {
final PreparedStatement preparedStatement = sharedConnection.prepareStatement("SELECT 1");
// Make sure it is a streaming statement:
preparedStatement.setFetchSize(Integer.MIN_VALUE);
for (int count = 1; count <= 10; count++) {
preparedStatement.close();
}
}
@Test
public void testCloseStatement() throws SQLException {
createTable("testStatementClose", "id int");
final Statement statement = sharedConnection.createStatement();
// Make sure it is a streaming statement:
statement.setFetchSize(1);
statement.execute("INSERT INTO testStatementClose (id) VALUES (1)");
for (int count = 1; count <= 10; count++) {
statement.close();
}
}
@Test
public void testClosePrepareStatement() throws SQLException {
createTable("testPrepareStatementClose", "id int");
sharedConnection.createStatement()
.execute("INSERT INTO testPrepareStatementClose(id) VALUES (1),(2),(3)");
final PreparedStatement preparedStatement = sharedConnection
.prepareStatement("SELECT * FROM testPrepareStatementClose");
preparedStatement.execute();
// Make sure it is a streaming statement:
preparedStatement.setFetchSize(1);
for (int count = 1; count <= 10; count++) {
preparedStatement.close();
}
}
@Test
public void rewriteErrorRewriteValues() throws SQLException {
prepareBatchUpdateException(true, true);
}
@Test
public void rewriteErrorRewriteMulti() throws SQLException {
prepareBatchUpdateException(false, true);
}
@Test
public void rewriteErrorStandard() throws SQLException {
prepareBatchUpdateException(false, false);
}
private void prepareBatchUpdateException(Boolean rewriteBatchedStatements,
Boolean allowMultiQueries) throws SQLException {
createTable("batchUpdateException", "i int,PRIMARY KEY (i)");
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", rewriteBatchedStatements.toString());
props.setProperty("allowMultiQueries", allowMultiQueries.toString());
props.setProperty("useServerPrepStmts", "false");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
verifyInsertCount(tmpConnection, 0);
PreparedStatement ps = tmpConnection
.prepareStatement("insert into batchUpdateException values(?)");
ps.setInt(1, 1);
ps.addBatch();
ps.setInt(1, 2);
ps.addBatch();
ps.setInt(1, 1); // will fail, duplicate primary key
ps.addBatch();
ps.setInt(1, 3);
ps.addBatch();
try {
ps.executeBatch();
fail("exception should be throw above");
} catch (BatchUpdateException bue) {
int[] updateCounts = bue.getUpdateCounts();
if (rewriteBatchedStatements || (sharedOptions().useBulkStmts && isMariadbServer()
&& minVersion(10, 2))) {
assertEquals(4, updateCounts.length);
assertEquals(Statement.EXECUTE_FAILED, updateCounts[0]);
assertEquals(Statement.EXECUTE_FAILED, updateCounts[1]);
assertEquals(Statement.EXECUTE_FAILED, updateCounts[2]);
assertEquals(Statement.EXECUTE_FAILED, updateCounts[3]);
verifyInsertCount(tmpConnection, 1);
} else {
assertEquals(4, updateCounts.length);
assertEquals(1, updateCounts[0]);
assertEquals(1, updateCounts[1]);
assertEquals(Statement.EXECUTE_FAILED, updateCounts[2]);
assertEquals(1, updateCounts[3]);
verifyInsertCount(tmpConnection, 4);
}
assertTrue(bue.getCause() instanceof SQLIntegrityConstraintViolationException);
}
}
}
/**
* Test that using -1 (last prepared Statement), if next execution has parameter corresponding,
* previous prepare will not be used.
*
* @throws Throwable if any error.
*/
@Test
public void testLastPrepareDiscarded() throws Throwable {
PreparedStatement preparedStatement1 = sharedConnection
.prepareStatement("INSERT INTO MultiTestA (data) VALUES (?)");
preparedStatement1.setString(1, "A");
preparedStatement1.execute();
PreparedStatement preparedStatement2 = sharedConnection
.prepareStatement("select * from (select ? `field1` from dual) as tt");
preparedStatement2.setString(1, "B");
try {
preparedStatement2.execute();
//must have thrown error if server prepare.
} catch (Exception e) {
//server prepare.
ResultSet rs = sharedConnection.createStatement().executeQuery("SELECT * FROM MultiTestA");
assertTrue(rs.next());
assertEquals("A", rs.getString(1));
assertFalse(rs.next()); //"B" must not have been saved in Table MultiTestA
}
}
@Test
public void testMultiGeneratedKeyRewrite() throws Throwable {
Assume.assumeFalse(isGalera());
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", "true");
props.setProperty("allowMultiQueries", "true");
props.setProperty("useServerPrepStmts", "false");
props.setProperty("sessionVariables", "auto_increment_increment=3");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
checkResults(tmpConnection);
checkResultsPrepare(tmpConnection);
checkResultsPrepareMulti(tmpConnection);
checkResultsPrepareBatch(tmpConnection);
}
}
@Test
public void testMultiGeneratedKey() throws Throwable {
Assume.assumeFalse(isGalera());
Properties props = new Properties();
props.setProperty("rewriteBatchedStatements", "false");
props.setProperty("allowMultiQueries", "true");
props.setProperty("useServerPrepStmts", "true");
props.setProperty("sessionVariables", "auto_increment_increment=3");
try (Connection tmpConnection = openNewConnection(connUri, props)) {
checkResults(tmpConnection);
checkResultsPrepare(tmpConnection);
checkResultsPrepareMulti(tmpConnection);
checkResultsPrepareBatch(tmpConnection);
}
}
private void checkResultsPrepareBatch(Connection connection) throws SQLException {
try (Statement stmt = connection.createStatement()) {
stmt.executeQuery("truncate table testMultiGeneratedKey");
//test single execution
PreparedStatement preparedStatement = connection
.prepareStatement("INSERT INTO testMultiGeneratedKey (text) VALUES (?)",
Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, "data1");
preparedStatement.addBatch();
preparedStatement.setString(1, "data2");
preparedStatement.addBatch();
int[] updates = preparedStatement.executeBatch();
assertEquals(2, updates.length);
ResultSet rs = preparedStatement.getGeneratedKeys();
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertTrue(rs.next());
assertEquals(4, rs.getInt(1));
assertFalse(rs.next());
assertFalse(preparedStatement.getMoreResults());
assertEquals(1, updates[0]);
assertEquals(1, updates[1]);
}
}
private void checkResultsPrepare(Connection connection) throws SQLException {
try (Statement stmt = connection.createStatement()) {
stmt.executeQuery("truncate table testMultiGeneratedKey");
//test single execution
PreparedStatement preparedStatement = connection
.prepareStatement("INSERT INTO testMultiGeneratedKey (text) VALUES (?)",
Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, "data1");
int update = preparedStatement.executeUpdate();
assertEquals(1, update);
ResultSet rs = preparedStatement.getGeneratedKeys();
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertFalse(rs.next());
}
}
private void checkResultsPrepareMulti(Connection connection) throws SQLException {
try (Statement stmt = connection.createStatement()) {
stmt.executeQuery("truncate table testMultiGeneratedKey");
//test single execution
PreparedStatement preparedStatement = connection
.prepareStatement("INSERT INTO testMultiGeneratedKey (text) VALUES (?);"
+ "INSERT INTO testMultiGeneratedKey (text) VALUES (?)",
Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, "data1");
preparedStatement.setString(2, "data2");
int update = preparedStatement.executeUpdate();
assertEquals(1, update);
ResultSet rs = preparedStatement.getGeneratedKeys();
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertFalse(rs.next());
assertFalse(preparedStatement.getMoreResults());
assertEquals(1, preparedStatement.getUpdateCount());
rs = preparedStatement.getGeneratedKeys();
assertTrue(rs.next());
assertEquals(4, rs.getInt(1));
assertFalse(rs.next());
assertFalse(preparedStatement.getMoreResults());
}
}
private void checkResults(Connection connection) throws SQLException {
try (Statement stmt = connection.createStatement()) {
stmt.executeQuery("truncate table testMultiGeneratedKey");
//test single execution
int update = stmt.executeUpdate(
"INSERT INTO testMultiGeneratedKey (text) VALUES ('data1'), ('data2'), ('data3');"
+ "INSERT INTO testMultiGeneratedKey (text) VALUES ('data4'), ('data5')",
Statement.RETURN_GENERATED_KEYS);
assertEquals(3, update);
ResultSet rs = stmt.getGeneratedKeys();
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertTrue(rs.next());
assertEquals(4, rs.getInt(1));
assertTrue(rs.next());
assertEquals(7, rs.getInt(1));
assertFalse(rs.next());
assertFalse(stmt.getMoreResults());
assertEquals(2, stmt.getUpdateCount());
rs = stmt.getGeneratedKeys();
assertTrue(rs.next());
assertEquals(10, rs.getInt(1));
assertTrue(rs.next());
assertEquals(13, rs.getInt(1));
assertFalse(rs.next());
assertFalse(stmt.getMoreResults());
assertEquals(-1, stmt.getUpdateCount());
update = stmt.executeUpdate("INSERT INTO testMultiGeneratedKey (text) VALUES ('data11')",
Statement.RETURN_GENERATED_KEYS);
assertEquals(1, update);
rs = stmt.getGeneratedKeys();
assertTrue(rs.next());
assertEquals(16, rs.getInt(1));
assertFalse(rs.next());
assertFalse(stmt.getMoreResults());
update = stmt
.executeUpdate("SELECT * FROM testMultiGeneratedKey", Statement.RETURN_GENERATED_KEYS);
assertEquals(0, update);
rs = stmt.getGeneratedKeys();
assertFalse(rs.next());
assertFalse(stmt.getMoreResults());
//test batch
stmt.executeQuery("truncate table testMultiGeneratedKey");
stmt.addBatch(
"INSERT INTO testMultiGeneratedKey (text) VALUES ('data0');INSERT INTO testMultiGeneratedKey (text) VALUES ('data1')");
stmt.addBatch("INSERT INTO testMultiGeneratedKey (text) VALUES ('data2')");
stmt.addBatch("INSERT INTO testMultiGeneratedKey (text) VALUES ('data3')");
int[] updates = stmt.executeBatch();
assertEquals(4, updates.length);
assertEquals(1, updates[0]);
assertEquals(1, updates[1]);
assertEquals(1, updates[2]);
assertEquals(1, updates[3]);
rs = stmt.getGeneratedKeys();
for (int i = 0; i < 4; i++) {
assertTrue(rs.next());
assertEquals(1 + i * 3, rs.getInt(1));
}
assertFalse(rs.next());
assertFalse(stmt.getMoreResults());
stmt.addBatch("INSERT INTO testMultiGeneratedKey (text) VALUES ('data11')");
stmt.executeBatch();
rs = stmt.getGeneratedKeys();
assertTrue(rs.next());
assertEquals(13, rs.getInt(1));
assertFalse(rs.next());
}
}
@Test
public void testInsertSelectBulk() throws SQLException {
try (Statement statement = sharedConnection.createStatement()) {
statement.execute("DROP TABLE IF EXISTS testInsertSelectBulk");
statement.execute("DROP TABLE IF EXISTS testInsertSelectBulk2");
statement.execute("CREATE TABLE testInsertSelectBulk(col int, val int)");
statement.execute("CREATE TABLE testInsertSelectBulk2(col int, val int)");
statement.execute("INSERT INTO testInsertSelectBulk(col, val) VALUES (0,1), (2,3)");
try (PreparedStatement preparedStatement = sharedConnection.prepareStatement(
"INSERT INTO testInsertSelectBulk2(col, val) VALUES "
+ "(?, (SELECT val FROM testInsertSelectBulk where col = ?))")) {
preparedStatement.setInt(1, 4);
preparedStatement.setInt(2, 0);
preparedStatement.addBatch();
preparedStatement.setInt(1, 5);
preparedStatement.setInt(2, 2);
preparedStatement.addBatch();
preparedStatement.executeBatch();
}
ResultSet rs = statement.executeQuery("SELECT * from testInsertSelectBulk2");
assertTrue(rs.next());
assertEquals(4, rs.getInt(1));
assertEquals(1, rs.getInt(2));
assertTrue(rs.next());
assertEquals(5, rs.getInt(1));
assertEquals(3, rs.getInt(2));
}
}
@Test
public void testAffectedRow() throws SQLException {
createTable("testAffectedRow", "id int");
testAffectedRow(false);
testAffectedRow(true);
}
private void testAffectedRow(boolean useAffectedRows) throws SQLException {
try (Connection con = setConnection(useAffectedRows ? "&useAffectedRows" : "")) {
Statement stmt = con.createStatement();
stmt.execute("TRUNCATE testAffectedRow");
stmt.execute("INSERT INTO testAffectedRow values (1), (1), (2), (3)");
int rowCount = stmt.executeUpdate("UPDATE testAffectedRow set id = 1");
assertEquals(useAffectedRows ? 2 : 4, rowCount);
}
}
@Test
public void shouldDuplicateKeyUpdateNotReturnExtraRows() throws Throwable {
try (Connection con = openNewConnection(connUri, new Properties())) {
try (Statement stmt = con.createStatement()) {
stmt.execute("truncate table testMultiGeneratedKey");
}
try (PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO testMultiGeneratedKey (id, text) VALUES (?, ?) "
+ "ON DUPLICATE KEY UPDATE text = VALUES(text)",
Statement.RETURN_GENERATED_KEYS)) {
// Insert a row.
pstmt.setInt(1, 1);
pstmt.setString(2, "initial");
assertEquals(1, pstmt.executeUpdate());
try (ResultSet rs = pstmt.getGeneratedKeys()) {
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertFalse(rs.next());
}
// Update the row.
pstmt.setInt(1, 1);
pstmt.setString(2, "updated");
assertEquals(2, pstmt.executeUpdate());
try (ResultSet rs = pstmt.getGeneratedKeys()) {
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
//will be corrected in 2.5.0
//assertTrue(rs.next());
}
}
}
}
@Test
public void insertBatchMultiInsert() throws Throwable {
Properties properties = new Properties();
properties.setProperty("allowMultiQueries", "true");
try (Connection con = openNewConnection(connUri, properties)) {
try (Statement stmt = con.createStatement()) {
stmt.execute("truncate table testMultiGeneratedKey");
}
try (PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO testMultiGeneratedKey (text) VALUES (?)",
Statement.RETURN_GENERATED_KEYS)) {
// Insert a row.
pstmt.setString(1, "initial");
pstmt.addBatch();
pstmt.setString(1, "updated");
pstmt.addBatch();
pstmt.executeBatch();
try (ResultSet rs = pstmt.getGeneratedKeys()) {
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertTrue(rs.next());
assertEquals(2, rs.getInt(1));
assertFalse(rs.next());
}
}
}
}
@Test
public void multiInsertReturnOneGenerated() throws Throwable {
try (Connection con = openNewConnection(connUri, new Properties())) {
try (Statement stmt = con.createStatement()) {
stmt.execute("truncate table testMultiGeneratedKey");
}
try (PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO testMultiGeneratedKey (text) VALUES (?), (?)",
Statement.RETURN_GENERATED_KEYS)) {
// Insert a row.
pstmt.setString(1, "initial");
pstmt.setString(2, "updated");
pstmt.executeUpdate();
try (ResultSet rs = pstmt.getGeneratedKeys()) {
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
//Will change in 2.5.0
assertTrue(rs.next());
}
}
}
}
@Test
public void testAffectedRowBatch() throws SQLException {
createTable("testAffectedRowBatch", "id int PRIMARY KEY, data varchar(10)");
testAffectedRowBatch(false);
testAffectedRowBatch(true);
testAffectedRowLongBatch(false);
testAffectedRowLongBatch(true);
}
private void testAffectedRowBatch(boolean useAffectedRows) throws SQLException {
try (Connection con = setConnection("&rewriteBatchedStatements" + (useAffectedRows ? "&useAffectedRows" : ""))) {
Statement stmt = con.createStatement();
stmt.execute("TRUNCATE testAffectedRowBatch");
try (PreparedStatement preparedStatement = con.prepareStatement(
"INSERT INTO testAffectedRowBatch values (?, ?)")) {
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "1");
preparedStatement.addBatch();
preparedStatement.setInt(1, 2);
preparedStatement.setString(2, "0");
preparedStatement.addBatch();
int[] res = preparedStatement.executeBatch();
assertEquals(2, res.length);
assertEquals(Statement.SUCCESS_NO_INFO, res[0]);
assertEquals(Statement.SUCCESS_NO_INFO, res[1]);
preparedStatement.setInt(1, 3);
preparedStatement.setString(2, "0");
preparedStatement.addBatch();
res = preparedStatement.executeBatch();
assertEquals(1, res.length);
assertEquals(1, res[0]);
}
try (PreparedStatement preparedStatement = con.prepareStatement(
"INSERT INTO testAffectedRowBatch (id) values (?) ON DUPLICATE KEY UPDATE data = '0'")) {
preparedStatement.setInt(1, 1);
preparedStatement.addBatch();
preparedStatement.setInt(1, 2);
preparedStatement.addBatch();
int[] res = preparedStatement.executeBatch();
assertEquals(2, res.length);
assertEquals(Statement.SUCCESS_NO_INFO, res[0]);
assertEquals(Statement.SUCCESS_NO_INFO, res[1]);
preparedStatement.setInt(1, 6);
preparedStatement.addBatch();
res = preparedStatement.executeBatch();
assertEquals(1, res.length);
assertEquals(1, res[0]);
preparedStatement.setInt(1, 1);
preparedStatement.addBatch();
preparedStatement.setInt(1, 2);
preparedStatement.addBatch();
res = preparedStatement.executeBatch();
assertEquals(2, res.length);
if (useAffectedRows) {
assertEquals(0, res[0]);
assertEquals(0, res[1]);
} else {
assertEquals(Statement.SUCCESS_NO_INFO, res[0]);
assertEquals(Statement.SUCCESS_NO_INFO, res[1]);
}
}
}
}
private void testAffectedRowLongBatch(boolean useAffectedRows) throws SQLException {
try (Connection con = setConnection("&rewriteBatchedStatements" + (useAffectedRows ? "&useAffectedRows" : ""))) {
Statement stmt = con.createStatement();
stmt.execute("TRUNCATE testAffectedRowBatch");
try (PreparedStatement preparedStatement = con.prepareStatement(
"INSERT INTO testAffectedRowBatch values (?, ?)")) {
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "1");
preparedStatement.addBatch();
preparedStatement.setInt(1, 2);
preparedStatement.setString(2, "0");
preparedStatement.addBatch();
long[] res = preparedStatement.executeLargeBatch();
assertEquals(2, res.length);
assertEquals(Statement.SUCCESS_NO_INFO, res[0]);
assertEquals(Statement.SUCCESS_NO_INFO, res[1]);
preparedStatement.setInt(1, 3);
preparedStatement.setString(2, "0");
preparedStatement.addBatch();
res = preparedStatement.executeLargeBatch();
assertEquals(1, res.length);
assertEquals(1, res[0]);
}
try (PreparedStatement preparedStatement = con.prepareStatement(
"INSERT INTO testAffectedRowBatch (id) values (?) ON DUPLICATE KEY UPDATE data = '0'")) {
preparedStatement.setInt(1, 1);
preparedStatement.addBatch();
preparedStatement.setInt(1, 2);
preparedStatement.addBatch();
long[] res = preparedStatement.executeLargeBatch();
assertEquals(2, res.length);
assertEquals(Statement.SUCCESS_NO_INFO, res[0]);
assertEquals(Statement.SUCCESS_NO_INFO, res[1]);
preparedStatement.setInt(1, 6);
preparedStatement.addBatch();
res = preparedStatement.executeLargeBatch();
assertEquals(1, res.length);
assertEquals(1, res[0]);
preparedStatement.setInt(1, 1);
preparedStatement.addBatch();
preparedStatement.setInt(1, 2);
preparedStatement.addBatch();
res = preparedStatement.executeLargeBatch();
assertEquals(2, res.length);
if (useAffectedRows) {
assertEquals(0, res[0]);
assertEquals(0, res[1]);
} else {
assertEquals(Statement.SUCCESS_NO_INFO, res[0]);
assertEquals(Statement.SUCCESS_NO_INFO, res[1]);
}
}
}
}
}
|
package uk.ac.ebi.subs.api;
import uk.ac.ebi.subs.data.client.*;
import uk.ac.ebi.subs.data.client.Study;
import uk.ac.ebi.subs.data.component.*;
import uk.ac.ebi.subs.data.status.ProcessingStatusEnum;
import uk.ac.ebi.subs.data.status.SubmissionStatusEnum;
import uk.ac.ebi.subs.repository.model.*;
import uk.ac.ebi.subs.repository.model.Assay;
import uk.ac.ebi.subs.repository.model.Sample;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class Helpers {
public static Submission generateSubmission() {
Submission s = new Submission();
s.setTeam(generateTestTeam());
s.setSubmitter(generateTestSubmitter());
return s;
}
private static Submitter generateTestSubmitter() {
Submitter u = new Submitter();
u.setEmail("test@test.org");
return u;
}
public static List<Sample> generateTestSamples() {
return generateTestSamples(2);
}
public static List<uk.ac.ebi.subs.data.client.Sample> generateTestClientSamples(int numberOfSamplesRequired) {
List<uk.ac.ebi.subs.data.client.Sample> samples = new ArrayList<>(numberOfSamplesRequired);
for (int i = 1; i <= numberOfSamplesRequired; i++) {
uk.ac.ebi.subs.data.client.Sample s = new uk.ac.ebi.subs.data.client.Sample();
samples.add(s);
s.setAlias("D" + i);
s.setTitle("NA12878_D" + i);
s.setDescription("Material derived from cell line NA12878");
s.setTaxon("Homo sapiens");
s.setTaxonId(9606L);
s.setArchive(Archive.BioSamples);
Attribute cellLineType = attribute("Cell line type", "EBV-LCL cell line");
Term ebvLclCellLine = new Term();
ebvLclCellLine.setUrl("http://purl.obolibrary.org/obo/BTO_0003335");
cellLineType.getTerms().add(ebvLclCellLine);
s.getAttributes().add(cellLineType);
SampleRelationship derivedFrom = new SampleRelationship();
derivedFrom.setAccession("SAME123392");
derivedFrom.setRelationshipNature("Derived from");
s.getSampleRelationships().add(derivedFrom);
}
return samples;
}
public static List<uk.ac.ebi.subs.data.client.Study> generateTestClientStudies(int numberOfStudiesRequired) {
List<uk.ac.ebi.subs.data.client.Study> studies= new ArrayList<>(numberOfStudiesRequired);
for (int i = 1; i <= numberOfStudiesRequired; i++) {
uk.ac.ebi.subs.data.client.Study s = new uk.ac.ebi.subs.data.client.Study();
studies.add(s);
Attribute studyType = new Attribute();
studyType.setName("study_type");
studyType.setValue("Whole Genome Sequencing");
s.setAlias("Study" + i);
s.setTitle("My Sequencing Study " + i);
s.setDescription("We sequenced some humans to discover variants linked with a disease");
s.setArchive(Archive.Ena);
Attribute studyAbstract = new Attribute();
studyAbstract.setName("study_abstract");
studyAbstract.setValue(s.getDescription());
s.getAttributes().add(studyType);
s.getAttributes().add(studyAbstract);
LocalDate releaseDate = LocalDate.parse("2020-12-25");
s.setReleaseDate(java.sql.Date.valueOf(releaseDate));
}
return studies;
}
private static Attribute attribute(String name, String value){
Attribute attribute = new Attribute();
attribute.setName(name);
attribute.setValue(value);
return attribute;
}
public static List<uk.ac.ebi.subs.data.client.Assay> generateTestClientAssays(int numberOfAssaysRequired) {
List<uk.ac.ebi.subs.data.client.Assay> assays = new ArrayList<>(numberOfAssaysRequired);
Study study = generateTestClientStudies(1).get(0);
StudyRef studyRef = new StudyRef();
studyRef.setAlias(study.getAlias());
studyRef.setTeam(TEAM_NAME);
List<uk.ac.ebi.subs.data.client.Sample> samples = generateTestClientSamples(numberOfAssaysRequired);
for (int i = 1; i <= numberOfAssaysRequired; i++) {
uk.ac.ebi.subs.data.client.Assay a = new uk.ac.ebi.subs.data.client.Assay();
assays.add(a);
a.setAlias("A" + i);
a.setTitle("Assay " + i);
a.setDescription("Human sequencing experiment");
a.setStudyRef(studyRef);
a.setArchive(Archive.Ena);
SampleRef sampleRef = new SampleRef();
sampleRef.setAlias(samples.get(i-1).getAlias());
sampleRef.setTeam(TEAM_NAME);
SampleUse sampleUse = new SampleUse();
sampleUse.setSampleRef( sampleRef);
a.getSampleUses().add(sampleUse);
a.getAttributes().add(attribute("library_strategy","WGS"));
a.getAttributes().add(attribute("library_source","GENOMIC"));
a.getAttributes().add(attribute("library_selection","RANDOM"));
a.getAttributes().add(attribute("library_layout","SINGLE"));
a.getAttributes().add(attribute("platform_type","ILLUMINA"));
a.getAttributes().add(attribute("instrument_model","Illumina HiSeq 2000"));
}
return assays;
}
public static List<uk.ac.ebi.subs.data.client.AssayData> generateTestClientAssayData(int numberOfAssaysRequired) {
List<uk.ac.ebi.subs.data.client.AssayData> assayData = new ArrayList<>(numberOfAssaysRequired);
List<uk.ac.ebi.subs.data.client.Assay> assays = generateTestClientAssays(numberOfAssaysRequired);
for (int i = 1; i <= numberOfAssaysRequired; i++) {
uk.ac.ebi.subs.data.client.AssayData ad = new uk.ac.ebi.subs.data.client.AssayData();
assayData.add(ad);
ad.setAlias("AD" + i);
ad.setTitle("AssayData" + i);
ad.setDescription("Human sequencing experiment run");
ad.setArchive(Archive.Ena);
AssayRef assayRef = new AssayRef();
assayRef.setAlias(assays.get(i-1).getAlias());
assayRef.setTeam(TEAM_NAME);
ad.setAssayRef(assayRef);
File file = new File();
file.setName("sequencingData.cram");
file.setType("CRAM");
file.setChecksum("4bb1c4561d99d88c8b38a40d694267dc");
ad.getFiles().add(file);
}
return assayData;
}
public static List<Sample> generateTestSamples(int numberOfSamplesRequired) {
List<Sample> samples = new ArrayList<>(numberOfSamplesRequired);
for (int i = 1; i <= numberOfSamplesRequired; i++) {
Sample s = new Sample();
samples.add(s);
s.setId(createId());
s.setAlias("D" + i);
s.setTitle("Donor " + i);
s.setDescription("Human sample donor");
s.setTaxon("Homo sapiens");
s.setTaxonId(9606L);
s.setProcessingStatus(new ProcessingStatus(ProcessingStatusEnum.Draft));
}
return samples;
}
public static Team generateTestTeam() {
Team d = new Team();
d.setName(TEAM_NAME);
return d;
}
private static String TEAM_NAME = "my-team";
public static Submission generateTestSubmission() {
Submission sub = new Submission();
Team d = new Team();
sub.setId(createId());
sub.setTeam(generateTestTeam());
sub.setSubmissionStatus(new SubmissionStatus(SubmissionStatusEnum.Draft));
return sub;
}
private static String createId() {
return UUID.randomUUID().toString();
}
}
|
package uk.ac.ebi.spot.goci.curation.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import uk.ac.ebi.spot.goci.model.Gene;
import uk.ac.ebi.spot.goci.model.RiskAllele;
import uk.ac.ebi.spot.goci.model.SingleNucleotidePolymorphism;
import uk.ac.ebi.spot.goci.repository.GeneRepository;
import uk.ac.ebi.spot.goci.repository.RiskAlleleRepository;
import uk.ac.ebi.spot.goci.repository.SingleNucleotidePolymorphismRepository;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Service
public class LociAttributesService {
private SingleNucleotidePolymorphismRepository singleNucleotidePolymorphismRepository;
private GeneRepository geneRepository;
private RiskAlleleRepository riskAlleleRepository;
// Constructor
@Autowired
public LociAttributesService(SingleNucleotidePolymorphismRepository singleNucleotidePolymorphismRepository,
GeneRepository geneRepository,
RiskAlleleRepository riskAlleleRepository) {
this.singleNucleotidePolymorphismRepository = singleNucleotidePolymorphismRepository;
this.geneRepository = geneRepository;
this.riskAlleleRepository = riskAlleleRepository;
}
public Collection<Gene> createGene(Collection<String> authorReportedGenes) {
Collection<Gene> locusGenes = new ArrayList<Gene>();
for (String authorReportedGene : authorReportedGenes) {
// Check if gene already exists, note we may have duplicates so for moment just take first one
List<Gene> genesInDatabase = geneRepository.findByGeneNameIgnoreCase(authorReportedGene);
Gene gene;
// Exists in database already
if (genesInDatabase.size() > 0) {
gene = genesInDatabase.get(0);
}
// If gene doesn't exist then create and save
else {
// Create new gene
Gene newGene = new Gene();
newGene.setGeneName(authorReportedGene);
// Save gene
gene = geneRepository.save(newGene);
}
// Add genes to collection
locusGenes.add(gene);
}
return locusGenes;
}
public RiskAllele createRiskAllele(String curatorEnteredRiskAllele, SingleNucleotidePolymorphism snp) {
//Create new risk allele, at present we always create a new risk allele for each locus within an association
RiskAllele riskAllele = new RiskAllele();
riskAllele.setRiskAlleleName(curatorEnteredRiskAllele);
riskAllele.setSnp(snp);
// Save risk allele
riskAlleleRepository.save(riskAllele);
return riskAllele;
}
public void deleteRiskAllele(RiskAllele riskAllele) {
riskAlleleRepository.delete(riskAllele);
}
public SingleNucleotidePolymorphism createSnp(String curatorEnteredSNP) {
// Check if SNP already exists database, note database contains duplicates
List<SingleNucleotidePolymorphism> singleNucleotidePolymorphisms =
singleNucleotidePolymorphismRepository.findByRsIdIgnoreCase(curatorEnteredSNP);
SingleNucleotidePolymorphism snp;
if (singleNucleotidePolymorphisms.size() > 0) {
snp = singleNucleotidePolymorphisms.get(0);
}
// If SNP doesn't exist, create and save
else {
// Create new SNP
SingleNucleotidePolymorphism newSNP = new SingleNucleotidePolymorphism();
newSNP.setRsId(curatorEnteredSNP);
// Save SNP
snp = singleNucleotidePolymorphismRepository.save(newSNP);
}
return snp;
}
}
|
package org.innovateuk.ifs.project.status.service;
import org.innovateuk.ifs.BaseRestServiceUnitTest;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.project.status.resource.ProjectTeamStatusResource;
import org.innovateuk.ifs.project.status.resource.CompetitionProjectsStatusResource;
import org.innovateuk.ifs.project.status.resource.ProjectStatusResource;
import org.junit.Assert;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.assertTrue;
import static org.springframework.http.HttpStatus.OK;
public class StatusRestServiceImplTest extends BaseRestServiceUnitTest<StatusRestServiceImpl> {
private static final String competitionURL = "/project/competition";
private static final String projectRestURL = "/project";
@Override
protected StatusRestServiceImpl registerRestServiceUnderTest() {
return new StatusRestServiceImpl();
}
@Test
public void getCompetitionStatus() {
Long competitionId = 1L;
String applicationSearchString = "12";
CompetitionProjectsStatusResource returnedResponse = new CompetitionProjectsStatusResource();
setupGetWithRestResultExpectations(competitionURL + "/" + competitionId + "?applicationSearchString=" + applicationSearchString, CompetitionProjectsStatusResource.class, returnedResponse);
RestResult<CompetitionProjectsStatusResource> result = service.getCompetitionStatus(competitionId, applicationSearchString);
assertTrue(result.isSuccess());
Assert.assertEquals(returnedResponse, result.getSuccess());
setupGetWithRestResultVerifications(competitionURL + "/" + competitionId + "?applicationSearchString=" + applicationSearchString, null, CompetitionProjectsStatusResource.class);
}
@Test
public void getStatusByProjectId() {
ProjectStatusResource returnedResponse = new ProjectStatusResource();
setupGetWithRestResultExpectations(projectRestURL + "/123/status", ProjectStatusResource.class, returnedResponse);
ProjectStatusResource result = service.getProjectStatus(123L).getSuccess();
Assert.assertEquals(returnedResponse, result);
setupGetWithRestResultVerifications(projectRestURL + "/123/status", null, ProjectStatusResource.class);
}
@Test
public void getProjectTeamStatus() {
String expectedUrl = projectRestURL + "/123/team-status";
setupGetWithRestResultExpectations(expectedUrl, ProjectTeamStatusResource.class, null, OK);
RestResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(123L, Optional.empty());
assertTrue(result.isSuccess());
setupGetWithRestResultVerifications(projectRestURL + "/123/team-status", null, ProjectTeamStatusResource.class);
}
@Test
public void getProjectTeamStatusWithFilterByUserId() {
String expectedUrl = projectRestURL + "/123/team-status?filterByUserId=456";
setupGetWithRestResultExpectations(expectedUrl, ProjectTeamStatusResource.class, null, OK);
RestResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(123L, Optional.of(456L));
assertTrue(result.isSuccess());
setupGetWithRestResultVerifications(projectRestURL + "/123/team-status?filterByUserId=456", null, ProjectTeamStatusResource.class);
}
}
|
package uk.ac.ebi.quickgo.index.annotation.coterms;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument;
import com.google.common.base.Preconditions;
import java.util.*;
import java.util.function.Predicate;
import org.springframework.batch.item.ItemWriter;
import static uk.ac.ebi.quickgo.index.annotation.coterms.GeneProductBatch.buildBatch;
public class AnnotationCoOccurringTermsAggregator implements ItemWriter<AnnotationDocument> {
//A list of all unique geneProducts encountered - it exists so we can get a count of the total unique gene products.
private final Set<String> geneProductList;
//Determines which annotations get processed.
private final Predicate<AnnotationDocument> toBeProcessed;
private GeneProductBatch geneProductBatch;
private final CoTermMatrix coTerms;
private final TermGPCount termGPCount;
public AnnotationCoOccurringTermsAggregator(Predicate<AnnotationDocument> toBeProcessed) {
Preconditions
.checkArgument(toBeProcessed != null, "Null predicate passed AnnotationCoOccurringTermsAggregator" +
" constructor");
this.toBeProcessed = toBeProcessed;
this.coTerms = new CoTermMatrix();
geneProductList = new HashSet<>();
termGPCount = new TermGPCount();
geneProductBatch = new GeneProductBatch();
}
/**
* Number of unique gene products processed from Annotations
*
* @return unique gene product count
*/
public long getTotalOfAnnotatedGeneProducts() {
return geneProductList.size();
}
/**
* This is the count of all unique gene products for terms encountered during processing. We hold this figure
* separately as it is used many times.
*
* @return map of GO terms to count of unique gene products for the term.
*/
public Map<String, HitCount> getGeneProductCounts() {
return termGPCount.termGPCount;
}
/**
* Holds a termN by termN matrix, each cell of which holds the count of gp this intersection of terms hold
*
* @return map of processed terms to all co-occurring terms, together with count of how many times they have
* co-occurred.
*/
public Map<String, Map<String, HitCount>> getCoTerms() {
return coTerms.coTermMatrix;
}
/**
* For each AnnotationDocument item passed to this method, check whether it passed the criteria for aggregating,
* and if so add its data to the aggregated data.
*
* @param items a list of AnnotationDocuments.
* @throws java.lang.Exception - if there are errors. The framework will catch the exception and convert or rethrow it as appropriate.
*/
@Override
public void write(List<? extends AnnotationDocument> items) throws Exception {
Preconditions.checkArgument(items != null, "Null annotation passed to process");
items.stream()
.filter(this.toBeProcessed::test)
.forEach(this::addGOTermToAggregationForGeneProduct);
}
/**
* Add the data in an AnnotationDocument instance to the aggregation.
* The documents are processed by this class in the gene product order.
* So the first thing to do is check if this doc has a previously unseen gene product id.
* If it doesn't we use the existing aggregation object (newOrExistingBatch instance) to aggregate too.
* If it is a new gene product the we have a new newOrExistingBatch instance created.
* Add the data in this document to the target newOrExistingBatch.
* Add the gene product id to the list of geneproduct ids that have been processed (we need a list of all gene
* products processed for the statistics calculations at the end of the calculation.
*
* @param doc
*/
private void addGOTermToAggregationForGeneProduct(AnnotationDocument doc) {
if (geneProductBatch.geneProduct == null) {
geneProductBatch.geneProduct = doc.geneProductId;
}
if (!doc.geneProductId.equals(geneProductBatch.geneProduct)) {
increaseCountsForTermsInBatch();
geneProductBatch = buildBatch(doc);
}else{
geneProductBatch.addTerm(doc.goId);
}
geneProductList.add(doc.geneProductId); //set so each gp is only added once.
}
/**
* The client must call finish() when all annotation documents have been processed by the write method to wrap up
* processing.
*/
public void finish() {
increaseCountsForTermsInBatch();
}
/**
* Got to the end of the list of annotations for this gene product
* Record which terms annotate the same gene products.
*/
private void increaseCountsForTermsInBatch() {
for (String termId : geneProductBatch.terms) {
coTerms.incrementCountForCo_occurringTerms(termId, geneProductBatch.terms);
termGPCount.incrementGeneProductCountForTerm(termId);
}
}
}
/**
* A data bucket for aggregating annotation document data. Each batch is created for all data with the same gene
* product id.
*/
class GeneProductBatch {
//A set of all terms encountered for a Gene Product. Therefore all these terms are co-occurring with each other.
final Set<String> terms;
//The input file has annotations in gene product order, so we use this value to note changes in gene product.
public String geneProduct;
public GeneProductBatch() {
terms = new HashSet<>();
}
void addTerm(String termId) {
terms.add(termId);
}
/**
* Create a new GeneProductBatch to aggregate terms for the 'new' gene product id.
* @param doc
* @return
*/
static GeneProductBatch buildBatch(AnnotationDocument doc){
GeneProductBatch geneProductBatch = new GeneProductBatch();
geneProductBatch.geneProduct = doc.geneProductId;
geneProductBatch.addTerm(doc.goId);
return geneProductBatch;
}
}
/**
* This class represents a matrix of term to compared term, and its used to hold the number of permutation occurrences.
*/
class CoTermMatrix {
// Key is the target term, the value is a map of all the GO terms that are used in annotations for the same gene
// product. i.e. Key =>target term, value=> map (key=>co-occurring term, value => HitCountForCo-occurrence)
// For example key=>'GO:0003824', value=> map(entry 1 :: key=>'GO:0008152' value=>1346183 hits, entry 2 key=>'GO:0016740' value=>1043613 hits)
final Map<String, Map<String, HitCount>> coTermMatrix;
public CoTermMatrix() {
coTermMatrix = new TreeMap<>();
}
/**
* For all terms encountered for gene product batch, increment its hit count. If this is a new {@code termId}, then
* its hit count is initialised as 1.
* @param termId single term from batch
* @param termsInBatch a list of all terms encountered in annotations for a particular gene product.
*/
void incrementCountForCo_occurringTerms(String termId, Set<String> termsInBatch) {
Map<String, HitCount> co_occurringTerms = getCo_occurringTerms(termId);
//Loop through all the terms we have encountered in this batch and update the quantities
for (String co_occurringTerm : termsInBatch) {
//Get 'permanent' record for this termId/termId permutation
HitCount permutationHitCount = co_occurringTerms.get(co_occurringTerm);
//Create if it doesn't exist.
if (permutationHitCount == null) {
permutationHitCount = new HitCount();
co_occurringTerms.put(co_occurringTerm, permutationHitCount);
}
//Update it with a count of 'one' as this batch is for one gene protein and so the count must be one
permutationHitCount.hits++;
}
}
/**
* Get the co-stats for this termId
*
* @param termId
* @return All terms that are co-occurring term to argument
*/
private Map<String, HitCount> getCo_occurringTerms(String termId) {
//look in the store
Map<String, HitCount> termCoTerms = coTermMatrix.get(termId);
//Create if it doesn't exist.
if (termCoTerms == null) {
termCoTerms = new HashMap<>();
coTermMatrix.put(termId, termCoTerms);
}
return termCoTerms;
}
}
class TermGPCount {
final Map<String, HitCount> termGPCount;
public TermGPCount() {
this.termGPCount = new HashMap<>();
}
/**
* For every term, increment by one the count of gene products for this term
*/
void incrementGeneProductCountForTerm(String term) {
HitCount hitCount = termGPCount.get(term);
if (hitCount == null) {
hitCount = new HitCount();
termGPCount.put(term, hitCount);
}
hitCount.hits++;
}
}
|
package com.jme3.network.service.serializer;
import com.jme3.network.Client;
import com.jme3.network.Message;
import com.jme3.network.MessageListener;
import com.jme3.network.message.SerializerRegistrationsMessage;
import com.jme3.network.serializing.Serializer;
import com.jme3.network.service.AbstractClientService;
import com.jme3.network.service.ClientServiceManager;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
*
* @author Paul Speed
*/
public class ClientSerializerRegistrationsService extends AbstractClientService
implements MessageListener<Client> {
static final Logger log = Logger.getLogger(SerializerRegistrationsMessage.class.getName());
@Override
protected void onInitialize( ClientServiceManager serviceManager ) {
// Make sure our message type is registered if it isn't already
if( Serializer.getExactSerializerRegistration(SerializerRegistrationsMessage.class) == null ) {
// This is the minimum we'd need just to be able to register
// the rest... otherwise we can't even receive this message.
Serializer.registerClass(SerializerRegistrationsMessage.class);
Serializer.registerClass(SerializerRegistrationsMessage.Registration.class);
} else {
log.log(Level.INFO, "Skipping registration of SerializerRegistrationsMessage.");
}
// Add our listener for that message type
serviceManager.getClient().addMessageListener(this, SerializerRegistrationsMessage.class);
}
@Override
public void messageReceived( Client source, Message m ) {
// We only wait for one kind of message...
SerializerRegistrationsMessage msg = (SerializerRegistrationsMessage)m;
msg.registerAll();
}
}
|
package org.apache.aries.jndi.legacy.support;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
import javax.naming.spi.InitialContextFactoryBuilder;
/**
* Some OSGi based server runtimes, such as jetty OSGi and virgo rely on the thread context classloader
* to make their JNDI InitialContextFactory's available in OSGi, rather than relying on the OSGi JNDI spec.
* This is a little bizare, but perhaps is just a point in time statement. In any case to support them
* using Aries JNDI we have this ICFB which uses the Thread context classloader. We don't ship it in the
* jndi uber bundle because it is only for these runtimes which haven't caught up with the latest OSGi specs.
* Normally we want to enourage the use of the OSGi spec, but this is a backstop for those wanting to use
* Aries JNDI and one of these runtimes.
*
*/
public class LegacyInitialContextFinder implements InitialContextFactoryBuilder {
public InitialContextFactory createInitialContextFactory(
Hashtable<?, ?> environment) throws NamingException
{
String icf = (String) environment.get(Context.INITIAL_CONTEXT_FACTORY);
if (icf != null) {
ClassLoader cl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
try {
Class<?> icfClass = Class.forName(icf, false, cl);
if (InitialContextFactory.class.isAssignableFrom(icfClass)) {
return (InitialContextFactory) icfClass.newInstance();
}
} catch (ClassNotFoundException e) {
// If the ICF doesn't exist this is expected. Should return null so the next builder is queried.
} catch (InstantiationException e) {
// If the ICF couldn't be created just ignore and return null.
} catch (IllegalAccessException e) {
// If the default constructor is private, just ignore and return null.
}
}
return null;
}
}
|
package com.badlogic.gdx.graphics.glutils;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.utils.BufferUtils;
/**
* <p>
* A {@link VertexData} implementation that uses vertex buffer objects and vertex array objects.
* (This is required for OpenGL 3.0+ core profiles. In particular, the default VAO has been
* deprecated, as has the use of client memory for passing vertex attributes.) Use of VAOs should
* give a slight performance benefit since you don't have to bind the attributes on every draw
* anymore.
* </p>
*
* <p>
* If the OpenGL ES context was lost you can call {@link #invalidate()} to recreate a new OpenGL vertex buffer object.
* </p>
*
* <p>
* VertexBufferObjectWithVAO objects must be disposed via the {@link #dispose()} method when no longer needed
* </p>
*
* Code adapted from {@link VertexBufferObject}.
* @author mzechner, Dave Clayton <contact@redskyforge.com>, Nate Austin <nate.austin gmail>
*/
public class VertexBufferObjectWithVAO implements VertexData {
final static IntBuffer tmpHandle = BufferUtils.newIntBuffer(1);
final VertexAttributes attributes;
final FloatBuffer buffer;
final ByteBuffer byteBuffer;
int bufferHandle;
final boolean isStatic;
final int usage;
boolean isDirty = false;
boolean isBound = false;
boolean vaoDirty = true;
int vaoHandle = -1;
/**
* Constructs a new interleaved VertexBufferObjectWithVAO.
*
* @param isStatic whether the vertex data is static.
* @param numVertices the maximum number of vertices
* @param attributes the {@link com.badlogic.gdx.graphics.VertexAttribute}s.
*/
public VertexBufferObjectWithVAO(boolean isStatic, int numVertices, VertexAttribute... attributes) {
this(isStatic, numVertices, new VertexAttributes(attributes));
}
/**
* Constructs a new interleaved VertexBufferObjectWithVAO.
*
* @param isStatic whether the vertex data is static.
* @param numVertices the maximum number of vertices
* @param attributes the {@link VertexAttributes}.
*/
public VertexBufferObjectWithVAO(boolean isStatic, int numVertices, VertexAttributes attributes) {
this.isStatic = isStatic;
this.attributes = attributes;
byteBuffer = BufferUtils.newUnsafeByteBuffer(this.attributes.vertexSize * numVertices);
buffer = byteBuffer.asFloatBuffer();
buffer.flip();
byteBuffer.flip();
bufferHandle = Gdx.gl20.glGenBuffer();
usage = isStatic ? GL20.GL_STATIC_DRAW : GL20.GL_DYNAMIC_DRAW;
}
@Override
public VertexAttributes getAttributes() {
return attributes;
}
@Override
public int getNumVertices() {
return buffer.limit() * 4 / attributes.vertexSize;
}
@Override
public int getNumMaxVertices() {
return byteBuffer.capacity() / attributes.vertexSize;
}
@Override
public FloatBuffer getBuffer() {
isDirty = true;
return buffer;
}
private void bufferChanged() {
if (isBound) {
Gdx.gl20.glBufferData(GL20.GL_ARRAY_BUFFER, byteBuffer.limit(), byteBuffer, usage);
isDirty = false;
}
}
@Override
public void setVertices(float[] vertices, int offset, int count) {
isDirty = true;
BufferUtils.copy(vertices, byteBuffer, count, offset);
buffer.position(0);
buffer.limit(count);
bufferChanged();
}
@Override
public void updateVertices(int targetOffset, float[] vertices, int sourceOffset, int count) {
isDirty = true;
final int pos = byteBuffer.position();
byteBuffer.position(targetOffset * 4);
BufferUtils.copy(vertices, sourceOffset, count, byteBuffer);
byteBuffer.position(pos);
buffer.position(0);
bufferChanged();
}
/**
* Binds this VertexBufferObject for rendering via glDrawArrays or glDrawElements
*
* @param shader the shader
*/
@Override
public void bind(ShaderProgram shader) {
bind(shader, null);
}
@Override
public void bind(ShaderProgram shader, int[] locations) {
GL30 gl = Gdx.gl30;
if (vaoDirty || !gl.glIsVertexArray(vaoHandle)) {
tmpHandle.clear();
gl.glGenVertexArrays(1, tmpHandle);
vaoHandle = tmpHandle.get(0);
gl.glBindVertexArray(vaoHandle);
//initialize the VAO with our vertex attributes and buffer:
bindAttributes(shader, locations);
vaoDirty = false;
} else {
//else simply bind the VAO.
gl.glBindVertexArray(vaoHandle);
}
//if our data has changed upload it:
bindData(gl);
isBound = true;
}
private void bindAttributes(ShaderProgram shader, int[] locations) {
final GL20 gl = Gdx.gl20;
gl.glBindBuffer(GL20.GL_ARRAY_BUFFER, bufferHandle);
final int numAttributes = attributes.size();
if (locations == null) {
for (int i = 0; i < numAttributes; i++) {
final VertexAttribute attribute = attributes.get(i);
final int location = shader.getAttributeLocation(attribute.alias);
if (location < 0) continue;
shader.enableVertexAttribute(location);
shader.setVertexAttribute(location, attribute.numComponents, attribute.type, attribute.normalized, attributes.vertexSize,
attribute.offset);
}
} else {
for (int i = 0; i < numAttributes; i++) {
final VertexAttribute attribute = attributes.get(i);
final int location = locations[i];
if (location < 0) continue;
shader.enableVertexAttribute(location);
shader.setVertexAttribute(location, attribute.numComponents, attribute.type, attribute.normalized, attributes.vertexSize,
attribute.offset);
}
}
}
private void bindData(GL20 gl) {
if (isDirty) {
gl.glBindBuffer(GL20.GL_ARRAY_BUFFER, bufferHandle);
byteBuffer.limit(buffer.limit() * 4);
gl.glBufferData(GL20.GL_ARRAY_BUFFER, byteBuffer.limit(), byteBuffer, usage);
isDirty = false;
}
}
/**
* Unbinds this VertexBufferObject.
*
* @param shader the shader
*/
@Override
public void unbind(final ShaderProgram shader) {
unbind(shader, null);
}
@Override
public void unbind(final ShaderProgram shader, final int[] locations) {
GL30 gl = Gdx.gl30;
gl.glBindVertexArray(0);
isBound = false;
}
//TODO: should invalidate be added to the VertexData interface?
/**
* Invalidates the VertexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss.
*/
public void invalidate() {
bufferHandle = Gdx.gl20.glGenBuffer();
isDirty = true;
vaoDirty = true;
}
/**
* Disposes of all resources this VertexBufferObject uses.
*/
@Override
public void dispose() {
GL30 gl = Gdx.gl30;
gl.glBindBuffer(GL20.GL_ARRAY_BUFFER, 0);
gl.glDeleteBuffer(bufferHandle);
bufferHandle = 0;
BufferUtils.disposeUnsafeByteBuffer(byteBuffer);
if (gl.glIsVertexArray(vaoHandle)) {
tmpHandle.clear();
tmpHandle.put(vaoHandle);
tmpHandle.flip();
gl.glDeleteVertexArrays(1, tmpHandle);
}
}
}
|
package org.eclipse.kura.net.admin.monitor;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.kura.KuraException;
import org.eclipse.kura.core.net.NetworkConfiguration;
import org.eclipse.kura.core.net.modem.ModemInterfaceConfigImpl;
import org.eclipse.kura.linux.net.dns.LinuxDns;
import org.eclipse.kura.linux.net.dns.LinuxNamed;
import org.eclipse.kura.linux.net.util.LinuxNetworkUtil;
import org.eclipse.kura.net.IP4Address;
import org.eclipse.kura.net.IPAddress;
import org.eclipse.kura.net.NetConfig;
import org.eclipse.kura.net.NetConfigIP4;
import org.eclipse.kura.net.NetInterfaceAddressConfig;
import org.eclipse.kura.net.NetInterfaceConfig;
import org.eclipse.kura.net.NetInterfaceStatus;
import org.eclipse.kura.net.NetInterfaceType;
import org.eclipse.kura.net.NetworkPair;
import org.eclipse.kura.net.admin.NetworkConfigurationService;
import org.eclipse.kura.net.admin.event.NetworkConfigurationChangeEvent;
import org.eclipse.kura.net.admin.event.NetworkStatusChangeEvent;
import org.eclipse.kura.net.dhcp.DhcpServerConfig;
import org.eclipse.kura.net.dns.DnsMonitorService;
import org.eclipse.kura.net.dns.DnsServerConfigIP4;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DnsMonitorServiceImpl implements DnsMonitorService, EventHandler {
private static final Logger logger = LoggerFactory.getLogger(DnsMonitorServiceImpl.class);
private static final String[] EVENT_TOPICS = new String[] {
NetworkStatusChangeEvent.NETWORK_EVENT_STATUS_CHANGE_TOPIC,
NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC };
private static final long THREAD_INTERVAL = 60000;
private static final long THREAD_TERMINATION_TOUT = 1; // in seconds
private static Future<?> monitorTask;
private ExecutorService executor;
private boolean enabled;
private static AtomicBoolean stopThread;
private NetworkConfigurationService netConfigService;
private NetworkConfiguration networkConfiguration;
private Set<NetworkPair<IP4Address>> allowedNetworks;
private Set<IP4Address> forwarders;
private LinuxDns dnsUtil;
public void setNetworkConfigurationService(NetworkConfigurationService netConfigService) {
this.netConfigService = netConfigService;
}
public void unsetNetworkConfigurationService(NetworkConfigurationService netConfigService) {
this.netConfigService = null;
}
protected void activate(ComponentContext componentContext) {
logger.debug("Activating DnsProxyMonitor Service...");
Dictionary<String, String[]> d = new Hashtable<>();
d.put(EventConstants.EVENT_TOPIC, EVENT_TOPICS);
componentContext.getBundleContext().registerService(EventHandler.class.getName(), this, d);
try {
this.networkConfiguration = this.netConfigService.getNetworkConfiguration();
} catch (KuraException e) {
logger.error("Could not get initial network configuration", e);
}
this.dnsUtil = LinuxDns.getInstance();
stopThread = new AtomicBoolean();
// FIXME - brute force handler for DNS updates
this.executor = Executors.newSingleThreadExecutor();
stopThread.set(false);
monitorTask = this.executor.submit(() -> {
while (!stopThread.get()) {
Thread.currentThread().setName("DnsMonitorServiceImpl");
Set<IPAddress> dnsServers = DnsMonitorServiceImpl.this.dnsUtil.getDnServers();
// Check that resolv.conf matches what is configured
Set<IPAddress> configuredServers = getConfiguredDnsServers();
if (!configuredServers.equals(dnsServers)) {
setDnsServers(configuredServers);
dnsServers = configuredServers;
}
Set<IP4Address> fwds = new HashSet<>();
if (dnsServers != null && !dnsServers.isEmpty()) {
for (IPAddress dnsServer : dnsServers) {
logger.debug("Found DNS Server: {}", dnsServer.getHostAddress());
fwds.add((IP4Address) dnsServer);
}
}
if (fwds != null && !fwds.isEmpty() && !fwds.equals(DnsMonitorServiceImpl.this.forwarders)) {
// there was a change - deal with it
logger.info("Detected DNS resolv.conf change - restarting DNS proxy");
DnsMonitorServiceImpl.this.forwarders = fwds;
try {
LinuxNamed linuxNamed = LinuxNamed.getInstance();
DnsServerConfigIP4 currentDnsServerConfig = linuxNamed.getDnsServerConfig();
DnsServerConfigIP4 newDnsServerConfig = new DnsServerConfigIP4(
DnsMonitorServiceImpl.this.forwarders, DnsMonitorServiceImpl.this.allowedNetworks);
if (currentDnsServerConfig.equals(newDnsServerConfig)) {
logger.debug("DNS server config has changed - updating from " + currentDnsServerConfig
+ " to " + newDnsServerConfig);
reconfigureDNSProxy(newDnsServerConfig);
}
} catch (KuraException e) {
logger.warn(e.getMessage(), e);
}
}
try {
monitorWait();
} catch (InterruptedException e) {
logger.debug("DNS monitor interrupted", e);
}
}
});
}
protected void deactivate(ComponentContext componentContext) {
if (monitorTask != null && !monitorTask.isDone()) {
stopThread.set(true);
monitorNotity();
logger.debug("Cancelling DnsMonitorServiceImpl task ...");
monitorTask.cancel(true);
logger.info("DnsMonitorServiceImpl task cancelled? = {}", monitorTask.isDone());
monitorTask = null;
}
if (this.executor != null) {
logger.debug("Terminating DnsMonitorServiceImpl Thread ...");
this.executor.shutdownNow();
try {
this.executor.awaitTermination(THREAD_TERMINATION_TOUT, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.warn("Interrupted", e);
Thread.currentThread().interrupt();
}
logger.info("DnsMonitorServiceImpl Thread terminated? - {}", this.executor.isTerminated());
this.executor = null;
}
}
protected String getCurrentIpAddress(String interfaceName) throws KuraException {
return LinuxNetworkUtil.getCurrentIpAddress(interfaceName);
}
protected boolean pppHasAddress(int pppNo) throws KuraException {
return LinuxNetworkUtil.hasAddress("ppp" + pppNo);
}
protected void reconfigureDNSProxy(DnsServerConfigIP4 dnsServerConfigIP4) {
try {
LinuxNamed linuxNamed = LinuxNamed.getInstance();
logger.debug("Disabling DNS proxy");
linuxNamed.disable();
logger.debug("Writing config");
linuxNamed.setConfig(dnsServerConfigIP4);
if (this.enabled) {
sleep(500);
logger.debug("Starting DNS proxy");
linuxNamed.enable();
} else {
logger.debug("DNS proxy not enabled");
}
} catch (KuraException e) {
logger.warn(e.getMessage(), e);
}
}
@Override
public void handleEvent(Event event) {
logger.debug("handleEvent - topic: {}", event.getTopic());
String topic = event.getTopic();
if (topic.equals(NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC)) {
NetworkConfigurationChangeEvent netConfigChangedEvent = (NetworkConfigurationChangeEvent) event;
String[] propNames = netConfigChangedEvent.getPropertyNames();
if (propNames != null && propNames.length > 0) {
Map<String, Object> props = new HashMap<>();
for (String propName : propNames) {
Object prop = netConfigChangedEvent.getProperty(propName);
if (prop != null) {
props.put(propName, prop);
}
}
try {
this.networkConfiguration = new NetworkConfiguration(props);
} catch (Exception e) {
logger.warn(e.getMessage(), e);
}
}
updateDnsResolverConfig();
updateDnsProxyConfig();
} else if (topic.equals(NetworkStatusChangeEvent.NETWORK_EVENT_STATUS_CHANGE_TOPIC)) {
updateDnsResolverConfig();
updateDnsProxyConfig();
}
}
private void updateDnsResolverConfig() {
logger.debug("Updating resolver config");
setDnsServers(getConfiguredDnsServers());
}
private void updateDnsProxyConfig() {
this.enabled = false;
this.allowedNetworks = new HashSet<>();
this.forwarders = new HashSet<>();
if ((this.networkConfiguration != null) && (this.networkConfiguration.getNetInterfaceConfigs() != null)) {
List<NetInterfaceConfig<? extends NetInterfaceAddressConfig>> netInterfaceConfigs = this.networkConfiguration
.getNetInterfaceConfigs();
for (NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig : netInterfaceConfigs) {
if (netInterfaceConfig.getType() == NetInterfaceType.ETHERNET
|| netInterfaceConfig.getType() == NetInterfaceType.WIFI
|| netInterfaceConfig.getType() == NetInterfaceType.MODEM) {
try {
getAllowedNetworks(netInterfaceConfig);
} catch (KuraException e) {
logger.error("Error updating dns proxy", e);
}
}
}
}
Set<IPAddress> dnsServers = this.dnsUtil.getDnServers();
if (dnsServers != null && !dnsServers.isEmpty()) {
for (IPAddress dnsServer : dnsServers) {
logger.debug("Found DNS Server: {}", dnsServer.getHostAddress());
this.forwarders.add((IP4Address) dnsServer);
}
}
DnsServerConfigIP4 dnsServerConfigIP4 = new DnsServerConfigIP4(this.forwarders, this.allowedNetworks);
reconfigureDNSProxy(dnsServerConfigIP4);
}
private void getAllowedNetworks(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig)
throws KuraException {
String interfaceName = netInterfaceConfig.getName();
logger.debug("Getting DNS proxy config for {}", interfaceName);
List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig
.getNetInterfaceAddresses();
if (netInterfaceAddressConfigs != null && !netInterfaceAddressConfigs.isEmpty()) {
for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) {
List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs();
if (netConfigs != null && !netConfigs.isEmpty()) {
for (int i = 0; i < netConfigs.size(); i++) {
NetConfig netConfig = netConfigs.get(i);
if ((netConfig instanceof DhcpServerConfig) && ((DhcpServerConfig) netConfig).isPassDns()) {
logger.debug(
"Found an allowed network: " + ((DhcpServerConfig) netConfig).getRouterAddress()
+ "/" + ((DhcpServerConfig) netConfig).getPrefix());
this.enabled = true;
// this is an 'allowed network'
this.allowedNetworks.add(new NetworkPair<IP4Address>(
(IP4Address) ((DhcpServerConfig) netConfig).getRouterAddress(),
((DhcpServerConfig) netConfig).getPrefix()));
}
}
}
}
}
}
private boolean isEnabledForWan(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) {
for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceConfig.getNetInterfaceAddresses()) {
if (netInterfaceAddressConfig != null) {
List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs();
if (netConfigs != null) {
for (NetConfig netConfig : netConfigs) {
if (netConfig instanceof NetConfigIP4) {
return NetInterfaceStatus.netIPv4StatusEnabledWAN
.equals(((NetConfigIP4) netConfig).getStatus());
}
}
}
}
}
return false;
}
private void setDnsServers(Set<IPAddress> newServers) {
LinuxDns linuxDns = this.dnsUtil;
Set<IPAddress> currentServers = linuxDns.getDnServers();
if (newServers == null || newServers.isEmpty()) {
logger.warn("Not Setting DNS servers to empty");
return;
}
if (currentServers != null && !currentServers.isEmpty()) {
if (!currentServers.equals(newServers)) {
logger.info("Change to DNS - setting dns servers: " + newServers);
linuxDns.setDnServers(newServers);
} else {
logger.debug("No change to DNS servers - not updating");
}
} else {
logger.info("Current DNS servers are null - setting dns servers: " + newServers);
linuxDns.setDnServers(newServers);
}
}
// Get a list of dns servers for all WAN interfaces
private Set<IPAddress> getConfiguredDnsServers() {
LinkedHashSet<IPAddress> serverList = new LinkedHashSet<>();
if (this.networkConfiguration != null) {
if (this.networkConfiguration.getNetInterfaceConfigs() != null) {
List<NetInterfaceConfig<? extends NetInterfaceAddressConfig>> netInterfaceConfigs = this.networkConfiguration
.getNetInterfaceConfigs();
// If there are multiple WAN interfaces, their configured DNS servers are all included in no particular
// order
for (NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig : netInterfaceConfigs) {
if ((netInterfaceConfig.getType() == NetInterfaceType.ETHERNET
|| netInterfaceConfig.getType() == NetInterfaceType.WIFI
|| netInterfaceConfig.getType() == NetInterfaceType.MODEM)
&& isEnabledForWan(netInterfaceConfig)) {
try {
Set<IPAddress> servers = getConfiguredDnsServers(netInterfaceConfig);
logger.trace("{} is WAN, adding its dns servers: {}", netInterfaceConfig.getName(),
servers);
serverList.addAll(servers);
} catch (KuraException e) {
logger.error("Error adding dns servers for " + netInterfaceConfig.getName(), e);
}
}
}
}
}
return serverList;
}
// Get a list of dns servers for the specified NetInterfaceConfig
private Set<IPAddress> getConfiguredDnsServers(
NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) throws KuraException {
String interfaceName = netInterfaceConfig.getName();
logger.trace("Getting dns servers for {}", interfaceName);
LinuxDns linuxDns = this.dnsUtil;
LinkedHashSet<IPAddress> serverList = new LinkedHashSet<>();
for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceConfig.getNetInterfaceAddresses()) {
for (NetConfig netConfig : netInterfaceAddressConfig.getConfigs()) {
if (netConfig instanceof NetConfigIP4) {
NetConfigIP4 netConfigIP4 = (NetConfigIP4) netConfig;
List<IP4Address> userServers = netConfigIP4.getDnsServers();
if (netConfigIP4.isDhcp()) {
// If DHCP but there are user defined entries, use those instead
if (userServers != null && !userServers.isEmpty()) {
logger.debug("Configured for DHCP with user-defined servers - adding: {}", userServers);
serverList.addAll(userServers);
} else {
if (netInterfaceConfig.getType().equals(NetInterfaceType.MODEM)) {
// FIXME - don't like this
// cannot use interfaceName here because it one config behind
int pppNo = ((ModemInterfaceConfigImpl) netInterfaceConfig).getPppNum();
if (pppHasAddress(pppNo)) {
List<IPAddress> servers = linuxDns.getPppDnServers();
if (servers != null) {
logger.debug("Adding PPP dns servers: {}", servers);
serverList.addAll(servers);
}
}
} else {
String currentAddress = getCurrentIpAddress(interfaceName);
List<IPAddress> servers = linuxDns.getDhcpDnsServers(interfaceName, currentAddress);
if (!servers.isEmpty()) {
logger.debug("Configured for DHCP - adding DHCP servers: {}", servers);
serverList.addAll(servers);
}
}
}
} else {
// If static, use the user defined entries
logger.debug("Configured for static - adding user-defined servers: {}", userServers);
serverList.addAll(userServers);
}
}
}
}
return serverList;
}
/**
* Sleep at least <code>millis</code> ms, even if sleep is interrupted
*/
private static void sleep(int millis) {
long start = System.currentTimeMillis();
long now = start;
long end = start + millis;
while (now < end) {
try {
Thread.sleep(end - now);
} catch (InterruptedException e) {
logger.debug("sleep interrupted: ", e);
Thread.currentThread().interrupt();
}
now = System.currentTimeMillis();
}
}
private void monitorNotity() {
if (stopThread != null) {
synchronized (stopThread) {
stopThread.notifyAll();
}
}
}
private void monitorWait() throws InterruptedException {
if (stopThread != null) {
synchronized (stopThread) {
stopThread.wait(THREAD_INTERVAL);
}
}
}
}
|
package ubic.gemma.web.services.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ubic.gemma.core.association.phenotype.PhenotypeAssociationManagerService;
import ubic.gemma.core.association.phenotype.PhenotypeExceptions.EntityNotFoundException;
import ubic.gemma.core.genome.gene.service.GeneService;
import ubic.gemma.model.genome.Taxon;
import ubic.gemma.model.genome.gene.phenotype.EvidenceFilter;
import ubic.gemma.persistence.service.BaseVoEnabledService;
import ubic.gemma.persistence.service.expression.experiment.ExpressionExperimentService;
import ubic.gemma.persistence.service.genome.ChromosomeService;
import ubic.gemma.persistence.service.genome.taxon.TaxonService;
import ubic.gemma.web.services.rest.util.*;
import ubic.gemma.web.services.rest.util.args.*;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashSet;
/**
* RESTful interface for taxa.
*
* @author tesarst
*/
@Service
@Path("/taxa")
public class TaxaWebService extends WebService {
private TaxonService taxonService;
private GeneService geneService;
private ExpressionExperimentService expressionExperimentService;
private PhenotypeAssociationManagerService phenotypeAssociationManagerService;
private ChromosomeService chromosomeService;
/**
* Required by spring
*/
public TaxaWebService() {
}
/**
* Constructor for service autowiring
*/
@Autowired
public TaxaWebService( TaxonService taxonService, GeneService geneService,
ExpressionExperimentService expressionExperimentService,
PhenotypeAssociationManagerService phenotypeAssociationManagerService,
ChromosomeService chromosomeService ) {
this.taxonService = taxonService;
this.geneService = geneService;
this.expressionExperimentService = expressionExperimentService;
this.phenotypeAssociationManagerService = phenotypeAssociationManagerService;
this.chromosomeService = chromosomeService;
}
/**
* Lists all available taxa. Does not offer any advanced filtering or sorting functionality.
* The reason for this is that Taxa are a relatively small set of objects that rarely change.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public ResponseDataObject all( // Params:
@Context final HttpServletResponse sr // The servlet response, needed for response code setting.
) {
return Responder.autoCode( taxonService.loadAllValueObjects(), sr );
}
/**
* Retrieves single taxon based on the given identifier.
*
* @param taxonArg can either be Taxon ID or one of its string identifiers:
* scientific name, common name, abbreviation. It is recommended to use ID for efficiency.
*/
@GET
@Path("/{taxonArg: [a-zA-Z0-9%20\\.]+}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public ResponseDataObject taxon( // Params:
@PathParam("taxonArg") TaxonArg<Object> taxonArg, // Required
@Context final HttpServletResponse sr // The servlet response, needed for response code setting.
) {
return Responder.autoCode( taxonArg.getValueObject( taxonService ), sr );
}
/**
* Finds genes overlapping a given region.
*
* @param taxonArg can either be Taxon ID or one of its string identifiers:
* scientific name, common name, abbreviation. It is recommended to use the ID for efficiency.
* @param chromosomeName - eg: 3, 21, X
* @param strand - '+' or '-'. Defaults to '+'. (WIP, currently does not do anything).
* @param start - start of the region (nucleotide position).
* @param size - size of the region (in nucleotides).
* @return GeneValue objects of the genes in the region.
*/
@GET
@Path("/{taxonArg: [a-zA-Z0-9%20\\.]+}/chromosomes/{chromosomeArg: [a-zA-Z0-9\\.]+}/genes")
@Produces(MediaType.APPLICATION_JSON)
public ResponseDataObject taxonChromosomeGenes( // Params:
@PathParam("taxonArg") TaxonArg<Object> taxonArg, // Required
@PathParam("chromosomeArg") String chromosomeName, // Required
@QueryParam("strand") @DefaultValue("+") String strand, //Optional, default +
@QueryParam("start") LongArg start, // Required
@QueryParam("size") IntArg size, // Required
@Context final HttpServletResponse sr ) {
super.checkReqArg( start, "start" );
super.checkReqArg( size, "size" );
return Responder.autoCode(
taxonArg.getGenesOnChromosome( taxonService, chromosomeService, geneService, chromosomeName,
start.getValue(), size.getValue() ), sr );
}
/**
* Retrieves genes matching the identifier on the given taxon.
*
* @param taxonArg can either be Taxon ID or one of its string identifiers:
* scientific name, common name, abbreviation. It is recommended to use the ID for efficiency.
* @param geneArg can either be the NCBI ID, Ensembl ID or official symbol. NCBI ID is most efficient (and
* guaranteed to be unique). Official symbol returns a gene homologue on a random taxon.
*/
@GET
@Path("/{taxonArg: [a-zA-Z0-9%20\\.]+}/genes/{geneArg: [a-zA-Z0-9\\.]+}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public ResponseDataObject genes( // Params:
@PathParam("taxonArg") TaxonArg<Object> taxonArg, // Required
@PathParam("geneArg") GeneArg<Object> geneArg, // Required
@Context final HttpServletResponse sr // The servlet response, needed for response code setting.
) {
return Responder.autoCode( geneArg.getGenesOnTaxon( geneService, taxonService, taxonArg ), sr );
}
/**
* Retrieves gene evidence for the gene on the given taxon.
*
* @param taxonArg can either be Taxon ID or one of its string identifiers:
* scientific name, common name, abbreviation. It is recommended to use the ID for efficiency.
* @param geneArg can either be the NCBI ID, Ensembl ID or official symbol. NCBI ID is most efficient (and
* guaranteed to be unique). Official symbol returns a gene homologue on a random taxon.
*/
@GET
@Path("/{taxonArg: [a-zA-Z0-9%20\\.]+}/genes/{geneArg: [a-zA-Z0-9\\.]+}/evidence")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public ResponseDataObject genesEvidence( // Params:
@PathParam("taxonArg") TaxonArg<Object> taxonArg, // Required
@PathParam("geneArg") GeneArg<Object> geneArg, // Required
@Context final HttpServletResponse sr // The servlet response, needed for response code setting.
) {
Taxon taxon = taxonArg.getPersistentObject( taxonService );
return Responder
.autoCode( geneArg.getGeneEvidence( geneService, phenotypeAssociationManagerService, taxon ), sr );
}
/**
* Retrieves gene location for the gene on the given taxon.
*
* @param taxonArg can either be Taxon ID or one of its string identifiers:
* scientific name, common name, abbreviation. It is recommended to use the ID for efficiency.
* @param geneArg can either be the NCBI ID, Ensembl ID or official symbol. NCBI ID is most efficient (and
* guaranteed to be unique). Official symbol returns a gene homologue on a random taxon.
*/
@GET
@Path("/{taxonArg: [a-zA-Z0-9%20\\.]+}/genes/{geneArg: [a-zA-Z0-9\\.]+}/locations")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public ResponseDataObject genesLocation( // Params:
@PathParam("taxonArg") TaxonArg<Object> taxonArg, // Required
@PathParam("geneArg") GeneArg<Object> geneArg, // Required
@Context final HttpServletResponse sr // The servlet response, needed for response code setting.
) {
Taxon taxon = taxonArg.getPersistentObject( taxonService );
return Responder.autoCode( geneArg.getGeneLocation( geneService, taxon ), sr );
}
/**
* Retrieves datasets for the given taxon. Filtering allowed exactly like in {@link DatasetsWebService#all(DatasetFilterArg, IntArg, IntArg, SortArg, HttpServletResponse)}
*
* @param taxonArg can either be Taxon ID or one of its string identifiers:
* scientific name, common name, abbreviation. It is recommended to use the ID for efficiency.
* @see WebServiceWithFiltering#all(FilterArg, IntArg, IntArg, SortArg, HttpServletResponse, BaseVoEnabledService) for details about the
* filter, offset, limit and sort arguments.
*/
@GET
@Path("/{taxonArg: [a-zA-Z0-9%20\\.]+}/datasets")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public ResponseDataObject taxonDatasets( // Params:
@PathParam("taxonArg") TaxonArg<Object> taxonArg, // Required
@QueryParam("filter") @DefaultValue("") DatasetFilterArg filter, // Optional, default null
@QueryParam("offset") @DefaultValue("0") IntArg offset, // Optional, default 0
@QueryParam("limit") @DefaultValue("20") IntArg limit, // Optional, default 20
@QueryParam("sort") @DefaultValue("+id") SortArg sort, // Optional, default +id
@Context final HttpServletResponse sr // The servlet response, needed for response code setting.
) {
return Responder.autoCode(
taxonArg.getTaxonDatasets( expressionExperimentService, taxonArg.getPersistentObject( taxonService ),
filter.getObjectFilters(), offset.getValue(), limit.getValue(), sort.getField(), sort.isAsc() ),
sr );
}
/**
* Loads all phenotypes for the given taxon. Unfortunately, pagination is not possible as the
* phenotypes are loaded in a tree structure.
*
* @param taxonArg the taxon to list the phenotypes for.
* @param editableOnly whether to only list editable phenotypes.
* @return a list of Simple Tree value objects allowing a reconstruction of a tree.
*/
@GET
@Path("/{taxonArg: [a-zA-Z0-9%20\\.]+}/phenotypes")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public ResponseDataObject taxonPhenotypes( // Params:
@PathParam("taxonArg") TaxonArg<Object> taxonArg, // Required
@QueryParam("editableOnly") @DefaultValue("false") BoolArg editableOnly, // Optional, default false
@Context final HttpServletResponse sr // The servlet response, needed for response code setting
) {
Taxon taxon = taxonArg.getPersistentObject( taxonService );
return Responder.autoCode( phenotypeAssociationManagerService
.loadAllPhenotypesAsTree( new EvidenceFilter( taxon.getId(), editableOnly.getValue() ) ), sr );
}
/**
* Given a set of phenotypes, return all genes associated with them.
*
* @param taxonArg the taxon to list the genes for.
* @param editableOnly whether to only list editable genes.
* @param phenotypes phenotype value URIs separated by commas.
* @return a list of genes associated with given phenotypes.
*/
@GET
@Path("/{taxonArg: [a-zA-Z0-9%20\\.]+}/phenotypes/candidates")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public ResponseDataObject findCandidateGenes( // Params:
@PathParam("taxonArg") TaxonArg<Object> taxonArg, // Required
@QueryParam("phenotypes") ArrayStringArg phenotypes, // Required
@QueryParam("editableOnly") @DefaultValue("false") BoolArg editableOnly, // Optional, default false
@Context final HttpServletResponse sr // The servlet response, needed for response code setting)
) {
super.checkReqArg( phenotypes, "phenotypes" );
return this.getCandidateGenes( taxonArg, editableOnly, phenotypes, sr );
}
/**
* Tries to retrieve candidate genes for given phenotypes, handles known exceptions that can occur
*
* @param taxonArg the taxon to list the genes for.
* @param editableOnly whether to only list editable genes.
* @param phenotypes phenotype value URIs.
* @return a list of genes associated with given phenotypes
* @throws GemmaApiException in case one of the given phenotypes was not found, or one of the given arguments
* is malformed.
*/
private ResponseDataObject getCandidateGenes( TaxonArg<Object> taxonArg, BoolArg editableOnly,
ArrayStringArg phenotypes, HttpServletResponse sr ) {
Object response;
try {
response = this.phenotypeAssociationManagerService.findCandidateGenes(
new EvidenceFilter( taxonArg.getPersistentObject( taxonService ).getId(), editableOnly.getValue() ),
new HashSet<>( phenotypes.getValue() ) );
} catch ( EntityNotFoundException e ) {
WellComposedErrorBody errorBody = new WellComposedErrorBody( Response.Status.NOT_FOUND, e.getMessage() );
throw new GemmaApiException( errorBody );
}
return Responder.autoCode( response, sr );
}
}
|
package uk.ac.kent.dover.fastGraph;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
import org.json.*;
import uk.ac.kent.displayGraph.*;
public class FastGraph {
protected static final int NODE_LABEL_START_OFFSET = 0; // integer
protected static final int NODE_LABEL_LENGTH_OFFSET = 4; // short
protected static final int NODE_IN_CONNECTION_START_OFFSET = 6; // integer
protected static final int NODE_IN_DEGREE_OFFSET = 10; // integer
protected static final int NODE_OUT_CONNECTION_START_OFFSET = 14; // integer
protected static final int NODE_OUT_DEGREE_OFFSET = 18; // integer
protected static final int NODE_WEIGHT_OFFSET = 22; // integer
protected static final int NODE_TYPE_OFFSET = 26; // byte
protected static final int NODE_AGE_OFFSET = 27; // byte
protected static final int EDGE_NODE1_OFFSET = 0; // integer
protected static final int EDGE_NODE2_OFFSET = 4; // integer
protected static final int EDGE_LABEL_START_OFFSET = 8; // integer
protected static final int EDGE_LABEL_LENGTH_OFFSET = 12; // short
protected static final int EDGE_WEIGHT_OFFSET = 14; // integer
protected static final int EDGE_TYPE_OFFSET = 18; // byte
protected static final int EDGE_AGE_OFFSET = 19; // byte
protected static final int CONNECTION_EDGE_OFFSET = 0; // integer, edge is first of the pair
protected static final int CONNECTION_NODE_OFFSET = 4; // integer, node is straight after the edge
public static final int DEFAULT_AVERAGE_LABEL_LENGTH = 20;
protected static final int NODE_BYTE_SIZE = 28;
protected static final int EDGE_BYTE_SIZE = 20;
protected static final int CONNECTION_PAIR_SIZE = 8; // this is an edge index plus an node index
public static final String INFO_SPLIT_STRING = "~";
public static final int MAX_BYTE_BUFFER_SIZE = Integer.MAX_VALUE-5000;
private ByteBuffer nodeBuf;
private ByteBuffer edgeBuf;
private ByteBuffer connectionBuf;
private ByteBuffer nodeLabelBuf;
private ByteBuffer edgeLabelBuf;
private int numberOfNodes;
private int numberOfEdges;
private String name = "";
private boolean direct;
/**
* No direct access to constructor, as a number of data structures need to be created when
* graph nodes and edges are added.
*
* @param nodeTotal the number of nodes in the graph
* @param edgeTotal the number of edges in the graph
* @param direct if true then off heap ByteBuffers, if false then on heap ByteBuffers
*/
private FastGraph(int nodeTotal, int edgeTotal, boolean direct) {
this.numberOfNodes = nodeTotal;
this.numberOfEdges = edgeTotal;
this.direct = direct;
init();
}
/**
* @param args not used
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Debugger.enabled = true;
long time;
// FastGraph g1 = randomGraphFactory(1,0,false);
// FastGraph g1 = randomGraphFactory(2,1,false);
// FastGraph g1 = randomGraphFactory(5,6,1,true);
// FastGraph g1 = randomGraphFactory(8,9,1,false);
// FastGraph g1 = randomGraphFactory(100,1000,1,false); // 1 hundred nodes, 1 thousand edges
// FastGraph g1 = randomGraphFactory(10000,100000,1,false); // 10 thousand nodes, 100 thousand edges
// FastGraph g1 = randomGraphFactory(100000,1000000,1,false); // 100 thousand nodes, 1 million edges
// FastGraph g1 = randomGraphFactory(1000000,10000000,1,false); // 1 million nodes, 10 million edges
// FastGraph g1 = randomGraphFactory(5000000,50000000,1,false); // limit for edgeLabelBuf at 20 chars per label
// FastGraph g1 = randomGraphFactory(4847571,68993773,1,false); // Size of LiveJournal1 example from SNAP
// FastGraph g1 = randomGraphFactory(10000000,100000000,1,false); // 10 million nodes, 100 million edges, close to edgeBuf limit, but fails on heap space with 14g, but pass with heap space of 30g
time = System.currentTimeMillis();
// FastGraph g1 = adjacencyListGraphFactory(7115,103689,null,"Wiki-Vote.txt",false);
// FastGraph g1 = adjacencyListGraphFactory(36692,367662,null,"Email-Enron1.txt",false);
// FastGraph g1 = adjacencyListGraphFactory(81306,2420766,null,"twitter_combined.txt",false); // SNAP web page gives 1768149 edges
// FastGraph g1 = adjacencyListGraphFactory(1696415,11095298,null,"as-skitter.txt",false);
// FastGraph g1 = adjacencyListGraphFactory(1632803,30622564,null,"soc-pokec-relationships.txt",false);
// FastGraph g1 = adjacencyListGraphFactory(4847571,68993773,null,"soc-LiveJournal1.txt",false);
System.out.println("snap load time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
/*
time = System.currentTimeMillis();
g1.saveBuffers(null,g1.getName());
System.out.println("saveBuffers test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
*/
String name = "random-n-100-e-1000";
//String name = "as-skitter.txt";
//String name = "soc-pokec-relationships.txt-short";
//String name = "soc-pokec-relationships.txt-veryshort-veryshort";
//String name = "Wiki-Vote.txt";
// String name = g1.getName();
FastGraph g2;
try {
//time = System.currentTimeMillis();
g2 = loadBuffersGraphFactory(null,name);
Debugger.log("Number of nodes: " + g2.getNumberOfNodes());
Debugger.log("Number of edges: " + g2.getNumberOfEdges());
Debugger.resetTime();
EnumerateSubgraph es = new EnumerateSubgraph(g2);
FastGraph[] gs = es.enumerateSubgraphs(4);
Debugger.outputTime("Time for enumeration");
Debugger.log("number of subgraphs " + gs.length);
/*
time = System.currentTimeMillis();
LinkedList<Integer> nodes = new LinkedList<Integer>();
LinkedList<Integer> edges = new LinkedList<Integer>();
//FastGraph g3 = g2.removeNodesAndEdgesFromGraph(nodes,edges,1500,100);
//FastGraph g3 = g2.removeNodesAndEdgesFromGraph(nodes,edges,1500000,10000000);
FastGraph g3 = g2;
long deletionTime = (long) ((System.currentTimeMillis()-time)/1000.0);
System.out.println("deletion test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
//g3.relabelFastGraph(g3.getNumberOfNodes()/10);
System.out.println("relabelling test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
System.out.println("deletion test time (from before) " + deletionTime+" seconds");
System.out.println("New graph has: nodes: " + g3.getNumberOfNodes() + " and edges: " + g3.getNumberOfEdges());
time = System.currentTimeMillis();
//g3.setName(g2.getName()+"-relabelled");
//g3.saveBuffers(null,g3.getName());
System.out.println("saveBuffers test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
//FastGraph g4 = loadBuffersGraphFactory(null,g3.getName());
Graph dg = g2.generateDisplayGraph();
boolean consistent = dg.consistent();
System.out.println("consistent: " + consistent);
*/
//just for testing
System.out.println();
/*
System.out.println("graph now has the labels (taken from the buffer):");
FastGraphNodeType[] ntypes = FastGraphNodeType.values();
for(int j = 0; j < g4.getNumberOfNodes(); j++) {
byte type = g4.getNodeType(j);
System.out.println(g4.getNodeLabel(j) + " " + type + " (" + ntypes[type] + ")");
}
System.out.println();
System.out.println("edges now have the types (taken from the buffer):");
for(int j = 0; j < g4.getNumberOfEdges(); j++) {
byte type = g4.getEdgeType(j);
System.out.println("n1" + g4.getEdgeNode1(j) + " n2" + g4.getEdgeNode2(j) + " type " + type + " (" + g4.getEdgeLabel(j) + ")");
}
*/
// int[] degrees = g2.countInstancesOfNodeDegrees(4);
// System.out.println(Arrays.toString(degrees));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Relabels the current FastGraph with the family groups in subgraphs/families folder.<br>
* Any remaining nodes and edges are labelled randomly.
* Each family is tested against each of the induced subgraphs and will be relabeled if the two are isomorphic
*
* @param subgraphsToTest How many subgraphs will be induced for each family.
*
* @throws Exception If there is a problem loading the family subgraphs, or if there is a problem inducing a subgraph
*/
public void relabelFastGraph(int subgraphsToTest) throws Exception{
System.out.println("Relabelling FastGraph");
long time = System.currentTimeMillis();
//load node and edge labels arrays
String[] nodeLabels = new String[this.getNumberOfNodes()];
String[] edgeLabels = new String[this.getNumberOfEdges()];
//load node and edge Types arrays
byte[] nodeTypes = new byte[this.getNumberOfNodes()];
byte[] edgeTypes = new byte[this.getNumberOfEdges()];
//create induction class
InducedSubgraph is = new InducedSubgraph(this);
//create Name Picker class
NamePicker np = new NamePicker();
//number of families found
int fams = 0;
//load family subgraphs
FastGraph[] families = loadFamilies();
for(FastGraph family : families) {
System.out.println("Testing family " + family.getName());
ExactIsomorphism ei = new ExactIsomorphism(family);
int familyNodesSize = family.getNumberOfNodes();
for (int i = 0; i < subgraphsToTest; i++) { //induce subgraphs to test
if(i%10000 == 0) {
System.out.println("Testing subgraph " + i);
}
LinkedList<Integer> subNodes = new LinkedList<Integer>();
LinkedList<Integer> subEdges = new LinkedList<Integer>();
//create a subgraph and build to a FastGraph
is.createInducedSubgraph(subNodes, subEdges, familyNodesSize);
FastGraph subgraph = this.generateGraphFromSubgraph(Util.convertLinkedList(subNodes), Util.convertLinkedList(subEdges));
//is this FastGraph isomorphic to the one in the constructor (i.e. the family)
boolean isomorphic = ei.isomorphic(subgraph);
if(isomorphic) {
fams++;
//rename original graph
//pick a surname, so all family members have the same surname
String surname = np.getSurname();
// System.out.println("Family name: " + surname);
for(int n : subNodes) {
nodeLabels[n] = np.getForename() + " " + surname;
nodeTypes[n] = FastGraphNodeType.CHILD.getValue();
}
//set the parents
nodeTypes[subNodes.get(0)] = FastGraphNodeType.PARENT.getValue();
nodeTypes[subNodes.get(1)] = FastGraphNodeType.PARENT.getValue();
//label the edges with types rather than names
for(int e : subEdges) {
//if this is the parent's relationship
if ((getEdgeNode1(e) == subNodes.get(0) && getEdgeNode2(e) == subNodes.get(1)) ||
(getEdgeNode1(e) == subNodes.get(1) && getEdgeNode2(e) == subNodes.get(0))) {
edgeTypes[e] = FastGraphEdgeType.MARRIED.getValue();
edgeLabels[e] = FastGraphEdgeType.MARRIED.toString();
//if this is the parent child relationship
} else if (getEdgeNode1(e) == subNodes.get(0) || getEdgeNode1(e) == subNodes.get(1) ||
getEdgeNode2(e) == subNodes.get(0) || getEdgeNode2(e) == subNodes.get(1)) {
edgeTypes[e] = FastGraphEdgeType.PARENT.getValue();
edgeLabels[e] = FastGraphEdgeType.PARENT.toString();
//otherwise these are siblings
} else {
edgeTypes[e] = FastGraphEdgeType.SIBLING.getValue();
edgeLabels[e] = FastGraphEdgeType.SIBLING.toString();
}
}//end for each subEdge
} //end if isomorphic
}//end for each subgraph to test
}//end foreach family
System.out.println("## Number of families found: " + fams);
//replace the blanks with other names
for(int j = 0; j < nodeLabels.length; j++) {
if (nodeLabels[j] == null) {
nodeLabels[j] = np.getName();
}
}
//Leave node types as they are - these are not used
Random r = new Random(nodeBuf.getLong(0));
//replace the blanks with other edge types
FastGraphEdgeType[] values = FastGraphEdgeType.values();
for(int j = 0; j < edgeTypes.length; j++) {
if (edgeTypes[j] == FastGraphEdgeType.UNKNOWN.getValue()) {
//pick a random relationship
byte relationship = (byte) (r.nextInt(values.length - 4)+4); //ignore the family relationships
edgeTypes[j] = relationship;
edgeLabels[j] = values[relationship].toString();
}
}
//Set all node & edge labels, and node & edge types
this.setAllNodeLabels(nodeLabels);
this.setAllEdgeLabels(edgeLabels);
for(int i = 0; i < nodeTypes.length; i++) {
this.setNodeType(i, nodeTypes[i]);
}
for(int i = 0; i < edgeTypes.length; i++) {
this.setEdgeType(i, edgeTypes[i]);
}
}
/**
* Loads the families subgraphs
* @return A list of FastGraphs based on the family subgraphs
* @throws Exception If the node or edge count can't be converted, or the file can't be loaded
*/
public FastGraph[] loadFamilies() throws Exception {
File folder = new File(Launcher.startingWorkingDirectory+File.separatorChar+"subgraphs"+File.separatorChar+"families");
File[] listOfFiles = folder.listFiles();
LinkedList<FastGraph> graphs = new LinkedList<>();
for (File f : listOfFiles) {
String[] splits = f.getName().split("-");
int nodeCount = Integer.parseInt(splits[2]);
int edgeCount = Integer.parseInt(splits[4]);
System.out.println(f + " n" + nodeCount + "e" + edgeCount);
FastGraph g = nodeListEdgeListGraphFactory(nodeCount, edgeCount, folder.getPath() + File.separatorChar + f.getName(), f.getName(), direct);
System.out.println("new g nodes" + g.getNumberOfNodes());
graphs.add(g);
}
//System.out.println(Arrays.toString(listOfFiles));
FastGraph[] graphArray = new FastGraph[graphs.size()];
Util.convertLinkedListObject(graphs, graphArray);
return graphArray;
}
/**
* This method creates a new FastGraph of the rough size given in targetNodes and targetEdges. <br>
* The new graph will never have fewer nodes than the target, but may have fewer edges. <br>
* <b>Note: This may take some time to complete</b>
*
* @param nodes The list of nodes to be removed
* @param edges The list of edges to be removed
* @param targetNodes The target number of nodes
* @param targetEdges The target number of edges
* @return A new FastGraph that is roughly the size of the target
* @throws FastGraphException If there is an exception here, e.g. targetNodes is too big
*/
public FastGraph removeNodesAndEdgesFromGraph(LinkedList<Integer> nodes, LinkedList<Integer> edges, int targetNodes, int targetEdges) throws FastGraphException {
System.out.println("Suggesting nodes and egdes to remove");
long time = System.currentTimeMillis();
int currentTotalNodes = getNumberOfNodes();
int currentTotalEdges = getNumberOfEdges();
//if a graph of the same size has been specified
if (targetNodes == currentTotalNodes && targetEdges == currentTotalEdges) {
return this;
}
//if the node target is too big
if(targetNodes > currentTotalNodes) {
throw new FastGraphException("The target node size is too big");
}
//if the edge target is too big
if(targetEdges > currentTotalEdges) {
throw new FastGraphException("The target edge size is too big");
}
int nodeReductionAmount = currentTotalNodes - targetNodes; //how many nodes we need to remove
int edgeReductionAmount = currentTotalEdges - targetEdges; //how many edges we need to remove
LinkedHashSet<Integer> edgesToRemove = new LinkedHashSet<Integer>(); //edges that need removing
LinkedHashSet<Integer> nodesToRemove = new LinkedHashSet<Integer>(); //nodes that need removing
System.out.println("Current Nodes: " + currentTotalNodes + " Target Nodes: " + targetNodes);
System.out.println("Current Edges: " + currentTotalEdges + " Target Edges: " + targetEdges);
System.out.println("setup test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
System.out.println();
time = System.currentTimeMillis();
System.out.println("# Starting STEP ONE");
//STEP ONE:
//Find a subgraph with the required number of nodes. Remove it
InducedSubgraph is = new InducedSubgraph(this);
LinkedList<Integer> subNodes = new LinkedList<Integer>();
LinkedList<Integer> subEdges = new LinkedList<Integer>();
is.createInducedSubgraph(subNodes, subEdges, nodeReductionAmount);
nodesToRemove.addAll(subNodes);
edgesToRemove.addAll(subEdges);
//delete all edges connecting to the nodes to be deleted
for(int n : nodesToRemove) {
Util.addAll(edgesToRemove, this.getNodeConnectingInEdges(n));
Util.addAll(edgesToRemove, this.getNodeConnectingOutEdges(n));
}
System.out.println("After induction test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
System.out.println("nodes to remove size: " + nodesToRemove.size() + " edges to remove size: " + edgesToRemove.size());
System.out.println();
//STEP TWO:
//if we haven't removed enough nodes
System.out.println("# Starting STEP TWO");
time = System.currentTimeMillis();
if(nodeReductionAmount > nodesToRemove.size()) { //could we thread these to make this quicker?
Random r = new Random(nodeBuf.getLong(1));
//make local stores, as we might not want to remove these nodes if they are too big
LinkedHashSet<Integer> localEdgesToRemove = new LinkedHashSet<Integer>(); //edges that need removing
LinkedHashSet<Integer> localNodesToRemove = new LinkedHashSet<Integer>(); //nodes that need removing
int chances = 10; //if a tree is too big, then skip it. But only do this 10 times, in case we are stuck
while(nodeReductionAmount > nodesToRemove.size() && chances > 0) {
//long time2 = System.currentTimeMillis();
localNodesToRemove.clear();
localEdgesToRemove.clear();
int stillToRemove = nodeReductionAmount - nodesToRemove.size(); //what nodes are left to remove
this.buildTree(localNodesToRemove, localEdgesToRemove, r, 3);
//System.out.println("Tree: " + localNodesToRemove);
//System.out.println("nodeRA: " + nodeReductionAmount + " stillTR: " + stillToRemove + " localNodesToRemove: " + localNodesToRemove.size());
if (localNodesToRemove.size() <= stillToRemove) {
nodesToRemove.addAll(localNodesToRemove);
edgesToRemove.addAll(localEdgesToRemove);
//delete all edges connecting to the nodes in this tree
for(int n : localNodesToRemove) {
Util.addAll(edgesToRemove, this.getNodeConnectingInEdges(n));
Util.addAll(edgesToRemove, this.getNodeConnectingOutEdges(n));
}
} else {
chances--; //Avoids getting stuck if there are no further options
continue;
}
//System.out.println("After this tree test time " + (System.currentTimeMillis()-time2)/1000.0+" seconds");
}
}
System.out.println("After tree test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
System.out.println("nodes to remove size: " + nodesToRemove.size() + " edges to remove size: " + edgesToRemove.size());
System.out.println();
//STEP THREE:
//if we haven't removed enough nodes
//pick some at random
System.out.println("# Starting STEP THREE");
time = System.currentTimeMillis();
if(nodeReductionAmount > nodesToRemove.size()) {
Random r = new Random(nodeBuf.getLong(2));
while(nodeReductionAmount > nodesToRemove.size()) {
int n = r.nextInt(this.getNumberOfNodes());
nodesToRemove.add(n);
edgesToRemove.addAll(Util.convertArray(this.getNodeConnectingEdges(n)));
}
}
System.out.println("After node removal test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
System.out.println("nodes to remove size: " + nodesToRemove.size() + " edges to remove size: " + edgesToRemove.size());
System.out.println();
//STEP FOUR:
//if we haven't removed enough edges
//pick some at random
System.out.println("# Starting STEP FOUR");
time = System.currentTimeMillis();
if(edgeReductionAmount > edgesToRemove.size()) {
Random r = new Random(edgeBuf.getLong(2));
while(edgeReductionAmount > edgesToRemove.size()) {
int e = r.nextInt(this.getNumberOfEdges());
edgesToRemove.add(e);
}
}
System.out.println("After edge removal test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
System.out.println("nodes to remove size: " + nodesToRemove.size() + " edges to remove size: " + edgesToRemove.size());
System.out.println();
nodes.addAll(nodesToRemove);
edges.addAll(edgesToRemove);
time = System.currentTimeMillis();
System.out.println("Building new FastGraph");
FastGraph g = this.generateGraphByDeletingItems(Util.convertLinkedList(nodes), Util.convertLinkedList(edges), false);
System.out.println("After FastGraph building test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
return g;
}
/**
* Builds a tree like structure from a random node, to a particular depth
*
* @param nodes A LinkedHashSet of nodes, ready to be populated with nodes to be removed
* @param edges A LinkedHashSet of edges, ready to be populated with nodes to be removed
* @param r A random number generator used to pick a starting place.
* @param depth The depth of the tree. 1 would equal the starting node and it's children. 2 would be the same as 1, but with grandchildren.
*/
public void buildTree(LinkedHashSet<Integer> nodes, LinkedHashSet<Integer> edges, Random r, int depth) {
int startingNode = r.nextInt(this.getNumberOfNodes());
nodes.add(startingNode);
edges.addAll(Util.convertArray(this.getNodeConnectingEdges(startingNode)));
LinkedList<Integer> startingNodes = new LinkedList<>();
startingNodes.add(startingNode);
//while we are not at the required depth
while(depth != 0) {
//System.out.println("Starting Node: " + startingNode);
int[] cn = new int[0]; //get ready to store connecting nodes
for (int sn : startingNodes) { //for each of the starting nodes
cn = this.getNodeConnectingNodes(sn); //get this node's connecting nodes
//System.out.println(" Connecting Nodes: " + Arrays.toString(cn));
for(int n : cn) {
nodes.add(n); //add them all the the tree
edges.addAll(Util.convertArray(this.getNodeConnectingEdges(n))); //add the edges too
}
}
startingNodes = Util.convertArray(cn); // make the connections the starting nodes for the next loop
depth--; //"We need to go deeper"
}
}
/**
* @return the number of nodes in the graph
*/
public int getNumberOfNodes() {
return numberOfNodes;
}
/**
* @return the number of edges in the graph
*/
public int getNumberOfEdges() {
return numberOfEdges;
}
/**
* @return the graph name
*/
public String getName() {
return name;
}
/**
* @return the direct flag, false is on heap, true is off heap
*/
public boolean getDirect() {
return direct;
}
/**
*
* @return the node ByteBuffer
*/
public ByteBuffer getNodeBuf() {
return nodeBuf;
}
/**
*
* @return the edge ByteBuffer
*/
public ByteBuffer getEdgeBuf() {
return edgeBuf;
}
/**
*
* @return the node label ByteBuffer
*/
public ByteBuffer getNodeLabelBuf() {
return nodeLabelBuf;
}
/**
*
* @return the edge label ByteBuffer
*/
public ByteBuffer getEdgeLabelBuf() {
return edgeLabelBuf;
}
/**
*
* @return the connections ByteBuffer
*/
public ByteBuffer getConnectionBuf() {
return connectionBuf;
}
/**
* @param nodeIndex the node
* @return the node label
*/
public String getNodeLabel(int nodeIndex) {
int labelStart = nodeBuf.getInt(NODE_LABEL_START_OFFSET+nodeIndex*NODE_BYTE_SIZE);
int labelLength = nodeBuf.getShort(NODE_LABEL_LENGTH_OFFSET+nodeIndex*NODE_BYTE_SIZE);
char[] label = new char[labelLength];
for(int i = 0; i < labelLength; i++) {
int offset = labelStart+i*2;
char c = nodeLabelBuf.getChar(offset);
label[i] = c;
}
String ret = new String(label);
return ret;
}
/**
* @param nodeIndex the node
* @return the node weight
*/
public int getNodeWeight(int nodeIndex) {
int weight = nodeBuf.getInt(NODE_WEIGHT_OFFSET+nodeIndex*NODE_BYTE_SIZE);
return weight;
}
/**
* @param nodeIndex the node
* @return the node type
*/
public byte getNodeType(int nodeIndex) {
byte type = nodeBuf.get(NODE_TYPE_OFFSET+nodeIndex*NODE_BYTE_SIZE);
return type;
}
/**
* @param nodeIndex the node
* @return the node age
*/
public byte getNodeAge(int nodeIndex) {
byte age = nodeBuf.get(NODE_AGE_OFFSET+nodeIndex*NODE_BYTE_SIZE);
return age;
}
/**
* @param nodeIndex the node
* @return the node degree (number of connecting edges)
*/
public int getNodeDegree(int nodeIndex) {
int degree = getNodeInDegree(nodeIndex)+getNodeOutDegree(nodeIndex);
return degree;
}
/**
* @param nodeIndex the node
* @return the node in-degree (number of edges entering the node)
*/
public int getNodeInDegree(int nodeIndex) {
int degree = nodeBuf.getInt(NODE_IN_DEGREE_OFFSET+nodeIndex*NODE_BYTE_SIZE);
return degree;
}
/**
* @param nodeIndex the node
* @return the node out-degree (number of edges leaving the node)
*/
public int getNodeOutDegree(int nodeIndex) {
int degree = nodeBuf.getInt(NODE_OUT_DEGREE_OFFSET+nodeIndex*NODE_BYTE_SIZE);
return degree;
}
/**
* @param nodeIndex the node
* @return all connecting edges
*/
public int[] getNodeConnectingEdges(int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeDegree(nodeIndex);
int[] ret = new int[degree];
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_EDGE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
return ret;
}
/**
* This version puts the connecting edges in the argument array, to avoid repeated object creation and so speed up multiple accesses.
* create array with size of either getNodeDegree(nodeIndex) or maxDegree(). array elements beyond nodeDegree(nodeIndex)-1 are undefined.
* Will throw an exception if ret is not large enough.
*
* @param ret this is populated with the connecting edges found
* @param nodeIndex the node
* @return all connecting edges via parameter array.
*/
public void getNodeConnectingEdges(int[] ret, int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeDegree(nodeIndex);
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_EDGE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
}
/**
* @param nodeIndex the node
* @return all node neighbours.
*/
public int[] getNodeConnectingNodes(int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeDegree(nodeIndex);
int[] ret = new int[degree];
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_NODE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
return ret;
}
/**
* This version puts the connecting nodes in the argument array, to avoid repeated object creation and so speed up multiple accesses.
* create array with size of either getNodeDegree(nodeIndex) or maxDegree(). array elements beyond nodeDegree(nodeIndex)-1 are undefined.
* Will throw an exception if ret is not large enough.
*
* @param ret this is populated with the connecting nodes found
* @param nodeIndex the node
* @return all node neighbours.
*/
public void getNodeConnectingNodes(int[] ret, int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeDegree(nodeIndex);
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_NODE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
}
/**
* For directed graphs.
*
* @param nodeIndex the node
* @return all connecting edges for the node
*/
public int[] getNodeConnectingInEdges(int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeInDegree(nodeIndex);
int[] ret = new int[degree];
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_EDGE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
return ret;
}
/**
* For directed graphs.
* This version puts the connecting edges in the argument array, to avoid repeated object creation and so speed up multiple accesses.
* create array with size of either getNodeInDegree(nodeIndex) or maxDegree(). array elements beyond nodeDegree(nodeIndex)-1 are undefined.
* Will throw an exception if ret is not large enough.
*
* @param ret this is populated with the connecting edges found
* @param nodeIndex the node
* @return all connecting edges that enter the node via the parameter array.
*/
public void getNodeConnectingInEdges(int[] ret, int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeInDegree(nodeIndex);
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_EDGE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
}
/**
* For directed graphs.
*
* @param nodeIndex the node
* @return all node neighbours that are on the end of edges that enter the node.
*/
public int[] getNodeConnectingInNodes(int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeInDegree(nodeIndex);
int[] ret = new int[degree];
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_NODE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
return ret;
}
/**
* For directed graphs.
* This version puts the connecting nodes in the argument array, to avoid repeated object creation and so speed up multiple accesses.
* create array with size of either getNodeInDegree(nodeIndex) or maxDegree(). array elements beyond nodeDegree(nodeIndex)-1 are undefined.
* Will throw an exception if ret is not large enough.
*
* @param ret this is populated with the connecting nodes found
* @param nodeIndex the node
* @return all node neighbours that are on the end of edges that enter the node via the parameter array.
*/
public void getNodeConnectingInNodes(int[] ret, int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeInDegree(nodeIndex);
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_NODE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
}
/**
* For directed graphs.
*
* @param nodeIndex the node
* @return all edges that leave the node.
*/
public int[] getNodeConnectingOutEdges(int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_OUT_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeOutDegree(nodeIndex);
int[] ret = new int[degree];
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_EDGE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
return ret;
}
/**
* For directed graphs.
* This version puts the connecting nodes in the argument array, to avoid repeated object creation and so speed up multiple accesses.
* create array with size of either getNodeOutDegree(nodeIndex) or maxDegree(). array elements beyond nodeDegree(nodeIndex)-1 are undefined.
* Will throw an exception if ret is not large enough.
*
* @param ret this is populated with the connecting edges found
* @param nodeIndex the node
* @return all edges that leave the node via the argument array.
*/
public void getNodeConnectingOutEdges(int[] ret, int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_OUT_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeOutDegree(nodeIndex);
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_EDGE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
}
/**
* For directed graphs.
*
* @param nodeIndex the node
* @return all node neighbours that are on the end of edges that leave the passed node.
*/
public int[] getNodeConnectingOutNodes(int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_OUT_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeOutDegree(nodeIndex);
int[] ret = new int[degree];
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_NODE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
return ret;
}
/**
* For directed graphs.
* This version puts the connecting nodes in the argument array, to avoid repeated object creation and so speed up multiple accesses.
* create array with size of either getNodeOutDegree(nodeIndex) or maxDegree(). array elements beyond nodeDegree(nodeIndex)-1 are undefined.
* Will throw an exception if ret is not large enough.
*
* @param ret this is populated with the connecting nodes found
* @param nodeIndex the node
* @return all node neighbours that are on the end of edges that leave the passed node via the parameter array.
*/
public void getNodeConnectingOutNodes(int[] ret, int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_OUT_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeOutDegree(nodeIndex);
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_NODE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
}
/**
* @param edgeIndex the edge
* @return the edge label
*/
public String getEdgeLabel(int edgeIndex) {
int labelStart = edgeBuf.getInt(EDGE_LABEL_START_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
int labelLength = edgeBuf.getShort(EDGE_LABEL_LENGTH_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
char[] label = new char[labelLength];
for(int i = 0; i < labelLength; i++) {
int offset = labelStart+i*2;
char c = edgeLabelBuf.getChar(offset);
label[i] = c;
}
String ret = new String(label);
return ret;
}
/**
* @param edgeIndex the edge
* @return the first connecting node (the node the edge leaves for directed graphs).
*/
public int getEdgeNode1(int edgeIndex) {
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
return n1;
}
/**
* @param edgeIndex the edge
* @return the second connecting node (the node the edge enters for directed graphs).
*/
public int getEdgeNode2(int edgeIndex) {
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
return n2;
}
/**
* @param edgeIndex the edge
* @return the edge weight
*/
public int getEdgeWeight(int edgeIndex) {
int type = edgeBuf.getInt(EDGE_WEIGHT_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
return type;
}
/**
* @param edgeIndex the edge
* @return the edge type
*/
public byte getEdgeType(int edgeIndex) {
byte type= edgeBuf.get(EDGE_TYPE_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
return type;
}
/**
* @param edgeIndex the edge
* @return the edge age
*/
public byte getEdgeAge(int edgeIndex) {
byte age = edgeBuf.get(EDGE_AGE_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
return age;
}
/**
* Names should be simple alphanumeric. Spaces and dashes are permitted. Note that tilde ("~") cannot be used.
* @param name the name of the graph
*/
public void setName(String name) {
this.name = name;
}
/**
* @param nodeIndex the node
* @param weight the new node weight
*/
public void setNodeWeight(int nodeIndex, int weight) {
nodeBuf.putInt(NODE_WEIGHT_OFFSET+nodeIndex*NODE_BYTE_SIZE, weight);
}
/**
* @param nodeIndex the node
* @param type the new node type
*/
public void setNodeType(int nodeIndex, byte type) {
nodeBuf.put(NODE_TYPE_OFFSET+nodeIndex*NODE_BYTE_SIZE, type);
}
/**
* @param nodeIndex the node
* @return the node age
*/
public void setNodeAge(int nodeIndex, byte age) {
nodeBuf.put(NODE_AGE_OFFSET+nodeIndex*NODE_BYTE_SIZE, age);
}
/**
* @param edgeIndex the edge
* @param weight the new edge weight
*/
public void setEdgeWeight(int edgeIndex, int weight) {
edgeBuf.putInt(EDGE_WEIGHT_OFFSET+edgeIndex*EDGE_BYTE_SIZE, weight);
}
/**
* @param edgeIndex the edge
* @param type the new edge type
*/
public void setEdgeType(int edgeIndex, byte type) {
edgeBuf.put(EDGE_TYPE_OFFSET+edgeIndex*EDGE_BYTE_SIZE, type);
}
/**
* @param edgeIndex the edge
* @return the edge age
*/
public void setEdgeAge(int edgeIndex, byte age) {
edgeBuf.put(EDGE_AGE_OFFSET+edgeIndex*EDGE_BYTE_SIZE, age);
}
/**
* Change all the node labels in the graph. Creates a new nodeLabelBuf, changes the label pointers in nodeBuf.
*
* @param labels Must contain the same number of labels as number of nodes in the graph
*/
public void setAllNodeLabels(String[] labels) {
long totalLabelLength = 0;
for(int i = 0; i < numberOfNodes; i++) {
totalLabelLength += labels[i].length();
}
if(totalLabelLength*2 > MAX_BYTE_BUFFER_SIZE) {
throw new OutOfMemoryError("Tried to create a nodeLabelBuf with too many chars");
}
int bufSize = (int)(totalLabelLength*2); // this cast is safe because of the previous test
if(!direct) {
nodeLabelBuf = ByteBuffer.allocate(bufSize);
} else {
nodeLabelBuf = ByteBuffer.allocateDirect(bufSize);
}
nodeLabelBuf.clear();
int labelOffset = 0;
for(int i = 0; i < numberOfNodes; i++) {
String label = labels[i];
char[] labelArray = label.toCharArray();
short labelLength = (short)(labelArray.length);
nodeBuf.putInt(NODE_LABEL_START_OFFSET+i*NODE_BYTE_SIZE,labelOffset); // label start
nodeBuf.putShort(NODE_LABEL_LENGTH_OFFSET+i*NODE_BYTE_SIZE,labelLength); // label size
for(int j = 0; j < labelArray.length; j++) {
char c = labelArray[j];
nodeLabelBuf.putChar(labelOffset,c);
labelOffset += 2; // increment by 2 as it is a char (2 bytes)
}
}
}
/**
* Change all the edge labels in the graph. Creates a new edgeLabelBuf, changes the label pointers in edgeBuf
*
* @param labels Must contain the same number of labels as there are edges in the graph
* @throws OutofMemoryError
*/
public void setAllEdgeLabels(String[] labels) {
long totalLabelLength = 0;
for(int i = 0; i < numberOfEdges; i++) {
totalLabelLength += labels[i].length();
}
if(totalLabelLength*2 > MAX_BYTE_BUFFER_SIZE) {
throw new OutOfMemoryError("Tried to create a edgeLabelBuf with too many chars");
}
int bufSize = (int)(totalLabelLength*2); // this cast is safe because of the previous test
if(!direct) {
edgeLabelBuf = ByteBuffer.allocate(bufSize);
} else {
edgeLabelBuf = ByteBuffer.allocateDirect(bufSize);
}
edgeLabelBuf.clear();
int labelOffset = 0;
for(int i = 0; i < numberOfEdges; i++) {
String label = labels[i];
char[] labelArray = label.toCharArray();
short labelLength = (short)(labelArray.length);
edgeBuf.putInt(EDGE_LABEL_START_OFFSET+i*EDGE_BYTE_SIZE,labelOffset); // label start
edgeBuf.putShort(EDGE_LABEL_LENGTH_OFFSET+i*EDGE_BYTE_SIZE,labelLength); // label size
for(int j = 0; j < labelArray.length; j++) {
char c = labelArray[j];
edgeLabelBuf.putChar(labelOffset,c);
labelOffset += 2; // increment by 2 as it is a char (2 bytes)
}
}
}
/**
* gets the other node connecting to the edge.
* If the argument node is not connected to the edge, then an undefined node will
* be returned.
*
* @param edge the edge
* @param node the known node
* @return the node on the opposite side of the edge
*/
public int oppositeEnd(int edge, int node) {
int n1 = getEdgeNode1(edge);
int n2 = getEdgeNode2(edge);
if(n1 == node) {
return n2;
}
return n1;
}
/**
* Allocates space for the node, edge and connection ByteBuffers. The label ByteBuffers
* are created later
*/
private void init() {
if(!direct) {
nodeBuf = ByteBuffer.allocate(numberOfNodes*NODE_BYTE_SIZE);
edgeBuf = ByteBuffer.allocate(numberOfEdges*EDGE_BYTE_SIZE);
connectionBuf = ByteBuffer.allocate(numberOfEdges*2*CONNECTION_PAIR_SIZE);
// nodeLabelBuf and edgeLabelBuf now created in Factories by setAllNodeLabels
} else {
nodeBuf = ByteBuffer.allocateDirect(numberOfNodes*NODE_BYTE_SIZE);
edgeBuf = ByteBuffer.allocateDirect(numberOfEdges*EDGE_BYTE_SIZE);
connectionBuf = ByteBuffer.allocateDirect(numberOfEdges*2*CONNECTION_PAIR_SIZE);
// nodeLabelBuf and edgeLabelBuf now created in Factories by setAllNodeLabels
}
nodeBuf.clear();
edgeBuf.clear();
connectionBuf.clear();
}
/**
* Create a FastGraph from a json string.
*
* @param json the json as a string
* @param direct if true then off heap ByteBuffers, if false then on heap ByteBuffers
* @return the created FastGraph.
*/
public static FastGraph jsonStringGraphFactory(String json, boolean direct) {
int nodeCount = 0;
int edgeCount = 0;
JSONObject jsonObj = new JSONObject(json);
String graphName = jsonObj.getString("name");
JSONArray nodes = jsonObj.getJSONArray("nodes");
Iterator<Object> itNodes = nodes.iterator();
while(itNodes.hasNext()) {
JSONObject node = (JSONObject)(itNodes.next());
int index = node.getInt("nodeIndex");
if(index+1 > nodeCount) {
nodeCount = index+1;
}
}
JSONArray edges = jsonObj.getJSONArray("edges");
Iterator<Object> itEdges = edges.iterator();
while(itEdges.hasNext()) {
JSONObject edge = (JSONObject)(itEdges.next());
int index = edge.getInt("edgeIndex");
if(index+1 > edgeCount) {
edgeCount = index+1;
}
}
FastGraph g = new FastGraph(nodeCount,edgeCount,direct);
g.populateFromJsonString(jsonObj);
g.setName(graphName);
return g;
}
/**
* Generate a random graph of the desired size. Self sourcing edges and parallel edges may exist.
*
* @param numberOfNodes the number of nodes in the graph
* @param numberOfEdges the number of edges in the graph
* @param direct if true then off heap ByteBuffers, if false then on heap ByteBuffers
* @return the created FastGraph
* @throws Exception
*/
public static FastGraph randomGraphFactory(int numberOfNodes, int numberOfEdges, boolean direct) throws Exception {
FastGraph graph = randomGraphFactory(numberOfNodes, numberOfEdges, -1, false, direct);
return graph;
}
/**
* Generate a random graph of the desired size. Self sourcing edges and parallel edges may exist.
*
* @param numberOfNodes the number of nodes in the graph
* @param numberOfEdges the number of edges in the graph
* @param seed random number seed, -1 for current time
* @param direct if true then off heap ByteBuffers, if false then on heap ByteBuffers
* @return the created FastGraph
* @throws Exception
*/
public static FastGraph randomGraphFactory(int numberOfNodes, int numberOfEdges, long seed, boolean direct) throws Exception {
FastGraph graph = randomGraphFactory(numberOfNodes, numberOfEdges, seed, false, direct);
return graph;
}
/**
* Generate a random graph of the desired size. Self sourcing edges and parallel edges may exist.
*
* @param numberOfNodes the number of nodes in the graph
* @param numberOfEdges the number of edges in the graph
* @param seed random number seed, -1 for current time
* @param direct if true then off heap ByteBuffers, if false then on heap ByteBuffers
* @return the created FastGraph
* @throws Exception
*/
public static FastGraph randomGraphFactory(int numberOfNodes, int numberOfEdges, long seed, boolean simple, boolean direct) throws Exception {
FastGraph g = new FastGraph(numberOfNodes,numberOfEdges,direct);
g.setName("random-n-"+numberOfNodes+"-e-"+numberOfEdges);
g.populateRandomGraph(simple, seed);
return g;
}
/**
* creates a FastGraph by loading in various files from the given directory, or data under
* current working directory if directory is null.
*
* @param directory where the files are held, or if null fileBaseName under data under the current working directory
* @param fileBaseName the name of the files, to which extensions are added
* @return the created FastGraph
* @throws IOException If the buffers cannot be loaded
* @See loadBuffers
*/
public static FastGraph loadBuffersGraphFactory(String directory, String fileBaseName) throws IOException {
FastGraph g = loadBuffers(null,fileBaseName);
return g;
}
/**
* Populates the FastGraph ByteBuffers from a json string.
* @param jsonObj the json code after parsing
*/
private void populateFromJsonString(JSONObject jsonObj) {
//long time;
String[] nodeLabels = new String[numberOfNodes];
String[] edgeLabels = new String[numberOfEdges];
int inStart = -888;
int inLength = -3;
int outStart = -777;
int outLength = -2;
int index = -1;
int weight = -5;
byte type = -7;
byte age = -9;
String label;
//the nodes are the first elements
JSONArray nodes = jsonObj.getJSONArray("nodes");
Iterator<Object> itNodes = nodes.iterator();
while(itNodes.hasNext()) {
JSONObject node = (JSONObject)(itNodes.next());
index = node.getInt("nodeIndex");
weight = node.getInt("nodeWeight");
type = (byte)(node.getInt("nodeType"));
age = (byte)(node.getInt("nodeAge"));
label = node.getString("nodeLabel");
nodeBuf.putInt(NODE_IN_CONNECTION_START_OFFSET+index*NODE_BYTE_SIZE,inStart); // offset for inward connecting edges/nodes
nodeBuf.putInt(NODE_IN_DEGREE_OFFSET+index*NODE_BYTE_SIZE,inLength); // number of inward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_CONNECTION_START_OFFSET+index*NODE_BYTE_SIZE,outStart); // offset for outward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_DEGREE_OFFSET+index*NODE_BYTE_SIZE,outLength); // number of outward connecting edges/nodes
nodeBuf.putInt(NODE_WEIGHT_OFFSET+index*NODE_BYTE_SIZE,weight); // weight
nodeBuf.put(NODE_TYPE_OFFSET+index*NODE_BYTE_SIZE,type); // type
nodeBuf.put(NODE_AGE_OFFSET+index*NODE_BYTE_SIZE,age); // age
// save labels for later
nodeLabels[index] = label;
}
setAllNodeLabels(nodeLabels);
ArrayList<ArrayList<Integer>> nodeIn = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of inward edges
for(int i = 0; i < numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(100);
nodeIn.add(i,edges);
}
ArrayList<ArrayList<Integer>> nodeOut = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of outward edges
for(int i = 0; i < numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(100);
nodeOut.add(i,edges);
}
ArrayList<Integer> inEdgeList;
ArrayList<Integer> outEdgeList;
int node1;
int node2;
index = -1;
weight = -101;
type = -103;
age = -105;
//time = System.currentTimeMillis();
//populate the edges
JSONArray edges = jsonObj.getJSONArray("edges");
Iterator<Object> itEdges = edges.iterator();
while(itEdges.hasNext()) {
JSONObject edge = (JSONObject)(itEdges.next());
index = edge.getInt("edgeIndex");
node1 = edge.getInt("node1");
node2 = edge.getInt("node2");
weight = edge.getInt("edgeWeight");
type = (byte)(edge.getInt("edgeType"));
age = (byte)(edge.getInt("edgeAge"));
label = edge.getString("edgeLabel");
edgeBuf.putInt(EDGE_NODE1_OFFSET+index*EDGE_BYTE_SIZE,node1); // one end of edge
edgeBuf.putInt(EDGE_NODE2_OFFSET+index*EDGE_BYTE_SIZE,node2); // other end of edge
edgeBuf.putInt(EDGE_WEIGHT_OFFSET+index*EDGE_BYTE_SIZE,weight); // weight
edgeBuf.put(EDGE_TYPE_OFFSET+index*EDGE_BYTE_SIZE,type); // type
edgeBuf.put(EDGE_AGE_OFFSET+index*EDGE_BYTE_SIZE,age); // age
// save labels for later
edgeLabels[index] = label;
// store connecting nodes
inEdgeList = nodeIn.get(node2);
inEdgeList.add(index);
outEdgeList = nodeOut.get(node1);
outEdgeList.add(index);
}
setAllEdgeLabels(edgeLabels);
// Initialise the connection buffer, modifying the node buffer connection data
int offset = 0;
for(int i = 0; i < numberOfNodes; i++) {
// setting the in connection offset and length
ArrayList<Integer> inEdges = nodeIn.get(i);
int inEdgeLength = inEdges.size();
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_CONNECTION_START_OFFSET,offset);
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_DEGREE_OFFSET,inEdgeLength);
// now put the in edge/node pairs
for(int edgeIndex : inEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+edgeIndex+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,edgeIndex);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
// setting the out connection offset and length
ArrayList<Integer> outEdges = nodeOut.get(i);
int outEdgeLength = outEdges.size();
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_CONNECTION_START_OFFSET,offset);
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_DEGREE_OFFSET,outEdgeLength);
// now put the out edge/node pairs
for(int edgeIndex : outEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+edgeIndex+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,edgeIndex);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
}
}
/**
* saves the current graph to several files, in directory given to base name given (i.e. fileBaseName should have no extension).
* If directory is null, then to a directory named data under current working directory.
*
* @param directory where the files are to be stored, or if null fileBaseName under data under the current working directory
* @param fileBaseName the name of the files, to which extensions are added
*/
public void saveBuffers(String directory, String fileBaseName) {
String directoryAndBaseName = "";
if(directory != null) {
if(directory.charAt(directory.length()-1)== File.separatorChar) {
directoryAndBaseName = directory+fileBaseName;
} else {
directoryAndBaseName = directory+File.separatorChar+fileBaseName;
}
} else {
directoryAndBaseName = Launcher.startingWorkingDirectory+File.separatorChar+"data"+File.separatorChar+fileBaseName+File.separatorChar+fileBaseName;
new File(Launcher.startingWorkingDirectory+File.separatorChar+"data"+File.separatorChar+fileBaseName).mkdirs();
}
try {
FileOutputStream fos = new FileOutputStream(directoryAndBaseName+".info");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
writer.write("name"+INFO_SPLIT_STRING+name+"\n");
writer.write("numberOfNodes"+INFO_SPLIT_STRING+numberOfNodes+"\n");
writer.write("numberOfEdges"+INFO_SPLIT_STRING+numberOfEdges+"\n");
writer.write("numberOfNodeLabelBytes"+INFO_SPLIT_STRING+nodeLabelBuf.capacity()+"\n");
writer.write("numberOfEdgeLabelBytes"+INFO_SPLIT_STRING+edgeLabelBuf.capacity()+"\n");
String directValue = "false";
if(direct) {
directValue = "true";
}
writer.write("direct"+INFO_SPLIT_STRING+directValue+"\n");
writer.close();
fos.close();
} catch(Exception e) {
System.out.println("ERROR executing info file save in saveBuffers("+directory+","+fileBaseName+")");
e.printStackTrace();
}
try {
writeBuf(directoryAndBaseName+".nodeBuf",nodeBuf);
writeBuf(directoryAndBaseName+".edgeBuf",edgeBuf);
writeBuf(directoryAndBaseName+".connectionBuf",connectionBuf);
writeBuf(directoryAndBaseName+".nodeLabelBuf",nodeLabelBuf);
writeBuf(directoryAndBaseName+".edgeLabelBuf",edgeLabelBuf);
} catch(Exception e) {
System.out.println("ERROR executing buffer save in saveBuffers("+directory+","+fileBaseName+")");
e.printStackTrace();
}
}
/**
* Save a ByteBuffer to a file.
*
* @param file name to write to
* @param buf buffer to be written
* @throws Exception if file save fails
*/
private void writeBuf(String fileName, ByteBuffer buf) throws Exception {
try {
buf.rewind();
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file, false);
FileChannel wChannel = fos.getChannel();
wChannel.write(buf);
fos.flush();
wChannel.close();
fos.close();
} catch(Exception e) {
System.out.println("ERROR executing writeBuf("+fileName+","+buf+")");
e.printStackTrace();
}
}
public static FastGraph adjacencyListGraphFactory(int nodeCount, int edgeCount, String dir, String fileName, boolean direct) throws Exception {
FastGraph g = new FastGraph(nodeCount,edgeCount,direct);
g.setName(fileName);
g.loadAdjacencyListGraph(dir,fileName);
return g;
}
/**
* Assumes edges represented by one node index pair per line delimited by
* tabs or spaces, ignores lines starting with # and any line without a tab.
* Looks for the file in given directory. If directory is null, then to a
* directory named /data/snap under current working directory.
*
* @param dir the directory for the file, if null then a directory called data/ under the current working directory
* @param fileName the fileName for the file
*
* @throws IOException If the buffers cannot be loaded
*/
private void loadAdjacencyListGraph(String dir, String fileName) throws Exception {
String directory = dir;
if(directory == null) {
directory = Launcher.startingWorkingDirectory+File.separatorChar+"data"+File.separatorChar+"snap";
}
String path = null;
if(directory.charAt(directory.length()-1)== File.separatorChar) {
path = directory+fileName;
} else {
path = directory+File.separatorChar+fileName;
}
int edgeIndex = 0;
int nodeIndex = 0;
HashMap<String,Integer> nodeSnapIdToIndexMap = new HashMap<String,Integer>(numberOfNodes*4);
HashMap<Integer,String> nodeIndexToSnapIdMap = new HashMap<Integer,String>(numberOfNodes*4);
HashMap<Integer,Integer> edgeNode1Map = new HashMap<Integer,Integer>(numberOfEdges*4);
HashMap<Integer,Integer> edgeNode2Map = new HashMap<Integer,Integer>(numberOfEdges*4);
File f = new File(path);
if(!f.exists()) {
throw new IOException("Problem loading file "+path+". If you expect to access a SNAP file try downloading the file from:\nhttps://snap.stanford.edu/data/\nthen unzipping it and placing it in the directory "+directory);
//System.exit(1);
}
FileInputStream is = new FileInputStream(path);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String[] splitLine;
String line = "";
long time = System.currentTimeMillis();
while(line != null) {
line = br.readLine();
if(line == null) {
continue;
}
if(line.length() == 0) {
continue;
}
if(line.charAt(0) == '
continue;
}
splitLine = line.split(" ");
if(splitLine.length < 2) {
splitLine = line.split("\t");
if(splitLine.length < 2) {
System.out.println("FAILED TO RECOGNISE LINE:"+line+" in loadAdjacencyListGraph("+directory+","+fileName+")");
continue;
}
}
String node1String = splitLine[0];
String node2String = splitLine[1];
if(!nodeSnapIdToIndexMap.containsKey(node1String)) {
nodeSnapIdToIndexMap.put(node1String,nodeIndex);
nodeIndexToSnapIdMap.put(nodeIndex,node1String);
nodeIndex++;
}
if(!nodeSnapIdToIndexMap.containsKey(node2String)) {
nodeSnapIdToIndexMap.put(node2String,nodeIndex);
nodeIndexToSnapIdMap.put(nodeIndex,node2String);
nodeIndex++;
}
edgeNode1Map.put(edgeIndex, nodeSnapIdToIndexMap.get(node1String));
edgeNode2Map.put(edgeIndex, nodeSnapIdToIndexMap.get(node2String));
edgeIndex++;
if(edgeIndex%1000000==0 ) {
System.out.println("edgesLoaded "+edgeIndex+" time "+(System.currentTimeMillis()-time)/1000.0);
}
}
String[] nodeLabels = new String[numberOfNodes];
String[] edgeLabels = new String[numberOfEdges];
int inStart = -88;
int inLength = -33;
int outStart = -77;
int outLength = -22;
int weight = -55;
byte type = -77;
byte age = -99;
for(int i = 0; i < numberOfNodes; i++) {
nodeBuf.putInt(NODE_IN_CONNECTION_START_OFFSET+i*NODE_BYTE_SIZE,inStart); // offset for inward connecting edges/nodes
nodeBuf.putInt(NODE_IN_DEGREE_OFFSET+i*NODE_BYTE_SIZE,inLength); // number of inward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_CONNECTION_START_OFFSET+i*NODE_BYTE_SIZE,outStart); // offset for outward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_DEGREE_OFFSET+i*NODE_BYTE_SIZE,outLength); // number of outward connecting edges/nodes
nodeBuf.putInt(NODE_WEIGHT_OFFSET+i*NODE_BYTE_SIZE,weight); // weight
nodeBuf.put(NODE_TYPE_OFFSET+i*NODE_BYTE_SIZE,type); // type
nodeBuf.put(NODE_AGE_OFFSET+i*NODE_BYTE_SIZE,age); // age
// save labels for later
String label = nodeIndexToSnapIdMap.get(i);
nodeLabels[i] = label;
}
setAllNodeLabels(nodeLabels);
ArrayList<ArrayList<Integer>> nodeIn = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of inward edges
for(int i = 0; i < numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(100);
nodeIn.add(i,edges);
}
ArrayList<ArrayList<Integer>> nodeOut = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of outward edges
for(int i = 0; i < numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(100);
nodeOut.add(i,edges);
}
ArrayList<Integer> inEdgeList;
ArrayList<Integer> outEdgeList;
int node1;
int node2;
weight = -51;
type = -53;
age = -55;
for(int i = 0; i < numberOfEdges; i++) {
node1 = edgeNode1Map.get(i);
node2 = edgeNode2Map.get(i);
edgeBuf.putInt(EDGE_NODE1_OFFSET+i*EDGE_BYTE_SIZE,node1); // one end of edge
edgeBuf.putInt(EDGE_NODE2_OFFSET+i*EDGE_BYTE_SIZE,node2); // other end of edge
edgeBuf.putInt(EDGE_WEIGHT_OFFSET+i*EDGE_BYTE_SIZE,weight); // weight
edgeBuf.put(EDGE_TYPE_OFFSET+i*EDGE_BYTE_SIZE,type); // type
edgeBuf.put(EDGE_AGE_OFFSET+i*EDGE_BYTE_SIZE,age); // age
// store labels for later
String label = "e"+i;
edgeLabels[i] = label;
// store connecting nodes
inEdgeList = nodeIn.get(node2);
inEdgeList.add(i);
outEdgeList = nodeOut.get(node1);
outEdgeList.add(i);
}
setAllEdgeLabels(edgeLabels);
// Initialise the connection buffer, modifying the node buffer connection data
//time = System.currentTimeMillis();
int offset = 0;
for(int i = 0; i < numberOfNodes; i++) {
// setting the in connection offset and length
ArrayList<Integer> inEdges = nodeIn.get(i);
int inEdgeLength = inEdges.size();
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_CONNECTION_START_OFFSET,offset);
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_DEGREE_OFFSET,inEdgeLength);
// now put the in edge/node pairs
for(int e : inEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+e*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+e*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+e+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,e);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
// setting the out connection offset and length
ArrayList<Integer> outEdges = nodeOut.get(i);
int outEdgeLength = outEdges.size();
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_CONNECTION_START_OFFSET,offset);
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_DEGREE_OFFSET,outEdgeLength);
// now put the out edge/node pairs
for(int e : outEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+e*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+e*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+e+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,e);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
}
}
/**
* Creates a graph from two files: baseFileName.nodes and baseFileName.edges.
* Files are structured as line *"\n" separated) lists of items. Each element
* in an item is tab ("\t") separated. Hence no tabs in file names are allowed.
* <br/>
* Nodes are lists of <code>index label weight type age</code>
* <br>
* where index must start at 0 and end at nodeCount-1, label is a string, weight is
* integer valued, type is byte valued and age is byte valued.
* <br/>
* Edges are lists of <code>index node1Index node2Index label weight type age</code>
* <br>
* where index must start at 0 and end at edgeCount-1, node1Index is a node index,
* node2Index is a nodeIndex, label is a string, weight is
* integer valued, type is byte valued and age is byte valued.
* <br>
* Ignores empty lines and lines starting with a hash ("#").
*
* @param nodeCount the number of nodes
* @param edgeCount the number of edges
* @param dir the directory for the file, if null then a directory called data/ under the current working directory
* @param baseFileName the base of the file name for the file, two files called baseFileName.nodes and baseFileName.edges are expected
* @param direct if true the ByteBuffers are direct, if false they are allocated on the heap
*
* @throws Exception Throws if the graph cannot be built correctly. Might be an IO error
*/
public static FastGraph nodeListEdgeListGraphFactory(int nodeCount, int edgeCount, String dir, String baseFileName, boolean direct) throws Exception {
FastGraph g = new FastGraph(nodeCount,edgeCount,direct);
g.setName(baseFileName);
g.loadnodeListEdgeListGraph(dir,baseFileName);
return g;
}
/**
* Populates a graph from two files: baseFileName.nodes and baseFileName.edges.
* Files are structured as line *"\n" separated) lists of items. Each element
* in an item is tab ("\t") separated. Hence no tabs in file names are allowed.
* <br/>
* Nodes are lists of <code>index label weight type age</code>
* <br>
* where index must start at 0 and end at nodeCount-1, label is a string, weight is
* integer valued, type is byte valued and age is byte valued.
* <br/>
* Edges are lists of <code>index node1Index node2Index label weight type age</code>
* <br>
* where index must start at 0 and end at edgeCount-1, node1Index is a node index,
* node2Index is a nodeIndex, label is a string, weight is
* integer valued, type is byte valued and age is byte valued.
* <br>
* Ignores empty lines and lines starting with a hash ("#").
*
* @param dir the directory for the file, if null then a directory called data/ under the current working directory
* @param baseFileName the base of the file name for the file, two files called baseFileName.nodes and baseFileName.edges are expected
*
* @throws IOException If the buffers cannot be loaded
*
*/
private void loadnodeListEdgeListGraph(String dir, String baseFileName) throws Exception {
String directory = dir;
if(directory == null) {
directory = Launcher.startingWorkingDirectory+File.separatorChar+"data";
}
String basePath = null;
if(directory.charAt(directory.length()-1)== File.separatorChar) {
basePath = directory+baseFileName;
} else {
basePath = directory+File.separatorChar+baseFileName;
}
String nodePath = basePath+".nodes";
File f = new File(nodePath);
if(!f.exists()) {
throw new IOException("Problem loading file "+nodePath);
}
FileInputStream is = new FileInputStream(nodePath);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
// load the nodes
String[] splitLine;
String[] nodeLabels = new String[numberOfNodes];
int inStart = -18;
int inLength = -13;
int outStart = -21;
int outLength = -23;
int index = -1;
String label;
int weight = -15;
byte type = -17;
byte age = -19;
String nodeLine = "";
while(nodeLine != null) {
nodeLine = br.readLine();
if(nodeLine == null) {
continue;
}
if(nodeLine.length() == 0) {
continue;
}
if(nodeLine.charAt(0) == '
continue;
}
splitLine = nodeLine.split("\t");
if(splitLine.length < 5) {
br.close();
throw new IOException("Not enough elements, needs 5 tab separated elements in "+nodeLine);
}
try {
index = Integer.parseInt(splitLine[0]);
} catch(NumberFormatException e) {
br.close();
throw new IOException("Problem parsing node index in line "+nodeLine);
}
if(index > numberOfNodes) {
br.close();
throw new IOException("index "+index+" is greater than the number of nodes "+numberOfNodes);
}
label = splitLine[1];
try {
weight = Integer.parseInt(splitLine[2]);
} catch(NumberFormatException e) {
br.close();
throw new IOException("Problem parsing node weight in line "+nodeLine);
}
try {
type = Byte.parseByte(splitLine[3]);
} catch(NumberFormatException e) {
br.close();
throw new IOException("Problem parsing node type in line "+nodeLine);
}
try {
age = Byte.parseByte(splitLine[4]);
} catch(NumberFormatException e) {
br.close();
throw new IOException("Problem parsing node age in line "+nodeLine);
}
nodeBuf.putInt(NODE_IN_CONNECTION_START_OFFSET+index*NODE_BYTE_SIZE,inStart); // offset for inward connecting edges/nodes
nodeBuf.putInt(NODE_IN_DEGREE_OFFSET+index*NODE_BYTE_SIZE,inLength); // number of inward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_CONNECTION_START_OFFSET+index*NODE_BYTE_SIZE,outStart); // offset for outward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_DEGREE_OFFSET+index*NODE_BYTE_SIZE,outLength); // number of outward connecting edges/nodes
nodeBuf.putInt(NODE_WEIGHT_OFFSET+index*NODE_BYTE_SIZE,weight); // weight
nodeBuf.put(NODE_TYPE_OFFSET+index*NODE_BYTE_SIZE,type); // type
nodeBuf.put(NODE_AGE_OFFSET+index*NODE_BYTE_SIZE,age); // age
// save labels for later
nodeLabels[index] = label;
}
br.close();
setAllNodeLabels(nodeLabels);
String[] edgeLabels = new String[numberOfEdges];
String edgePath = basePath+".edges";
f = new File(edgePath);
if(!f.exists()) {
throw new IOException("Problem loading file "+edgePath+""+directory);
}
is = new FileInputStream(edgePath);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
// load the Edges
ArrayList<ArrayList<Integer>> nodeIn = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of inward edges
for(int i = 0; i < numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(100);
nodeIn.add(i,edges);
}
ArrayList<ArrayList<Integer>> nodeOut = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of outward edges
for(int i = 0; i < numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(100);
nodeOut.add(i,edges);
}
ArrayList<Integer> inEdgeList;
ArrayList<Integer> outEdgeList;
int node1 = -64;
int node2 = -65;
String edgeLine = "";
while(edgeLine != null) {
edgeLine = br.readLine();
if(edgeLine == null) {
continue;
}
if(edgeLine.length() == 0) {
continue;
}
if(edgeLine.charAt(0) == '
continue;
}
splitLine = edgeLine.split("\t");
if(splitLine.length < 7) {
br.close();
throw new IOException("Not enough elements, needs 7 tab separated elements in "+edgeLine);
}
try {
index = Integer.parseInt(splitLine[0]);
} catch(NumberFormatException e) {
br.close();
throw new IOException("Problem parsing edge index in line "+edgeLine);
}
if(index > numberOfEdges) {
br.close();
throw new IOException("index "+index+" is greater than the number of edges "+numberOfEdges);
}
try {
node1 = Integer.parseInt(splitLine[1]);
} catch(NumberFormatException e) {
br.close();
throw new IOException("Problem parsing node 1 index in line "+edgeLine);
}
try {
node2 = Integer.parseInt(splitLine[2]);
} catch(NumberFormatException e) {
br.close();
throw new IOException("Problem parsing node 2 index in line "+edgeLine);
}
label = splitLine[3];
try {
weight = Integer.parseInt(splitLine[4]);
} catch(NumberFormatException e) {
br.close();
throw new IOException("Problem parsing edge weight in line "+edgeLine);
}
try {
type = Byte.parseByte(splitLine[5]);
} catch(NumberFormatException e) {
br.close();
throw new IOException("Problem parsing edge type in line "+edgeLine);
}
try {
age = Byte.parseByte(splitLine[6]);
} catch(NumberFormatException e) {
br.close();
throw new IOException("Problem parsing edge age in line "+edgeLine);
}
edgeBuf.putInt(EDGE_NODE1_OFFSET+index*EDGE_BYTE_SIZE,node1); // one end of edge
edgeBuf.putInt(EDGE_NODE2_OFFSET+index*EDGE_BYTE_SIZE,node2); // other end of edge
edgeBuf.putInt(EDGE_WEIGHT_OFFSET+index*EDGE_BYTE_SIZE,weight); // weight
edgeBuf.put(EDGE_TYPE_OFFSET+index*EDGE_BYTE_SIZE,type); // type
edgeBuf.put(EDGE_AGE_OFFSET+index*EDGE_BYTE_SIZE,age); // age
// save labels for later
edgeLabels[index] = label;
// store connecting nodes
inEdgeList = nodeIn.get(node2);
inEdgeList.add(index);
outEdgeList = nodeOut.get(node1);
outEdgeList.add(index);
}
br.close();
setAllEdgeLabels(edgeLabels);
// Initialise the connection buffer, modifying the node buffer connection data
//time = System.currentTimeMillis();
int offset = 0;
for(int i = 0; i < numberOfNodes; i++) {
// setting the in connection offset and length
ArrayList<Integer> inEdges = nodeIn.get(i);
int inEdgeLength = inEdges.size();
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_CONNECTION_START_OFFSET,offset);
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_DEGREE_OFFSET,inEdgeLength);
// now put the in edge/node pairs
for(int e : inEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+e*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+e*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+e+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,e);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
// setting the out connection offset and length
ArrayList<Integer> outEdges = nodeOut.get(i);
int outEdgeLength = outEdges.size();
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_CONNECTION_START_OFFSET,offset);
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_DEGREE_OFFSET,outEdgeLength);
// now put the out edge/node pairs
for(int e : outEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+e*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+e*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+e+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,e);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
}
}
@SuppressWarnings("resource")
private static FastGraph loadBuffers(String directory, String fileBaseName) throws IOException {
String directoryAndBaseName = Launcher.startingWorkingDirectory+File.separatorChar+"data"+File.separatorChar+fileBaseName+File.separatorChar+fileBaseName;
if(directory != null) {
if(directory.charAt(directory.length()-1)== File.separatorChar) {
directoryAndBaseName = directory+fileBaseName;
} else {
directoryAndBaseName = directory+File.separatorChar+fileBaseName;
}
}
FastGraph g = null;
File file;
FileChannel rChannel;
String line;
String[] splitLine;
FileInputStream is = new FileInputStream(directoryAndBaseName+".info");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
line = br.readLine();
splitLine = line.split(INFO_SPLIT_STRING);
String name = splitLine[1];
line = br.readLine();
splitLine = line.split(INFO_SPLIT_STRING);
int inNodeTotal = Integer.parseInt(splitLine[1]);
line = br.readLine();
splitLine = line.split(INFO_SPLIT_STRING);
int inEdgeTotal = Integer.parseInt(splitLine[1]);
line = br.readLine();
splitLine = line.split(INFO_SPLIT_STRING);
int inNodeLabelSize = Integer.parseInt(splitLine[1]);
line = br.readLine();
splitLine = line.split(INFO_SPLIT_STRING);
int inEdgeLabelSize = Integer.parseInt(splitLine[1]);
line = br.readLine();
splitLine = line.split(INFO_SPLIT_STRING);
String directValue = splitLine[1];
boolean inDirect = true;
if(directValue.equals("false")) {
inDirect = false;
}
br.close();
g = new FastGraph(inNodeTotal, inEdgeTotal, inDirect);
if(!inDirect) {
g.nodeLabelBuf = ByteBuffer.allocate(inNodeLabelSize);
g.edgeLabelBuf = ByteBuffer.allocate(inEdgeLabelSize);
} else {
g.nodeLabelBuf = ByteBuffer.allocateDirect(inNodeLabelSize);
g.edgeLabelBuf = ByteBuffer.allocateDirect(inEdgeLabelSize);
}
g.setName(name);
file = new File(directoryAndBaseName+".nodeBuf");
rChannel = new FileInputStream(file).getChannel();
rChannel.read(g.nodeBuf);
rChannel.close();
file = new File(directoryAndBaseName+".edgeBuf");
rChannel = new FileInputStream(file).getChannel();
rChannel.read(g.edgeBuf);
rChannel.close();
file = new File(directoryAndBaseName+".connectionBuf");
rChannel = new FileInputStream(file).getChannel();
rChannel.read(g.connectionBuf);
rChannel.close();
file = new File(directoryAndBaseName+".nodeLabelBuf");
rChannel = new FileInputStream(file).getChannel();
rChannel.read(g.nodeLabelBuf);
rChannel.close();
file = new File(directoryAndBaseName+".edgeLabelBuf");
rChannel = new FileInputStream(file).getChannel();
rChannel.read(g.edgeLabelBuf);
rChannel.close();
return g;
}
/**
* Creates a graph with the size specified by numberOfNodes and numberOfEdges. Possibly includes parallel edges and self sourcing nodes.
* If the graph is simple, and there are too many edges for the nodes, an exception is thrown
*
* @param seed the random number generator seed, -1 for current time
* @param simple if true then no selfsourcing edges or parallel edges
* @throws FastGraphException If the desired number of edges is more than a complete graph for when simple is true
*/
public void populateRandomGraph(boolean simple, long seed) throws FastGraphException {
if(simple) {
if((numberOfNodes*(numberOfNodes-1))/2 < numberOfEdges) {
throw new FastGraphException("Too many edges to generate a simple graph.");
}
}
//long time;
if(seed == -1) {
seed = System.currentTimeMillis();
}
Random r = new Random(seed);
String[] nodeLabels = new String[numberOfNodes];
String[] edgeLabels = new String[numberOfEdges];
int inStart = -888;
int inLength = -3;
int outStart = -777;
int outLength = -2;
int weight = -5;
byte type = -7;
byte age = -9;
//generate the nodes
for(int i = 0; i < numberOfNodes; i++) {
weight = r.nextInt(100);
nodeBuf.putInt(NODE_IN_CONNECTION_START_OFFSET+i*NODE_BYTE_SIZE,inStart); // offset for inward connecting edges/nodes
nodeBuf.putInt(NODE_IN_DEGREE_OFFSET+i*NODE_BYTE_SIZE,inLength); // number of inward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_CONNECTION_START_OFFSET+i*NODE_BYTE_SIZE,outStart); // offset for outward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_DEGREE_OFFSET+i*NODE_BYTE_SIZE,outLength); // number of outward connecting edges/nodes
nodeBuf.putInt(NODE_WEIGHT_OFFSET+i*NODE_BYTE_SIZE,weight); // weight
nodeBuf.put(NODE_TYPE_OFFSET+i*NODE_BYTE_SIZE,type); // type
nodeBuf.put(NODE_AGE_OFFSET+i*NODE_BYTE_SIZE,age); // age
// store labels for later
String label = "n"+i;
nodeLabels[i] = label;
}
setAllNodeLabels(nodeLabels);
ArrayList<ArrayList<Integer>> nodeIn = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of inward edges
for(int i = 0; i < numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(100);
nodeIn.add(i,edges);
}
ArrayList<ArrayList<Integer>> nodeOut = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of outward edges
for(int i = 0; i < numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(100);
nodeOut.add(i,edges);
}
ArrayList<Integer> inEdgeList;
ArrayList<Integer> outEdgeList;
int node1;
int node2;
weight = -101;
type = -103;
age = -105;
//generate the edges, with random node connections
HashSet<String> nodePairs = new HashSet<String>();
if(simple) {
nodePairs = new HashSet<String>(numberOfEdges);
}
for(int i = 0; i < numberOfEdges; i++) {
weight = r.nextInt(100);
node1 = r.nextInt(numberOfNodes);
node2 = r.nextInt(numberOfNodes);
if(simple) {
boolean parallel = false;
String pairString1 = Integer.toString(node1)+" "+Integer.toString(node2);
String pairString2 = Integer.toString(node2)+" "+Integer.toString(node1);
if(nodePairs.contains(pairString1) || nodePairs.contains(pairString2) ) {
parallel = true;
}
while(node2 == node1 || parallel) {
node1 = r.nextInt(numberOfNodes);
node2 = r.nextInt(numberOfNodes);
pairString1 = Integer.toString(node1)+" "+Integer.toString(node2);
pairString2 = Integer.toString(node2)+" "+Integer.toString(node1);
if(nodePairs.contains(pairString1) || nodePairs.contains(pairString2) ) {
parallel = true;
} else {
parallel = false;
}
}
nodePairs.add(pairString1);
}
edgeBuf.putInt(EDGE_NODE1_OFFSET+i*EDGE_BYTE_SIZE,node1); // one end of edge
edgeBuf.putInt(EDGE_NODE2_OFFSET+i*EDGE_BYTE_SIZE,node2); // other end of edge
edgeBuf.putInt(EDGE_WEIGHT_OFFSET+i*EDGE_BYTE_SIZE,weight); // weight
edgeBuf.put(EDGE_TYPE_OFFSET+i*EDGE_BYTE_SIZE,type); // type
edgeBuf.put(EDGE_AGE_OFFSET+i*EDGE_BYTE_SIZE,age); // age
// label
String label = "e"+i;
edgeLabels[i] = label;
// store connecting nodes
inEdgeList = nodeIn.get(node2);
inEdgeList.add(i);
outEdgeList = nodeOut.get(node1);
outEdgeList.add(i);
}
setAllEdgeLabels(edgeLabels);
// Initialise the connection buffer, modifying the node buffer connection data
int offset = 0;
for(int i = 0; i < numberOfNodes; i++) {
// setting the in connection offset and length
ArrayList<Integer> inEdges = nodeIn.get(i);
int inEdgeLength = inEdges.size();
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_CONNECTION_START_OFFSET,offset);
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_DEGREE_OFFSET,inEdgeLength);
// now put the in edge/node pairs
for(int e : inEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+e*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+e*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+e+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,e);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
// setting the out connection offset and length
ArrayList<Integer> outEdges = nodeOut.get(i);
int outEdgeLength = outEdges.size();
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_CONNECTION_START_OFFSET,offset);
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_DEGREE_OFFSET,outEdgeLength);
// now put the out edge/node pairs
for(int e : outEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+e*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+e*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+e+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,e);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
}
//System.out.println("connection put time " + (System.currentTimeMillis()-time)/1000.0+" seconds, direct "+edgeBuf.isDirect());
}
/**
* Creates a graph from a displayGraph.Graph. label becomes the displayGraph.Graph name
* node and edge labels, are taken from displayGraph.Graph nodes and edges.
* node and edge weights are from displayGraph node and edge scores. Types are
* from displayGraph edgeType edgeType if they can be parsed as bytes,
* otherwise they get a default of -1. Node and edge Age is from displayGraph age, but
* only least significant byte, as the displayGraph age is a integer.
* Order of nodes and edges is as in the displayGraph.Graph
*
* @param displayGraph the graph that the new FastGraph is based on
* @param direct if true then off heap ByteBuffers, if false then on heap ByteBuffers
* @return new FastGraph with attributes based on the given displayGraph.
*/
public static FastGraph displayGraphFactory(Graph displayGraph, boolean direct) {
FastGraph g = new FastGraph(displayGraph.getNodes().size(),displayGraph.getEdges().size(),direct);
g.setName(displayGraph.getLabel());
g.populateFromDisplayGraph(displayGraph);
return g;
}
/**
* Populates byteBuffers based on the contents of the displayGraph.graph.
* Nodes and edges are in the order they appear in the displayGraph.
*
* @param displayGraph the graph that the new FastGraph is based on
*/
private void populateFromDisplayGraph(Graph displayGraph) {
String[] nodeLabels = new String[numberOfNodes];
String[] edgeLabels = new String[numberOfEdges];
int inStart = -27;
int inLength = -37;
int outStart = -47;
int outLength = -57;
int weight = -67;
byte type = -77;
byte age = -87;
ByteBuffer bb = ByteBuffer.allocate(4); // used to convert from int to byte, due to lack of direct casting
// nodes first, will be in the same order as the list in the displayGraph
for(int i = 0; i < numberOfNodes; i++) {
Node dgn = displayGraph.getNodes().get(i);
weight = (int)(dgn.getScore());
bb.putInt(0,dgn.getAge());
age = bb.get(3); // get least significant byte of age
try {
type = Byte.parseByte(dgn.getType().getLabel());
} catch(NumberFormatException e) {
type = -1;
}
nodeBuf.putInt(NODE_IN_CONNECTION_START_OFFSET+i*NODE_BYTE_SIZE,inStart); // offset for inward connecting edges/nodes
nodeBuf.putInt(NODE_IN_DEGREE_OFFSET+i*NODE_BYTE_SIZE,inLength); // number of inward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_CONNECTION_START_OFFSET+i*NODE_BYTE_SIZE,outStart); // offset for outward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_DEGREE_OFFSET+i*NODE_BYTE_SIZE,outLength); // number of outward connecting edges/nodes
nodeBuf.putInt(NODE_WEIGHT_OFFSET+i*NODE_BYTE_SIZE,weight); // weight
nodeBuf.put(NODE_TYPE_OFFSET+i*NODE_BYTE_SIZE,type); // type
nodeBuf.put(NODE_AGE_OFFSET+i*NODE_BYTE_SIZE,age); // age
// store labels for later
String label = dgn.getLabel();
nodeLabels[i] = label;
}
setAllNodeLabels(nodeLabels);
ArrayList<ArrayList<Integer>> nodeIn = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of inward edges
for(int i = 0; i < numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(100);
nodeIn.add(i,edges);
}
ArrayList<ArrayList<Integer>> nodeOut = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of outward edges
for(int i = 0; i < numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(100);
nodeOut.add(i,edges);
}
ArrayList<Integer> inEdgeList;
ArrayList<Integer> outEdgeList;
int node1;
int node2;
weight = -15;
type = -25;
age = -35;
// edges once nodes exist, will be in the same order as the list in the displayGraph
for(int i = 0; i < numberOfEdges; i++) {
Edge dge = displayGraph.getEdges().get(i);
node1 = displayGraph.getNodes().indexOf(dge.getFrom()); // we can find the FastGraph node index from its position in the displayGraph nodeList
node2 = displayGraph.getNodes().indexOf(dge.getTo()); // we can find the FastGraph node index from its position in the displayGraph nodeList
weight = (int)(dge.getScore());
bb.putInt(0,dge.getAge());
age = bb.get(3); // get least significant byte of age
try {
type = Byte.parseByte(dge.getType().getLabel());
} catch(NumberFormatException e) {
type = -1;
}
edgeBuf.putInt(EDGE_NODE1_OFFSET+i*EDGE_BYTE_SIZE,node1); // one end of edge
edgeBuf.putInt(EDGE_NODE2_OFFSET+i*EDGE_BYTE_SIZE,node2); // other end of edge
edgeBuf.putInt(EDGE_WEIGHT_OFFSET+i*EDGE_BYTE_SIZE,weight); // weight
edgeBuf.put(EDGE_TYPE_OFFSET+i*EDGE_BYTE_SIZE,type); // type
edgeBuf.put(EDGE_AGE_OFFSET+i*EDGE_BYTE_SIZE,age); // age
// store labels for later
String label = dge.getLabel();
edgeLabels[i] = label;
// store connecting nodes
inEdgeList = nodeIn.get(node2);
inEdgeList.add(i);
outEdgeList = nodeOut.get(node1);
outEdgeList.add(i);
}
setAllEdgeLabels(edgeLabels);
// Initialise the connection buffer, modifying the node buffer connection data
//time = System.currentTimeMillis();
int offset = 0;
for(int i = 0; i < numberOfNodes; i++) {
// setting the in connection offset and length
ArrayList<Integer> inEdges = nodeIn.get(i);
int inEdgeLength = inEdges.size();
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_CONNECTION_START_OFFSET,offset);
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_DEGREE_OFFSET,inEdgeLength);
// now put the in edge/node pairs
for(int edgeIndex : inEdges) {
int nodeIndex = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
if(n1 == i) {
nodeIndex = n2;
} else if(n2 == i) {
nodeIndex = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+edgeIndex+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,edgeIndex);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,nodeIndex);
offset += CONNECTION_PAIR_SIZE;
}
// setting the out connection offset and length
ArrayList<Integer> outEdges = nodeOut.get(i);
int outEdgeLength = outEdges.size();
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_CONNECTION_START_OFFSET,offset);
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_DEGREE_OFFSET,outEdgeLength);
// now put the out edge/node pairs
for(int edgeIndex : outEdges) {
int nodeIndex = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
if(n1 == i) {
nodeIndex = n2;
} else if(n2 == i) {
nodeIndex = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+edgeIndex+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,edgeIndex);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,nodeIndex);
offset += CONNECTION_PAIR_SIZE;
}
}
}
/**
* Generates a new graph from the subgraph specified by the parameters. All
* edges connected to deleted nodes are also removed.
*
*
* @param nodesToDelete nodes in this graph that will not appear in the new graph
* @param edgesToDelete edges in this graph that will not appear in the new graph
* @param orphanEdgeCheckNeeded If the method calling this has already checked for orphan nodes, then false.
* @return the new FastGraph
*/
public FastGraph generateGraphByDeletingItems(int[] nodesToDelete, int[] edgesToDelete, boolean orphanEdgeCheckNeeded) {
System.out.println("Nodes to remove: " + Arrays.toString(nodesToDelete));
long time = System.currentTimeMillis();
LinkedList<Integer> allEdgesToDeleteList = new LinkedList<Integer>();
LinkedList<Integer> allNodesToDeleteList = new LinkedList<Integer>();
System.out.println("Z setup " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
for(int e : edgesToDelete) {
allEdgesToDeleteList.add(e);
}
// delete the edges connecting to deleted nodes and create the node list
for(int n : nodesToDelete) {
allNodesToDeleteList.add(n);
if(orphanEdgeCheckNeeded) { //only check for orphan nodes if needed
int[] connectingEdges = getNodeConnectingEdges(n);
for(int e : connectingEdges) {
if(!allEdgesToDeleteList.contains(e)) {
allEdgesToDeleteList.add(e);
}
}
}
}
System.out.println("A Created the node and edge delete lists " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
// find the nodes that will remain
HashSet<Integer> remainingNodeList = new HashSet<Integer>(allNodesToDeleteList.size()*3);
for(int i = 0; i < getNumberOfNodes(); i++) {
remainingNodeList.add(i);
}
remainingNodeList.removeAll(allNodesToDeleteList); //this is quicker than checking each entry
System.out.println("AAA created the node remain lists " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
// turn it into an array
int[] remainingNodes = Util.convertHashSet(remainingNodeList);
System.out.println("AA converted the node remain lists " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
// find the edges that will remain
HashSet<Integer> remainingEdgeList = new HashSet<Integer>(allEdgesToDeleteList.size()*3);
for(int i = 0; i < getNumberOfEdges(); i++) {
remainingEdgeList.add(i);
}
remainingEdgeList.removeAll(allEdgesToDeleteList);
System.out.println("AB Created the edge remain lists " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
// turn it into an array
int[] remainingEdges = Util.convertHashSet(remainingEdgeList);
System.out.println("B converted the edge remain lists " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
FastGraph g = generateGraphFromSubgraph(remainingNodes,remainingEdges);
return g;
}
/**
* Generates a new graph from the subgraph specified by the parameters. The nodes at the end of the edges must be in subgraphEdges.
*
* @param subgraphNodes nodes in this graph that will appear in the new graph
* @param subgraphEdges edges in this graph that will appear in the new graph, must connect only to subgraphNodes
* @return the new FastGraph
*/
public FastGraph generateGraphFromSubgraph(int[] subgraphNodes, int[] subgraphEdges) {
long time = System.currentTimeMillis();
FastGraph g = new FastGraph(subgraphNodes.length, subgraphEdges.length, getDirect());
String[] nodeLabels = new String[subgraphNodes.length]; // stores the labels for creating the nodeLabelBuffer
HashMap<Integer,Integer> oldNodesToNew = new HashMap<>(subgraphNodes.length*4); // for reference when adding edges, multiplier reduces chances of clashes
// initial population of the new node array
int weight = -98;
byte type = -97;
byte age = -96;
int index = 0;
for(int n : subgraphNodes) {
weight = nodeBuf.getInt(NODE_WEIGHT_OFFSET+n*NODE_BYTE_SIZE);
type = nodeBuf.get(NODE_TYPE_OFFSET+n*NODE_BYTE_SIZE);
age = nodeBuf.get(NODE_AGE_OFFSET+n*NODE_BYTE_SIZE);
g.nodeBuf.putInt(NODE_WEIGHT_OFFSET+index*NODE_BYTE_SIZE,weight);
g.nodeBuf.put(NODE_TYPE_OFFSET+index*NODE_BYTE_SIZE,type);
g.nodeBuf.put(NODE_AGE_OFFSET+index*NODE_BYTE_SIZE,age);
// store labels for later
nodeLabels[index] = getNodeLabel(n);
// store old to new mapping for later
oldNodesToNew.put(n, index);
index++;
}
//System.out.println("C popluated the new node buffer " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
g.setAllNodeLabels(nodeLabels); // create the node label buffer
//System.out.println("D popluated the new node list buffer " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
ArrayList<ArrayList<Integer>> nodeIn = new ArrayList<ArrayList<Integer>>(subgraphNodes.length); // temporary store of inward edges
for(int nodeIndex = 0; nodeIndex < subgraphNodes.length; nodeIndex++) {
ArrayList<Integer> edges = new ArrayList<Integer>(100);
nodeIn.add(nodeIndex,edges);
}
ArrayList<ArrayList<Integer>> nodeOut = new ArrayList<ArrayList<Integer>>(subgraphNodes.length); // temporary store of outward edges
for(int nodeIndex = 0; nodeIndex < subgraphNodes.length; nodeIndex++) {
ArrayList<Integer> edges = new ArrayList<Integer>(100);
nodeOut.add(nodeIndex,edges);
}
//System.out.println("E created the neighbour store " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
//System.out.println(oldNodesToNew);
String[] edgeLabels = new String[subgraphEdges.length]; // stores the labels for creating the edgeLabelBuffer
ArrayList<Integer> inEdgeList;
ArrayList<Integer> outEdgeList;
// create the edges
index = 0;
edgeBuf.position(0);
g.edgeBuf.position(0);
for(int e : subgraphEdges) {
weight = edgeBuf.getInt(EDGE_WEIGHT_OFFSET+e*EDGE_BYTE_SIZE);
type = edgeBuf.get(EDGE_TYPE_OFFSET+e*EDGE_BYTE_SIZE);
age = edgeBuf.get(EDGE_AGE_OFFSET+e*EDGE_BYTE_SIZE);
g.edgeBuf.putInt(EDGE_WEIGHT_OFFSET+index*EDGE_BYTE_SIZE,weight);
g.edgeBuf.put(EDGE_TYPE_OFFSET+index*EDGE_BYTE_SIZE,type);
g.edgeBuf.put(EDGE_AGE_OFFSET+index*EDGE_BYTE_SIZE,age);
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+e*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+e*EDGE_BYTE_SIZE);
//System.out.print("old node n1: " + n1);
int gn1 = oldNodesToNew.get(n1);
//System.out.print(", new node n1: " + gn1);
//System.out.print(", old node n2: " + n2);
int gn2 = oldNodesToNew.get(n2);
//System.out.print(", new node n2: " + gn2);
//System.out.println();
g.edgeBuf.putInt(EDGE_NODE1_OFFSET+index*EDGE_BYTE_SIZE,gn1); // one end of edge
g.edgeBuf.putInt(EDGE_NODE2_OFFSET+index*EDGE_BYTE_SIZE,gn2); // other end of edge
// store labels for later
edgeLabels[index] = getEdgeLabel(e);
// store connecting edges
inEdgeList = nodeIn.get(gn2);
inEdgeList.add(index);
outEdgeList = nodeOut.get(gn1);
outEdgeList.add(index);
index++;
}
//System.out.println("F populated the new edge buffer " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
g.setAllEdgeLabels(edgeLabels);
//System.out.println("G populated the new edge label buffer " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
// Initialise the connection buffer, modifying the node buffer connection data
//time = System.currentTimeMillis();
int offset = 0;
for(int node = 0; node < subgraphNodes.length; node++) {
if(node%100000 == 0) {
//System.out.println("H populated "+node+" nodes in connection buffer " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
}
// setting the in connection offset and length
ArrayList<Integer> inEdges = nodeIn.get(node);
int inEdgeLength = inEdges.size();
g.nodeBuf.putInt(node*NODE_BYTE_SIZE+NODE_IN_CONNECTION_START_OFFSET,offset);
g.nodeBuf.putInt(node*NODE_BYTE_SIZE+NODE_IN_DEGREE_OFFSET,inEdgeLength);
// now put the in edge/node pairs
for(int edgeIndex : inEdges) {
int nodeIndex = -1;
int n1 = g.edgeBuf.getInt(EDGE_NODE1_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
int n2 = g.edgeBuf.getInt(EDGE_NODE2_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
if(n1 == node) {
nodeIndex = n2;
} else if(n2 == node) {
nodeIndex = n1;
} else {
System.out.println("ERROR A When finding connections for node "+node+" connecting edge "+edgeIndex+ " has connecting nodes "+n1+" "+n2);
}
g.connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,edgeIndex);
g.connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,nodeIndex);
offset += CONNECTION_PAIR_SIZE;
}
// setting the out connection offset and length
ArrayList<Integer> outEdges = nodeOut.get(node);
int outEdgeLength = outEdges.size();
g.nodeBuf.putInt(node*NODE_BYTE_SIZE+NODE_OUT_CONNECTION_START_OFFSET,offset);
g.nodeBuf.putInt(node*NODE_BYTE_SIZE+NODE_OUT_DEGREE_OFFSET,outEdgeLength);
// now put the out edge/node pairs
for(int edgeIndex : outEdges) {
int nodeIndex = -1;
int n1 = g.edgeBuf.getInt(EDGE_NODE1_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
int n2 = g.edgeBuf.getInt(EDGE_NODE2_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
if(n1 == node) {
nodeIndex = n2;
} else if(n2 == node) {
nodeIndex = n1;
} else {
System.out.println("ERROR B When finding connections for node "+node+" connecting edge "+edgeIndex+ " has connecting nodes "+n1+" "+n2);
}
g.connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,edgeIndex);
g.connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,nodeIndex);
offset += CONNECTION_PAIR_SIZE;
}
}
return g;
}
/**
* @return the largest degree for a node in the graph.
*/
public int maximumDegree() {
int max = 0;
for(int i = 0; i < numberOfNodes; i++) {
int inDegree = nodeBuf.getInt(NODE_IN_DEGREE_OFFSET+i*NODE_BYTE_SIZE);
int outDegree = nodeBuf.getInt(NODE_OUT_DEGREE_OFFSET+i*NODE_BYTE_SIZE);
int degree = inDegree+outDegree;
if(degree > max) {
max = degree;
}
}
return max;
}
/**
* Creates a displayGraph.Graph which can then be accessed, manipulated and visualized
* using that package. displayGraph.Graph name becomes this FastGraph label
* The displayGraph.Graph node and edge labels, are taken
* from this FastGraph nodes and edges. node and edge weights become node
* and edge scores node and edge ages become ages in displayGraph nodes and edges.
* New NodeType and EdgeType are created if needed with label of the integer of this type.
* Order of nodes and edges in the displayGraph.Graph is as this FastGraph.
*
* @return a displayGraph.Graph with the same data as this Fast Graph
*/
public Graph generateDisplayGraph() {
Graph g = new Graph(getName());
for(int i = 0; i < numberOfNodes; i++) {
Node n = new Node();
n.setLabel(getNodeLabel(i));
n.setScore(getNodeWeight(i));
n.setAge(getNodeAge(i));
String typeLabel = Integer.toString(getNodeType(i));
NodeType type = NodeType.withLabel(typeLabel);
if(type == null) {
type = new NodeType(typeLabel);
}
n.setType(type);
g.addNode(n);
}
for(int i = 0; i < numberOfEdges; i++) {
Node n1 = g.getNodes().get(getEdgeNode1(i));
Node n2 = g.getNodes().get(getEdgeNode2(i));
Edge e = new Edge(n1,n2);
e.setLabel(getEdgeLabel(i));
e.setScore(getEdgeWeight(i));
e.setAge(getEdgeAge(i));
String typeLabel = Integer.toString(getEdgeType(i));
EdgeType type = EdgeType.withLabel(typeLabel);
if(type == null) {
type = new EdgeType(typeLabel);
}
e.setType(type);
g.addEdge(e);
}
return g;
}
/**
* Counts the number of instances of nodes with various degrees.
*
* @param maxDegrees The maximum number of degrees to look for. If given 3, will count all nodes with degrees 0,1,2.
* @return The list of number of nodes at each degree.
*/
public int[] countInstancesOfNodeDegrees(int maxDegrees) {
int[] res = new int[maxDegrees];
for(int n = 0; n < getNumberOfNodes(); n++) {
int deg = getNodeDegree(n);
if (deg < maxDegrees) {
//System.out.print(deg + " ");
//System.out.println(res[deg]);
res[deg]++;
}
}
return res;
}
/**
* Check the consistency of a graph. Checks: <ul>
* <li> If edges link to node indexes outside of the current range</li>
* <li> If all edges are reflected in the connection lists</li>
* <li> If the connection list data points to the correct edges</li>
* <li> If the nodes and edges in the connection list are correct</li>
* </ul>
*
* @return true if the graph is consistent, false otherwise
*/
public boolean checkConsistency() {
// consistency of edges
for(int e = 0; e < getNumberOfEdges(); e++) {
int node1 = getEdgeNode1(e);
int node2 = getEdgeNode2(e);
if(node1 < 0 || node1 >= getNumberOfNodes()) {
Debugger.log("INCONSISTENT. Edge "+e+" has node1 "+node1+ " but there are only "+getNumberOfNodes()+" nodes");
return false;
}
if(node2 < 0 || node2 >= getNumberOfNodes()) {
Debugger.log("INCONSISTENT. Edge "+e+" has node2 "+node2+ " but there are only "+getNumberOfNodes()+" nodes");
return false;
}
if(!Util.convertArray(getNodeConnectingOutEdges(node1)).contains(e)) {
Debugger.log("INCONSISTENT. Edge "+e+" has node1 "+node1+ " but it is not in the node out list");
return false;
}
if(!Util.convertArray(getNodeConnectingInEdges(node2)).contains(e)) {
Debugger.log("INCONSISTENT. Edge "+e+" has node2 "+node2+ " but it is not in the node in list");
return false;
}
}
// consistency of nodes and connection lists
for(int n = 0; n < getNumberOfNodes(); n++) {
if(getNodeConnectingOutEdges(n).length != getNodeConnectingOutNodes(n).length) {
Debugger.log("INCONSISTENT. Node "+n+" has different number of out edges to out nodes");
return false;
}
if(getNodeConnectingInEdges(n).length != getNodeConnectingInNodes(n).length) {
Debugger.log("INCONSISTENT. Node "+n+" has different number of in edges to in nodes");
return false;
}
for(int i = 0; i < getNodeConnectingOutEdges(n).length; i++) {
int connectingEdge = getNodeConnectingOutEdges(n)[i];
int otherEnd = oppositeEnd(connectingEdge, n);
int connectingNode = getNodeConnectingOutNodes(n)[i];
if(otherEnd != connectingNode) {
Debugger.log("INCONSISTENT. Node "+n+" has inconsitent edge and node in connecting out list");
return false;
}
if(n != oppositeEnd(connectingEdge, otherEnd)) {
Debugger.log("INCONSISTENT. Node "+n+" has edge in connecting out list that does not point to the node");
return false;
}
}
for(int i = 0; i < getNodeConnectingInEdges(n).length; i++) {
int connectingEdge = getNodeConnectingInEdges(n)[i];
int otherEnd = oppositeEnd(connectingEdge, n);
int connectingNode = getNodeConnectingInNodes(n)[i];
if(otherEnd != connectingNode) {
Debugger.log("INCONSISTENT. Node "+n+" has inconsitent edge and node in connecting in list");
return false;
}
if(n != oppositeEnd(connectingEdge, otherEnd)) {
Debugger.log("INCONSISTENT. Node "+n+" has edge in connecting in list that does not point to the node");
return false;
}
}
}
return true;
}
}
|
package com.pizza.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Table(name="T_ORDERED_ITEM")
public class HOrderedItem {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "ITEM", nullable = false)
@Enumerated(EnumType.STRING)
private Item item;
@Column(name = "COUNT", nullable = false)
private int count;
@Column(name = "USER", nullable = false)
private String user;
@Column(name = "DETAILS", nullable = false)
private String details;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ORDER_ID", nullable=false)
@JsonIgnore
private HOrder order;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public HOrder getOrder() {
return order;
}
public void setOrder(HOrder order) {
this.order = order;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
|
package uk.ac.kent.dover.fastGraph;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
import org.json.*;
import uk.ac.kent.displayGraph.*;
import Jama.Matrix;
import Jama.EigenvalueDecomposition;
public class FastGraph {
private static final int NODE_LABEL_START_OFFSET = 0; // integer
private static final int NODE_LABEL_LENGTH_OFFSET = 4; // short
private static final int NODE_IN_CONNECTION_START_OFFSET = 6; // integer
private static final int NODE_IN_DEGREE_OFFSET = 10; // short
private static final int NODE_OUT_CONNECTION_START_OFFSET = 12; // integer
private static final int NODE_OUT_DEGREE_OFFSET = 16; // short
private static final int NODE_WEIGHT_OFFSET = 18; // integer
private static final int NODE_TYPE_OFFSET = 22; // byte
private static final int NODE_AGE_OFFSET = 23; // byte
private static final int EDGE_NODE1_OFFSET = 0; // integer
private static final int EDGE_NODE2_OFFSET = 4; // integer
private static final int EDGE_LABEL_START_OFFSET = 8; // integer
private static final int EDGE_LABEL_LENGTH_OFFSET = 12; // short
private static final int EDGE_WEIGHT_OFFSET = 14; // integer
private static final int EDGE_TYPE_OFFSET = 18; // byte
private static final int EDGE_AGE_OFFSET = 19; // byte
private static final int CONNECTION_EDGE_OFFSET = 0; // integer, edge is first of the pair
private static final int CONNECTION_NODE_OFFSET = 4; // integer, node is straight after the edge
public static final int DEFAULT_AVERAGE_LABEL_LENGTH = 20;
private static final int NODE_BYTE_SIZE = 24;
private static final int EDGE_BYTE_SIZE = 20;
private static final int CONNECTION_PAIR_SIZE = 8; // this is an edge index plus an node index
public static final String INFO_SPLIT_STRING = "~";
public static final int MAX_BYTE_BUFFER_SIZE = Integer.MAX_VALUE-5000;
private ByteBuffer nodeBuf;
private ByteBuffer edgeBuf;
private ByteBuffer connectionBuf;
private ByteBuffer nodeLabelBuf;
private ByteBuffer edgeLabelBuf;
private int numberOfNodes;
private int numberOfEdges;
private String name = "";
private boolean direct;
/**
* No direct access to constructor, as a number of data structures need to be created when
* graph nodes and edges are added.
*
* @param nodeTotal the number of nodes in the graph
* @param edgeTotal the number of edges in the graph
* @param direct if true then off heap ByteBuffers, if false then on heap ByteBuffers
*/
private FastGraph(int nodeTotal, int edgeTotal, boolean direct) {
this.numberOfNodes = nodeTotal;
this.numberOfEdges = edgeTotal;
this.direct = direct;
init();
}
/**
* @param args not used
* @throws Exception
*/
public static void main(String[] args) throws Exception {
long time;
// FastGraph g1 = randomGraphFactory(2,1,false);
// FastGraph g1 = randomGraphFactory(5,6,true);
// FastGraph g1 = randomGraphFactory(10000,100000,false); // 10 thousand nodes, 100 thousand edges
// FastGraph g1 = randomGraphFactory(1000000,10000000,false); // 1 million nodes, 10 million edges
// FastGraph g1 = randomGraphFactory(5000000,50000000,false); // limit for edgeLabelBuf at 20 chars per label
// FastGraph g1 = randomGraphFactory(4847571,68993773,false); // Size of LiveJournal1 example from SNAP
// FastGraph g1 = randomGraphFactory(10000000,100000000,false); // 10 million nodes, 100 million edges, close to edgeBuf limit, but fails on heap space with 14g, but pass with heap space of 30g
// time = System.currentTimeMillis();
FastGraph g1 = adjacencyListGraphFactory(7115,103689,null,"Wiki-Vote.txt",false);
// FastGraph g1 = adjacencyListGraphFactory(36692,367662,null,"Email-Enron1.txt",false);
// FastGraph g1 = adjacencyListGraphFactory(81306,2420766,null,"twitter_combined.txt",false); // SNAP web page gives 1768149 edges
// FastGraph g1 = adjacencyListGraphFactory(1632803,30622564,null,"soc-pokec-relationships.txt",false);
// FastGraph g1 = adjacencyListGraphFactory(4847571,68993773,null,"soc-LiveJournal1.txt",false);
//System.out.println("snap load time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
g1.saveBuffers(null,g1.getName());
System.out.println("saveBuffers test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
/*
Graph displayGraph = g1.generateDisplayGraph();
displayGraph.randomizeNodePoints(new Point(50,50), 200, 200);
uk.ac.kent.displayGraph.display.GraphWindow gw = new uk.ac.kent.displayGraph.display.GraphWindow(displayGraph);
time = System.currentTimeMillis();
String name = "random-n-2-e-1";
// String name = g1.getName();
FastGraph g2;
try {
g2 = loadBuffersGraphFactory(null,name);
System.out.println("create graph from file test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
time = System.currentTimeMillis();
boolean connected = g2.isConnected();
System.out.println("connected test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
System.out.println("connected "+connected);
time = System.currentTimeMillis();
int[][] matrix = g2.buildIntAdjacencyMatrix();
//boolean[][] matrix = g2.buildBooleanAdjacencyMatrix();
System.out.println("building matrix test time " + (System.currentTimeMillis()-time)/1000.0+" seconds");
g2.printMatrix(matrix);
System.out.println(Arrays.toString(g2.findEigenvalues(matrix)));
System.out.println(matrix.length);
} catch (Exception e) {
e.printStackTrace();
}
*/
}
/**
* @return the number of nodes in the graph
*/
public int getNumberOfNodes() {
return numberOfNodes;
}
/**
* @return the number of edges in the graph
*/
public int getNumberOfEdges() {
return numberOfEdges;
}
/**
* Names should be simple alphanumeric. Spaces and dashes are permitted. Note that tilde ("~") cannot be used.
* @param name the name of the graph
*/
public void setName(String name) {
this.name = name;
}
/**
* @param nodeIndex the node
* @return the node label
*/
public String getNodeLabel(int nodeIndex) {
int labelStart = nodeBuf.getInt(NODE_LABEL_START_OFFSET+nodeIndex*NODE_BYTE_SIZE);
int labelLength = nodeBuf.getShort(NODE_LABEL_LENGTH_OFFSET+nodeIndex*NODE_BYTE_SIZE);
char[] label = new char[labelLength];
for(int i = 0; i < labelLength; i++) {
int offset = labelStart+i*2;
char c = nodeLabelBuf.getChar(offset);
label[i] = c;
}
String ret = new String(label);
return ret;
}
/**
* @param nodeIndex the node
* @return the node weight
*/
public int getNodeWeight(int nodeIndex) {
int type= nodeBuf.getInt(NODE_WEIGHT_OFFSET+nodeIndex*NODE_BYTE_SIZE);
return type;
}
/**
* @param nodeIndex the node
* @return the node type
*/
public byte getNodeType(int nodeIndex) {
byte type= nodeBuf.get(NODE_TYPE_OFFSET+nodeIndex*NODE_BYTE_SIZE);
return type;
}
/**
* @param nodeIndex the node
* @return the node age
*/
public byte getNodeAge(int nodeIndex) {
byte age = nodeBuf.get(NODE_AGE_OFFSET+nodeIndex*NODE_BYTE_SIZE);
return age;
}
/**
* @param nodeIndex the node
* @return the node degree (number of connecting edges)
*/
public int getNodeDegree(int nodeIndex) {
int degree = getNodeInDegree(nodeIndex)+getNodeOutDegree(nodeIndex);
return degree;
}
/**
* @param nodeIndex the node
* @return the node in-degree (number of edges entering the node)
*/
public short getNodeInDegree(int nodeIndex) {
short degree = nodeBuf.getShort(NODE_IN_DEGREE_OFFSET+nodeIndex*NODE_BYTE_SIZE);
return degree;
}
/**
* @param nodeIndex the node
* @return the node out-degree (number of edges leaving the node)
*/
public short getNodeOutDegree(int nodeIndex) {
short degree = nodeBuf.getShort(NODE_OUT_DEGREE_OFFSET+nodeIndex*NODE_BYTE_SIZE);
return degree;
}
/**
* @param nodeIndex the node
* @return all connecting edges
*/
public int[] getNodeConnectingEdges(int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeDegree(nodeIndex);
int[] ret = new int[degree];
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_EDGE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
return ret;
}
/**
* This version puts the connecting edges in the argument array, to avoid repeated object creation and so speed up multiple accesses.
* create array with size of either getNodeDegree(nodeIndex) or maxDegree(). array elements beyond nodeDegree(nodeIndex)-1 are undefined.
* Will throw an exception if ret is not large enough.
*
* @param ret this is populated with the connecting edges found
* @param nodeIndex the node
* @return all connecting edges via parameter array.
*/
public void getNodeConnectingEdges(int[] ret, int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeDegree(nodeIndex);
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_EDGE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
}
/**
* @param nodeIndex the node
* @return all node neighbours.
*/
public int[] getNodeConnectingNodes(int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeDegree(nodeIndex);
int[] ret = new int[degree];
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_NODE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
return ret;
}
/**
* This version puts the connecting nodes in the argument array, to avoid repeated object creation and so speed up multiple accesses.
* create array with size of either getNodeDegree(nodeIndex) or maxDegree(). array elements beyond nodeDegree(nodeIndex)-1 are undefined.
* Will throw an exception if ret is not large enough.
*
* @param ret this is populated with the connecting nodes found
* @param nodeIndex the node
* @return all node neighbours.
*/
public void getNodeConnectingNodes(int[] ret, int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeDegree(nodeIndex);
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_NODE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
}
/**
* For directed graphs.
*
* @param nodeIndex the node
* @return all connecting edges for the node
*/
public int[] getNodeConnectingInEdges(int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeInDegree(nodeIndex);
int[] ret = new int[degree];
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_EDGE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
return ret;
}
/**
* For directed graphs.
* This version puts the connecting edges in the argument array, to avoid repeated object creation and so speed up multiple accesses.
* create array with size of either getNodeInDegree(nodeIndex) or maxDegree(). array elements beyond nodeDegree(nodeIndex)-1 are undefined.
* Will throw an exception if ret is not large enough.
*
* @param ret this is populated with the connecting edges found
* @param nodeIndex the node
* @return all connecting edges that enter the node via the parameter array.
*/
public void getNodeConnectingInEdges(int[] ret, int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeInDegree(nodeIndex);
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_EDGE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
}
/**
* For directed graphs.
*
* @param nodeIndex the node
* @return all node neighbours that are on the end of edges that enter the node.
*/
public int[] getNodeConnectingInNodes(int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeInDegree(nodeIndex);
int[] ret = new int[degree];
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_NODE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
return ret;
}
/**
* For directed graphs.
* This version puts the connecting nodes in the argument array, to avoid repeated object creation and so speed up multiple accesses.
* create array with size of either getNodeInDegree(nodeIndex) or maxDegree(). array elements beyond nodeDegree(nodeIndex)-1 are undefined.
* Will throw an exception if ret is not large enough.
*
* @param ret this is populated with the connecting nodes found
* @param nodeIndex the node
* @return all node neighbours that are on the end of edges that enter the node via the parameter array.
*/
public void getNodeConnectingInNodes(int[] ret, int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeInDegree(nodeIndex);
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_NODE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
}
/**
* For directed graphs.
*
* @param nodeIndex the node
* @return all edges that leave the node.
*/
public int[] getNodeConnectingOutEdges(int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_OUT_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeOutDegree(nodeIndex);
int[] ret = new int[degree];
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_EDGE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
return ret;
}
/**
* For directed graphs.
* This version puts the connecting nodes in the argument array, to avoid repeated object creation and so speed up multiple accesses.
* create array with size of either getNodeOutDegree(nodeIndex) or maxDegree(). array elements beyond nodeDegree(nodeIndex)-1 are undefined.
* Will throw an exception if ret is not large enough.
*
* @param ret this is populated with the connecting edges found
* @param nodeIndex the node
* @return all edges that leave the node via the argument array.
*/
public void getNodeConnectingOutEdges(int[] ret, int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_OUT_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeOutDegree(nodeIndex);
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_EDGE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
}
/**
* For directed graphs.
*
* @param nodeIndex the node
* @return all node neighbours that are on the end of edges that leave the passed node.
*/
public int[] getNodeConnectingOutNodes(int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_OUT_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeOutDegree(nodeIndex);
int[] ret = new int[degree];
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_NODE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
return ret;
}
/**
* For directed graphs.
* This version puts the connecting nodes in the argument array, to avoid repeated object creation and so speed up multiple accesses.
* create array with size of either getNodeOutDegree(nodeIndex) or maxDegree(). array elements beyond nodeDegree(nodeIndex)-1 are undefined.
* Will throw an exception if ret is not large enough.
*
* @param ret this is populated with the connecting nodes found
* @param nodeIndex the node
* @return all node neighbours that are on the end of edges that leave the passed node via the parameter array.
*/
public void getNodeConnectingOutNodes(int[] ret, int nodeIndex) {
int connectionOffset = nodeBuf.getInt(NODE_OUT_CONNECTION_START_OFFSET+nodeIndex*NODE_BYTE_SIZE); // in offset is the first one
int degree = getNodeOutDegree(nodeIndex);
for(int i = 0; i < degree; i++) {
// don't need the edge, so step over edge/node pairs and the ege
int nodeOffset = connectionOffset+(i*CONNECTION_PAIR_SIZE)+CONNECTION_NODE_OFFSET;
int node = connectionBuf.getInt(nodeOffset);
ret[i] = node;
}
}
/**
* @param edgeIndex the edge
* @return the edge label
*/
public String getEdgeLabel(int edgeIndex) {
int labelStart = edgeBuf.getInt(EDGE_LABEL_START_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
int labelLength = edgeBuf.getShort(EDGE_LABEL_LENGTH_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
char[] label = new char[labelLength];
for(int i = 0; i < labelLength; i++) {
int offset = labelStart+i*2;
char c = edgeLabelBuf.getChar(offset);
label[i] = c;
}
String ret = new String(label);
return ret;
}
/**
* @param edgeIndex the edge
* @return the first connecting node (the node the edge leaves for directed graphs).
*/
public int getEdgeNode1(int edgeIndex) {
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
return n1;
}
/**
* @param edgeIndex the edge
* @return the second connecting node (the node the edge enters for directed graphs).
*/
public int getEdgeNode2(int edgeIndex) {
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
return n2;
}
/**
* @param edgeIndex the edge
* @return the edge weight
*/
public int getEdgeWeight(int edgeIndex) {
int type= edgeBuf.getInt(EDGE_WEIGHT_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
return type;
}
/**
* @param edgeIndex the edge
* @return the edge type
*/
public byte getEdgeType(int edgeIndex) {
byte type= edgeBuf.get(EDGE_TYPE_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
return type;
}
/**
* @param edgeIndex the edge
* @return the edge age
*/
public byte getEdgeAge(int edgeIndex) {
byte age = edgeBuf.get(EDGE_AGE_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
return age;
}
/**
* @return the graph name
*/
public String getName() {
return name;
}
/**
* Change all the node labels in the graph. Creates a new nodeLabelBuf, changes the label pointers in nodeBuf.
*
* @param labels Must contain the same number of labels as number of nodes in the graph
*/
public void setAllNodeLabels(String[] labels) {
long totalLabelLength = 0;
for(int i = 0; i < numberOfNodes; i++) {
totalLabelLength += labels[i].length();
}
if(totalLabelLength*2 > MAX_BYTE_BUFFER_SIZE) {
throw new OutOfMemoryError("Tried to create a nodeLabelBuf with too many chars");
}
int bufSize = (int)(totalLabelLength*2); // this cast is safe because of the previous test
if(!direct) {
nodeLabelBuf = ByteBuffer.allocate(bufSize);
} else {
nodeLabelBuf = ByteBuffer.allocateDirect(bufSize);
}
nodeLabelBuf.clear();
int labelOffset = 0;
for(int i = 0; i < numberOfNodes; i++) {
String label = labels[i];
char[] labelArray = label.toCharArray();
short labelLength = (short)(labelArray.length);
nodeBuf.putInt(NODE_LABEL_START_OFFSET+i*NODE_BYTE_SIZE,labelOffset); // label start
nodeBuf.putShort(NODE_LABEL_LENGTH_OFFSET+i*NODE_BYTE_SIZE,labelLength); // label size
for(int j = 0; j < labelArray.length; j++) {
char c = labelArray[j];
nodeLabelBuf.putChar(labelOffset,c);
labelOffset += 2; // increment by 2 as it is a char (2 bytes)
}
}
}
/**
* Change all the edge labels in the graph. Creates a new edgeLabelBuf, changes the label pointers in edgeBuf
*
* @param labels Must contain the same number of labels as there are edges in the graph
* @throws OutofMemoryError
*/
public void setAllEdgeLabels(String[] labels) {
long totalLabelLength = 0;
for(int i = 0; i < numberOfEdges; i++) {
totalLabelLength += labels[i].length();
}
if(totalLabelLength*2 > MAX_BYTE_BUFFER_SIZE) {
throw new OutOfMemoryError("Tried to create a edgeLabelBuf with too many chars");
}
int bufSize = (int)(totalLabelLength*2); // this cast is safe because of the previous test
if(!direct) {
edgeLabelBuf = ByteBuffer.allocate(bufSize);
} else {
edgeLabelBuf = ByteBuffer.allocateDirect(bufSize);
}
edgeLabelBuf.clear();
int labelOffset = 0;
for(int i = 0; i < numberOfEdges; i++) {
String label = labels[i];
char[] labelArray = label.toCharArray();
short labelLength = (short)(labelArray.length);
edgeBuf.putInt(EDGE_LABEL_START_OFFSET+i*EDGE_BYTE_SIZE,labelOffset); // label start
edgeBuf.putShort(EDGE_LABEL_LENGTH_OFFSET+i*EDGE_BYTE_SIZE,labelLength); // label size
for(int j = 0; j < labelArray.length; j++) {
char c = labelArray[j];
edgeLabelBuf.putChar(labelOffset,c);
labelOffset += 2; // increment by 2 as it is a char (2 bytes)
}
}
}
/**
* Allocates space for the node, edge and connection ByteBuffers. The label ByteBuffers
* are created later
*/
private void init() {
if(!direct) {
nodeBuf = ByteBuffer.allocate(numberOfNodes*NODE_BYTE_SIZE);
edgeBuf = ByteBuffer.allocate(numberOfEdges*EDGE_BYTE_SIZE);
connectionBuf = ByteBuffer.allocate(numberOfEdges*2*CONNECTION_PAIR_SIZE);
// nodeLabelBuf and edgeLabelBuf now created in Factories by setAllNodeLabels
} else {
nodeBuf = ByteBuffer.allocateDirect(numberOfNodes*NODE_BYTE_SIZE);
edgeBuf = ByteBuffer.allocateDirect(numberOfEdges*EDGE_BYTE_SIZE);
connectionBuf = ByteBuffer.allocateDirect(numberOfEdges*2*CONNECTION_PAIR_SIZE);
// nodeLabelBuf and edgeLabelBuf now created in Factories by setAllNodeLabels
}
nodeBuf.clear();
edgeBuf.clear();
connectionBuf.clear();
}
/**
* Create a FastGraph from a json string.
*
* @param json the json as a string
* @param direct if true then off heap ByteBuffers, if false then on heap ByteBuffers
* @return the created FastGraph.
*/
public static FastGraph jsonStringGraphFactory(String json, boolean direct) {
int nodeCount = 0;
int edgeCount = 0;
JSONObject jsonObj = new JSONObject(json);
String graphName = jsonObj.getString("name");
JSONArray nodes = jsonObj.getJSONArray("nodes");
Iterator<Object> itNodes = nodes.iterator();
while(itNodes.hasNext()) {
JSONObject node = (JSONObject)(itNodes.next());
int index = node.getInt("nodeIndex");
if(index+1 > nodeCount) {
nodeCount = index+1;
}
}
JSONArray edges = jsonObj.getJSONArray("edges");
Iterator<Object> itEdges = edges.iterator();
while(itEdges.hasNext()) {
JSONObject edge = (JSONObject)(itEdges.next());
int index = edge.getInt("edgeIndex");
if(index+1 > edgeCount) {
edgeCount = index+1;
}
}
FastGraph g = new FastGraph(nodeCount,edgeCount,direct);
g.populateFromJsonString(jsonObj);
g.setName(graphName);
return g;
}
/**
* Generate a random graph of the desired size. Self sourcing edges may exist.
*
* @param numberOfNodes the number of nodes in the graph
* @param numberOfEdges the number of edges in the graph
* @param direct if true then off heap ByteBuffers, if false then on heap ByteBuffers
* @return the created FastGraph
*/
public static FastGraph randomGraphFactory(int numberOfNodes, int numberOfEdges, boolean direct) {
FastGraph g = new FastGraph(numberOfNodes,numberOfEdges,direct);
g.setName("random-n-"+numberOfNodes+"-e-"+numberOfEdges);
g.populateRandomGraph();
return g;
}
/**
* creates a FastGraph by loading in various files from the given directory, or data under
* current working directory if directory is null.
*
* @param directory where the files are held, or if null fileBaseName under data under the current working directory
* @param fileBaseName the name of the files, to which extensions are added
* @return the created FastGraph
* @throws IOException If the buffers cannot be loaded
* @See loadBuffers
*/
public static FastGraph loadBuffersGraphFactory(String directory, String fileBaseName) throws IOException {
FastGraph g = loadBuffers(null,fileBaseName);
return g;
}
/**
* Populates the FastGraph ByteBuffers from a json string.
* @param jsonObj the json code after parsing
*/
private void populateFromJsonString(JSONObject jsonObj) {
//long time;
String[] nodeLabels = new String[numberOfNodes];
String[] edgeLabels = new String[numberOfEdges];
int inStart = -888;
short inLength = -3;
int outStart = -777;
short outLength = -2;
int index = -1;
int weight = -5;
byte type = -7;
byte age = -9;
String label;
//time = System.currentTimeMillis();
JSONArray nodes = jsonObj.getJSONArray("nodes");
Iterator<Object> itNodes = nodes.iterator();
while(itNodes.hasNext()) {
JSONObject node = (JSONObject)(itNodes.next());
index = node.getInt("nodeIndex");
weight = node.getInt("nodeWeight");
type = (byte)(node.getInt("nodeType"));
age = (byte)(node.getInt("nodeAge"));
label = node.getString("nodeLabel");
nodeBuf.putInt(NODE_IN_CONNECTION_START_OFFSET+index*NODE_BYTE_SIZE,inStart); // offset for inward connecting edges/nodes
nodeBuf.putShort(NODE_IN_DEGREE_OFFSET+index*NODE_BYTE_SIZE,inLength); // number of inward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_CONNECTION_START_OFFSET+index*NODE_BYTE_SIZE,outStart); // offset for outward connecting edges/nodes
nodeBuf.putShort(NODE_OUT_DEGREE_OFFSET+index*NODE_BYTE_SIZE,outLength); // number of outward connecting edges/nodes
nodeBuf.putInt(NODE_WEIGHT_OFFSET+index*NODE_BYTE_SIZE,weight); // weight
nodeBuf.put(NODE_TYPE_OFFSET+index*NODE_BYTE_SIZE,type); // type
nodeBuf.put(NODE_AGE_OFFSET+index*NODE_BYTE_SIZE,age); // age
// save labels for later
nodeLabels[index] = label;
}
setAllNodeLabels(nodeLabels);
ArrayList<ArrayList<Integer>> nodeIn = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of inward edges
for(int i = 0; i< numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(20);
nodeIn.add(i,edges);
}
ArrayList<ArrayList<Integer>> nodeOut = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of outward edges
for(int i = 0; i< numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(20);
nodeOut.add(i,edges);
}
ArrayList<Integer> inEdgeList;
ArrayList<Integer> outEdgeList;
int node1;
int node2;
index = -1;
weight = -101;
type = -103;
age = -105;
//time = System.currentTimeMillis();
JSONArray edges = jsonObj.getJSONArray("edges");
Iterator<Object> itEdges = edges.iterator();
while(itEdges.hasNext()) {
JSONObject edge = (JSONObject)(itEdges.next());
index = edge.getInt("edgeIndex");
node1 = edge.getInt("node1");
node2 = edge.getInt("node2");
weight = edge.getInt("edgeWeight");
type = (byte)(edge.getInt("edgeType"));
age = (byte)(edge.getInt("edgeAge"));
label = edge.getString("edgeLabel");
edgeBuf.putInt(EDGE_NODE1_OFFSET+index*EDGE_BYTE_SIZE,node1); // one end of edge
edgeBuf.putInt(EDGE_NODE2_OFFSET+index*EDGE_BYTE_SIZE,node2); // other end of edge
edgeBuf.putInt(EDGE_WEIGHT_OFFSET+index*EDGE_BYTE_SIZE,weight); // weight
edgeBuf.put(EDGE_TYPE_OFFSET+index*EDGE_BYTE_SIZE,type); // type
edgeBuf.put(EDGE_AGE_OFFSET+index*EDGE_BYTE_SIZE,age); // age
// save labels for later
edgeLabels[index] = label;
// store connecting nodes
inEdgeList = nodeIn.get(node2);
inEdgeList.add(index);
outEdgeList = nodeOut.get(node1);
outEdgeList.add(index);
}
setAllEdgeLabels(edgeLabels);
// Initialise the connection buffer, modifying the node buffer connection data
//time = System.currentTimeMillis();
int offset = 0;
for(int i = 0; i< numberOfNodes; i++) {
// setting the in connection offset and length
ArrayList<Integer> inEdges = nodeIn.get(i);
short inEdgeLength = (short)(inEdges.size());
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_CONNECTION_START_OFFSET,offset);
nodeBuf.putShort(i*NODE_BYTE_SIZE+NODE_IN_DEGREE_OFFSET,inEdgeLength);
// now put the in edge/node pairs
for(int edgeIndex : inEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+edgeIndex+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,edgeIndex);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
// setting the out connection offset and length
ArrayList<Integer> outEdges = nodeOut.get(i);
short outEdgeLength = (short)(outEdges.size());
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_CONNECTION_START_OFFSET,offset);
nodeBuf.putShort(i*NODE_BYTE_SIZE+NODE_OUT_DEGREE_OFFSET,outEdgeLength);
// now put the out edge/node pairs
for(int edgeIndex : outEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+edgeIndex+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,edgeIndex);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
}
//System.out.println("connection put time " + (System.currentTimeMillis()-time)/1000.0+" seconds, direct "+edgeBuf.isDirect());
}
/**
* saves the current graph to several files, in directory given to base name given (i.e. fileBaseName should have no extension).
* If directory is null, then to a directory named data under current working directory. Directory should
* already exist.
* @param directory where the files are to be stored, or if null fileBaseName under data under the current working directory
* @param fileBaseName the name of the files, to which extensions are added
*/
@SuppressWarnings("resource")
public void saveBuffers(String directory, String fileBaseName) {
File file;
String directoryAndBaseName = "";
if(directory != null) {
if(directory.charAt(directory.length()-1)== File.separatorChar) {
directoryAndBaseName = directory+fileBaseName;
} else {
directoryAndBaseName = directory+File.separatorChar+fileBaseName;
}
} else {
directoryAndBaseName = Launcher.startingWorkingDirectory+File.separatorChar+"data"+File.separatorChar+fileBaseName+File.separatorChar+fileBaseName;
new File(Launcher.startingWorkingDirectory+File.separatorChar+"data"+File.separatorChar+fileBaseName).mkdirs();
}
boolean append;
FileChannel wChannel;
try {
FileOutputStream fso = new FileOutputStream(directoryAndBaseName+".info");
Writer writer = new BufferedWriter(new OutputStreamWriter(fso, "utf-8"));
writer.write("name"+INFO_SPLIT_STRING+name+"\n");
writer.write("numberOfNodes"+INFO_SPLIT_STRING+numberOfNodes+"\n");
writer.write("numberOfEdges"+INFO_SPLIT_STRING+numberOfEdges+"\n");
writer.write("numberOfNodeLabelBytes"+INFO_SPLIT_STRING+nodeLabelBuf.capacity()+"\n");
writer.write("numberOfEdgeLabelBytes"+INFO_SPLIT_STRING+nodeLabelBuf.capacity()+"\n");
String directValue = "false";
if(direct) {
directValue = "true";
}
writer.write("direct"+INFO_SPLIT_STRING+directValue+"\n");
writer.close();
file = new File(directoryAndBaseName+".nodeBuf");
append = false;
wChannel = new FileOutputStream(file, append).getChannel();
wChannel.write(nodeBuf);
wChannel.close();
file = new File(directoryAndBaseName+".edgeBuf");
append = false;
wChannel = new FileOutputStream(file, append).getChannel();
wChannel.write(edgeBuf);
wChannel.close();
file = new File(directoryAndBaseName+".connectionBuf");
append = false;
wChannel = new FileOutputStream(file, append).getChannel();
wChannel.write(connectionBuf);
wChannel.close();
file = new File(directoryAndBaseName+".nodeLabelBuf");
append = false;
wChannel = new FileOutputStream(file, append).getChannel();
wChannel.write(nodeLabelBuf);
wChannel.close();
file = new File(directoryAndBaseName+".edgeLabelBuf");
append = false;
wChannel = new FileOutputStream(file, append).getChannel();
wChannel.write(edgeLabelBuf);
wChannel.close();
}catch(Exception e) {
System.out.println("ERROR executing saveBuffers("+directory+","+fileBaseName+")");
e.printStackTrace();
}
}
public static FastGraph adjacencyListGraphFactory(int nodeCount, int edgeCount, String directory, String fileName, boolean direct) throws Exception {
FastGraph g = new FastGraph(nodeCount,edgeCount,direct);
g.setName(fileName);
g.loadAdjacencyListGraph(directory,fileName);
return g;
}
/**
* Assumes edges represented by one node index pair per line delimited by
* tabs or spaces, ignores lines starting with # and any line without a tab.
* Looks for the file in given directory. If directory is null, then to a
* directory named /data/snap under current working directory.
*
* @throws IOException If the buffers cannot be loaded
*/
private void loadAdjacencyListGraph(String dir, String fileName) throws Exception {
String directory = dir;
if(directory == null) {
directory = Launcher.startingWorkingDirectory+File.separatorChar+"data"+File.separatorChar+"snap";
}
String path = null;
if(directory.charAt(directory.length()-1)== File.separatorChar) {
path = directory+fileName;
} else {
path = directory+File.separatorChar+fileName;
}
int edgeIndex = 0;
int nodeIndex = 0;
HashMap<String,Integer> nodeSnapIdToIndexMap = new HashMap<String,Integer>(numberOfNodes*4);
HashMap<Integer,String> nodeIndexToSnapIdMap = new HashMap<Integer,String>(numberOfNodes*4);
HashMap<Integer,Integer> edgeNode1Map = new HashMap<Integer,Integer>(numberOfEdges*4);
HashMap<Integer,Integer> edgeNode2Map = new HashMap<Integer,Integer>(numberOfEdges*4);
File f = new File(path);
if(!f.exists()) {
throw new IOException("Problem loading file "+path+". If you expect to access a SNAP file try downloading the file from:\nhttps://snap.stanford.edu/data/\nthen unzipping it and placing it in the directory "+directory);
//System.exit(1);
}
FileInputStream is = new FileInputStream(path);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String[] splitLine;
String line = "";
long time = System.currentTimeMillis();
while(line != null) {
line = br.readLine();
if(line == null) {
continue;
}
if(line.length() == 0) {
continue;
}
if(line.charAt(0) == '
continue;
}
splitLine = line.split(" ");
if(splitLine.length < 2) {
splitLine = line.split("\t");
if(splitLine.length < 2) {
System.out.println("FAILED TO RECOGNISE LINE:"+line+" in loadAdjacencyListGraph("+directory+","+fileName+")");
continue;
}
}
String node1String = splitLine[0];
String node2String = splitLine[1];
if(!nodeSnapIdToIndexMap.containsKey(node1String)) {
nodeSnapIdToIndexMap.put(node1String,nodeIndex);
nodeIndexToSnapIdMap.put(nodeIndex,node1String);
nodeIndex++;
}
if(!nodeSnapIdToIndexMap.containsKey(node2String)) {
nodeSnapIdToIndexMap.put(node2String,nodeIndex);
nodeIndexToSnapIdMap.put(nodeIndex,node2String);
nodeIndex++;
}
edgeNode1Map.put(edgeIndex, nodeSnapIdToIndexMap.get(node1String));
edgeNode2Map.put(edgeIndex, nodeSnapIdToIndexMap.get(node2String));
edgeIndex++;
if(edgeIndex%1000000==0 ) {
System.out.println("edgesLoaded "+edgeIndex+" time "+(System.currentTimeMillis()-time)/1000.0);
}
}
String[] nodeLabels = new String[numberOfNodes];
String[] edgeLabels = new String[numberOfEdges];
int inStart = -88;
short inLength = -33;
int outStart = -77;
short outLength = -22;
int weight = -55;
byte type = -77;
byte age = -99;
for(int i = 0; i< numberOfNodes; i++) {
nodeBuf.putInt(NODE_IN_CONNECTION_START_OFFSET+i*NODE_BYTE_SIZE,inStart); // offset for inward connecting edges/nodes
nodeBuf.putShort(NODE_IN_DEGREE_OFFSET+i*NODE_BYTE_SIZE,inLength); // number of inward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_CONNECTION_START_OFFSET+i*NODE_BYTE_SIZE,outStart); // offset for outward connecting edges/nodes
nodeBuf.putShort(NODE_OUT_DEGREE_OFFSET+i*NODE_BYTE_SIZE,outLength); // number of outward connecting edges/nodes
nodeBuf.putInt(NODE_WEIGHT_OFFSET+i*NODE_BYTE_SIZE,weight); // weight
nodeBuf.put(NODE_TYPE_OFFSET+i*NODE_BYTE_SIZE,type); // type
nodeBuf.put(NODE_AGE_OFFSET+i*NODE_BYTE_SIZE,age); // age
// save labels for later
String label = nodeIndexToSnapIdMap.get(i);
nodeLabels[i] = label;
}
setAllNodeLabels(nodeLabels);
ArrayList<ArrayList<Integer>> nodeIn = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of inward edges
for(int i = 0; i< numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(20);
nodeIn.add(i,edges);
}
ArrayList<ArrayList<Integer>> nodeOut = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of outward edges
for(int i = 0; i< numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(20);
nodeOut.add(i,edges);
}
ArrayList<Integer> inEdgeList;
ArrayList<Integer> outEdgeList;
int node1;
int node2;
weight = -51;
type = -53;
age = -55;
for(int i = 0; i< numberOfEdges; i++) {
node1 = edgeNode1Map.get(i);
node2 = edgeNode2Map.get(i);
edgeBuf.putInt(EDGE_NODE1_OFFSET+i*EDGE_BYTE_SIZE,node1); // one end of edge
edgeBuf.putInt(EDGE_NODE2_OFFSET+i*EDGE_BYTE_SIZE,node2); // other end of edge
edgeBuf.putInt(EDGE_WEIGHT_OFFSET+i*EDGE_BYTE_SIZE,weight); // weight
edgeBuf.put(EDGE_TYPE_OFFSET+i*EDGE_BYTE_SIZE,type); // type
edgeBuf.put(EDGE_AGE_OFFSET+i*EDGE_BYTE_SIZE,age); // age
// store labels for later
String label = "e"+i;
edgeLabels[i] = label;
// store connecting nodes
inEdgeList = nodeIn.get(node2);
inEdgeList.add(i);
outEdgeList = nodeOut.get(node1);
outEdgeList.add(i);
}
setAllEdgeLabels(edgeLabels);
// Initialise the connection buffer, modifying the node buffer connection data
//time = System.currentTimeMillis();
int offset = 0;
for(int i = 0; i< numberOfNodes; i++) {
// setting the in connection offset and length
ArrayList<Integer> inEdges = nodeIn.get(i);
short inEdgeLength = (short)(inEdges.size());
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_CONNECTION_START_OFFSET,offset);
nodeBuf.putShort(i*NODE_BYTE_SIZE+NODE_IN_DEGREE_OFFSET,inEdgeLength);
// now put the in edge/node pairs
for(int e : inEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+e*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+e*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+e+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,e);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
// setting the out connection offset and length
ArrayList<Integer> outEdges = nodeOut.get(i);
short outEdgeLength = (short)(outEdges.size());
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_CONNECTION_START_OFFSET,offset);
nodeBuf.putShort(i*NODE_BYTE_SIZE+NODE_OUT_DEGREE_OFFSET,outEdgeLength);
// now put the out edge/node pairs
for(int e : outEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+e*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+e*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+e+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,e);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
}
}
@SuppressWarnings("resource")
private static FastGraph loadBuffers(String directory, String fileBaseName) throws IOException {
String directoryAndBaseName = Launcher.startingWorkingDirectory+File.separatorChar+"data"+File.separatorChar+fileBaseName+File.separatorChar+fileBaseName;
if(directory != null) {
if(directory.charAt(directory.length()-1)== File.separatorChar) {
directoryAndBaseName = directory+fileBaseName;
} else {
directoryAndBaseName = directory+File.separatorChar+fileBaseName;
}
}
FastGraph g = null;
File file;
FileChannel rChannel;
String line;
String[] splitLine;
FileInputStream is = new FileInputStream(directoryAndBaseName+".info");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
line = br.readLine();
splitLine = line.split(INFO_SPLIT_STRING);
String name = splitLine[1];
line = br.readLine();
splitLine = line.split(INFO_SPLIT_STRING);
int inNodeTotal = Integer.parseInt(splitLine[1]);
line = br.readLine();
splitLine = line.split(INFO_SPLIT_STRING);
int inEdgeTotal = Integer.parseInt(splitLine[1]);
line = br.readLine();
int inNodeLabelSize = Integer.parseInt(splitLine[1]);
line = br.readLine();
int inEdgeLabelSize = Integer.parseInt(splitLine[1]);
line = br.readLine();
splitLine = line.split(INFO_SPLIT_STRING);
String directValue = splitLine[1];
boolean inDirect = true;
if(directValue.equals("false")) {
inDirect = false;
}
br.close();
g = new FastGraph(inNodeTotal, inEdgeTotal, inDirect);
if(!inDirect) {
g.nodeLabelBuf = ByteBuffer.allocate(inNodeLabelSize);
g.edgeLabelBuf = ByteBuffer.allocate(inEdgeLabelSize);
} else {
g.edgeLabelBuf = ByteBuffer.allocateDirect(inEdgeLabelSize);
}
g.setName(name);
file = new File(directoryAndBaseName+".nodeBuf");
rChannel = new FileInputStream(file).getChannel();
rChannel.read(g.nodeBuf);
rChannel.close();
file = new File(directoryAndBaseName+".edgeBuf");
rChannel = new FileInputStream(file).getChannel();
rChannel.read(g.edgeBuf);
rChannel.close();
file = new File(directoryAndBaseName+".connectionBuf");
rChannel = new FileInputStream(file).getChannel();
rChannel.read(g.connectionBuf);
rChannel.close();
file = new File(directoryAndBaseName+".nodeLabelBuf");
rChannel = new FileInputStream(file).getChannel();
rChannel.read(g.nodeLabelBuf);
rChannel.close();
file = new File(directoryAndBaseName+".edgeLabelBuf");
rChannel = new FileInputStream(file).getChannel();
rChannel.read(g.edgeLabelBuf);
rChannel.close();
return g;
}
/**
* Creates a graph with the size specified by numberOfNodes and numberOfEdges
*/
public void populateRandomGraph() {
//long time;
Random r = new Random();
String[] nodeLabels = new String[numberOfNodes];
String[] edgeLabels = new String[numberOfEdges];
int inStart = -888;
short inLength = -3;
int outStart = -777;
short outLength = -2;
int weight = -5;
byte type = -7;
byte age = -9;
//time = System.currentTimeMillis();
for(int i = 0; i< numberOfNodes; i++) {
weight = r.nextInt(100);
nodeBuf.putInt(NODE_IN_CONNECTION_START_OFFSET+i*NODE_BYTE_SIZE,inStart); // offset for inward connecting edges/nodes
nodeBuf.putShort(NODE_IN_DEGREE_OFFSET+i*NODE_BYTE_SIZE,inLength); // number of inward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_CONNECTION_START_OFFSET+i*NODE_BYTE_SIZE,outStart); // offset for outward connecting edges/nodes
nodeBuf.putShort(NODE_OUT_DEGREE_OFFSET+i*NODE_BYTE_SIZE,outLength); // number of outward connecting edges/nodes
nodeBuf.putInt(NODE_WEIGHT_OFFSET+i*NODE_BYTE_SIZE,weight); // weight
nodeBuf.put(NODE_TYPE_OFFSET+i*NODE_BYTE_SIZE,type); // type
nodeBuf.put(NODE_AGE_OFFSET+i*NODE_BYTE_SIZE,age); // age
// store labels for later
String label = "n"+i;
nodeLabels[i] = label;
}
setAllNodeLabels(nodeLabels);
ArrayList<ArrayList<Integer>> nodeIn = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of inward edges
for(int i = 0; i< numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(20);
nodeIn.add(i,edges);
}
ArrayList<ArrayList<Integer>> nodeOut = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of outward edges
for(int i = 0; i< numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(20);
nodeOut.add(i,edges);
}
ArrayList<Integer> inEdgeList;
ArrayList<Integer> outEdgeList;
int node1;
int node2;
weight = -101;
type = -103;
age = -105;
//time = System.currentTimeMillis();
for(int i = 0; i< numberOfEdges; i++) {
weight = r.nextInt(100);
node1 = r.nextInt(numberOfNodes);
node2 = r.nextInt(numberOfNodes);
edgeBuf.putInt(EDGE_NODE1_OFFSET+i*EDGE_BYTE_SIZE,node1); // one end of edge
edgeBuf.putInt(EDGE_NODE2_OFFSET+i*EDGE_BYTE_SIZE,node2); // other end of edge
edgeBuf.putInt(EDGE_WEIGHT_OFFSET+i*EDGE_BYTE_SIZE,weight); // weight
edgeBuf.put(EDGE_TYPE_OFFSET+i*EDGE_BYTE_SIZE,type); // type
edgeBuf.put(EDGE_AGE_OFFSET+i*EDGE_BYTE_SIZE,age); // age
// label
String label = "e"+i;
edgeLabels[i] = label;
// store connecting nodes
inEdgeList = nodeIn.get(node2);
inEdgeList.add(i);
outEdgeList = nodeOut.get(node1);
outEdgeList.add(i);
}
setAllEdgeLabels(edgeLabels);
// Initialise the connection buffer, modifying the node buffer connection data
//time = System.currentTimeMillis();
int offset = 0;
for(int i = 0; i< numberOfNodes; i++) {
// setting the in connection offset and length
ArrayList<Integer> inEdges = nodeIn.get(i);
short inEdgeLength = (short)(inEdges.size());
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_CONNECTION_START_OFFSET,offset);
nodeBuf.putShort(i*NODE_BYTE_SIZE+NODE_IN_DEGREE_OFFSET,inEdgeLength);
// now put the in edge/node pairs
for(int e : inEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+e*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+e*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+e+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,e);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
// setting the out connection offset and length
ArrayList<Integer> outEdges = nodeOut.get(i);
short outEdgeLength = (short)(outEdges.size());
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_CONNECTION_START_OFFSET,offset);
nodeBuf.putShort(i*NODE_BYTE_SIZE+NODE_OUT_DEGREE_OFFSET,outEdgeLength);
// now put the out edge/node pairs
for(int e : outEdges) {
int n = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+e*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+e*EDGE_BYTE_SIZE);
if(n1 == i) {
n = n2;
} else if(n2 == i) {
n = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+e+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,e);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,n);
offset += CONNECTION_PAIR_SIZE;
}
}
//System.out.println("connection put time " + (System.currentTimeMillis()-time)/1000.0+" seconds, direct "+edgeBuf.isDirect());
}
/**
* Creates a graph from a displayGraph.Graph. label becomes the displayGraph.Graph name
* node and edge labels, are taken from displayGraph.Graph nodes and edges.
* node and edge weights are from displayGraph node and edge scores. Types are
* from displayGraph edgeType edgeType if they can be parsed as bytes,
* otherwise they get a default of -1. Node and edge Age is from displayGraph age, but
* only least significant byte, as the displayGraph age is a integer.
* Order of nodes and edges is as in the displayGraph.Graph
*
* @param displayGraph the graph that the new FastGraph is based on
* @param direct if true then off heap ByteBuffers, if false then on heap ByteBuffers
* @return new FastGraph with attributes based on the given displayGraph.
*/
public static FastGraph displayGraphFactory(Graph displayGraph, boolean direct) {
FastGraph g = new FastGraph(displayGraph.getNodes().size(),displayGraph.getEdges().size(),direct);
g.setName(displayGraph.getLabel());
g.populateFromDisplayGraph(displayGraph);
return g;
}
/**
* Populates byteBuffers based on the contents of the displayGraph.graph.
* Nodes and edges are in the order they appear in the displayGraph.
*
* @param displayGraph the graph that the new FastGraph is based on
*/
private void populateFromDisplayGraph(Graph displayGraph) {
String[] nodeLabels = new String[numberOfNodes];
String[] edgeLabels = new String[numberOfEdges];
int inStart = -27;
short inLength = -37;
int outStart = -47;
short outLength = -57;
int weight = -67;
byte type = -77;
byte age = -87;
ByteBuffer bb = ByteBuffer.allocate(4); // used to convert from int to byte, due to lack of direct casting
for(int i = 0; i< numberOfNodes; i++) {
Node dgn = displayGraph.getNodes().get(i);
weight = (int)(dgn.getScore());
bb.putInt(0,dgn.getAge());
age = bb.get(3); // get least significant byte of age
try {
type = Byte.parseByte(dgn.getType().getLabel());
} catch(NumberFormatException e) {
type = -1;
}
nodeBuf.putInt(NODE_IN_CONNECTION_START_OFFSET+i*NODE_BYTE_SIZE,inStart); // offset for inward connecting edges/nodes
nodeBuf.putShort(NODE_IN_DEGREE_OFFSET+i*NODE_BYTE_SIZE,inLength); // number of inward connecting edges/nodes
nodeBuf.putInt(NODE_OUT_CONNECTION_START_OFFSET+i*NODE_BYTE_SIZE,outStart); // offset for outward connecting edges/nodes
nodeBuf.putShort(NODE_OUT_DEGREE_OFFSET+i*NODE_BYTE_SIZE,outLength); // number of outward connecting edges/nodes
nodeBuf.putInt(NODE_WEIGHT_OFFSET+i*NODE_BYTE_SIZE,weight); // weight
nodeBuf.put(NODE_TYPE_OFFSET+i*NODE_BYTE_SIZE,type); // type
nodeBuf.put(NODE_AGE_OFFSET+i*NODE_BYTE_SIZE,age); // age
// store labels for later
String label = dgn.getLabel();
nodeLabels[i] = label;
}
setAllNodeLabels(nodeLabels);
ArrayList<ArrayList<Integer>> nodeIn = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of inward edges
for(int i = 0; i< numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(20);
nodeIn.add(i,edges);
}
ArrayList<ArrayList<Integer>> nodeOut = new ArrayList<ArrayList<Integer>>(numberOfNodes); // temporary store of outward edges
for(int i = 0; i< numberOfNodes; i++) {
ArrayList<Integer> edges = new ArrayList<Integer>(20);
nodeOut.add(i,edges);
}
ArrayList<Integer> inEdgeList;
ArrayList<Integer> outEdgeList;
int node1;
int node2;
weight = -15;
type = -25;
age = -35;
for(int i = 0; i< numberOfEdges; i++) {
Edge dge = displayGraph.getEdges().get(i);
node1 = displayGraph.getNodes().indexOf(dge.getFrom());
node2 = displayGraph.getNodes().indexOf(dge.getTo());
weight = (int)(dge.getScore());
bb.putInt(0,dge.getAge());
age = bb.get(3); // get least significant byte of age
try {
type = Byte.parseByte(dge.getType().getLabel());
} catch(NumberFormatException e) {
type = -1;
}
edgeBuf.putInt(EDGE_NODE1_OFFSET+i*EDGE_BYTE_SIZE,node1); // one end of edge
edgeBuf.putInt(EDGE_NODE2_OFFSET+i*EDGE_BYTE_SIZE,node2); // other end of edge
edgeBuf.putInt(EDGE_WEIGHT_OFFSET+i*EDGE_BYTE_SIZE,weight); // weight
edgeBuf.put(EDGE_TYPE_OFFSET+i*EDGE_BYTE_SIZE,type); // type
edgeBuf.put(EDGE_AGE_OFFSET+i*EDGE_BYTE_SIZE,age); // age
// store labels for later
String label = dge.getLabel();
edgeLabels[i] = label;
// store connecting nodes
inEdgeList = nodeIn.get(node2);
inEdgeList.add(i);
outEdgeList = nodeOut.get(node1);
outEdgeList.add(i);
}
setAllEdgeLabels(edgeLabels);
// Initialise the connection buffer, modifying the node buffer connection data
//time = System.currentTimeMillis();
int offset = 0;
for(int i = 0; i< numberOfNodes; i++) {
// setting the in connection offset and length
ArrayList<Integer> inEdges = nodeIn.get(i);
short inEdgeLength = (short)(inEdges.size());
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_IN_CONNECTION_START_OFFSET,offset);
nodeBuf.putShort(i*NODE_BYTE_SIZE+NODE_IN_DEGREE_OFFSET,inEdgeLength);
// now put the in edge/node pairs
for(int edgeIndex : inEdges) {
int nodeIndex = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
if(n1 == i) {
nodeIndex = n2;
} else if(n2 == i) {
nodeIndex = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+edgeIndex+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,edgeIndex);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,nodeIndex);
offset += CONNECTION_PAIR_SIZE;
}
// setting the out connection offset and length
ArrayList<Integer> outEdges = nodeOut.get(i);
short outEdgeLength = (short)(outEdges.size());
nodeBuf.putInt(i*NODE_BYTE_SIZE+NODE_OUT_CONNECTION_START_OFFSET,offset);
nodeBuf.putShort(i*NODE_BYTE_SIZE+NODE_OUT_DEGREE_OFFSET,outEdgeLength);
// now put the out edge/node pairs
for(int edgeIndex : outEdges) {
int nodeIndex = -1;
int n1 = edgeBuf.getInt(EDGE_NODE1_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
int n2 = edgeBuf.getInt(EDGE_NODE2_OFFSET+edgeIndex*EDGE_BYTE_SIZE);
if(n1 == i) {
nodeIndex = n2;
} else if(n2 == i) {
nodeIndex = n1;
} else {
System.out.println("ERROR When finding connections for node "+i+" connecting edge "+edgeIndex+ " has connecting nodes "+n1+" "+n2);
}
connectionBuf.putInt(CONNECTION_EDGE_OFFSET+offset,edgeIndex);
connectionBuf.putInt(CONNECTION_NODE_OFFSET+offset,nodeIndex);
offset += CONNECTION_PAIR_SIZE;
}
}
}
/**
* @return the largest degree for a node in the graph.
*/
public int maximumDegree() {
int max = 0;
for(int i = 0; i< numberOfNodes; i++) {
short inDegree = nodeBuf.getShort(NODE_IN_DEGREE_OFFSET+i*NODE_BYTE_SIZE);
short outDegree = nodeBuf.getShort(NODE_OUT_DEGREE_OFFSET+i*NODE_BYTE_SIZE);
int degree = inDegree+outDegree;
if(degree > max) {
max = degree;
}
}
return max;
}
/** Breadth first search through the graph.
* Note direct access to connectionBuf is a 3x speed up over accessing getNodeConnectingNodes(currentNode).
* Using arrays for nodeFlagBuf is a minor speed up on ByteBuffer
*
* @return true if the graph is connected, false otherwise. Empty graphs are connected.
*/
public boolean isConnected() {
boolean[] nodeFlag = new boolean[numberOfNodes];
if(numberOfNodes == 0) {
return true;
}
boolean visited = true;
int nodeCount = 0;
//int edgeCount = 0;
LinkedList<Integer> queue = new LinkedList<Integer>();
queue.add(0);
nodeFlag[0] = visited;
while(queue.size() != 0) {
int currentNode = queue.removeFirst();
nodeCount++;
int connectionOffset = nodeBuf.getInt(NODE_IN_CONNECTION_START_OFFSET+currentNode*NODE_BYTE_SIZE);
int degree = getNodeDegree(currentNode);
for(int i = 0; i < degree; i++) {
//edgeCount++;
// step over edge/node pairs and the edge
int nodeOffset = CONNECTION_NODE_OFFSET+connectionOffset+i*CONNECTION_PAIR_SIZE;
int connectingNode = connectionBuf.getInt(nodeOffset);
boolean flag = nodeFlag[connectingNode];
if(!flag) {
queue.add(connectingNode);
nodeFlag[connectingNode] = visited;
}
}
}
boolean allVisited = true;
if(nodeCount < numberOfNodes) {
allVisited = false;
}
//System.out.println("edges tested "+edgeCount);
//System.out.println("nodes tested "+nodeCount);
return allVisited;
}
/**
* Prints the contents of an adjacency matrix to the screen in a simple way
* Loops instead of using toDeepString() as it's better to display the matrix as a table
* @param matrix A 2D array of ints representing the graph
*/
public void printMatrix(int[][] matrix) {
for (int[] i : matrix) {
System.out.println(Arrays.toString(i));
}
}
/**
* Prints the contents of an adjacency matrix to the screen in a simple way
* Loops instead of using toDeepString() as it's better to display the matrix as a table
* @param matrix A 2D array of booleans representing the graph
*/
public void printMatrix(boolean[][] matrix) {
for (boolean[] i : matrix) {
System.out.println(Arrays.toString(i));
}
}
/**
* Builds an adjacency matrix from a graph.
* Assumes the graph is undirected
*
* @return A 2D array of ints representing the graph
*/
public int[][] buildIntAdjacencyMatrix() {
int[][] matrix = new int[getNumberOfNodes()][getNumberOfNodes()]; //create an 2D array that has the dimensions of the current graph
for (int n = 0; n < getNumberOfNodes(); n++) {
int[] connectingNodeIndexes = getNodeConnectingOutNodes(n);
for (int i : connectingNodeIndexes) {
matrix[n][i]++;
matrix[i][n]++;
}
}
return matrix;
}
/**
* Builds an adjacency matrix from a graph.
* Assumes a nodes only connects to another once
* Assumes the graph is undirected
*
* @return A 2D array of booleans representing the graph
*/
public boolean[][] buildBooleanAdjacencyMatrix() {
boolean[][] matrix = new boolean[getNumberOfNodes()][getNumberOfNodes()]; //create an 2D array that has the dimensions of the current graph
System.out.println("Matrix created");
for (int n = 0; n < getNumberOfNodes(); n++) {
int[] connectingNodeIndexes = getNodeConnectingOutNodes(n);
for (int i : connectingNodeIndexes) {
matrix[n][i] = true;
matrix[i][n] = true;
}
}
return matrix;
}
/**
* Builds an adjacency matrix from a graph.
* Assumes the graph is directed
*
* @return A 2D array of ints representing the graph
*/
public int[][] buildIntDirectedAdjacencyMatrix() {
int[][] matrix = new int[getNumberOfNodes()][getNumberOfNodes()]; //create an 2D array that has the dimensions of the current graph
for (int n = 0; n < getNumberOfNodes(); n++) {
int[] connectingNodeIndexes = getNodeConnectingOutNodes(n);
for (int i : connectingNodeIndexes) {
matrix[n][i]++;
}
}
return matrix;
}
/**
* Builds an adjacency matrix from a graph.
* Assumes a nodes only connects to another once
* Assumes the graph is directed
*
* @return A 2D array of booleans representing the graph
*/
public boolean[][] buildBooleanDirectedAdjacencyMatrix() {
boolean[][] matrix = new boolean[getNumberOfNodes()][getNumberOfNodes()]; //create an 2D array that has the dimensions of the current graph
for (int n = 0; n < getNumberOfNodes(); n++) {
int[] connectingNodeIndexes = getNodeConnectingOutNodes(n);
for (int i : connectingNodeIndexes) {
matrix[n][i] = true;
}
}
return matrix;
}
/**
* Converts an int[][] into a double[][]
* Used when creating eigenvalues
* @param inputMatrix The input 2D array
* @return The output 2D array
*/
private double[][] convertMatrix(int[][] inputMatrix) {
//have to convert the int[][] input into a double[][]
double[][] dArray = new double[inputMatrix.length][inputMatrix.length];
for (int row = 0; row < inputMatrix.length; row++) {
for (int column = 0; column < inputMatrix[0].length; column++) {
dArray[row][column] = (double) inputMatrix[row][column];
}
}
return dArray;
}
/**
* Converts an boolean[][] into a double[][]
* Used when creating eigenvalues
* @param inputMatrix The input 2D array
* @return The output 2D array
*/
private double[][] convertMatrix(boolean[][] inputMatrix) {
//have to convert the boolean[][] input into a double[][]
double[][] dArray = new double[inputMatrix.length][inputMatrix.length];
for (int row = 0; row < inputMatrix.length; row++) {
for (int column = 0; column < inputMatrix[0].length; column++) {
if (inputMatrix[row][column]) {
dArray[row][column] = 1;
} else {
dArray[row][column] = 0;
}
}
}
return dArray;
}
public double[] findEigenvalues(int[][] inputMatrix) {
return findEigenvalues(convertMatrix(inputMatrix));
}
public double[] findEigenvalues(boolean[][] inputMatrix) {
return findEigenvalues(convertMatrix(inputMatrix));
}
public double[] findEigenvalues(double[][] inputMatrix) {
int matrixSize = inputMatrix.length;
Matrix A = new Matrix(inputMatrix);
// compute the spectral decomposition
EigenvalueDecomposition e = A.eig();
//e.getD().print(6, 1);
//e.getV().print(6, 1);
double[] result = e.getRealEigenvalues();
Arrays.sort(result);
return result;
}
/**
* Creates a displayGraph.Graph which can then be accessed, manipulated and visualized
* using that package. displayGraph.Graph name becomes this FastGraph label
* The displayGraph.Graph node and edge labels, are taken
* from this FastGraph nodes and edges. node and edge weights become node
* and edge scores node and edge ages become ages in displayGraph nodes and edges.
* New NodeType and EdgeType are created if needed with label of the integer of this type.
* Order of nodes and edges in the displayGraph.Graph is as this FastGraph.
*
* @return a displayGraph.Graph with the same data as this Fast Graph
*/
public Graph generateDisplayGraph() {
Graph g = new Graph(getName());
for(int i = 0; i< numberOfNodes; i++) {
Node n = new Node();
n.setLabel(getNodeLabel(i));
n.setScore(getNodeWeight(i));
n.setAge(getNodeAge(i));
String typeLabel = Integer.toString(getNodeType(i));
NodeType type = NodeType.withLabel(typeLabel);
if(type == null) {
type = new NodeType(typeLabel);
}
n.setType(type);
g.addNode(n);
}
for(int i = 0; i< numberOfEdges; i++) {
Node n1 = g.getNodes().get(getEdgeNode1(i));
Node n2 = g.getNodes().get(getEdgeNode2(i));
Edge e = new Edge(n1,n2);
e.setLabel(getEdgeLabel(i));
e.setScore(getEdgeWeight(i));
e.setAge(getEdgeAge(i));
String typeLabel = Integer.toString(getEdgeType(i));
EdgeType type = EdgeType.withLabel(typeLabel);
if(type == null) {
type = new EdgeType(typeLabel);
}
e.setType(type);
g.addEdge(e);
}
return g;
}
}
|
package com.matthewtamlin.spyglass.library.handler_adapters;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import com.matthewtamlin.java_utilities.testing.Tested;
import com.matthewtamlin.spyglass.library.handler_annotations.BooleanHandler;
import com.matthewtamlin.spyglass.library.handler_annotations.ColorStateListHandler;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
@Tested(testMethod = "automated")
public class ColorStateListHandlerAdapter
implements HandlerAdapter<ColorStateList, ColorStateListHandler> {
@Override
public TypedArrayAccessor<ColorStateList> getAccessor(final ColorStateListHandler annotation) {
checkNotNull(annotation, "Argument \'annotation\' cannot be null.");
return new TypedArrayAccessor<ColorStateList>() {
@Override
public boolean valueExistsInArray(final TypedArray array) {
checkNotNull(array, "Argument \'array\' cannot be null.");
return array.getColorStateList(annotation.attributeId()) != null;
}
@Override
public ColorStateList getValueFromArray(final TypedArray array) {
checkNotNull(array, "Argument \'array\' cannot be null.");
if (valueExistsInArray(array)) {
return array.getColorStateList(annotation.attributeId());
} else {
throw new RuntimeException("No attribute found for attribute ID " +
annotation.attributeId());
}
}
};
}
@Override
public int getAttributeId(final ColorStateListHandler annotation) {
checkNotNull(annotation, "Argument \'annotation\' cannot be null.");
return annotation.attributeId();
}
@Override
public boolean attributeIsMandatory(final ColorStateListHandler annotation) {
checkNotNull(annotation, "Argument \'annotation\' cannot be null.");
return annotation.mandatory();
}
}
|
package org.safehaus.kiskis.mgmt.async.runner;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
import org.safehaus.kiskis.mgmt.shared.protocol.ExpiringCache;
import org.safehaus.kiskis.mgmt.shared.protocol.Response;
import org.safehaus.kiskis.mgmt.shared.protocol.Task;
import org.safehaus.kiskis.mgmt.shared.protocol.TaskRunner;
import org.safehaus.kiskis.mgmt.shared.protocol.api.AsyncTaskRunner;
import org.safehaus.kiskis.mgmt.shared.protocol.api.CommandManager;
import org.safehaus.kiskis.mgmt.shared.protocol.api.EntryExpiryCallback;
import org.safehaus.kiskis.mgmt.shared.protocol.api.TaskCallback;
import org.safehaus.kiskis.mgmt.shared.protocol.api.ui.CommandListener;
/**
*
* @author dilshat
*/
public class AsyncTaskRunnerImpl implements CommandListener, AsyncTaskRunner {
private static final Logger LOG = Logger.getLogger(AsyncTaskRunnerImpl.class.getName());
private static final String MODULE_NAME = "AsyncRunner";
private TaskRunner taskRunner;
private final ExpiringCache<UUID, ExecutorService> executors = new ExpiringCache<UUID, ExecutorService>();
public void setCommandManager(CommandManager commandManager) {
taskRunner = new TaskRunner(commandManager);
}
public void init() {
LOG.info(MODULE_NAME + " started");
}
public void destroy() {
executors.clear();
}
@Override
public void onCommand(final Response response) {
ExecutorService executor = executors.get(response.getTaskUuid());
if (executor != null) {
executor.execute(new Runnable() {
public void run() {
taskRunner.feedResponse(response);
}
});
}
}
@Override
public void executeTask(final Task task, final TaskCallback taskCallback) {
ExecutorService executor = executors.get(task.getUuid());
if (executor == null) {
executor = Executors.newSingleThreadExecutor();
executors.put(task.getUuid(), executor, task.getAvgTimeout() * 1000 + 10000, new EntryExpiryCallback<ExecutorService>() {
public void onEntryExpiry(ExecutorService entry) {
try {
entry.shutdown();
} catch (Exception e) {
}
}
});
}
executor.execute(new Runnable() {
public void run() {
taskRunner.runTask(task, taskCallback);
}
});
}
@Override
public String getName() {
return MODULE_NAME;
}
}
|
package org.safehaus.subutai.hive.services;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.safehaus.subutai.api.agentmanager.AgentManager;
import org.safehaus.subutai.api.hive.Config;
import org.safehaus.subutai.api.hive.Hive;
import org.safehaus.subutai.common.JsonUtil;
import org.safehaus.subutai.shared.protocol.Agent;
public class RestService {
private static final String OPERATION_ID = "OPERATION_ID";
private Hive hiveManager;
private AgentManager agentManager;
public void setAgentManager( AgentManager agentManager ) {
this.agentManager = agentManager;
}
public void setHiveManager( Hive hiveManager ) {
this.hiveManager = hiveManager;
}
@GET
@Path( "getClusters" )
@Produces( { MediaType.APPLICATION_JSON } )
public String getClusters() {
List<Config> configs = hiveManager.getClusters();
ArrayList<String> clusterNames = new ArrayList();
for ( Config config : configs ) {
clusterNames.add( config.getClusterName() );
}
return JsonUtil.GSON.toJson( clusterNames );
}
@GET
@Path( "getCluster" )
@Produces( { MediaType.APPLICATION_JSON } )
public String getCluster(
@QueryParam( "clusterName" ) String clusterName
) {
Config config = hiveManager.getCluster( clusterName );
return JsonUtil.GSON.toJson( config );
}
@GET
@Path( "installCluster" )
@Produces({ MediaType.APPLICATION_JSON })
public String installCluster(
@QueryParam( "clusterName" ) String clusterName,
@QueryParam( "hadoopClusterName" ) String hadoopClusterName,
@QueryParam( "server" ) String server,
@QueryParam( "clients" ) List<String> clients
) {
Config config = new Config();
config.setClusterName( clusterName );
config.setHadoopClusterName(hadoopClusterName);
Agent serverAgent = agentManager.getAgentByHostname( server );
config.setServer( serverAgent );
for ( String client : clients ) {
Agent agent = agentManager.getAgentByHostname( client );
config.getClients().add( agent );
}
UUID uuid = hiveManager.installCluster( config );
return JsonUtil.toJson( OPERATION_ID, uuid );
}
@GET
@Path( "uninstallCluster" )
@Produces( { MediaType.APPLICATION_JSON } )
public String uninstallCluster(
@QueryParam( "clusterName" ) String clusterName
) {
UUID uuid = hiveManager.uninstallCluster( clusterName );
return JsonUtil.toJson( OPERATION_ID, uuid );
}
@GET
@Path( "addNode" )
@Produces( { MediaType.APPLICATION_JSON } )
public String addNode(
@QueryParam( "clusterName" ) String clusterName,
@QueryParam( "hostname" ) String hostname
) {
UUID uuid = hiveManager.addNode( clusterName, hostname );
return JsonUtil.toJson( OPERATION_ID, uuid );
}
@GET
@Path( "destroyNode" )
@Produces( { MediaType.APPLICATION_JSON } )
public String destroyNode(
@QueryParam( "clusterName" ) String clusterName,
@QueryParam( "hostname" ) String hostname
) {
UUID uuid = hiveManager.destroyNode( clusterName, hostname );
return JsonUtil.toJson( OPERATION_ID, uuid );
}
}
|
package org.motechproject.nms.mobileacademy.service.impl;
import org.apache.commons.collections.CollectionUtils;
import org.joda.time.DateTime;
import org.motechproject.event.MotechEvent;
import org.motechproject.event.listener.EventRelay;
import org.motechproject.mtraining.domain.Bookmark;
import org.motechproject.mtraining.repository.BookmarkDataService;
import org.motechproject.nms.mobileacademy.domain.CompletionRecord;
import org.motechproject.nms.mobileacademy.domain.Course;
import org.motechproject.nms.mobileacademy.dto.MaBookmark;
import org.motechproject.nms.mobileacademy.repository.CompletionRecordDataService;
import org.motechproject.nms.mobileacademy.repository.CourseDataService;
import org.motechproject.nms.mobileacademy.service.MobileAcademyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Simple implementation of the {@link MobileAcademyService} interface.
*/
@Service("mobileAcademyService")
public class MobileAcademyServiceImpl implements MobileAcademyService {
private static final String FINAL_BOOKMARK = "Chapter11_Quiz";
private static final String COURSE_COMPLETED = "nms.ma.course.completed";
private static final String SCORES_KEY = "scoresByChapter";
private static final int CHAPTER_COUNT = 11;
private static final int PASS_SCORE = 22;
/**
* Bookmark data service
*/
private BookmarkDataService bookmarkDataService;
/**
* Completion record data service
*/
private CompletionRecordDataService completionRecordDataService;
/**
* Course data service
*/
private CourseDataService courseDataService;
/**
* Eventing system for course completion processing
*/
private EventRelay eventRelay;
private static final Logger LOGGER = LoggerFactory.getLogger(MobileAcademyServiceImpl.class);
@Autowired
public MobileAcademyServiceImpl(BookmarkDataService bookmarkDataService,
CourseDataService courseDataService,
CompletionRecordDataService completionRecordDataService,
EventRelay eventRelay) {
this.bookmarkDataService = bookmarkDataService;
this.courseDataService = courseDataService;
this.completionRecordDataService = completionRecordDataService;
this.eventRelay = eventRelay;
}
@Override
public Course getCourse() {
// Make this course name configurable
String lookupName = "MobileAcademyCourse";
return courseDataService.findCourseByName(lookupName);
}
@Override
public void setCourse(Course course) {
Course existing = courseDataService.findCourseByName(course.getName());
if (existing == null) {
courseDataService.create(course);
} else {
course.setId(existing.getId());
courseDataService.update(course);
}
}
@Override
public int getCourseVersion() {
Course course = getCourse();
if (course != null) {
DateTime version = course.getModificationDate();
return (int) version.getMillis();
} else {
// return -1 and let the caller handle the upstream response
return -1;
}
}
@Override
public MaBookmark getBookmark(Long callingNumber, Long callId) {
List<Bookmark> bookmarks = bookmarkDataService.findBookmarksForUser(callingNumber.toString());
if (CollectionUtils.isEmpty(bookmarks)) {
return null;
}
if (bookmarks.size() > 1) {
LOGGER.debug("Found more than 1 instance of valid bookmark, picking top");
}
Bookmark existingBookmark = bookmarks.get(0);
MaBookmark toReturn = setMaBookmarkProperties(existingBookmark);
toReturn.setCallId(callId);
return toReturn;
}
@Override
public void setBookmark(MaBookmark saveBookmark) {
String callingNumber = saveBookmark.getCallingNumber().toString();
List<Bookmark> existing = bookmarkDataService.findBookmarksForUser(callingNumber);
if (CollectionUtils.isEmpty(existing)) {
// if no bookmarks exist for user
LOGGER.info("No bookmarks found for user " + callingNumber);
bookmarkDataService.create(setBookmarkProperties(saveBookmark, new Bookmark()));
} else {
// error check
if (existing.size() > 1) {
LOGGER.error("Found more than 1 bookmark for calling number. This should never be possible.");
LOGGER.error("Contact dev team about calling number: " + callingNumber);
}
// update the first bookmark
LOGGER.info("Updating the first bookmark for user");
bookmarkDataService.update(setBookmarkProperties(saveBookmark, existing.get(0)));
}
if (saveBookmark.getBookmark() != null
&& saveBookmark.getScoresByChapter() != null
&& saveBookmark.getBookmark().equals(FINAL_BOOKMARK)
&& saveBookmark.getScoresByChapter().size() == CHAPTER_COUNT) {
LOGGER.debug("Found last bookmark and 11 scores. Starting evaluation & notification");
evaluateCourseCompletion(saveBookmark.getCallingNumber(), saveBookmark.getScoresByChapter());
}
}
// Map the dto to the domain object
private Bookmark setBookmarkProperties(MaBookmark fromBookmark, Bookmark toBookmark) {
toBookmark.setExternalId(fromBookmark.getCallingNumber().toString());
if (toBookmark.getProgress() == null) {
toBookmark.setProgress(new HashMap<String, Object>());
}
toBookmark.getProgress().put("callId", fromBookmark.getCallId());
// This guarantees that we always update to the latest scores
if (fromBookmark.getScoresByChapter() != null) {
toBookmark.getProgress().put(SCORES_KEY, fromBookmark.getScoresByChapter());
}
if (fromBookmark.getBookmark() != null) {
toBookmark.setChapterIdentifier(fromBookmark.getBookmark().split("_")[0]);
toBookmark.setLessonIdentifier(fromBookmark.getBookmark().split("_")[1]);
}
return toBookmark;
}
// Map domain object to dto
private MaBookmark setMaBookmarkProperties(Bookmark fromBookmark) {
MaBookmark toReturn = new MaBookmark();
toReturn.setCallingNumber(Long.parseLong(fromBookmark.getExternalId()));
String bookmark = fromBookmark.getChapterIdentifier() + "_" + fromBookmark.getLessonIdentifier();
Map<String, Integer> scores = getScores(fromBookmark);
// default behavior to map the data
toReturn.setBookmark(bookmark);
toReturn.setScoresByChapter(scores);
// if the bookmark is final and scores pass, reset it
if (bookmark.equals(FINAL_BOOKMARK) && getTotalScore(scores) >= PASS_SCORE) {
LOGGER.debug("We need to reset bookmark to new state.");
toReturn.setScoresByChapter(null);
toReturn.setBookmark(null);
}
return toReturn;
}
// Get scores by chapter from bookmark
private Map<String, Integer> getScores(Bookmark bookmark) throws ClassCastException {
if (bookmark != null && bookmark.getProgress() != null) {
return (Map<String, Integer>) bookmark.getProgress().get(SCORES_KEY);
}
return null;
}
/**
* Helper method to check whether a course meets completion criteria
* @param callingNumber calling number of flw
* @param scores scores in quiz
*/
private void evaluateCourseCompletion(Long callingNumber, Map<String, Integer> scores) {
int totalScore = getTotalScore(scores);
if (getTotalScore(scores) < PASS_SCORE) {
// nothing to do
LOGGER.debug("User with calling number: " + callingNumber + " failed with score: " + totalScore);
return;
}
// We know that they completed the course here. Start post-processing
CompletionRecord cr = completionRecordDataService.findRecordByCallingNumber(callingNumber);
if (cr == null) {
cr = new CompletionRecord(callingNumber, totalScore, false, 1);
completionRecordDataService.create(cr);
} else {
LOGGER.debug("Found existing completion record, updating it");
int completionCount = cr.getCompletionCount();
cr.setCompletionCount(completionCount + 1);
cr.setScore(totalScore);
completionRecordDataService.update(cr);
}
// we updated the completion record. Start event message to trigger notification workflow
Map<String, Object> eventParams = new HashMap<>();
eventParams.put("callingNumber", callingNumber);
MotechEvent motechEvent = new MotechEvent(COURSE_COMPLETED, eventParams);
eventRelay.sendEventMessage(motechEvent);
LOGGER.debug("Sent event message to process completion notification");
}
/**
* Get total scores from all chapters
* @param scoresByChapter scores by chapter
* @return total score
*/
private static int getTotalScore(Map<String, Integer> scoresByChapter) {
if (scoresByChapter == null) {
return 0;
}
int totalScore = 0;
for (int chapterCount = 1; chapterCount <= CHAPTER_COUNT; chapterCount++) {
totalScore += scoresByChapter.get(String.valueOf(chapterCount));
}
return totalScore;
}
}
|
package burp;
import java.io.IOException;
import java.lang.InterruptedException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import com.google.gson.Gson;
import java.awt.Component;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.BorderFactory;
public class BurpExtender implements IBurpExtender, IExtensionStateListener,
IHttpListener, IScannerListener, IProxyListener, ITab {
static final String NAME = "Burp Buddy";
private EventServer wss;
private Gson gson = new Gson();
private IExtensionHelpers helpers;
private PrintWriter stdout;
private PrintWriter stderr;
private IBurpExtenderCallbacks callbacks;
private JPanel panel;
private JScrollPane scroll;
@Override
public void registerExtenderCallbacks (final IBurpExtenderCallbacks callbacks) {
this.callbacks = callbacks;
callbacks.setExtensionName(NAME);
stdout = new PrintWriter(callbacks.getStdout(), true);
stderr = new PrintWriter(callbacks.getStderr(), true);
helpers = callbacks.getHelpers();
String ip = "127.0.0.1";
int port = 8000;
InetSocketAddress address = new InetSocketAddress(ip, port);
wss = new EventServer(stdout, stderr, address);
wss.start();
stdout.println("WebSocket server started at ws://" + ip + ":" + port);
callbacks.registerExtensionStateListener(this);
callbacks.registerHttpListener(this);
callbacks.registerScannerListener(this);
// create our UI
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
panel = new JPanel();
scroll = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setBorder(BorderFactory.createEmptyBorder());
// add the custom tab to Burp's UI
callbacks.addSuiteTab(BurpExtender.this);
}
});
}
@Override
public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse requestResponse) {
if (messageIsRequest) {
BHttpRequest req = BHttpRequestFactory.create(requestResponse, helpers.analyzeRequest(requestResponse),
callbacks);
wss.sendToAll(gson.toJson(req));
} else {
BHttpResponse resp = BHttpResponseFactory.create(requestResponse,
helpers.analyzeResponse(requestResponse.getResponse()), callbacks);
wss.sendToAll(gson.toJson(resp));
}
}
@Override
public void processProxyMessage(boolean messageIsRequest, IInterceptedProxyMessage message) {
}
@Override
public void newScanIssue(IScanIssue scanIssue) {
BScanIssue issue = BScanIssueFactory.create(scanIssue, callbacks);
wss.sendToAll(gson.toJson(issue));
}
@Override
public void extensionUnloaded() {
try {
wss.stop();
stdout.println("WebSocket server stopped");
} catch(IOException e) {
stderr.println("Exception when stopping WebSocket server");
stderr.println(e.getMessage());
} catch(InterruptedException e) {
stderr.println("Exception when stopping WebSocket server");
stderr.println(e.getMessage());
}
}
@Override public String getTabCaption()
{
return "Burp Buddy";
}
@Override public Component getUiComponent()
{
return scroll;
}
}
|
package org.codehaus.modello.plugin.xpp3;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.codehaus.modello.ModelloException;
import org.codehaus.modello.model.Model;
import org.codehaus.modello.model.ModelAssociation;
import org.codehaus.modello.model.ModelClass;
import org.codehaus.modello.model.ModelDefault;
import org.codehaus.modello.model.ModelField;
import org.codehaus.modello.plugin.java.javasource.JClass;
import org.codehaus.modello.plugin.java.javasource.JField;
import org.codehaus.modello.plugin.java.javasource.JMethod;
import org.codehaus.modello.plugin.java.javasource.JParameter;
import org.codehaus.modello.plugin.java.javasource.JSourceCode;
import org.codehaus.modello.plugin.java.javasource.JSourceWriter;
import org.codehaus.modello.plugin.java.javasource.JType;
import org.codehaus.modello.plugin.java.metadata.JavaClassMetadata;
import org.codehaus.modello.plugins.xml.metadata.XmlAssociationMetadata;
import org.codehaus.modello.plugins.xml.metadata.XmlFieldMetadata;
import org.codehaus.plexus.util.StringUtils;
/**
* @author <a href="mailto:jason@modello.org">Jason van Zyl</a>
* @author <a href="mailto:evenisse@codehaus.org">Emmanuel Venisse</a>
* @version $Id$
*/
public class Xpp3ReaderGenerator
extends AbstractXpp3Generator
{
public void generate( Model model, Properties parameters )
throws ModelloException
{
initialize( model, parameters );
try
{
generateXpp3Reader();
}
catch ( IOException ex )
{
throw new ModelloException( "Exception while generating XPP3 Reader.", ex );
}
}
private void generateXpp3Reader()
throws ModelloException, IOException
{
Model objectModel = getModel();
String packageName = objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() )
+ ".io.xpp3";
String unmarshallerName = getFileName( "Xpp3Reader" );
JSourceWriter sourceWriter = newJSourceWriter( packageName, unmarshallerName );
JClass jClass = new JClass( packageName + '.' + unmarshallerName );
initHeader( jClass );
suppressAllWarnings( objectModel, jClass );
jClass.addImport( "org.codehaus.plexus.util.ReaderFactory" );
jClass.addImport( "org.codehaus.plexus.util.xml.pull.MXParser" );
jClass.addImport( "org.codehaus.plexus.util.xml.pull.XmlPullParser" );
jClass.addImport( "org.codehaus.plexus.util.xml.pull.XmlPullParserException" );
jClass.addImport( "java.io.InputStream" );
jClass.addImport( "java.io.IOException" );
jClass.addImport( "java.io.Reader" );
jClass.addImport( "java.text.DateFormat" );
jClass.addImport( "java.util.Locale" );
addModelImports( jClass, null );
// Write option setters
// The Field
JField addDefaultEntities = new JField( JType.BOOLEAN, "addDefaultEntities" );
addDefaultEntities.setComment(
"If set the parser will be loaded with all single characters from the XHTML specification.\n" +
"The entities used:\n" + "<ul>\n" + "<li>http:
"<li>http:
"<li>http:
addDefaultEntities.setInitString( "true" );
jClass.addField( addDefaultEntities );
// The setter
JMethod addDefaultEntitiesSetter = new JMethod( "setAddDefaultEntities" );
addDefaultEntitiesSetter.addParameter( new JParameter( JType.BOOLEAN, "addDefaultEntities" ) );
addDefaultEntitiesSetter.setSourceCode( "this.addDefaultEntities = addDefaultEntities;" );
addDefaultEntitiesSetter.setComment( "Sets the state of the \"add default entities\" flag." );
jClass.addMethod( addDefaultEntitiesSetter );
// The getter
JMethod addDefaultEntitiesGetter = new JMethod( "getAddDefaultEntities", JType.BOOLEAN, null );
addDefaultEntitiesGetter.setComment( "Returns the state of the \"add default entities\" flag." );
addDefaultEntitiesGetter.setSourceCode( "return addDefaultEntities;" );
jClass.addMethod( addDefaultEntitiesGetter );
ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() );
JClass rootType = new JClass( root.getName() );
// Write the read(XmlPullParser,boolean) method which will do the unmarshalling.
JMethod unmarshall = new JMethod( "read", rootType, null );
unmarshall.getModifiers().makePrivate();
unmarshall.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) );
unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) );
unmarshall.addException( new JClass( "IOException" ) );
unmarshall.addException( new JClass( "XmlPullParserException" ) );
JSourceCode sc = unmarshall.getSourceCode();
String tagName = resolveTagName( root );
sc.add( "int eventType = parser.getEventType();" );
sc.add( "while ( eventType != XmlPullParser.END_DOCUMENT )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( eventType == XmlPullParser.START_TAG )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( strict && ! parser.getName().equals( \"" + tagName + "\" ) )" );
sc.add( "{" );
sc.addIndented( "throw new XmlPullParserException( \"Expected root element '" + tagName + "' but "
+ "found '\" + parser.getName() + \"'\", parser, null );" );
sc.add( "}" );
sc.add( root.getName() + ' ' + tagName + " = parse" + root.getName() + "( parser, strict );" );
sc.add( tagName + ".setModelEncoding( parser.getInputEncoding() );" );
sc.add( "return " + tagName + ';' );
sc.unindent();
sc.add( "}" );
sc.add( "eventType = parser.next();" );
sc.unindent();
sc.add( "}" );
sc.add( "throw new XmlPullParserException( \"Expected root element '" + tagName + "' but "
+ "found no element at all: invalid XML document\", parser, null );" );
jClass.addMethod( unmarshall );
// Write the read(Reader[,boolean]) methods which will do the unmarshalling.
unmarshall = new JMethod( "read", rootType, null );
unmarshall.setComment( "@see ReaderFactory#newXmlReader" );
unmarshall.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) );
unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) );
unmarshall.addException( new JClass( "IOException" ) );
unmarshall.addException( new JClass( "XmlPullParserException" ) );
sc = unmarshall.getSourceCode();
sc.add( "XmlPullParser parser = new MXParser();" );
sc.add( "" );
sc.add( "parser.setInput( reader );" );
sc.add( "" );
writeParserInitialization( sc );
sc.add( "" );
sc.add( "return read( parser, strict );" );
jClass.addMethod( unmarshall );
unmarshall = new JMethod( "read", rootType, null );
unmarshall.setComment( "@see ReaderFactory#newXmlReader" );
unmarshall.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) );
unmarshall.addException( new JClass( "IOException" ) );
unmarshall.addException( new JClass( "XmlPullParserException" ) );
sc = unmarshall.getSourceCode();
sc.add( "return read( reader, true );" );
jClass.addMethod( unmarshall );
// Write the read(InputStream[,boolean]) methods which will do the unmarshalling.
unmarshall = new JMethod( "read", rootType, null );
unmarshall.addParameter( new JParameter( new JClass( "InputStream" ), "in" ) );
unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) );
unmarshall.addException( new JClass( "IOException" ) );
unmarshall.addException( new JClass( "XmlPullParserException" ) );
sc = unmarshall.getSourceCode();
sc.add( "Reader reader = ReaderFactory.newXmlReader( in );" );
sc.add( "" );
sc.add( "return read( reader, strict );" );
jClass.addMethod( unmarshall );
unmarshall = new JMethod( "read", rootType, null );
unmarshall.addParameter( new JParameter( new JClass( "InputStream" ), "in" ) );
unmarshall.addException( new JClass( "IOException" ) );
unmarshall.addException( new JClass( "XmlPullParserException" ) );
sc = unmarshall.getSourceCode();
sc.add( "Reader reader = ReaderFactory.newXmlReader( in );" );
sc.add( "" );
sc.add( "return read( reader );" );
jClass.addMethod( unmarshall );
// Write the class parsers
writeAllClassesParser( objectModel, jClass );
// Write helpers
writeHelpers( jClass );
jClass.print( sourceWriter );
sourceWriter.close();
}
private void writeAllClassesParser( Model objectModel, JClass jClass )
{
ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() );
for ( Iterator i = objectModel.getClasses( getGeneratedVersion() ).iterator(); i.hasNext(); )
{
ModelClass clazz = (ModelClass) i.next();
JavaClassMetadata javaClassMetadata = (JavaClassMetadata) clazz.getMetadata( JavaClassMetadata.ID );
if ( !javaClassMetadata.isEnabled() )
{
// Skip import of those classes that are not enabled for the java plugin.
continue;
}
writeClassParser( clazz, jClass, root.getName().equals( clazz.getName() ) );
}
}
private void writeClassParser( ModelClass modelClass, JClass jClass, boolean rootElement )
{
JavaClassMetadata javaClassMetadata =
(JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.class.getName() );
// Skip abstract classes, no way to parse them out into objects
if ( javaClassMetadata.isAbstract() )
{
return;
}
String className = modelClass.getName();
String capClassName = capitalise( className );
String uncapClassName = uncapitalise( className );
JMethod unmarshall = new JMethod( "parse" + capClassName, new JClass( className ), null );
unmarshall.getModifiers().makePrivate();
unmarshall.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) );
unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) );
unmarshall.addException( new JClass( "IOException" ) );
unmarshall.addException( new JClass( "XmlPullParserException" ) );
JSourceCode sc = unmarshall.getSourceCode();
sc.add( "String tagName = parser.getName();" );
sc.add( className + " " + uncapClassName + " = new " + className + "();" );
ModelField contentField = null;
List modelFields = modelClass.getAllFields( getGeneratedVersion(), true );
modelFields = getNonTransientFields( modelFields );
// read all XML attributes first
contentField = writeClassAttributesParser( modelFields, uncapClassName, rootElement, sc, jClass );
// then read content, either content field or elements
if ( contentField != null )
{
writePrimitiveField( contentField, contentField.getType(), uncapClassName,
"set" + capitalise( contentField.getName() ), sc, jClass );
}
else
{
//Write other fields
sc.add( "java.util.Set parsed = new java.util.HashSet();" );
sc.add( "while ( parser.nextTag() == XmlPullParser.START_TAG )" );
sc.add( "{" );
sc.indent();
boolean addElse = false;
for ( Iterator i = modelFields.iterator(); i.hasNext(); )
{
ModelField field = (ModelField) i.next();
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
if ( !xmlFieldMetadata.isAttribute() )
{
processField( field, xmlFieldMetadata, addElse, sc, uncapClassName, jClass );
addElse = true;
}
}
if ( addElse )
{
sc.add( "else" );
sc.add( "{" );
sc.indent();
}
sc.add( "checkUnknownElement( parser, strict );" );
if ( addElse )
{
sc.unindent();
sc.add( "}" );
}
sc.unindent();
sc.add( "}" );
}
sc.add( "return " + uncapClassName + ";" );
jClass.addMethod( unmarshall );
}
private ModelField writeClassAttributesParser( List modelFields, String objectName, boolean rootElement, JSourceCode sc, JClass jClass )
{
ModelField contentField = null;
sc.add( "for ( int i = parser.getAttributeCount() - 1; i >= 0; i
sc.add( "{" );
sc.indent();
sc.add( "String name = parser.getAttributeName( i );" );
sc.add( "String value = parser.getAttributeValue( i );" );
sc.add( "" );
sc.add( "if ( name.indexOf( ':' ) >= 0 )" );
sc.add( "{" );
sc.addIndented( "// just ignore attributes with non-default namespace (for example: xmlns:xsi)" );
sc.add( "}" );
if ( rootElement )
{
sc.add( "else if ( \"xmlns\".equals( name ) )" );
sc.add( "{" );
sc.addIndented( "// ignore xmlns attribute in root class, which is a reserved attribute name" );
sc.add( "}" );
}
for ( Iterator i = modelFields.iterator(); i.hasNext(); )
{
ModelField field = (ModelField) i.next();
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
if ( xmlFieldMetadata.isAttribute() )
{
String tagName = resolveTagName( field, xmlFieldMetadata );
sc.add( "else if ( \"" + tagName + "\".equals( name ) )");
sc.add( "{" );
sc.indent();
writePrimitiveField( field, field.getType(), objectName, "set" + capitalise( field.getName() ), sc,
jClass );
sc.unindent();
sc.add( "}" );
}
// TODO check if we have already one with this type and throws Exception
if ( xmlFieldMetadata.isContent() )
{
contentField = field;
}
}
sc.add( "else if ( strict )" );
sc.add( "{" );
sc.addIndented( "throw new XmlPullParserException( \"Unknown attribute '\" + name + \"' for tag '\" + tagName + \"'\", parser, null );" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
return contentField;
}
/**
* Generate code to process a field represented as an XML element.
*
* @param field the field to process
* @param xmlFieldMetadata its XML metadata
* @param addElse add an <code>else</code> statement before generating a new <code>if</code>
* @param sc the method source code to add to
* @param objectName the object name in the source
* @param jClass the generated class source file
*/
private void processField( ModelField field, XmlFieldMetadata xmlFieldMetadata, boolean addElse, JSourceCode sc,
String objectName, JClass jClass )
{
String fieldTagName = resolveTagName( field, xmlFieldMetadata );
String capFieldName = capitalise( field.getName() );
String singularName = singular( field.getName() );
String alias;
if ( StringUtils.isEmpty( field.getAlias() ) )
{
alias = "null";
}
else
{
alias = "\"" + field.getAlias() + "\"";
}
String tagComparison = ( addElse ? "else " : "" )
+ "if ( checkFieldWithDuplicate( parser, \"" + fieldTagName + "\", " + alias + ", parsed ) )";
if ( !( field instanceof ModelAssociation ) )
{
//ModelField
sc.add( tagComparison );
sc.add( "{" );
sc.indent();
writePrimitiveField( field, field.getType(), objectName, "set" + capitalise( field.getName() ), sc,
jClass );
sc.unindent();
sc.add( "}" );
}
else
{ // model association
ModelAssociation association = (ModelAssociation) field;
String associationName = association.getName();
if ( association.isOneMultiplicity() )
{
sc.add( tagComparison );
sc.add( "{" );
sc.addIndented( objectName + ".set" + capFieldName + "( parse" + association.getTo() + "( parser, strict ) );" );
sc.add( "}" );
}
else
{
//MANY_MULTIPLICITY
XmlAssociationMetadata xmlAssociationMetadata =
(XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID );
String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata );
String type = association.getType();
if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) )
{
boolean wrappedItems = xmlAssociationMetadata.isWrappedItems();
if ( wrappedItems )
{
sc.add( tagComparison );
sc.add( "{" );
sc.indent();
sc.add( type + " " + associationName + " = " + association.getDefaultValue() + ";" );
sc.add( objectName + ".set" + capFieldName + "( " + associationName + " );" );
sc.add( "while ( parser.nextTag() == XmlPullParser.START_TAG )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( parser.getName().equals( \"" + valuesTagName + "\" ) )" );
sc.add( "{" );
sc.indent();
}
else
{
sc.add( ( addElse ? "else " : "" )
+ "if ( parser.getName().equals( \"" + valuesTagName + "\" ) )" );
sc.add( "{" );
sc.indent();
sc.add( type + " " + associationName + " = " + objectName + ".get" + capFieldName + "();" );
sc.add( "if ( " + associationName + " == null )" );
sc.add( "{" );
sc.indent();
sc.add( associationName + " = " + association.getDefaultValue() + ";" );
sc.add( objectName + ".set" + capFieldName + "( " + associationName + " );" );
sc.unindent();
sc.add( "}" );
}
if ( isClassInModel( association.getTo(), field.getModelClass().getModel() ) )
{
sc.add( associationName + ".add( parse" + association.getTo() + "( parser, strict ) );" );
}
else
{
writePrimitiveField( association, association.getTo(), associationName, "add", sc, jClass );
}
if ( wrappedItems )
{
sc.unindent();
sc.add( "}" );
sc.add( "else" );
sc.add( "{" );
sc.addIndented( "checkUnknownElement( parser, strict );" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.unindent();
sc.add( "}" );
}
else
{
sc.unindent();
sc.add( "}" );
}
}
else
{
//Map or Properties
sc.add( tagComparison );
sc.add( "{" );
sc.indent();
if ( xmlAssociationMetadata.isMapExplode() )
{
sc.add( "while ( parser.nextTag() == XmlPullParser.START_TAG )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( parser.getName().equals( \"" + valuesTagName + "\" ) )" );
sc.add( "{" );
sc.indent();
sc.add( "String key = null;" );
sc.add( "String value = null;" );
sc.add( "// " + xmlAssociationMetadata.getMapStyle() + " mode." );
sc.add( "while ( parser.nextTag() == XmlPullParser.START_TAG )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( parser.getName().equals( \"key\" ) )" );
sc.add( "{" );
sc.addIndented( "key = parser.nextText();" );
sc.add( "}" );
sc.add( "else if ( parser.getName().equals( \"value\" ) )" );
sc.add( "{" );
sc.addIndented( "value = parser.nextText()" + ( xmlFieldMetadata.isTrim() ? ".trim()" : "" )
+ ";" );
sc.add( "}" );
sc.add( "else" );
sc.add( "{" );
sc.addIndented( "parser.nextText();" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" );
sc.unindent();
sc.add( "}" );
sc.add( "parser.next();" );
sc.unindent();
sc.add( "}" );
}
else
{
//INLINE Mode
sc.add( "while ( parser.nextTag() == XmlPullParser.START_TAG )" );
sc.add( "{" );
sc.indent();
sc.add( "String key = parser.getName();" );
sc.add( "String value = parser.nextText()" + ( xmlFieldMetadata.isTrim() ? ".trim()" : "" )
+ ";" );
sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" );
sc.unindent();
sc.add( "}" );
}
sc.unindent();
sc.add( "}" );
}
}
}
}
private void writePrimitiveField( ModelField field, String type, String objectName, String setterName,
JSourceCode sc, JClass jClass )
{
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
String tagName = resolveTagName( field, xmlFieldMetadata);
String parserGetter;
if ( xmlFieldMetadata.isAttribute() )
{
parserGetter = "value"; // local variable created in the parsing block
}
else
{
parserGetter = "parser.nextText()";
}
/* TODO: this and a default
if ( xmlFieldMetadata.isRequired() )
{
parserGetter = "getRequiredAttributeValue( " + parserGetter + ", \"" + tagName + "\", parser, strict )";
}
*/
if ( xmlFieldMetadata.isTrim() )
{
parserGetter = "getTrimmedValue( " + parserGetter + " )";
}
if ( "boolean".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getBooleanValue( " + parserGetter + ", \"" + tagName +
"\", parser, \"" + field.getDefaultValue() + "\" ) );" );
}
else if ( "char".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getCharacterValue( " + parserGetter + ", \"" + tagName +
"\", parser ) );" );
}
else if ( "double".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getDoubleValue( " + parserGetter + ", \"" + tagName +
"\", parser, strict ) );" );
}
else if ( "float".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getFloatValue( " + parserGetter + ", \"" + tagName +
"\", parser, strict ) );" );
}
else if ( "int".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getIntegerValue( " + parserGetter + ", \"" + tagName +
"\", parser, strict ) );" );
}
else if ( "long".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getLongValue( " + parserGetter + ", \"" + tagName +
"\", parser, strict ) );" );
}
else if ( "short".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getShortValue( " + parserGetter + ", \"" + tagName +
"\", parser, strict ) );" );
}
else if ( "byte".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getByteValue( " + parserGetter + ", \"" + tagName +
"\", parser, strict ) );" );
}
else if ( "String".equals( type ) || "Boolean".equals( type ) )
{
// TODO: other Primitive types
sc.add( objectName + "." + setterName + "( " + parserGetter + " );" );
}
else if ( "Date".equals( type ) )
{
sc.add( "String dateFormat = " +
( xmlFieldMetadata.getFormat() != null ? "\"" + xmlFieldMetadata.getFormat() + "\"" : "null" ) + ";" );
sc.add( objectName + "." + setterName + "( getDateValue( " + parserGetter + ", \"" + tagName +
"\", dateFormat, parser ) );" );
}
else if ( "DOM".equals( type ) )
{
jClass.addImport( "org.codehaus.plexus.util.xml.Xpp3DomBuilder" );
sc.add( objectName + "." + setterName + "( Xpp3DomBuilder.build( parser ) );" );
}
else
{
throw new IllegalArgumentException( "Unknown type: " + type );
}
}
private void writeParserInitialization( JSourceCode sc )
{
sc.add( "if ( addDefaultEntities )" );
sc.add( "{" );
sc.indent();
sc.add( "
sc.add( "// Latin 1 entities" );
sc.add( "
sc.add( "" );
sc.add( "parser.defineEntityReplacementText( \"nbsp\", \"\\u00a0\" );" );
sc.add( "parser.defineEntityReplacementText( \"iexcl\", \"\\u00a1\" );" );
sc.add( "parser.defineEntityReplacementText( \"cent\", \"\\u00a2\" );" );
sc.add( "parser.defineEntityReplacementText( \"pound\", \"\\u00a3\" );" );
sc.add( "parser.defineEntityReplacementText( \"curren\", \"\\u00a4\" );" );
sc.add( "parser.defineEntityReplacementText( \"yen\", \"\\u00a5\" );" );
sc.add( "parser.defineEntityReplacementText( \"brvbar\", \"\\u00a6\" );" );
sc.add( "parser.defineEntityReplacementText( \"sect\", \"\\u00a7\" );" );
sc.add( "parser.defineEntityReplacementText( \"uml\", \"\\u00a8\" );" );
sc.add( "parser.defineEntityReplacementText( \"copy\", \"\\u00a9\" );" );
sc.add( "parser.defineEntityReplacementText( \"ordf\", \"\\u00aa\" );" );
sc.add( "parser.defineEntityReplacementText( \"laquo\", \"\\u00ab\" );" );
sc.add( "parser.defineEntityReplacementText( \"not\", \"\\u00ac\" );" );
sc.add( "parser.defineEntityReplacementText( \"shy\", \"\\u00ad\" );" );
sc.add( "parser.defineEntityReplacementText( \"reg\", \"\\u00ae\" );" );
sc.add( "parser.defineEntityReplacementText( \"macr\", \"\\u00af\" );" );
sc.add( "parser.defineEntityReplacementText( \"deg\", \"\\u00b0\" );" );
sc.add( "parser.defineEntityReplacementText( \"plusmn\", \"\\u00b1\" );" );
sc.add( "parser.defineEntityReplacementText( \"sup2\", \"\\u00b2\" );" );
sc.add( "parser.defineEntityReplacementText( \"sup3\", \"\\u00b3\" );" );
sc.add( "parser.defineEntityReplacementText( \"acute\", \"\\u00b4\" );" );
sc.add( "parser.defineEntityReplacementText( \"micro\", \"\\u00b5\" );" );
sc.add( "parser.defineEntityReplacementText( \"para\", \"\\u00b6\" );" );
sc.add( "parser.defineEntityReplacementText( \"middot\", \"\\u00b7\" );" );
sc.add( "parser.defineEntityReplacementText( \"cedil\", \"\\u00b8\" );" );
sc.add( "parser.defineEntityReplacementText( \"sup1\", \"\\u00b9\" );" );
sc.add( "parser.defineEntityReplacementText( \"ordm\", \"\\u00ba\" );" );
sc.add( "parser.defineEntityReplacementText( \"raquo\", \"\\u00bb\" );" );
sc.add( "parser.defineEntityReplacementText( \"frac14\", \"\\u00bc\" );" );
sc.add( "parser.defineEntityReplacementText( \"frac12\", \"\\u00bd\" );" );
sc.add( "parser.defineEntityReplacementText( \"frac34\", \"\\u00be\" );" );
sc.add( "parser.defineEntityReplacementText( \"iquest\", \"\\u00bf\" );" );
sc.add( "parser.defineEntityReplacementText( \"Agrave\", \"\\u00c0\" );" );
sc.add( "parser.defineEntityReplacementText( \"Aacute\", \"\\u00c1\" );" );
sc.add( "parser.defineEntityReplacementText( \"Acirc\", \"\\u00c2\" );" );
sc.add( "parser.defineEntityReplacementText( \"Atilde\", \"\\u00c3\" );" );
sc.add( "parser.defineEntityReplacementText( \"Auml\", \"\\u00c4\" );" );
sc.add( "parser.defineEntityReplacementText( \"Aring\", \"\\u00c5\" );" );
sc.add( "parser.defineEntityReplacementText( \"AElig\", \"\\u00c6\" );" );
sc.add( "parser.defineEntityReplacementText( \"Ccedil\", \"\\u00c7\" );" );
sc.add( "parser.defineEntityReplacementText( \"Egrave\", \"\\u00c8\" );" );
sc.add( "parser.defineEntityReplacementText( \"Eacute\", \"\\u00c9\" );" );
sc.add( "parser.defineEntityReplacementText( \"Ecirc\", \"\\u00ca\" );" );
sc.add( "parser.defineEntityReplacementText( \"Euml\", \"\\u00cb\" );" );
sc.add( "parser.defineEntityReplacementText( \"Igrave\", \"\\u00cc\" );" );
sc.add( "parser.defineEntityReplacementText( \"Iacute\", \"\\u00cd\" );" );
sc.add( "parser.defineEntityReplacementText( \"Icirc\", \"\\u00ce\" );" );
sc.add( "parser.defineEntityReplacementText( \"Iuml\", \"\\u00cf\" );" );
sc.add( "parser.defineEntityReplacementText( \"ETH\", \"\\u00d0\" );" );
sc.add( "parser.defineEntityReplacementText( \"Ntilde\", \"\\u00d1\" );" );
sc.add( "parser.defineEntityReplacementText( \"Ograve\", \"\\u00d2\" );" );
sc.add( "parser.defineEntityReplacementText( \"Oacute\", \"\\u00d3\" );" );
sc.add( "parser.defineEntityReplacementText( \"Ocirc\", \"\\u00d4\" );" );
sc.add( "parser.defineEntityReplacementText( \"Otilde\", \"\\u00d5\" );" );
sc.add( "parser.defineEntityReplacementText( \"Ouml\", \"\\u00d6\" );" );
sc.add( "parser.defineEntityReplacementText( \"times\", \"\\u00d7\" );" );
sc.add( "parser.defineEntityReplacementText( \"Oslash\", \"\\u00d8\" );" );
sc.add( "parser.defineEntityReplacementText( \"Ugrave\", \"\\u00d9\" );" );
sc.add( "parser.defineEntityReplacementText( \"Uacute\", \"\\u00da\" );" );
sc.add( "parser.defineEntityReplacementText( \"Ucirc\", \"\\u00db\" );" );
sc.add( "parser.defineEntityReplacementText( \"Uuml\", \"\\u00dc\" );" );
sc.add( "parser.defineEntityReplacementText( \"Yacute\", \"\\u00dd\" );" );
sc.add( "parser.defineEntityReplacementText( \"THORN\", \"\\u00de\" );" );
sc.add( "parser.defineEntityReplacementText( \"szlig\", \"\\u00df\" );" );
sc.add( "parser.defineEntityReplacementText( \"agrave\", \"\\u00e0\" );" );
sc.add( "parser.defineEntityReplacementText( \"aacute\", \"\\u00e1\" );" );
sc.add( "parser.defineEntityReplacementText( \"acirc\", \"\\u00e2\" );" );
sc.add( "parser.defineEntityReplacementText( \"atilde\", \"\\u00e3\" );" );
sc.add( "parser.defineEntityReplacementText( \"auml\", \"\\u00e4\" );" );
sc.add( "parser.defineEntityReplacementText( \"aring\", \"\\u00e5\" );" );
sc.add( "parser.defineEntityReplacementText( \"aelig\", \"\\u00e6\" );" );
sc.add( "parser.defineEntityReplacementText( \"ccedil\", \"\\u00e7\" );" );
sc.add( "parser.defineEntityReplacementText( \"egrave\", \"\\u00e8\" );" );
sc.add( "parser.defineEntityReplacementText( \"eacute\", \"\\u00e9\" );" );
sc.add( "parser.defineEntityReplacementText( \"ecirc\", \"\\u00ea\" );" );
sc.add( "parser.defineEntityReplacementText( \"euml\", \"\\u00eb\" );" );
sc.add( "parser.defineEntityReplacementText( \"igrave\", \"\\u00ec\" );" );
sc.add( "parser.defineEntityReplacementText( \"iacute\", \"\\u00ed\" );" );
sc.add( "parser.defineEntityReplacementText( \"icirc\", \"\\u00ee\" );" );
sc.add( "parser.defineEntityReplacementText( \"iuml\", \"\\u00ef\" );" );
sc.add( "parser.defineEntityReplacementText( \"eth\", \"\\u00f0\" );" );
sc.add( "parser.defineEntityReplacementText( \"ntilde\", \"\\u00f1\" );" );
sc.add( "parser.defineEntityReplacementText( \"ograve\", \"\\u00f2\" );" );
sc.add( "parser.defineEntityReplacementText( \"oacute\", \"\\u00f3\" );" );
sc.add( "parser.defineEntityReplacementText( \"ocirc\", \"\\u00f4\" );" );
sc.add( "parser.defineEntityReplacementText( \"otilde\", \"\\u00f5\" );" );
sc.add( "parser.defineEntityReplacementText( \"ouml\", \"\\u00f6\" );" );
sc.add( "parser.defineEntityReplacementText( \"divide\", \"\\u00f7\" );" );
sc.add( "parser.defineEntityReplacementText( \"oslash\", \"\\u00f8\" );" );
sc.add( "parser.defineEntityReplacementText( \"ugrave\", \"\\u00f9\" );" );
sc.add( "parser.defineEntityReplacementText( \"uacute\", \"\\u00fa\" );" );
sc.add( "parser.defineEntityReplacementText( \"ucirc\", \"\\u00fb\" );" );
sc.add( "parser.defineEntityReplacementText( \"uuml\", \"\\u00fc\" );" );
sc.add( "parser.defineEntityReplacementText( \"yacute\", \"\\u00fd\" );" );
sc.add( "parser.defineEntityReplacementText( \"thorn\", \"\\u00fe\" );" );
sc.add( "parser.defineEntityReplacementText( \"yuml\", \"\\u00ff\" );" );
sc.add( "" );
sc.add( "
sc.add( "// Special entities" );
sc.add( "
sc.add( "" );
// These are required to be handled by the parser by the XML specification
// sc.add( "parser.defineEntityReplacementText( \"quot\", \"\\u0022\" );" );
// sc.add( "parser.defineEntityReplacementText( \"amp\", \"\\u0026\" );" );
// sc.add( "parser.defineEntityReplacementText( \"lt\", \"\\u003c\" );" );
// sc.add( "parser.defineEntityReplacementText( \"gt\", \"\\u003e\" );" );
// sc.add( "parser.defineEntityReplacementText( \"apos\", \"\\u0027\" );" );
sc.add( "parser.defineEntityReplacementText( \"OElig\", \"\\u0152\" );" );
sc.add( "parser.defineEntityReplacementText( \"oelig\", \"\\u0153\" );" );
sc.add( "parser.defineEntityReplacementText( \"Scaron\", \"\\u0160\" );" );
sc.add( "parser.defineEntityReplacementText( \"scaron\", \"\\u0161\" );" );
sc.add( "parser.defineEntityReplacementText( \"Yuml\", \"\\u0178\" );" );
sc.add( "parser.defineEntityReplacementText( \"circ\", \"\\u02c6\" );" );
sc.add( "parser.defineEntityReplacementText( \"tilde\", \"\\u02dc\" );" );
sc.add( "parser.defineEntityReplacementText( \"ensp\", \"\\u2002\" );" );
sc.add( "parser.defineEntityReplacementText( \"emsp\", \"\\u2003\" );" );
sc.add( "parser.defineEntityReplacementText( \"thinsp\", \"\\u2009\" );" );
sc.add( "parser.defineEntityReplacementText( \"zwnj\", \"\\u200c\" );" );
sc.add( "parser.defineEntityReplacementText( \"zwj\", \"\\u200d\" );" );
sc.add( "parser.defineEntityReplacementText( \"lrm\", \"\\u200e\" );" );
sc.add( "parser.defineEntityReplacementText( \"rlm\", \"\\u200f\" );" );
sc.add( "parser.defineEntityReplacementText( \"ndash\", \"\\u2013\" );" );
sc.add( "parser.defineEntityReplacementText( \"mdash\", \"\\u2014\" );" );
sc.add( "parser.defineEntityReplacementText( \"lsquo\", \"\\u2018\" );" );
sc.add( "parser.defineEntityReplacementText( \"rsquo\", \"\\u2019\" );" );
sc.add( "parser.defineEntityReplacementText( \"sbquo\", \"\\u201a\" );" );
sc.add( "parser.defineEntityReplacementText( \"ldquo\", \"\\u201c\" );" );
sc.add( "parser.defineEntityReplacementText( \"rdquo\", \"\\u201d\" );" );
sc.add( "parser.defineEntityReplacementText( \"bdquo\", \"\\u201e\" );" );
sc.add( "parser.defineEntityReplacementText( \"dagger\", \"\\u2020\" );" );
sc.add( "parser.defineEntityReplacementText( \"Dagger\", \"\\u2021\" );" );
sc.add( "parser.defineEntityReplacementText( \"permil\", \"\\u2030\" );" );
sc.add( "parser.defineEntityReplacementText( \"lsaquo\", \"\\u2039\" );" );
sc.add( "parser.defineEntityReplacementText( \"rsaquo\", \"\\u203a\" );" );
sc.add( "parser.defineEntityReplacementText( \"euro\", \"\\u20ac\" );" );
sc.add( "" );
sc.add( "
sc.add( "// Symbol entities" );
sc.add( "
sc.add( "" );
sc.add( "parser.defineEntityReplacementText( \"fnof\", \"\\u0192\" );" );
sc.add( "parser.defineEntityReplacementText( \"Alpha\", \"\\u0391\" );" );
sc.add( "parser.defineEntityReplacementText( \"Beta\", \"\\u0392\" );" );
sc.add( "parser.defineEntityReplacementText( \"Gamma\", \"\\u0393\" );" );
sc.add( "parser.defineEntityReplacementText( \"Delta\", \"\\u0394\" );" );
sc.add( "parser.defineEntityReplacementText( \"Epsilon\", \"\\u0395\" );" );
sc.add( "parser.defineEntityReplacementText( \"Zeta\", \"\\u0396\" );" );
sc.add( "parser.defineEntityReplacementText( \"Eta\", \"\\u0397\" );" );
sc.add( "parser.defineEntityReplacementText( \"Theta\", \"\\u0398\" );" );
sc.add( "parser.defineEntityReplacementText( \"Iota\", \"\\u0399\" );" );
sc.add( "parser.defineEntityReplacementText( \"Kappa\", \"\\u039a\" );" );
sc.add( "parser.defineEntityReplacementText( \"Lambda\", \"\\u039b\" );" );
sc.add( "parser.defineEntityReplacementText( \"Mu\", \"\\u039c\" );" );
sc.add( "parser.defineEntityReplacementText( \"Nu\", \"\\u039d\" );" );
sc.add( "parser.defineEntityReplacementText( \"Xi\", \"\\u039e\" );" );
sc.add( "parser.defineEntityReplacementText( \"Omicron\", \"\\u039f\" );" );
sc.add( "parser.defineEntityReplacementText( \"Pi\", \"\\u03a0\" );" );
sc.add( "parser.defineEntityReplacementText( \"Rho\", \"\\u03a1\" );" );
sc.add( "parser.defineEntityReplacementText( \"Sigma\", \"\\u03a3\" );" );
sc.add( "parser.defineEntityReplacementText( \"Tau\", \"\\u03a4\" );" );
sc.add( "parser.defineEntityReplacementText( \"Upsilon\", \"\\u03a5\" );" );
sc.add( "parser.defineEntityReplacementText( \"Phi\", \"\\u03a6\" );" );
sc.add( "parser.defineEntityReplacementText( \"Chi\", \"\\u03a7\" );" );
sc.add( "parser.defineEntityReplacementText( \"Psi\", \"\\u03a8\" );" );
sc.add( "parser.defineEntityReplacementText( \"Omega\", \"\\u03a9\" );" );
sc.add( "parser.defineEntityReplacementText( \"alpha\", \"\\u03b1\" );" );
sc.add( "parser.defineEntityReplacementText( \"beta\", \"\\u03b2\" );" );
sc.add( "parser.defineEntityReplacementText( \"gamma\", \"\\u03b3\" );" );
sc.add( "parser.defineEntityReplacementText( \"delta\", \"\\u03b4\" );" );
sc.add( "parser.defineEntityReplacementText( \"epsilon\", \"\\u03b5\" );" );
sc.add( "parser.defineEntityReplacementText( \"zeta\", \"\\u03b6\" );" );
sc.add( "parser.defineEntityReplacementText( \"eta\", \"\\u03b7\" );" );
sc.add( "parser.defineEntityReplacementText( \"theta\", \"\\u03b8\" );" );
sc.add( "parser.defineEntityReplacementText( \"iota\", \"\\u03b9\" );" );
sc.add( "parser.defineEntityReplacementText( \"kappa\", \"\\u03ba\" );" );
sc.add( "parser.defineEntityReplacementText( \"lambda\", \"\\u03bb\" );" );
sc.add( "parser.defineEntityReplacementText( \"mu\", \"\\u03bc\" );" );
sc.add( "parser.defineEntityReplacementText( \"nu\", \"\\u03bd\" );" );
sc.add( "parser.defineEntityReplacementText( \"xi\", \"\\u03be\" );" );
sc.add( "parser.defineEntityReplacementText( \"omicron\", \"\\u03bf\" );" );
sc.add( "parser.defineEntityReplacementText( \"pi\", \"\\u03c0\" );" );
sc.add( "parser.defineEntityReplacementText( \"rho\", \"\\u03c1\" );" );
sc.add( "parser.defineEntityReplacementText( \"sigmaf\", \"\\u03c2\" );" );
sc.add( "parser.defineEntityReplacementText( \"sigma\", \"\\u03c3\" );" );
sc.add( "parser.defineEntityReplacementText( \"tau\", \"\\u03c4\" );" );
sc.add( "parser.defineEntityReplacementText( \"upsilon\", \"\\u03c5\" );" );
sc.add( "parser.defineEntityReplacementText( \"phi\", \"\\u03c6\" );" );
sc.add( "parser.defineEntityReplacementText( \"chi\", \"\\u03c7\" );" );
sc.add( "parser.defineEntityReplacementText( \"psi\", \"\\u03c8\" );" );
sc.add( "parser.defineEntityReplacementText( \"omega\", \"\\u03c9\" );" );
sc.add( "parser.defineEntityReplacementText( \"thetasym\", \"\\u03d1\" );" );
sc.add( "parser.defineEntityReplacementText( \"upsih\", \"\\u03d2\" );" );
sc.add( "parser.defineEntityReplacementText( \"piv\", \"\\u03d6\" );" );
sc.add( "parser.defineEntityReplacementText( \"bull\", \"\\u2022\" );" );
sc.add( "parser.defineEntityReplacementText( \"hellip\", \"\\u2026\" );" );
sc.add( "parser.defineEntityReplacementText( \"prime\", \"\\u2032\" );" );
sc.add( "parser.defineEntityReplacementText( \"Prime\", \"\\u2033\" );" );
sc.add( "parser.defineEntityReplacementText( \"oline\", \"\\u203e\" );" );
sc.add( "parser.defineEntityReplacementText( \"frasl\", \"\\u2044\" );" );
sc.add( "parser.defineEntityReplacementText( \"weierp\", \"\\u2118\" );" );
sc.add( "parser.defineEntityReplacementText( \"image\", \"\\u2111\" );" );
sc.add( "parser.defineEntityReplacementText( \"real\", \"\\u211c\" );" );
sc.add( "parser.defineEntityReplacementText( \"trade\", \"\\u2122\" );" );
sc.add( "parser.defineEntityReplacementText( \"alefsym\", \"\\u2135\" );" );
sc.add( "parser.defineEntityReplacementText( \"larr\", \"\\u2190\" );" );
sc.add( "parser.defineEntityReplacementText( \"uarr\", \"\\u2191\" );" );
sc.add( "parser.defineEntityReplacementText( \"rarr\", \"\\u2192\" );" );
sc.add( "parser.defineEntityReplacementText( \"darr\", \"\\u2193\" );" );
sc.add( "parser.defineEntityReplacementText( \"harr\", \"\\u2194\" );" );
sc.add( "parser.defineEntityReplacementText( \"crarr\", \"\\u21b5\" );" );
sc.add( "parser.defineEntityReplacementText( \"lArr\", \"\\u21d0\" );" );
sc.add( "parser.defineEntityReplacementText( \"uArr\", \"\\u21d1\" );" );
sc.add( "parser.defineEntityReplacementText( \"rArr\", \"\\u21d2\" );" );
sc.add( "parser.defineEntityReplacementText( \"dArr\", \"\\u21d3\" );" );
sc.add( "parser.defineEntityReplacementText( \"hArr\", \"\\u21d4\" );" );
sc.add( "parser.defineEntityReplacementText( \"forall\", \"\\u2200\" );" );
sc.add( "parser.defineEntityReplacementText( \"part\", \"\\u2202\" );" );
sc.add( "parser.defineEntityReplacementText( \"exist\", \"\\u2203\" );" );
sc.add( "parser.defineEntityReplacementText( \"empty\", \"\\u2205\" );" );
sc.add( "parser.defineEntityReplacementText( \"nabla\", \"\\u2207\" );" );
sc.add( "parser.defineEntityReplacementText( \"isin\", \"\\u2208\" );" );
sc.add( "parser.defineEntityReplacementText( \"notin\", \"\\u2209\" );" );
sc.add( "parser.defineEntityReplacementText( \"ni\", \"\\u220b\" );" );
sc.add( "parser.defineEntityReplacementText( \"prod\", \"\\u220f\" );" );
sc.add( "parser.defineEntityReplacementText( \"sum\", \"\\u2211\" );" );
sc.add( "parser.defineEntityReplacementText( \"minus\", \"\\u2212\" );" );
sc.add( "parser.defineEntityReplacementText( \"lowast\", \"\\u2217\" );" );
sc.add( "parser.defineEntityReplacementText( \"radic\", \"\\u221a\" );" );
sc.add( "parser.defineEntityReplacementText( \"prop\", \"\\u221d\" );" );
sc.add( "parser.defineEntityReplacementText( \"infin\", \"\\u221e\" );" );
sc.add( "parser.defineEntityReplacementText( \"ang\", \"\\u2220\" );" );
sc.add( "parser.defineEntityReplacementText( \"and\", \"\\u2227\" );" );
sc.add( "parser.defineEntityReplacementText( \"or\", \"\\u2228\" );" );
sc.add( "parser.defineEntityReplacementText( \"cap\", \"\\u2229\" );" );
sc.add( "parser.defineEntityReplacementText( \"cup\", \"\\u222a\" );" );
sc.add( "parser.defineEntityReplacementText( \"int\", \"\\u222b\" );" );
sc.add( "parser.defineEntityReplacementText( \"there4\", \"\\u2234\" );" );
sc.add( "parser.defineEntityReplacementText( \"sim\", \"\\u223c\" );" );
sc.add( "parser.defineEntityReplacementText( \"cong\", \"\\u2245\" );" );
sc.add( "parser.defineEntityReplacementText( \"asymp\", \"\\u2248\" );" );
sc.add( "parser.defineEntityReplacementText( \"ne\", \"\\u2260\" );" );
sc.add( "parser.defineEntityReplacementText( \"equiv\", \"\\u2261\" );" );
sc.add( "parser.defineEntityReplacementText( \"le\", \"\\u2264\" );" );
sc.add( "parser.defineEntityReplacementText( \"ge\", \"\\u2265\" );" );
sc.add( "parser.defineEntityReplacementText( \"sub\", \"\\u2282\" );" );
sc.add( "parser.defineEntityReplacementText( \"sup\", \"\\u2283\" );" );
sc.add( "parser.defineEntityReplacementText( \"nsub\", \"\\u2284\" );" );
sc.add( "parser.defineEntityReplacementText( \"sube\", \"\\u2286\" );" );
sc.add( "parser.defineEntityReplacementText( \"supe\", \"\\u2287\" );" );
sc.add( "parser.defineEntityReplacementText( \"oplus\", \"\\u2295\" );" );
sc.add( "parser.defineEntityReplacementText( \"otimes\", \"\\u2297\" );" );
sc.add( "parser.defineEntityReplacementText( \"perp\", \"\\u22a5\" );" );
sc.add( "parser.defineEntityReplacementText( \"sdot\", \"\\u22c5\" );" );
sc.add( "parser.defineEntityReplacementText( \"lceil\", \"\\u2308\" );" );
sc.add( "parser.defineEntityReplacementText( \"rceil\", \"\\u2309\" );" );
sc.add( "parser.defineEntityReplacementText( \"lfloor\", \"\\u230a\" );" );
sc.add( "parser.defineEntityReplacementText( \"rfloor\", \"\\u230b\" );" );
sc.add( "parser.defineEntityReplacementText( \"lang\", \"\\u2329\" );" );
sc.add( "parser.defineEntityReplacementText( \"rang\", \"\\u232a\" );" );
sc.add( "parser.defineEntityReplacementText( \"loz\", \"\\u25ca\" );" );
sc.add( "parser.defineEntityReplacementText( \"spades\", \"\\u2660\" );" );
sc.add( "parser.defineEntityReplacementText( \"clubs\", \"\\u2663\" );" );
sc.add( "parser.defineEntityReplacementText( \"hearts\", \"\\u2665\" );" );
sc.add( "parser.defineEntityReplacementText( \"diams\", \"\\u2666\" );" );
sc.add( "" );
sc.unindent();
sc.add( "}" );
}
private void writeHelpers( JClass jClass )
{
JMethod method = new JMethod( "getTrimmedValue", new JClass( "String" ), null );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
JSourceCode sc = method.getSourceCode();
sc.add( "if ( s != null )" );
sc.add( "{" );
sc.addIndented( "s = s.trim();" );
sc.add( "}" );
sc.add( "return s;" );
jClass.addMethod( method );
method = new JMethod( "getRequiredAttributeValue", new JClass( "String" ), null );
method.addException( new JClass( "XmlPullParserException" ) );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) );
method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) );
method.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) );
sc = method.getSourceCode();
sc.add( "if ( s == null )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( strict )" );
sc.add( "{" );
sc.addIndented(
"throw new XmlPullParserException( \"Missing required value for attribute '\" + attribute + \"'\", parser, null );" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.add( "return s;" );
jClass.addMethod( method );
method = new JMethod( "getBooleanValue", JType.BOOLEAN, null );
method.addException( new JClass( "XmlPullParserException" ) );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) );
method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) );
sc = method.getSourceCode();
sc.add( "return getBooleanValue( s, attribute, parser, null );" );
jClass.addMethod( method );
method = new JMethod( "getBooleanValue", JType.BOOLEAN, null );
method.addException( new JClass( "XmlPullParserException" ) );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) );
method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) );
method.addParameter( new JParameter( new JClass( "String" ), "defaultValue" ) );
sc = method.getSourceCode();
sc.add( "if ( s != null && s.length() != 0 )" );
sc.add( "{" );
sc.addIndented( "return Boolean.valueOf( s ).booleanValue();" );
sc.add( "}" );
sc.add( "if ( defaultValue != null )" );
sc.add( "{" );
sc.addIndented( "return Boolean.valueOf( defaultValue ).booleanValue();" );
sc.add( "}" );
sc.add( "return false;" );
jClass.addMethod( method );
method = new JMethod( "getCharacterValue", JType.CHAR, null );
method.addException( new JClass( "XmlPullParserException" ) );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) );
method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) );
sc = method.getSourceCode();
sc.add( "if ( s != null )" );
sc.add( "{" );
sc.addIndented( "return s.charAt( 0 );" );
sc.add( "}" );
sc.add( "return 0;" );
jClass.addMethod( method );
method = convertNumericalType( "getIntegerValue", JType.INT, "Integer.valueOf( s ).intValue()", "an integer" );
jClass.addMethod( method );
method = convertNumericalType( "getShortValue", JType.SHORT, "Short.valueOf( s ).shortValue()",
"a short integer" );
jClass.addMethod( method );
method = convertNumericalType( "getByteValue", JType.BYTE, "Byte.valueOf( s ).byteValue()", "a byte" );
jClass.addMethod( method );
method = convertNumericalType( "getLongValue", JType.LONG, "Long.valueOf( s ).longValue()", "a long integer" );
jClass.addMethod( method );
method = convertNumericalType( "getFloatValue", JType.FLOAT, "Float.valueOf( s ).floatValue()",
"a floating point number" );
jClass.addMethod( method );
method = convertNumericalType( "getDoubleValue", JType.DOUBLE, "Double.valueOf( s ).doubleValue()",
"a floating point number" );
jClass.addMethod( method );
method = new JMethod( "getDateValue", new JClass( "java.util.Date" ), null );
method.addException( new JClass( "XmlPullParserException" ) );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) );
method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) );
method.addException( new JClass( "XmlPullParserException" ) );
sc = method.getSourceCode();
sc.add( "return getDateValue( s, attribute, null, parser );" );
jClass.addMethod( method );
method = new JMethod( "getDateValue", new JClass( "java.util.Date" ), null );
method.addException( new JClass( "XmlPullParserException" ) );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) );
method.addParameter( new JParameter( new JClass( "String" ), "dateFormat" ) );
method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) );
method.addException( new JClass( "XmlPullParserException" ) );
writeDateParsingHelper( method.getSourceCode(), "new XmlPullParserException( e.getMessage() )" );
jClass.addMethod( method );
method = new JMethod( "checkFieldWithDuplicate", JType.BOOLEAN, null );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) );
method.addParameter( new JParameter( new JClass( "String" ), "tagName" ) );
method.addParameter( new JParameter( new JClass( "String" ), "alias" ) );
method.addParameter( new JParameter( new JClass( "java.util.Set" ), "parsed" ) );
method.addException( new JClass( "XmlPullParserException" ) );
sc = method.getSourceCode();
sc.add( "if ( !( parser.getName().equals( tagName ) || parser.getName().equals( alias ) ) )" );
sc.add( "{" );
sc.addIndented( "return false;" );
sc.add( "}" );
sc.add( "if ( parsed.contains( tagName ) )" );
sc.add( "{" );
sc.addIndented(
"throw new XmlPullParserException( \"Duplicated tag: '\" + tagName + \"'\", parser, null );" );
sc.add( "}" );
sc.add( "parsed.add( tagName );" );
sc.add( "return true;" );
jClass.addMethod( method );
method = new JMethod( "checkUnknownElement", null, null );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) );
method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) );
method.addException( new JClass( "XmlPullParserException" ) );
method.addException( new JClass( "IOException" ) );
sc = method.getSourceCode();
sc.add( "if ( strict )" );
sc.add( "{" );
sc.addIndented(
"throw new XmlPullParserException( \"Unrecognised tag: '\" + parser.getName() + \"'\", parser, null );" );
sc.add( "}" );
sc.add( "" );
sc.add( "// swallow up to end tag since this is not valid" );
sc.add( "while ( parser.next() != XmlPullParser.END_TAG ) {}" );
jClass.addMethod( method );
}
private JMethod convertNumericalType( String methodName, JType returnType, String expression, String typeDesc )
{
JMethod method = new JMethod( methodName, returnType, null );
method.addException( new JClass( "XmlPullParserException" ) );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) );
method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) );
method.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) );
JSourceCode sc = method.getSourceCode();
sc.add( "if ( s != null )" );
sc.add( "{" );
sc.indent();
sc.add( "try" );
sc.add( "{" );
sc.addIndented( "return " + expression + ";" );
sc.add( "}" );
sc.add( "catch ( NumberFormatException e )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( strict )" );
sc.add( "{" );
sc.addIndented( "throw new XmlPullParserException( \"Unable to parse element '\" + attribute + \"', must be " +
typeDesc + "\", parser, null );" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.add( "return 0;" );
return method;
}
}
|
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
public class WelcomeScreen extends JPanel implements ActionListener {
private static final long serialVersionUID = -5432368345116470291L;
private JButton play;
private JButton howToPlay;
private SpringLayout layout;
public WelcomeScreen(){
layout = new SpringLayout();
setLayout(layout);
play = new JButton("Play");
play.addActionListener(this);
add(play);
howToPlay = new JButton("How to Play");
howToPlay.addActionListener(this);
add(howToPlay);
layout.putConstraint(SpringLayout.WEST, play, 20, SpringLayout.WEST,
this);
layout.putConstraint(SpringLayout.NORTH, play, 20, SpringLayout.NORTH,
this);
layout.putConstraint(SpringLayout.NORTH, howToPlay, 20,
SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, howToPlay, 20, SpringLayout.EAST, play);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == play){
}
}
}
|
package member_system;
import java.util.ArrayList;
import sql_connect_database.SQL_InsertTypeIncomeOutlay;
import manage_incomeoutlay.NomalTypeOfUser;
import manage_incomeoutlay.TypeOfUse;
import connect_database.InsertIncomeOutlay;
import connect_database.InsertTypeIncomeOutlay;
import connect_database.InsertUser;
public class RegisterManager implements RegisterAble {
private InsertUser insertUser;
public RegisterManager(InsertUser insertUser) {
// TODO Auto-generated constructor stub
this.insertUser = insertUser;
}
@Override
public User register(User user) throws Exception {
boolean check;
try
{
check = insertUser.insertUser(user);
if(check)
{
this.addTypeIncomeOutlay(user);
return user;
}
else
{
return null;
}
}
catch(Exception ex)
{
throw(ex);
}
}
private void addTypeIncomeOutlay(User user) throws Exception
{
String income = "income";
String outcome = "outcome";
String low = "low";
String avg = "avg";
String height = "height";
InsertTypeIncomeOutlay insertTypeIncomeOutlay = new SQL_InsertTypeIncomeOutlay();
ArrayList<TypeOfUse> allType = new ArrayList<TypeOfUse>();
allType.add( new NomalTypeOfUser("ค่าอาหาร",outcome, height));
allType.add( new NomalTypeOfUser("ค่าที่พักอาศัย",outcome, height));
allType.add( new NomalTypeOfUser("ค่าสารณูปโภคที่สำคัญ",outcome, height));
allType.add( new NomalTypeOfUser("ค่าเดินทางที่สำคัญ",outcome, height));
allType.add( new NomalTypeOfUser("ค่าใช้จ่ายภายในบ้าน",outcome, avg));
allType.add( new NomalTypeOfUser("ค่าเสื้อผ้า",outcome, avg));
allType.add( new NomalTypeOfUser("ค่ารักษาพยาบาลเมื่อเจ็บป่วย",outcome, avg));
allType.add( new NomalTypeOfUser("ค่าพักผ่อนสังสรรค์",outcome, low));
allType.add( new NomalTypeOfUser("ค่าของขวัญในงานมงคลต่างๆ",outcome, low));
allType.add( new NomalTypeOfUser("เงินเดือน",income, height));
allType.add( new NomalTypeOfUser("ดอกเบี้ย",income, height));
allType.add( new NomalTypeOfUser("เงินปันผล",income, height));
allType.add( new NomalTypeOfUser("รายได้เสริม",income, height));
for(int i=0;i<allType.size();i++)
{
TypeOfUse typeOfuse = allType.get(i);
insertTypeIncomeOutlay.insertTypeIncomeOutlay(user, typeOfuse);
}
}
}
|
package org.motechproject.mobile.omp.manager.orserve;
import org.motechproject.mobile.core.model.GatewayRequest;
import org.motechproject.mobile.core.model.GatewayResponse;
import org.motechproject.mobile.core.model.MStatus;
import org.motechproject.mobile.core.service.MotechContext;
import org.motechproject.mobile.core.util.MotechException;
import org.motechproject.mobile.omp.manager.GatewayManager;
import org.motechproject.mobile.omp.manager.GatewayMessageHandler;
import com.outreachcity.orserve.messaging.SMSMessenger;
import com.outreachcity.orserve.messaging.SMSMessengerSoap;
import java.net.URL;
import java.util.Set;
import javax.xml.namespace.QName;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.Date;
import org.apache.log4j.Logger;
/**
* Handles all interactions with the OutReach Server message gateway
*
* @author Kofi A. Asamoah (yoofi@dreamoval.com)
* @date Jul 15, 2009
*/
public class ORServeGatewayManagerImpl implements GatewayManager {
private String productCode;
private String senderId;
private GatewayMessageHandler messageHandler;
private static Logger logger = Logger.getLogger(ORServeGatewayManagerImpl.class);
/**
*
* @see GatewayManager.send
*/
public Set<GatewayResponse> sendMessage(GatewayRequest messageDetails, MotechContext context) {
String gatewayResponse;
if(messageDetails == null)
return null;
logger.debug("Building ORServe message gateway webservice proxy class");
URL wsdlURL = null;
try {
wsdlURL = new URL("http:
} catch ( MalformedURLException e ) {
logger.error("Error creating web service client", e);
throw new MotechException(e.getMessage());
}
logger.debug("Calling sendMessage method of ORServe message gateway");
logger.debug(messageDetails);
try{
SMSMessenger messenger = new SMSMessenger(wsdlURL, new QName("http:
SMSMessengerSoap soap = messenger.getSMSMessengerSoap();
gatewayResponse = soap.sendMessage(URLEncoder.encode(messageDetails.getMessage(), "UTF-8"), messageDetails.getRecipientsNumber(), getSenderId(), getProductCode(), String.valueOf(messageDetails.getGatewayRequestDetails().getNumberOfPages()));
}
catch(Exception ex){
logger.error("Error sending message", ex);
throw new MotechException(ex.getMessage());
}
messageDetails.setDateSent(new Date());
logger.debug("Parsing gateway response");
return messageHandler.parseMessageResponse(messageDetails, gatewayResponse, context);
}
/**
*
* @see GatewayManager.getMessageStatus
*/
public String getMessageStatus(GatewayResponse response) {
String gatewayResponse;
logger.debug("Building ORServe message gateway webservice proxy class");
URL wsdlURL = null;
try {
wsdlURL = new URL("http:
} catch ( MalformedURLException e ) {
logger.error("Error creating web service client", e);
gatewayResponse = e.getMessage();
}
SMSMessenger messenger = new SMSMessenger(wsdlURL, new QName("http:
SMSMessengerSoap soap = messenger.getSMSMessengerSoap();
logger.debug("Calling getMessageStatus method of ORServe message gateway");
try{
gatewayResponse = soap.getMessageStatus(response.getGatewayMessageId(), productCode);
}
catch(Exception ex){
logger.error("Error querying message", ex);
gatewayResponse = ex.getMessage();
}
return gatewayResponse;
}
public MStatus mapMessageStatus(GatewayResponse response) {
return messageHandler.parseMessageStatus(response.getResponseText());
}
/**
* @return the productCode
*/
public String getProductCode() {
return productCode;
}
/**
* @param productCode the productCode to set
*/
public void setProductCode(String productCode) {
logger.debug("Setting ORServeGatewayManagerImpl.productCode");
logger.debug(productCode);
this.productCode = productCode;
}
/**
* @return the senderId
*/
public String getSenderId() {
return senderId;
}
/**
* @param senderId the senderId to set
*/
public void setSenderId(String senderId) {
logger.debug("Setting ORServeGatewayManagerImpl.senderId");
logger.debug(senderId);
this.senderId = senderId;
}
/**
* @return the messageHandler
*/
public GatewayMessageHandler getMessageHandler() {
return messageHandler;
}
/**
* @param messageHandler the messageHandler to set
*/
public void setMessageHandler(GatewayMessageHandler messageHandler) {
logger.debug("Setting SMSMessagingServiceImpl.handler:");
logger.debug(messageHandler);
this.messageHandler = messageHandler;
}
}
|
package org.nd4j.linalg.lossfunctions.impl;
import lombok.EqualsAndHashCode;
import org.apache.commons.math3.util.Pair;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.transforms.LogSoftMax;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.lossfunctions.ILossFunction;
import org.nd4j.linalg.ops.transforms.Transforms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@EqualsAndHashCode
public class LossBinaryXENT implements ILossFunction {
private static Logger logger = LoggerFactory.getLogger(LossBinaryXENT.class);
private INDArray scoreArray(INDArray labels, INDArray preOutput, String activationFn, INDArray mask) {
INDArray scoreArr;
if ("softmax".equals(activationFn)) {
//Use LogSoftMax op to avoid numerical issues when calculating score
INDArray logsoftmax = Nd4j.getExecutioner().execAndReturn(new LogSoftMax(preOutput.dup()));
scoreArr = logsoftmax.muli(labels);
} else {
INDArray output = Nd4j.getExecutioner().execAndReturn(Nd4j.getOpFactory().createTransform(activationFn, preOutput.dup()));
scoreArr = Transforms.log(output, true).muli(labels);
INDArray secondTerm = output.rsub(1);
Transforms.log(secondTerm,false);
secondTerm.muli(labels.rsub(1));
scoreArr.addi(secondTerm);
}
if (mask != null) {
scoreArr.muliColumnVector(mask);
}
return scoreArr;
}
@Override
public double computeScore(INDArray labels, INDArray preOutput, String activationFn, INDArray mask, boolean average) {
INDArray scoreArr = scoreArray(labels, preOutput, activationFn, mask);
double score = -scoreArr.sumNumber().doubleValue();
if (average) {
score /= scoreArr.size(0);
}
return score;
}
@Override
public INDArray computeScoreArray(INDArray labels, INDArray preOutput, String activationFn, INDArray mask) {
INDArray scoreArr = scoreArray(labels, preOutput, activationFn, mask);
return scoreArr.sum(1).muli(-1);
}
@Override
public INDArray computeGradient(INDArray labels, INDArray preOutput, String activationFn, INDArray mask) {
INDArray grad;
INDArray output = Nd4j.getExecutioner().execAndReturn(Nd4j.getOpFactory().createTransform(activationFn, preOutput.dup()));
if ("softmax".equals(activationFn)) {
grad = output.subi(labels);
} else {
// So, the derivative of XE(preoutput, label, activation) wrt preoutput is
// for sanity sake, we'll call activation(preoutput) = a and activation'(preoutput) = a'
// XE = label * log(a) + (1-label) * log(1-a)
// d XE/d preoutput = a' * (label - a) / (a * (1-a))
grad = Nd4j.getExecutioner().execAndReturn(Nd4j.getOpFactory().createTransform(activationFn, preOutput.dup()).derivative());
INDArray denominator = output.mul(output.rsub(1)); // output * (1-output)
INDArray numerator = output.sub(labels);
grad.muli(numerator).divi(denominator);
}
if (mask != null) {
grad.muliColumnVector(mask);
}
return grad;
}
@Override
public Pair<Double, INDArray> computeGradientAndScore(INDArray labels, INDArray preOutput, String activationFn, INDArray mask, boolean average) {
//TODO: probably a more efficient way to do this...
return new Pair<>(
computeScore(labels, preOutput, activationFn, mask, average),
computeGradient(labels, preOutput, activationFn, mask));
}
@Override
public String toString() {
return "LossBinaryXENT()";
}
}
|
package org.treebase.oai.web.controller;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;
import org.treebase.oai.web.command.Identify;
import org.treebase.oai.web.command.OAIPMHCommand;
import org.treebase.oai.web.util.IdentifyUtil;
import org.cipres.treebase.domain.admin.Person;
import org.cipres.treebase.domain.study.ArticleCitation;
import org.cipres.treebase.domain.study.BookCitation;
import org.cipres.treebase.domain.study.Citation;
import org.cipres.treebase.domain.study.Study;
import org.cipres.treebase.domain.study.Submission;
import org.cipres.treebase.domain.study.SubmissionService;
import org.cipres.treebase.domain.study.StudyService;
public class OAIPMHController extends AbstractCommandController{
private SubmissionService submissionService;
private StudyService studyService;
private Identify identify;
public OAIPMHController(){
setCommandClass(OAIPMHCommand.class);
setCommandName("requestParams");
}
public SubmissionService getSubmissionService() {
return submissionService;
}
public void setSubmissionService(SubmissionService submissionService) {
this.submissionService = submissionService;
}
public StudyService getStudyService() {
return studyService;
}
public void setStudyService(StudyService studyService) {
this.studyService = studyService;
}
public Identify getIdentify() {
return identify;
}
public void setIdentify(Identify identify) {
this.identify = identify;
}
@Override
protected ModelAndView handle(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
// TODO Auto-generated method stub
OAIPMHCommand params = (OAIPMHCommand) command;
Map model=errors.getModel();
model.put("requestParams", params);
model.put("identify", this.identify);
if(errors.getErrorCount()>0){
if(errors.hasFieldErrors("metadataPrefix")){
model.put("error_code", "cannotDisseminateFormat");
model.put("error", "bad metadataPrefix");
return new ModelAndView("error",model);
}
if(errors.hasFieldErrors("verb")){
model.put("error_code", "badVerb");
model.put("error", "no verb was found");
return new ModelAndView("error",model);
}
if(errors.hasFieldErrors("identifier")){
model.put("error_code", "idDoesNotExist");
model.put("error", "no id was found");
return new ModelAndView("error",model);
}
}
Method method=null;
try{
method=this.getClass().getMethod(params.getVerb(), new Class[]{OAIPMHCommand.class, Map.class});
}catch(NoSuchMethodException nsme){
model.put("error_code", "badVerb");
model.put("error", "invalid verb");
return new ModelAndView("error",model);
}catch(NullPointerException e){
model.put("error_code", "badVerb");
model.put("error", "missing verb");
return (new ModelAndView("error",model));
}
return (ModelAndView) method.invoke(this, params, model);
}
public ModelAndView ListRecords(OAIPMHCommand params, Map model){
List<Submission> list=null;
try {
list = (List)submissionService.findSubmissionByCreateDateRange(IdentifyUtil.parseGranularity(identify.getGranularityPattern(),params.getModifiedFrom()),
IdentifyUtil.parseGranularity(identify.getGranularityPattern(),params.getModifiedUntil()));
} catch (ParseException e) {
model.put("error_code", "badArgument");
model.put("error", "invalid from or until format");
return (new ModelAndView("error",model));
}
model.put("recordList", getRecordList(list));
return (new ModelAndView("ListRecords",model));
}
public ModelAndView ListIdentifiers( OAIPMHCommand params, Map model){
List<Submission> list=null;
try {
list = (List)submissionService.findSubmissionByCreateDateRange(IdentifyUtil.parseGranularity(identify.getGranularityPattern(),params.getModifiedFrom()),
IdentifyUtil.parseGranularity(identify.getGranularityPattern(), params.getModifiedUntil()));
} catch (ParseException e) {
model.put("error_code", "badArgument");
model.put("error", "invalid from or until format");
return (new ModelAndView("error",model));
}
model.put("recordList", getRecordList(list));
return (new ModelAndView(params.getMetadataPrefix()+"_ListIdentifiers",model));
}
public ModelAndView GetRecord( OAIPMHCommand params, Map model){
Submission submission = null;
try{
long id = IdentifyUtil.parseID(params);
submission = studyService.findByID(id).getSubmission();
}catch(NumberFormatException nfe){
model.put("error_code", "badArgument");
model.put("error", "invalid id format");
return (new ModelAndView("error",model));
}
catch (NullPointerException e){
model.put("error_code", "idDoesNotExist");
model.put("error", "invalid id");
return (new ModelAndView("error",model));
}
model.put("record", getRecordMap(submission));
return (new ModelAndView("GetRecord",model));
}
public ModelAndView Identify(OAIPMHCommand params, Map model){
return (new ModelAndView("Identify",model));
}
public ModelAndView ListSets(OAIPMHCommand params, Map model){
model.put("error_code", "noSetHierarchy");
model.put("error", "This repository does not support sets");
return (new ModelAndView("error",model));
}
public ModelAndView ListMetadataFormats(OAIPMHCommand params, Map model){
Submission submission = null;
try{
long id = IdentifyUtil.parseID(params);
submission = studyService.findByID(id).getSubmission();
}catch(NumberFormatException nfe){
model.put("error_code", "badArgument");
model.put("error", "invalid id format");
return (new ModelAndView("error",model));
}
catch (NullPointerException e){
//id is optional for ListMetadataFormats
//return (new ModelAndView("error",model));
}
return (new ModelAndView("ListMetadataFormats",model));
}
private Map getRecordMap(Submission submission){
Map map= new HashMap();
Study study=submission.getStudy();
Citation citation=study.getCitation();
String publisher=null;
if(!study.isPublished())return null;
//System.out.println("ctype: "+citation.getCitationType());
try{
if(citation.getCitationType().toUpperCase().contains("BOOK"))
publisher=((BookCitation)citation).getPublisher();
else publisher=((ArticleCitation)citation).getJournal();
List<Person> authors=citation.getAuthors();
map.put("title", citation.getTitle());
map.put("creator", authors);
map.put("subject", citation.getKeywords());
if(study.getName()!=null&study.getNotes()!=null)
map.put("description", study.getName()+" "+study.getNotes());
else if(study.getNotes()==null)
map.put("description",study.getName());
else
map.put("description",study.getNotes());
map.put("publisher", publisher);
map.put("date", "published on "+citation.getPublishYear());
map.put("identifier", "TreeBASE.org/study/TB2:s"+study.getId());
map.put("datestamp", study.getReleaseDate());
}catch(NullPointerException e){
//study 253 citation= null, data should be fixed
System.err.println("study "+study.getId()+
" citation= "+e.getMessage());
return null;
}
//map.put("type", "text");
//map.put("language", "en");
//map.put("issued", citation.getPublishYear());
//map.put("abstract", citation.getAbstract());
return map;
}
private List getRecordList(List<Submission> sList)
{
List recordList=new ArrayList<Map>();
for(int i =0; i< sList.size(); i++){
Map map=getRecordMap(sList.get(i));
if(map!=null)recordList.add(map);
}
return recordList;
}
}
|
package Functions;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.scilab.forge.jlatexmath.*;
import ChemHelper.Equation;
import ChemHelper.Ions;
import Elements.Compound;
public abstract class Function {
public static final double C = 300000000, h = 6.626*Math.pow(10, -34);
private String name;
public Function(String name)
{
this.name = name;
}
public abstract JPanel getPanel(); //Return the frame containing all components for that chem function
public String toString()
{
return name;
}
public static JPanel wrapInFlow(Component comp){ //Wrap a component in a FlowLayout
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(comp);
return panel;
}
public static JLabel latex(Equation eq) { //only for equations at this point
JLabel label = new JLabel();
String str = "";
ArrayList<Compound> left = eq.getLeft();
ArrayList<Compound> right = eq.getRight();
ArrayList<ArrayList<Compound>> sides = new ArrayList<ArrayList<Compound>>();
sides.add(left);
sides.add(right);
for (ArrayList<Compound> side: sides) {
for (Compound comp: side) {
str += comp.getNum();
for (Ions ion: comp.getIons()) {
str += "\\text{" + ion.getElement().getSymbol() + "}";
if (ion.getCharge() < 0) {
str += "^{" + ion.getCharge() + "}";
}
else if (ion.getCharge() > 0) {
str += "^{+" + ion.getCharge() + "}";
}
if (ion.getNum()>1) {
str+= "_{" + ion.getNum() + "}";
}
}
str += "+";
}
str = str.substring(0, str.length()-1);
str+= "\\textbf{\\longrightarrow}";
}
str = str.substring(0,str.length()-26);//remove last rightarrow
TeXFormula formula = new TeXFormula (str);
TeXIcon icon = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 20);
BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
icon.paintIcon(new JLabel(), image.getGraphics(), 0, 0);
label.setIcon(icon);
return label;
}
// Written by Lewis/Loftus/Cocking
public static int gcd (int num1, int num2)
{
while (num1 != num2)
if (num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
return num1;
}
/*
* Returns the number of significant figures a number has, if numString is a String representation of a double.
*/
public static int sigFigs(String numString)
{
int sigFigs = numString.length();
if(numString.indexOf("-") != -1) sigFigs
if(numString.indexOf(".") != -1) sigFigs
//These characters lead the String to be longer than purely
else for(int index = numString.length() -1; index >= 0 && numString.charAt(index) == '0'; index--) sigFigs--;
//If a number does not contain a decimal point, for every 0 at the end of the number, subtract a sig fig.
return sigFigs;
}
/*
* Returns a String representation of the number with the given number of significant figures, unless that would require scientific notation
* because I didn't feel like doing that and might do it later.
* pre: sigFigs >= 1
*/
public static String withSigFigs(double num, int sigFigs)
{
int count = 0;
boolean neg = num < 0;
num = Math.abs(num);
String original = "" + num, numString = "";
int index;
if(num > 1)
{
for(; count < original.length() && original.charAt(count) != '.' && count < sigFigs; numString += original.charAt(count), count++);
if(count == sigFigs) // Adding extra zeros to the end if necessary.
{
if(count + 1 < original.length() && original.charAt(count) == '.' && original.charAt(count + 1) >= '5')
{
numString = numString.substring(0, numString.length() - 1) + ((char)(original.charAt(count - 1) + 1));
}
for(int i = count; i < original.length() && original.charAt(i) != '.'; i++, numString += '0');
if(neg) numString = '-' + numString;
return numString;
}
index = count + 1;
}
else
{
numString = "0";
index = 2;
}
numString += '.';
for(; index < original.length() && count < sigFigs; numString += original.charAt(index), count++, index++);
if(count == sigFigs && index < original.length() && original.charAt(index) >= '5')
{
numString = numString.substring(0, numString.length() - 1) + ((char)(original.charAt(index - 1) + 1));
}
for(; count < sigFigs; count++, numString += '0');
return numString;
}
}
|
package com.ready.rain.mobs;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferStrategy;
public class Animation{
boolean dir = false;
double rot = 0;
public void AnimateLegs(BufferStrategy bs, int x,int y, boolean moving){
if (moving == true){
if(rot >= 70){
dir = true;
}
if(rot <= -70){
dir = false;
}
if(dir == false){
rot++;
}else{
rot
}
}else{
if(rot >= 0)rot -= 0.5;
if(rot <= 0)rot += 0.5;
}
Graphics2D g1 = (Graphics2D) bs.getDrawGraphics();
g1.translate(x + 100/2, y);
g1.rotate(Math.toRadians(rot));
g1.translate(-x - 100/2, -y);
g1.fillRect(x, y, 100, 150);
g1.dispose();
Graphics2D g2 = (Graphics2D) bs.getDrawGraphics();
g2.translate(x + 100/2, y);
g2.rotate(Math.toRadians(-rot));
g2.translate(-x - 100/2, -y);
g2.fillRect(x, y, 100, 150);
g2.dispose();
}
}
|
package org.eclipse.emf.emfstore.server.accesscontrol;
import java.util.Set;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.emfstore.server.core.MethodInvocation;
import org.eclipse.emf.emfstore.server.exceptions.AccessControlException;
import org.eclipse.emf.emfstore.server.model.ProjectId;
import org.eclipse.emf.emfstore.server.model.SessionId;
import org.eclipse.emf.emfstore.server.model.accesscontrol.ACOrgUnitId;
import org.eclipse.emf.emfstore.server.model.accesscontrol.ACUser;
/**
* Control for the authorization of users.
*
* @author koegel
*/
public interface AuthorizationControl {
/**
* Check if the given session is valid.
*
* @param sessionId the session id
* @throws AccessControlException if the session is invalid
*/
void checkSession(SessionId sessionId) throws AccessControlException;
/**
* Check if the session is valid for admin access to the given project.
*
* @param sessionId the session id
* @param projectId the project id
* @throws AccessControlException if the session is invalid for admin access
*/
void checkProjectAdminAccess(SessionId sessionId, ProjectId projectId) throws AccessControlException;
/**
* Check if the session is valid for server admin access.
*
* @param sessionId the session id
* @throws AccessControlException if the session is invalid for server admin access
*/
void checkServerAdminAccess(SessionId sessionId) throws AccessControlException;
/**
* Check if the session may read the given model elements in the project.
*
* @param sessionId session id
* @param projectId project id
* @param modelElements a set of model elements
* @throws AccessControlException if the session may not read any of the model elements
*/
void checkReadAccess(SessionId sessionId, ProjectId projectId, Set<EObject> modelElements)
throws AccessControlException;
/**
* Check if the session may write the given model elements in the project.
*
* @param sessionId session id
* @param projectId project id
* @param modelElements a set of model elements
* @throws AccessControlException if the session may not write any of the model elements
*/
void checkWriteAccess(SessionId sessionId, ProjectId projectId, Set<EObject> modelElements)
throws AccessControlException;
/**
* This method looks up the session id on the server and returns the relating user. Please notice that the returned
* user also contains roles which are not contained in the original user. These extra roles come from the user's
* groups.
*
* @param sessionId session id
* @return ACUser user with roles from resolved user and it's groups
* @throws AccessControlException exception
*/
ACUser resolveUser(SessionId sessionId) throws AccessControlException;
/**
* This method looks up the orgUnit id the server and returns the relating user. Please notice that the returned
* user also contains roles which are not contained in the original user. These extra roles come from the user's
* groups.
*
* @param orgUnitId OrgUnit id
* @return ACUser user with roles from resolved user and it's groups
* @throws AccessControlException exception
*/
ACUser resolveUser(ACOrgUnitId orgUnitId) throws AccessControlException;
/**
* Checks whether a given operation may be executed.
*
* @param op
* the operation the user intends to execute
*
* @throws AccessControlException in case access is denied
*/
void checkAccess(MethodInvocation op) throws AccessControlException;
}
|
package com.chrisdoyle.validation;
import com.chrisdoyle.validation.tests.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.util.Properties;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
/**
* Command line junit test runner for Gradle-Fury validation
*
* borrowed from Apache jUDDI's TCK Test Runner
* @author alex
*/
public class Main {
/**
* used for string replacement
*/
static final String VERSION = "\\$version";
/**
* run these tests after 'gradlew install -Pprofile=sources,javadoc
*/
static final Class[] normalTests = new Class[]{
Test_Issue12.class,
Test_Issue22.class,
Test_Issues_23_27.class,
Test_Issue25.class,
Test_Issue27.class,
Test_Issue31.class,
Test_Issue38.class,
Test_Issue46.class,
Test_Issue51.class,
Test_Issue59.class,
Test_Issue144.class,
ValidatePoms.class
};
/**
* run these tests after
* 'gradlew install -Pprofile=sources,javadoc'
* 'gradlew publishArtifacts -Pprofile=sources,javadoc,sign'
*
*/
static final Class[] signatureTests = new Class[]{
Test_Issue12Sigs.class,
TestPostPublication.class,
};
/**
* run these tests after
* 'gradlew install -Pprofile=sources,javadoc'
* 'gradlew publishArtifacts -Pprofile=sources,javadoc'
*
*/
static final Class[] noSignatureTests = new Class[]{
TestPostPublicationNoSig.class,
};
static final Class[] siteTests = new Class[]{
SiteTests.class,
};
/**
* all artifacts that are expected to be signed, in the gradle build folders
*/
public final static String[] allSignedArtifacts = new String[]{
"./hello-world-aar/build/outputs/aar/hello-world-aar-$version-debug.aar" ,
"./hello-world-aar/build/outputs/aar/hello-world-aar-$version-release.aar" ,
"./hello-world-aar/build/libs/hello-world-aar-$version-debug-javadoc.jar" ,
"./hello-world-aar/build/libs/hello-world-aar-$version-debug-sources.jar" ,
"./hello-world-aar/build/libs/hello-world-aar-$version-release-javadoc.jar" ,
"./hello-world-aar/build/libs/hello-world-aar-$version-release-sources.jar" ,
"./hello-world-aar/build/publications/androidArtifacts/pom-default.xml" ,
"./hello-world-gmaps/build/outputs/apk/hello-world-gmaps-$version-debug.apk" ,
"./hello-world-gmaps/build/outputs/apk/hello-world-gmaps-$version-release.apk" ,
"./hello-world-gmaps/build/libs/hello-world-gmaps-$version-debug-javadoc.jar" ,
"./hello-world-gmaps/build/libs/hello-world-gmaps-$version-debug-sources.jar" ,
"./hello-world-gmaps/build/libs/hello-world-gmaps-$version-release-javadoc.jar" ,
"./hello-world-gmaps/build/libs/hello-world-gmaps-$version-release-sources.jar" ,
"./hello-world-gmaps/build/publications/androidArtifacts/pom-default.xml" ,
"./hello-world-apk/build/outputs/apk/hello-world-apk-$version-barDebug.apk" ,
"./hello-world-apk/build/outputs/apk/hello-world-apk-$version-barRelease.apk" ,
"./hello-world-apk/build/outputs/apk/hello-world-apk-$version-bazDebug.apk" ,
"./hello-world-apk/build/outputs/apk/hello-world-apk-$version-bazRelease.apk" ,
"./hello-world-apk/build/outputs/apk/hello-world-apk-$version-fooDebug.apk" ,
"./hello-world-apk/build/outputs/apk/hello-world-apk-$version-fooRelease.apk" ,
"./hello-world-apk/build/libs/hello-world-apk-$version-barDebug-javadoc.jar" ,
"./hello-world-apk/build/libs/hello-world-apk-$version-barDebug-sources.jar" ,
"./hello-world-apk/build/libs/hello-world-apk-$version-barRelease-javadoc.jar" ,
"./hello-world-apk/build/libs/hello-world-apk-$version-barRelease-sources.jar" ,
"./hello-world-apk/build/libs/hello-world-apk-$version-bazDebug-javadoc.jar" ,
"./hello-world-apk/build/libs/hello-world-apk-$version-bazDebug-sources.jar" ,
"./hello-world-apk/build/libs/hello-world-apk-$version-bazRelease-javadoc.jar" ,
"./hello-world-apk/build/libs/hello-world-apk-$version-bazRelease-sources.jar" ,
"./hello-world-apk/build/libs/hello-world-apk-$version-fooDebug-javadoc.jar" ,
"./hello-world-apk/build/libs/hello-world-apk-$version-fooDebug-sources.jar" ,
"./hello-world-apk/build/libs/hello-world-apk-$version-fooRelease-javadoc.jar" ,
"./hello-world-apk/build/libs/hello-world-apk-$version-fooRelease-sources.jar" ,
"./hello-world-apk/build/publications/androidArtifacts/pom-default.xml" ,
"./hello-world-apk-overrides/build/outputs/apk/hello-world-apk-overrides-$version-barDebug.apk" ,
"./hello-world-apk-overrides/build/outputs/apk/hello-world-apk-overrides-$version-barRelease.apk" ,
"./hello-world-apk-overrides/build/outputs/apk/hello-world-apk-overrides-$version-bazDebug.apk" ,
"./hello-world-apk-overrides/build/outputs/apk/hello-world-apk-overrides-$version-bazRelease.apk" ,
"./hello-world-apk-overrides/build/outputs/apk/hello-world-apk-overrides-$version-fooDebug.apk" ,
"./hello-world-apk-overrides/build/outputs/apk/hello-world-apk-overrides-$version-fooRelease.apk" ,
"./hello-world-apk-overrides/build/libs/hello-world-apk-overrides-$version-barDebug-javadoc.jar" ,
"./hello-world-apk-overrides/build/libs/hello-world-apk-overrides-$version-barDebug-sources.jar" ,
"./hello-world-apk-overrides/build/libs/hello-world-apk-overrides-$version-barRelease-javadoc.jar" ,
"./hello-world-apk-overrides/build/libs/hello-world-apk-overrides-$version-barRelease-sources.jar" ,
"./hello-world-apk-overrides/build/libs/hello-world-apk-overrides-$version-bazDebug-javadoc.jar" ,
"./hello-world-apk-overrides/build/libs/hello-world-apk-overrides-$version-bazDebug-sources.jar" ,
"./hello-world-apk-overrides/build/libs/hello-world-apk-overrides-$version-bazRelease-javadoc.jar" ,
"./hello-world-apk-overrides/build/libs/hello-world-apk-overrides-$version-bazRelease-sources.jar" ,
"./hello-world-apk-overrides/build/libs/hello-world-apk-overrides-$version-fooDebug-javadoc.jar" ,
"./hello-world-apk-overrides/build/libs/hello-world-apk-overrides-$version-fooDebug-sources.jar" ,
"./hello-world-apk-overrides/build/libs/hello-world-apk-overrides-$version-fooRelease-javadoc.jar" ,
"./hello-world-apk-overrides/build/libs/hello-world-apk-overrides-$version-fooRelease-sources.jar" ,
"./hello-world-apk-overrides/build/publications/androidArtifacts/pom-default.xml" ,
"./hello-world-lib/build/libs/hello-world-lib-$version.jar" ,
"./hello-world-lib/build/libs/hello-world-lib-$version-javadoc.jar" ,
"./hello-world-lib/build/libs/hello-world-lib-$version-sources.jar" ,
"./hello-world-lib/build/publications/javaArtifacts/pom-default.xml" ,
"./gradle-fury-validation/build/libs/gradle-fury-validation-$version.jar" ,
"./gradle-fury-validation/build/libs/gradle-fury-validation-$version-javadoc.jar" ,
"./gradle-fury-validation/build/libs/gradle-fury-validation-$version-sources.jar" ,
"./gradle-fury-validation/build/distributions/gradle-fury-validation-$version.zip" ,
"./gradle-fury-validation/build/publications/javaArtifacts/pom-default.xml" ,
"./hello-child/hello-grandchild-lib/build/libs/hello-grandchild-lib-$version.jar" ,
"./hello-child/hello-grandchild-lib/build/libs/hello-grandchild-lib-$version-javadoc.jar" ,
"./hello-child/hello-grandchild-lib/build/libs/hello-grandchild-lib-$version-sources.jar" ,
"./hello-child/hello-grandchild-lib/build/publications/javaArtifacts/pom-default.xml" ,
"./hello-universe-lib/build/libs/hello-universe-lib-$version.jar" ,
"./hello-universe-lib/build/libs/hello-universe-lib-$version-javadoc.jar" ,
"./hello-universe-lib/build/libs/hello-universe-lib-$version-sources.jar" ,
"./hello-universe-lib/build/publications/javaArtifacts/pom-default.xml" ,
"./hello-world-war/build/libs/hello-world-war-$version.war" ,
"./hello-world-war/build/libs/hello-world-war-$version-javadoc.jar" ,
"./hello-world-war/build/libs/hello-world-war-$version-sources.jar" ,
"./hello-world-war/build/publications/webApp/pom-default.xml" ,
"./hello-world-warDistAppJar/build/libs/hello-world-warDistAppJar-$version.war" ,
"./hello-world-warDistAppJar/build/distributions/hello-world-warDistAppJar-$version.zip" ,
"./hello-world-warDistAppJar/build/libs/hello-world-warDistAppJar-$version-javadoc.jar" ,
"./hello-world-warDistAppJar/build/libs/hello-world-warDistAppJar-$version-sources.jar" ,
"./hello-world-warDistAppJar/build/publications/javaArtifacts/pom-default.xml" ,
"./hello-world-app/build/libs/hello-world-app-$version.jar" ,
"./hello-world-app/build/libs/hello-world-app-$version-sources.jar" ,
"./hello-world-app/build/libs/hello-world-app-$version-javadoc.jar" ,
"./hello-world-app/build/publications/javaArtifacts/pom-default.xml" ,
"./hello-world-app/build/distributions/hello-world-app-$version.zip",
"./hello-world-dist/build/distributions/hello-world-dist-$version.zip" ,
"./hello-world-dist/build/distributions/pom-default.xml" ,
"./hello-world-kotlin/build/libs/hello-world-kotlin-$version.jar" ,
"./hello-world-kotlin/build/libs/hello-world-kotlin-$version-sources.jar" ,
"./hello-world-kotlin/build/libs/hello-world-kotlin-$version-javadoc.jar" ,
"./hello-world-kotlin/build/publications/javaArtifacts/pom-default.xml" ,
};
/**
* all artifacts that are expected to be published to maven local
*/
public final static String[] allArtifacts = new String[]{
"~/.m2/repository/com/chrisdoyle/hello-world-aar/$version/hello-world-aar-$version-debug.aar",
"~/.m2/repository/com/chrisdoyle/hello-world-aar/$version/hello-world-aar-$version-debug-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-aar/$version/hello-world-aar-$version-debug-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-aar/$version/hello-world-aar-$version.pom",
//gradhell is also published locally, but shouldn't be, ignoring for now
"~/.m2/repository/com/chrisdoyle/hello-grandchild-lib/$version/hello-grandchild-lib-$version.jar",
"~/.m2/repository/com/chrisdoyle/hello-grandchild-lib/$version/hello-grandchild-lib-$version-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-grandchild-lib/$version/hello-grandchild-lib-$version-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-grandchild-lib/$version/hello-grandchild-lib-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-lib/$version/hello-world-lib-$version.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-lib/$version/hello-world-lib-$version-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-lib/$version/hello-world-lib-$version-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-lib/$version/hello-world-lib-$version.pom",
"~/.m2/repository/com/chrisdoyle/gradle-fury-validation/$version/gradle-fury-validation-$version.jar",
"~/.m2/repository/com/chrisdoyle/gradle-fury-validation/$version/gradle-fury-validation-$version-sources.jar",
"~/.m2/repository/com/chrisdoyle/gradle-fury-validation/$version/gradle-fury-validation-$version-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/gradle-fury-validation/$version/gradle-fury-validation-$version.pom",
//broke for local publishing
//"~/.m2/repository/com/chrisdoyle/gradle-fury-validation/$version/gradle-fury-validation-$version.zip",
"~/.m2/repository/com/chrisdoyle/hello-universe-lib/$version/hello-universe-lib-$version.jar",
"~/.m2/repository/com/chrisdoyle/hello-universe-lib/$version/hello-universe-lib-$version-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-universe-lib/$version/hello-universe-lib-$version-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-universe-lib/$version/hello-universe-lib-$version.pom",
//TODO there should be a hello-world-dist too but it's broken for local publishing
"~/.m2/repository/com/chrisdoyle/hello-world-war/$version/hello-world-war-$version.war",
"~/.m2/repository/com/chrisdoyle/hello-world-war/$version/hello-world-war-$version-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-war/$version/hello-world-war-$version-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-war/$version/hello-world-war-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-apk/$version/hello-world-apk-$version-barDebug.apk",
"~/.m2/repository/com/chrisdoyle/hello-world-apk/$version/hello-world-apk-$version-barDebug-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-apk/$version/hello-world-apk-$version-barDebug-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-apk/$version/hello-world-apk-$version-bazDebug.apk",
"~/.m2/repository/com/chrisdoyle/hello-world-apk/$version/hello-world-apk-$version-bazDebug-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-apk/$version/hello-world-apk-$version-bazDebug-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-apk/$version/hello-world-apk-$version-fooDebug.apk",
"~/.m2/repository/com/chrisdoyle/hello-world-apk/$version/hello-world-apk-$version-fooDebug-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-apk/$version/hello-world-apk-$version-fooDebug-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-apk/$version/hello-world-apk-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-apk-overrides/$version/hello-world-apk-overrides-$version-barDebug.apk",
"~/.m2/repository/com/chrisdoyle/hello-world-apk-overrides/$version/hello-world-apk-overrides-$version-barDebug-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-apk-overrides/$version/hello-world-apk-overrides-$version-barDebug-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-apk-overrides/$version/hello-world-apk-overrides-$version-bazDebug.apk",
"~/.m2/repository/com/chrisdoyle/hello-world-apk-overrides/$version/hello-world-apk-overrides-$version-bazDebug-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-apk-overrides/$version/hello-world-apk-overrides-$version-bazDebug-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-apk-overrides/$version/hello-world-apk-overrides-$version-fooDebug.apk",
"~/.m2/repository/com/chrisdoyle/hello-world-apk-overrides/$version/hello-world-apk-overrides-$version-fooDebug-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-apk-overrides/$version/hello-world-apk-overrides-$version-fooDebug-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-apk-overrides/$version/hello-world-apk-overrides-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-kotlin/$version/hello-world-kotlin-$version.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-kotlin/$version/hello-world-kotlin-$version-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-kotlin/$version/hello-world-kotlin-$version-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-kotlin/$version/hello-world-kotlin-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-warDistAppJar/$version/hello-world-warDistAppJar-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-warDistAppJar/$version/hello-world-warDistAppJar-$version.war",
"~/.m2/repository/com/chrisdoyle/hello-world-warDistAppJar/$version/hello-world-warDistAppJar-$version.zip",
"~/.m2/repository/com/chrisdoyle/hello-world-warDistAppJar/$version/hello-world-warDistAppJar-$version-sources.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-warDistAppJar/$version/hello-world-warDistAppJar-$version-javadoc.jar",
"~/.m2/repository/com/chrisdoyle/hello-world-warDistAppJar/$version/hello-world-warDistAppJar-$version.pom",
};
/**
* all POMs
*/
public final static String[] allPoms = new String[]{
"~/.m2/repository/com/chrisdoyle/hello-world-aar/$version/hello-world-aar-$version.pom",
"~/.m2/repository/com/chrisdoyle/gradle-fury-validation/$version/gradle-fury-validation-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-lib/$version/hello-world-lib-$version.pom",
//broken with local publishing
// "~/.m2/repository/com/chrisdoyle/hello-world-dist/$version/hello-world-dist-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-universe-lib/$version/hello-universe-lib-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-grandchild-lib/$version/hello-grandchild-lib-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-apk/$version/hello-world-apk-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-apk-overrides/$version/hello-world-apk-overrides-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-war/$version/hello-world-war-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-app/$version/hello-world-app-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-dist/$version/hello-world-dist-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-kotlin/$version/hello-world-kotlin-$version.pom",
"~/.m2/repository/com/chrisdoyle/hello-world-warDistAppJar/$version/hello-world-warDistAppJar-$version.pom",
};
/**
* from gradle.properties, pom.version
*/
public static String version;
/**
* raw access to everything in gradle.properties
*/
public static Properties gradleProperties = new Properties();
/**
* the folder you're running this jar from. it should be the $rootDir of gradle-fury
*/
public static String cwdDir;
/**
* some location to gpg, loaded from gradle.properties
*/
public static String gpg = "/usr/bin/gpg";
/**
* main entry point
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//init
File cwd = new File(".");
System.out.println("============ Gradle Fury Validation ============");
System.out.println("CWD is " + cwd.getAbsolutePath());
cwdDir = cwd.getAbsolutePath();
init(cwd);
System.out.println("using " + gpg );
System.out.println("using " + version );
//this part does some basic string replacements for home dir, versioning etc
String homeDir = System.getProperty("user.home");
homeDir=homeDir.replace("\\","/"); //stupid windows!
System.out.println("Homedir is " + homeDir);
for (int i=0; i < allArtifacts.length; i++){
allArtifacts[i] = allArtifacts[i].replaceAll(VERSION, version);
allArtifacts[i] = allArtifacts[i].replaceAll( "~", homeDir);
}
for (int i=0; i < allPoms.length; i++){
allPoms[i] = allPoms[i].replaceAll(VERSION, version);
allPoms[i] = allPoms[i].replaceAll("~", homeDir);
}
for (int i=0; i < allSignedArtifacts.length; i++){
allSignedArtifacts[i] = allSignedArtifacts[i].replaceAll(VERSION, version);
allSignedArtifacts[i]=allSignedArtifacts[i].replaceFirst("\\,", cwdDir);
}
Class[] classesToRun=null;
//cli stuff
// create Options object
Options options = new Options();
options.addOption("publishWithSig", false, "Also run tests against nexus with gpg signatures");
options.addOption("publishWithNoSig", false, "Also run tests against nexus without signatures");
options.addOption("withSite", false, "Also run tests for the site");
options.addOption("help", false, "Help");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
if (cmd.hasOption("help")){
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "gradle-fury-validation", options );
return;
}
if (cmd.hasOption("publishWithSig")){
classesToRun = new Class[normalTests.length + signatureTests.length];
int index=0;
for (int i=0; i < normalTests.length; i++){
classesToRun[index] = normalTests[i];
index++;
}
for (int i=0; i < signatureTests.length; i++){
classesToRun[index] = signatureTests[i];
index++;
}
} else if (cmd.hasOption("publishWithNoSig")){
classesToRun = new Class[normalTests.length + noSignatureTests.length];
int index=0;
for (int i=0; i < normalTests.length; i++){
classesToRun[index] = normalTests[i];
index++;
}
for (int i=0; i < noSignatureTests.length; i++){
classesToRun[index] = noSignatureTests[i];
index++;
}
} else if (cmd.hasOption("withSite")){
classesToRun = new Class[normalTests.length + siteTests.length];
int index=0;
for (int i=0; i < normalTests.length; i++){
classesToRun[index] = normalTests[i];
index++;
}
for (int i=0; i < siteTests.length; i++){
classesToRun[index] = siteTests[i];
index++;
}
}else {
classesToRun = normalTests;
}
//execute the unit tests
Result result = null;
JUnitCore junit = new JUnitCore();
result = junit.run(classesToRun);
//String filename = "tck-results-" + new SimpleDateFormat("yyyyMMddhhmm").format(new Date()) + ".txt";
//FileWriter fw = new FileWriter(filename);
PrintStream bw = System.out;
bw.println("Technical Conformance Kit (TCK) Test Results generated " + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(new Date()));
bw.println("____________________________________________");
bw.println("Summary");
bw.println("Failed Test Cases: " + result.getFailureCount());
bw.println("Skipped Test Cases: " + result.getIgnoreCount());
bw.println("Ran Test Cases: " + result.getRunCount());
bw.println("Time: " + result.getRunTime());
bw.println("____________________________________________");
bw.println("Tests Ran");
for (int i = 0; i < normalTests.length; i++) {
bw.println(normalTests[i].getCanonicalName());
}
bw.println("____________________________________________");
bw.println("Failed Test cases");
bw.println("____________________________________________");
for (int i = 0; i < result.getFailures().size(); i++) {
try {
try {
bw.println(result.getFailures().get(i).getTestHeader());
} catch (Exception ex) {
bw.println(ex.getMessage());
}
try {
bw.println(result.getFailures().get(i).getDescription().getClassName());
}
catch (Exception ex) {
bw.println(ex.getMessage());
}
try {
bw.println(result.getFailures().get(i).getDescription().getMethodName() == null ? "null method!" : result.getFailures().get(i).getDescription().getMethodName());
} catch (Exception ex) {
bw.println(ex.getMessage());
}
try{
System.out.println("[FAIL] " + result.getFailures().get(i).getDescription().getClassName()+":" + result.getFailures().get(i).getDescription().getMethodName());
}catch (Exception ex){}
try {
bw.println(result.getFailures().get(i).getMessage() == null ? "no message" : result.getFailures().get(i).getMessage());
} catch (Exception ex) {
bw.println(ex.getMessage());
}
try {
bw.println(result.getFailures().get(i).getTrace());
} catch (Exception ex) {
bw.println(ex.getMessage());
}
bw.println("____________________________________________");
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("____________________________________________");
System.out.println("Summary");
System.out.println("Failed Test Cases: " + result.getFailureCount());
System.out.println("Skipped Test Cases: " + result.getIgnoreCount());
System.out.println("Ran Test Cases: " + result.getRunCount());
System.out.println("Time: " + result.getRunTime() + "ms which is " +
org.apache.commons.lang3.time.DurationFormatUtils.formatDurationHMS(result.getRunTime()));
System.out.println("
junit = null;
System.out.println("Exit code: " + result.getFailureCount());
System.exit(result.getFailureCount());
}
/**
* loads the gradle.properties file
* @param cwd
* @throws Exception
*/
static void init(File cwd) throws Exception {
File prop = new File(cwd.getAbsolutePath() + File.separator + "gradle.properties");
if (!prop.exists()) {
throw new Exception("can't find gradle.properties");
}
Properties p = new Properties();
p.load(new FileInputStream(prop));
prop = new File(cwd.getAbsolutePath() + File.separator + "local.properties");
if (prop.exists()){
p.load(new FileInputStream(prop));
}
if (p.containsKey("GPG_PATH"))
gpg = p.getProperty("GPG_PATH");
version = p.getProperty("pom.version");
gradleProperties=p;
}
}
|
package com.evolveum.midpoint.web.bean;
import com.evolveum.midpoint.task.api.Task;
public class TaskItem {
private String handlerUri;
private String objectRef;
private String oid;
private String name;
private Long lastRunStartTimestamp;
private Long lastRunFinishTimestamp;
public TaskItem(Task task){
this.handlerUri = task.getHanderUri();
this.objectRef = task.getObjectRef().getOid();
this.oid = task.getOid();
this.name = task.getName();
this.lastRunStartTimestamp = task.getLastRunStartTimestamp();
this.lastRunFinishTimestamp = task.getLastRunFinishTimestamp();
}
public String getHandlerUri() {
return handlerUri;
}
public void setHandlerUri(String handlerUri) {
this.handlerUri = handlerUri;
}
public String getObjectRef() {
return objectRef;
}
public void setObjectRef(String objectRef) {
this.objectRef = objectRef;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getLastRunStartTimestamp() {
return lastRunStartTimestamp;
}
public void setLastRunStartTimestamp(Long lastRunStartTimestamp) {
this.lastRunStartTimestamp = lastRunStartTimestamp;
}
public Long getLastRunFinishTimestamp() {
return lastRunFinishTimestamp;
}
public void setLastRunFinishTimestamp(Long lastRunFinishTimestamp) {
this.lastRunFinishTimestamp = lastRunFinishTimestamp;
}
}
|
package tankattack;
import javafx.animation.*;
import javafx.application.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.*;
import javafx.scene.control.Button;
import javafx.scene.effect.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.stage.Stage;
import javafx.util.*;
/**
*
* @author Ruslan
*/
public class TankAttack extends Application {
public static final double gameWidth = 600;
public static final double gameHeight = 600;
public static final int NUM_FRAMES_PER_SECOND = 30;
public static double buttonWidth = gameWidth / 5;
public static double buttonHeight = gameWidth / 10;
public static double PLAYER_SPEED = 2.5;
public static double MINION_SPEED = 2.1;
public static double BULLET_SPEED = 5.5;
public static double BULLET_DAMAGE = 10;
public static TankAttack sharedInstance;
private Stage currStage;
private World currWorld;
private Scene currScene;
@Override
public void start(Stage primaryStage) {
sharedInstance = this;
currStage = primaryStage;
displayStartMenu();
}
public void displayStartMenu() {
currStage.setTitle("Main Menu");
Group menuRoot = new Group();
final Scene mainMenu = new Scene(menuRoot, TankAttack.gameWidth, TankAttack.gameHeight, Color.CORNFLOWERBLUE);
// Launch Background Animation
launchAnimationForDisplayMenu(currStage, menuRoot);
// Create Buttons
createButtonsForDisplayMenu(currStage, menuRoot);
currStage.setScene(mainMenu);
currStage.show();
}
private void launchAnimationForDisplayMenu(Stage stage, Group root) {
// Most of this method was obtained from stackoverflow.com
Group circles = new Group();
for(int cont = 0 ; cont < 30 ; cont++) {
Circle circle = new Circle();
circle.setFill(Color.CRIMSON);
circle.setEffect(new GaussianBlur(Math.random() * 8 + 2));
circle.setOpacity(Math.random());
circle.setRadius(Math.random()*30);
circle.setCenterX(TankAttack.gameWidth * Math.random());
circle.setCenterY(TankAttack.gameHeight * Math.random());
circles.getChildren().add(circle);
double randScale = (Math.random() * 4) + 1;
KeyValue kValueX = new KeyValue(circle.scaleXProperty() , randScale);
KeyValue kValueY = new KeyValue(circle.scaleYProperty() , randScale);
KeyFrame kFrame = new KeyFrame(Duration.millis(5000 + (Math.random() * 5000)) , kValueX , kValueY);
Timeline timeL = new Timeline();
timeL.getKeyFrames().add(kFrame);
timeL.setAutoReverse(true);
timeL.setCycleCount(Animation.INDEFINITE);
timeL.play();
}
root.getChildren().add(circles);
}
private void createButtonsForDisplayMenu(Stage stage, Group root) {
VBox v = new VBox(TankAttack.gameHeight/20);
v.setTranslateY(TankAttack.gameHeight / 2);
v.setTranslateX(TankAttack.gameWidth/2 - TankAttack.buttonWidth/2);
Button start = this.createButton("START");
start.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
stage.setTitle("TANK ATTACK");
currWorld = new FirstWorld(stage);
initCurrWorld();
}
});
Button quit = this.createButton("QUIT");
quit.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
System.out.println("Quit button pressed.");
Platform.exit();
}
});
v.getChildren().addAll(start, quit);
root.getChildren().add(v);
}
private Button createButton(String text) {
Button returnButton = new Button();
if (!text.isEmpty()) {
returnButton.setText(text);
}
returnButton.setMinSize(buttonWidth, buttonHeight);
return returnButton;
}
public void transitionFromFirstWorldToSecondWorld() {
System.out.println("[transitionFromFirstWorldToSecondWorld] called");
currWorld = new SecondWorld(currStage);
initCurrWorld();
}
private void initCurrWorld() {
// Prior to this method, set currWorld.
// rest is good to go.
currScene = currWorld.createScene();
currStage.setScene(currScene);
currWorld.initAnimation();
}
public static void main(String[] args) {
launch(args);
}
}
|
package org.python.pydev.debug.newconsole;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.XmlRpcHandler;
import org.apache.xmlrpc.XmlRpcRequest;
import org.apache.xmlrpc.server.XmlRpcHandlerMapping;
import org.apache.xmlrpc.server.XmlRpcNoSuchHandlerException;
import org.apache.xmlrpc.server.XmlRpcServer;
import org.apache.xmlrpc.webserver.WebServer;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.python.pydev.core.FullRepIterable;
import org.python.pydev.core.ICompletionState;
import org.python.pydev.core.IToken;
import org.python.pydev.core.concurrency.ConditionEvent;
import org.python.pydev.core.concurrency.ConditionEventWithValue;
import org.python.pydev.core.log.Log;
import org.python.pydev.debug.core.PydevDebugPlugin;
import org.python.pydev.debug.newconsole.env.UserCanceledException;
import org.python.pydev.debug.newconsole.prefs.InteractiveConsolePrefs;
import org.python.pydev.editor.codecompletion.AbstractPyCodeCompletion;
import org.python.pydev.editor.codecompletion.PyCalltipsContextInformation;
import org.python.pydev.editor.codecompletion.PyCodeCompletionImages;
import org.python.pydev.editor.codecompletion.PyLinkedModeCompletionProposal;
import org.python.pydev.editorinput.PyOpenEditor;
import org.python.pydev.shared_core.callbacks.ICallback;
import org.python.pydev.shared_core.callbacks.ICallback0;
import org.python.pydev.shared_core.io.ThreadStreamReader;
import org.python.pydev.shared_core.process.ProcessUtils;
import org.python.pydev.shared_core.string.StringUtils;
import org.python.pydev.shared_core.structure.Tuple;
import org.python.pydev.shared_interactive_console.console.IScriptConsoleCommunication;
import org.python.pydev.shared_interactive_console.console.IXmlRpcClient;
import org.python.pydev.shared_interactive_console.console.InterpreterResponse;
import org.python.pydev.shared_interactive_console.console.ScriptXmlRpcClient;
import org.python.pydev.shared_ui.EditorUtils;
import org.python.pydev.shared_ui.proposals.IPyCompletionProposal;
import org.python.pydev.shared_ui.proposals.PyCompletionProposal;
import org.python.pydev.shared_ui.utils.RunInUiThread;
/**
* Communication with Xml-rpc with the client.
*
* After creating the comms, a successful {@link #hello(IProgressMonitor)} message must be sent before using other methods.
*
* @author Fabio
*/
public class PydevConsoleCommunication implements IScriptConsoleCommunication, XmlRpcHandler {
/**
* XML-RPC client for sending messages to the server.
*/
private IXmlRpcClient client;
/**
* This is the server responsible for giving input to a raw_input() requested
* and for opening editors (as a result of %edit in IPython)
*/
private WebServer webServer;
private final String[] commandArray;
private final String[] envp;
private StdStreamsThread stdStreamsThread;
private class StdStreamsThread extends Thread {
/**
* Responsible for getting the stdout of the process.
*/
private final ThreadStreamReader stdOutReader;
/**
* Responsible for getting the stderr of the process.
*/
private final ThreadStreamReader stdErrReader;
private volatile boolean stopped = false;
private final Object lock = new Object();
public StdStreamsThread(Process process) {
this.setName("StdStreamsThread: " + process);
this.setDaemon(true);
stdOutReader = new ThreadStreamReader(process.getInputStream());
stdErrReader = new ThreadStreamReader(process.getErrorStream());
stdOutReader.start();
stdErrReader.start();
}
@Override
public void run() {
while (!stopped) {
synchronized (lock) {
if (onContentsReceived != null) {
String stderrContents = stdErrReader.getAndClearContents();
String stdOutContents = stdOutReader.getAndClearContents();
if (stdOutContents.length() > 0 || stderrContents.length() > 0) {
onContentsReceived.call(new Tuple<String, String>(stdOutContents, stderrContents));
}
}
try {
lock.wait(50);
} catch (InterruptedException e) {
}
}
}
}
public void stopLoop() {
stopped = true;
lock.notifyAll();
stdOutReader.stopGettingOutput();
stdErrReader.stopGettingOutput();
}
}
/**
* Initializes the xml-rpc communication.
*
* @param port the port where the communication should happen.
* @param process this is the process that was spawned (server for the XML-RPC)
*
* @throws MalformedURLException
*/
public PydevConsoleCommunication(int port, final Process process, int clientPort, String[] commandArray,
String[] envp)
throws Exception {
this.commandArray = commandArray;
this.envp = envp;
finishedExecution = new ConditionEvent(new ICallback0<Boolean>() {
@Override
public Boolean call() {
try {
process.exitValue();
return true; // already exited
} catch (Exception e) {
return false;
}
}
}, 200);
//start the server that'll handle input requests
this.webServer = new WebServer(clientPort);
XmlRpcServer serverToHandleRawInput = this.webServer.getXmlRpcServer();
serverToHandleRawInput.setHandlerMapping(new XmlRpcHandlerMapping() {
public XmlRpcHandler getHandler(String handlerName) throws XmlRpcNoSuchHandlerException, XmlRpcException {
return PydevConsoleCommunication.this;
}
});
this.webServer.start();
this.stdStreamsThread = new StdStreamsThread(process);
this.stdStreamsThread.start();
IXmlRpcClient client = new ScriptXmlRpcClient(process);
client.setPort(port);
this.client = client;
}
/**
* Stops the communication with the client (passes message for it to quit).
*/
public void close() throws Exception {
if (this.client != null) {
Job job = new Job("Close console communication") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
PydevConsoleCommunication.this.client.execute("close", new Object[0]);
} catch (Exception e) {
//Ok, we can ignore this one on close.
}
PydevConsoleCommunication.this.client = null;
return Status.OK_STATUS;
}
};
job.schedule(); //finish it
}
if (this.stdStreamsThread != null) {
this.stdStreamsThread.stopLoop();
this.stdStreamsThread = null;
}
if (this.webServer != null) {
this.webServer.shutdown();
this.webServer = null;
}
}
/**
* Variables that control when we're expecting to give some input to the server or when we're
* adding some line to be executed
*/
/**
* Signals that the next command added should be sent as an input to the server.
*/
private volatile boolean waitingForInput;
/**
* Input that should be sent to the server (waiting for raw_input)
*/
private volatile String inputReceived;
/**
* Response that should be sent back to the shell.
*/
private volatile ConditionEventWithValue<InterpreterResponse> nextResponse = new ConditionEventWithValue<>(null, 20);
/**
* Helper to keep on busy loop.
*/
private volatile Object lock = new Object();
/**
* Keeps a flag indicating that we were able to communicate successfully with the shell at least once
* (if we haven't we may retry more than once the first time, as jython can take a while to initialize
* the communication)
* This is set to true on successful {@link #hello(IProgressMonitor)}
*/
private volatile boolean firstCommWorked = false;
private final ConditionEvent finishedExecution;
/**
* When non-null, the Debug Target to notify when the underlying process is suspended or running.
*/
private IPydevConsoleDebugTarget debugTarget = null;
private ICallback<Object, Tuple<String, String>> onContentsReceived;
/**
* Called when the server is requesting some input from this class.
*/
public Object execute(XmlRpcRequest request) throws XmlRpcException {
String methodName = request.getMethodName();
if ("RequestInput".equals(methodName)) {
return requestInput();
} else if ("IPythonEditor".equals(methodName)) {
return openEditor(request);
} else if ("NotifyAboutMagic".equals(methodName)) {
return "";
} else if ("NotifyFinished".equals(methodName)) {
finishedExecution.set();
return "";
}
Log.log("Unexpected call to execute for method name: " + methodName);
return "";
}
private Object openEditor(XmlRpcRequest request) {
try {
String filename = request.getParameter(0).toString();
final int lineNumber = Integer.parseInt(request.getParameter(1).toString());
final File fileToOpen = new File(filename);
if (!fileToOpen.exists()) {
final OutputStream out = new FileOutputStream(fileToOpen);
try {
out.close();
} catch (final IOException ioe) {
// ignore
}
}
RunInUiThread.async(new Runnable() {
public void run() {
IEditorPart editor = PyOpenEditor.doOpenEditorOnFileStore(fileToOpen);
if (editor instanceof ITextEditor && lineNumber >= 0) {
EditorUtils.showInEditor((ITextEditor) editor, lineNumber);
}
}
});
return true;
} catch (Exception e) {
return false;
}
}
private Object requestInput() {
waitingForInput = true;
inputReceived = null;
boolean needInput = true;
//let the busy loop from execInterpreter free and enter a busy loop
//in this function until execInterpreter gives us an input
setNextResponse(new InterpreterResponse(false, needInput));
//busy loop until we have an input
while (inputReceived == null) {
synchronized (lock) {
try {
lock.wait(10);
} catch (InterruptedException e) {
Log.log(e);
}
}
}
return inputReceived;
}
@Override
public void setOnContentsReceivedCallback(ICallback<Object, Tuple<String, String>> onContentsReceived) {
this.onContentsReceived = onContentsReceived;
}
/**
* Holding the last response (if the last response needed more input, we'll buffer contents internally until
* we do have a suitable line and will pass it in a batch to the interpreter).
*/
private InterpreterResponse lastResponse = null;
/**
* List with the strings to be passed to the interpreter once we have a line that's suitable for evaluation.
*/
private final List<String> moreBuffer = new ArrayList<>();
/**
* Executes a given line in the interpreter.
*
* @param command the command to be executed in the client
*/
public void execInterpreter(String command, final ICallback<Object, InterpreterResponse> onResponseReceived) {
setNextResponse(null);
if (waitingForInput) {
inputReceived = command;
waitingForInput = false;
//the thread that we started in the last exec is still alive if we were waiting for an input.
} else {
if (lastResponse != null && lastResponse.need_input == false && lastResponse.more) {
if (command.trim().length() > 0 && Character.isWhitespace(command.charAt(0))) {
moreBuffer.add(command);
//Pass same response back again (we still need more input to try to do some evaluation).
onResponseReceived.call(lastResponse);
return;
}
}
final String executeCommand;
if (moreBuffer.size() > 0) {
executeCommand = StringUtils.join("\n", moreBuffer) + "\n" + command;
moreBuffer.clear();
} else {
executeCommand = command;
}
//create a thread that'll keep locked until an answer is received from the server.
Job job = new Job("PyDev Console Communication") {
/**
* Executes the needed command
*
* @return a tuple with (null, more) or (error, false)
*
* @throws XmlRpcException
*/
private boolean exec() throws XmlRpcException {
if (client == null) {
return false;
}
Object ret = client.execute(executeCommand.contains("\n") ? "execMultipleLines" : "execLine",
new Object[] { executeCommand });
if (!(ret instanceof Boolean)) {
if (ret instanceof Object[]) {
Object[] objects = (Object[]) ret;
ret = StringUtils.join(" ", objects);
} else {
ret = "" + ret;
}
if (onContentsReceived != null) {
onContentsReceived.call(new Tuple<String, String>("", ret.toString()));
}
return false;
}
boolean more = (Boolean) ret;
return more;
}
@Override
protected IStatus run(IProgressMonitor monitor) {
final boolean needInput = false;
try {
if (!firstCommWorked) {
throw new Exception("hello must be called successfully before execInterpreter can be used.");
}
finishedExecution.unset();
boolean more = exec();
if (!more) {
finishedExecution.waitForSet();
}
setNextResponse(new InterpreterResponse(more, needInput));
} catch (Exception e) {
Log.log(e);
setNextResponse(new InterpreterResponse(false, needInput));
}
return Status.OK_STATUS;
}
};
job.schedule();
}
//busy loop until we have a response
InterpreterResponse waitForSet = nextResponse.waitForSet();
lastResponse = waitForSet;
onResponseReceived.call(waitForSet);
}
/**
* @return completions from the client
*/
public ICompletionProposal[] getCompletions(String text, String actTok, int offset, boolean showForTabCompletion)
throws Exception {
if (waitingForInput) {
return new ICompletionProposal[0];
}
Object fromServer = client.execute("getCompletions", new Object[] { text, actTok });
List<ICompletionProposal> ret = new ArrayList<ICompletionProposal>();
convertToICompletions(text, actTok, offset, fromServer, ret, showForTabCompletion);
ICompletionProposal[] proposals = ret.toArray(new ICompletionProposal[ret.size()]);
return proposals;
}
public static void convertToICompletions(final String text, String actTok, int offset, Object fromServer,
List<ICompletionProposal> ret, boolean showForTabCompletion) {
if (fromServer instanceof Object[]) {
Object[] objects = (Object[]) fromServer;
fromServer = Arrays.asList(objects);
}
if (fromServer instanceof List) {
int length = actTok.lastIndexOf('.');
if (length == -1) {
length = actTok.length();
} else {
length = actTok.length() - length - 1;
}
final String trimmedText = text.trim();
List comps = (List) fromServer;
for (Object o : comps) {
if (o instanceof Object[]) {
//name, doc, args, type
Object[] comp = (Object[]) o;
String name = (String) comp[0];
String docStr = (String) comp[1];
int type = extractInt(comp[3]);
String args = AbstractPyCodeCompletion.getArgs((String) comp[2], type,
ICompletionState.LOOKING_FOR_INSTANCED_VARIABLE);
String nameAndArgs = name + args;
int priority = IPyCompletionProposal.PRIORITY_DEFAULT;
if (type == IToken.TYPE_LOCAL) {
priority = IPyCompletionProposal.PRIORITY_LOCALS;
} else if (type == IToken.TYPE_PARAM) {
priority = IPyCompletionProposal.PRIORITY_LOCALS_1;
} else if (type == IToken.TYPE_IPYTHON_MAGIC) {
priority = IPyCompletionProposal.PRIORTTY_IPYTHON_MAGIC;
}
// ret.add(new PyCompletionProposal(name,
// offset-length, length, name.length(),
// PyCodeCompletionImages.getImageForType(type), name, null, docStr, priority));
int cursorPos = name.length();
if (args.length() > 1) {
cursorPos += 1;
}
int replacementOffset = offset - length;
PyCalltipsContextInformation pyContextInformation = null;
if (args.length() > 2) {
pyContextInformation = new PyCalltipsContextInformation(args, replacementOffset + name.length()
+ 1); //just after the parenthesis
} else {
//Support for IPython completions (non standard names)
//i.e.: %completions, cd ...
if (name.length() > 0) {
//magic ipython stuff (starting with %)
// Decrement the replacement offset _only_ if the token begins with %
// as ipthon completes a<tab> to %alias etc.
if (name.charAt(0) == '%' && text.length() > 0 && text.charAt(0) == '%') {
replacementOffset -= 1;
// handle cd -- we handle this by returning the full path from ipython
// TODO: perhaps we could do this for all completions
} else if (trimmedText.equals("cd") || trimmedText.startsWith("cd ")
|| trimmedText.equals("%cd") || trimmedText.startsWith("%cd ")) {
// text == the full search e.g. "cd works" ; "cd workspaces/foo"
// actTok == the last segment of the path e.g. "foo" ;
// nameAndArgs == full completion e.g. "workspaces/foo/"
if (showForTabCompletion) {
replacementOffset = 0;
length = text.length();
} else {
if (name.charAt(0) == '/') {
//Should be something as cd c:/temp/foo (and name is /temp/foo)
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c == name.charAt(0)) {
String sub = text.substring(i, text.length());
if (name.startsWith(sub)) {
replacementOffset -= (sub.length() - FullRepIterable
.getLastPart(actTok)
.length());
break;
}
}
}
}
}
}
}
}
ret.add(new PyLinkedModeCompletionProposal(nameAndArgs, replacementOffset, length, cursorPos,
PyCodeCompletionImages.getImageForType(type), nameAndArgs, pyContextInformation, docStr,
priority, PyCompletionProposal.ON_APPLY_DEFAULT, args, false));
}
}
}
}
/**
* Extracts an int from an object
*
* @param objToGetInt the object that should be gotten as an int
* @return int with the int the object represents
*/
private static int extractInt(Object objToGetInt) {
if (objToGetInt instanceof Integer) {
return (Integer) objToGetInt;
}
return Integer.parseInt(objToGetInt.toString());
}
/**
* @return the description of the given attribute in the shell
*/
public String getDescription(String text) throws Exception {
if (waitingForInput) {
return "Unable to get description: waiting for input.";
}
return client.execute("getDescription", new Object[] { text }).toString();
}
/**
* The Debug Target to notify when the underlying process is suspended or
* running.
*
* @param debugTarget
*/
public void setDebugTarget(IPydevConsoleDebugTarget debugTarget) {
this.debugTarget = debugTarget;
}
/**
* The Debug Target to notify when the underlying process is suspended or
* running.
*/
public IPydevConsoleDebugTarget getDebugTarget() {
return debugTarget;
}
/**
* Common code to handle all cases of setting nextResponse so that the
* attached debug target can be notified of effective state.
*
* @param nextResponse new next response
*/
private void setNextResponse(InterpreterResponse nextResponse) {
this.nextResponse.set(nextResponse);
updateDebugTarget(nextResponse);
}
/**
* Update the debug target (if non-null) of suspended state of console.
* @param nextResponse2
*/
private void updateDebugTarget(InterpreterResponse nextResponse) {
if (debugTarget != null) {
if (nextResponse == null || nextResponse.need_input == true) {
debugTarget.setSuspended(false);
} else {
debugTarget.setSuspended(true);
}
}
}
/**
* Request that pydevconsole connect (with pydevd) to the specified port
*
* @param localPort
* port for pydevd to connect to.
* @throws Exception if connection fails
*/
public void connectToDebugger(int localPort) throws Exception {
if (waitingForInput) {
throw new Exception("Can't connect debugger now, waiting for input");
}
Object result = client.execute("connectToDebugger", new Object[] { localPort });
Exception exception = null;
if (result instanceof Object[]) {
Object[] resultarray = (Object[]) result;
if (resultarray.length == 1) {
if ("connect complete".equals(resultarray[0])) {
return;
}
if (resultarray[0] instanceof String) {
exception = new Exception((String) resultarray[0]);
}
if (resultarray[0] instanceof Exception) {
exception = (Exception) resultarray[0];
}
}
}
throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR,
"pydevconsole failed to execute connectToDebugger", exception));
}
/**
* Wait for an established connection.
* @param monitor
* @throws Exception if no suitable response is received before the timeout
* @throws UserCanceledException if user cancelled with monitor
*/
public void hello(IProgressMonitor monitor) throws Exception, UserCanceledException {
int maximumAttempts = InteractiveConsolePrefs.getMaximumAttempts();
monitor.beginTask("Establishing Connection To Console Process", maximumAttempts);
try {
if (firstCommWorked) {
return;
}
// We'll do a connection attempt, we can try to
// connect n times (until the 1st time the connection
// is accepted) -- that's mostly because the server may take
// a while to get started.
String result = null;
for (int commAttempts = 0; commAttempts < maximumAttempts; commAttempts++) {
if (monitor.isCanceled()) {
throw new UserCanceledException("Canceled before hello was successful");
}
try {
Object[] resulta;
resulta = (Object[]) client.execute("hello", new Object[] { "Hello pydevconsole" });
result = resulta[0].toString();
} catch (XmlRpcException e) {
// We'll retry in a moment
}
if ("Hello eclipse".equals(result)) {
firstCommWorked = true;
break;
}
if (result.startsWith("Console already exited with value")) {
// Failed, probably some error starting the process
break;
}
try {
Thread.sleep(250);
} catch (InterruptedException e) {
// Retry now
}
monitor.worked(1);
}
if (!firstCommWorked) {
String commandLine = this.commandArray != null ? ProcessUtils.getArgumentsAsStr(this.commandArray)
: "(unable to determine command line)";
String environment = this.envp != null ? ProcessUtils.getEnvironmentAsStr(this.envp) : "null";
throw new Exception("Failed to recive suitable Hello response from pydevconsole. Last msg received: "
+ result + "\nCommand Line used: " + commandLine + "\n\nEnvironment:\n" + environment);
}
} finally {
monitor.done();
}
}
/**
* Not required for normal pydev console
*/
public void linkWithDebugSelection(boolean isLinkedWithDebug) {
throw new RuntimeException("Not implemented");
}
public void enableGui(String enableGuiName) throws Exception {
if (waitingForInput) {
throw new Exception("Can't connect debugger now, waiting for input");
}
client.execute("enableGui", new Object[] { enableGuiName });
}
}
|
package lecho.lib.hellocharts.renderer;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.text.TextUtils;
import lecho.lib.hellocharts.computator.ChartComputator;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.AxisAutoValues;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.util.FloatUtils;
import lecho.lib.hellocharts.view.Chart;
/**
* Default axes renderer. Can draw maximum four axes - two horizontal(top/bottom) and two vertical(left/right).
*/
public class AxesRenderer {
private static final int DEFAULT_AXIS_MARGIN_DP = 2;
/**
* Axis positions indexes, used for indexing tabs that holds axes parameters, see below.
*/
private static final int TOP = 0;
private static final int LEFT = 1;
private static final int RIGHT = 2;
private static final int BOTTOM = 3;
/**
* Used to measure label width. If label has mas 5 characters only 5 first characters of this array are used to
* measure text width.
*/
private static final char[] labelWidthChars = new char[]{'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'};
private Chart chart;
private ChartComputator computator;
private int axisMargin;
private float density;
private float scaledDensity;
private Paint[] labelPaintTab = new Paint[]{new Paint(), new Paint(), new Paint(), new Paint()};
private Paint[] namePaintTab = new Paint[]{new Paint(), new Paint(), new Paint(), new Paint()};
private Paint[] linePaintTab = new Paint[]{new Paint(), new Paint(), new Paint(), new Paint()};
private float[] nameBaselineTab = new float[4];
private float[] labelBaselineTab = new float[4];
private float[] separationLineTab = new float[4];
private int[] labelWidthTab = new int[4];
private int[] labelTextAscentTab = new int[4];
private int[] labelTextDescentTab = new int[4];
private int[] labelDimensionForMarginsTab = new int[4];
private int[] labelDimensionForStepsTab = new int[4];
private int[] tiltedLabelXTranslation = new int[4];
private int[] tiltedLabelYTranslation = new int[4];
private FontMetricsInt[] fontMetricsTab = new FontMetricsInt[]{new FontMetricsInt(), new FontMetricsInt(),
new FontMetricsInt(), new FontMetricsInt()};
/**
* Holds formatted axis value label.
*/
private char[] labelBuffer = new char[32];
/**
* Holds number of values that should be drown for each axis.
*/
private int[] valuesToDrawNumTab = new int[4];
/**
* Holds raw values to draw for each axis.
*/
private float[][] rawValuesTab = new float[4][0];
/**
* Holds auto-generated values that should be drawn, i.e if axis is inside not all auto-generated values should be
* drawn to avoid overdrawing. Used only for auto axes.
*/
private float[][] autoValuesToDrawTab = new float[4][0];
/**
* Holds custom values that should be drawn, used only for custom axes.
*/
private AxisValue[][] valuesToDrawTab = new AxisValue[4][0];
/**
* Buffers for axes lines coordinates(to draw grid in the background).
*/
private float[][] linesDrawBufferTab = new float[4][0];
/**
* Buffers for auto-generated values for each axis, used only if there are auto axes.
*/
private AxisAutoValues[] autoValuesBufferTab = new AxisAutoValues[]{new AxisAutoValues(),
new AxisAutoValues(), new AxisAutoValues(), new AxisAutoValues()};
public AxesRenderer(Context context, Chart chart) {
this.chart = chart;
computator = chart.getChartComputator();
density = context.getResources().getDisplayMetrics().density;
scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
axisMargin = ChartUtils.dp2px(density, DEFAULT_AXIS_MARGIN_DP);
for (int position = 0; position < 4; ++position) {
labelPaintTab[position].setStyle(Paint.Style.FILL);
labelPaintTab[position].setAntiAlias(true);
namePaintTab[position].setStyle(Paint.Style.FILL);
namePaintTab[position].setAntiAlias(true);
linePaintTab[position].setStyle(Paint.Style.STROKE);
linePaintTab[position].setAntiAlias(true);
}
}
public void onChartSizeChanged() {
onChartDataOrSizeChanged();
}
public void onChartDataChanged() {
onChartDataOrSizeChanged();
}
private void onChartDataOrSizeChanged() {
initAxis(chart.getChartData().getAxisXTop(), TOP);
initAxis(chart.getChartData().getAxisXBottom(), BOTTOM);
initAxis(chart.getChartData().getAxisYLeft(), LEFT);
initAxis(chart.getChartData().getAxisYRight(), RIGHT);
}
public void resetRenderer() {
this.computator = chart.getChartComputator();
}
/**
* Initialize attributes and measurement for axes(left, right, top, bottom);
*/
private void initAxis(Axis axis, int position) {
if (null == axis) {
return;
}
initAxisAttributes(axis, position);
initAxisMargin(axis, position);
initAxisMeasurements(axis, position);
}
private void initAxisAttributes(Axis axis, int position) {
initAxisPaints(axis, position);
initAxisTextAlignment(axis, position);
if (axis.hasTiltedLabels()) {
initAxisDimensionForTiltedLabels(position);
intiTiltedLabelsTranslation(axis, position);
} else {
initAxisDimension(position);
}
}
private void initAxisPaints(Axis axis, int position) {
Typeface typeface = axis.getTypeface();
if (null != typeface) {
labelPaintTab[position].setTypeface(typeface);
namePaintTab[position].setTypeface(typeface);
}
labelPaintTab[position].setColor(axis.getTextColor());
labelPaintTab[position].setTextSize(ChartUtils.sp2px(scaledDensity, axis.getTextSize()));
labelPaintTab[position].getFontMetricsInt(fontMetricsTab[position]);
namePaintTab[position].setColor(axis.getTextColor());
namePaintTab[position].setTextSize(ChartUtils.sp2px(scaledDensity, axis.getTextSize()));
linePaintTab[position].setColor(axis.getLineColor());
labelTextAscentTab[position] = Math.abs(fontMetricsTab[position].ascent);
labelTextDescentTab[position] = Math.abs(fontMetricsTab[position].descent);
labelWidthTab[position] = (int) labelPaintTab[position].measureText(labelWidthChars, 0,
axis.getMaxLabelChars());
}
private void initAxisTextAlignment(Axis axis, int position) {
namePaintTab[position].setTextAlign(Align.CENTER);
if (TOP == position || BOTTOM == position) {
labelPaintTab[position].setTextAlign(Align.CENTER);
} else if (LEFT == position) {
if (axis.isInside()) {
labelPaintTab[position].setTextAlign(Align.LEFT);
} else {
labelPaintTab[position].setTextAlign(Align.RIGHT);
}
} else if (RIGHT == position) {
if (axis.isInside()) {
labelPaintTab[position].setTextAlign(Align.RIGHT);
} else {
labelPaintTab[position].setTextAlign(Align.LEFT);
}
}
}
private void initAxisDimensionForTiltedLabels(int position) {
int pythagoreanFromLabelWidth = (int) Math.sqrt(Math.pow(labelWidthTab[position], 2) / 2);
int pythagoreanFromAscent = (int) Math.sqrt(Math.pow(labelTextAscentTab[position], 2) / 2);
labelDimensionForMarginsTab[position] = pythagoreanFromAscent + pythagoreanFromLabelWidth;
labelDimensionForStepsTab[position] = Math.round(labelDimensionForMarginsTab[position] * 0.75f);
}
private void initAxisDimension(int position) {
if (LEFT == position || RIGHT == position) {
labelDimensionForMarginsTab[position] = labelWidthTab[position];
labelDimensionForStepsTab[position] = labelTextAscentTab[position];
} else if (TOP == position || BOTTOM == position) {
labelDimensionForMarginsTab[position] = labelTextAscentTab[position] +
labelTextDescentTab[position];
labelDimensionForStepsTab[position] = labelWidthTab[position];
}
}
private void intiTiltedLabelsTranslation(Axis axis, int position) {
int pythagoreanFromLabelWidth = (int) Math.sqrt(Math.pow(labelWidthTab[position], 2) / 2);
int pythagoreanFromAscent = (int) Math.sqrt(Math.pow(labelTextAscentTab[position], 2) / 2);
int dx = 0;
int dy = 0;
if (axis.isInside()) {
if (LEFT == position) {
dx = pythagoreanFromAscent;
} else if (RIGHT == position) {
dy = -pythagoreanFromLabelWidth / 2;
} else if (TOP == position) {
dy = (pythagoreanFromAscent + pythagoreanFromLabelWidth / 2) - labelTextAscentTab[position];
} else if (BOTTOM == position) {
dy = -pythagoreanFromLabelWidth / 2;
}
} else {
if (LEFT == position) {
dy = -pythagoreanFromLabelWidth / 2;
} else if (RIGHT == position) {
dx = pythagoreanFromAscent;
} else if (TOP == position) {
dy = -pythagoreanFromLabelWidth / 2;
} else if (BOTTOM == position) {
dy = (pythagoreanFromAscent + pythagoreanFromLabelWidth / 2) - labelTextAscentTab[position];
}
}
tiltedLabelXTranslation[position] = dx;
tiltedLabelYTranslation[position] = dy;
}
private void initAxisMargin(Axis axis, int position) {
int margin = 0;
if (!axis.isInside() && (axis.isAutoGenerated() || !axis.getValues().isEmpty())) {
margin += axisMargin + labelDimensionForMarginsTab[position];
}
margin += getAxisNameMargin(axis, position);
insetContentRectWithAxesMargins(margin, position);
}
private int getAxisNameMargin(Axis axis, int position) {
int margin = 0;
if (!TextUtils.isEmpty(axis.getName())) {
margin += labelTextAscentTab[position];
margin += labelTextDescentTab[position];
margin += axisMargin;
}
return margin;
}
private void insetContentRectWithAxesMargins(int axisMargin, int position) {
if (LEFT == position) {
chart.getChartComputator().insetContentRect(axisMargin, 0, 0, 0);
} else if (RIGHT == position) {
chart.getChartComputator().insetContentRect(0, 0, axisMargin, 0);
} else if (TOP == position) {
chart.getChartComputator().insetContentRect(0, axisMargin, 0, 0);
} else if (BOTTOM == position) {
chart.getChartComputator().insetContentRect(0, 0, 0, axisMargin);
}
}
private void initAxisMeasurements(Axis axis, int position) {
if (LEFT == position) {
if (axis.isInside()) {
labelBaselineTab[position] = computator.getContentRectMinusAxesMargins().left + axisMargin;
nameBaselineTab[position] = computator.getContentRectMinusAxesMargins().left - axisMargin
- labelTextDescentTab[position];
} else {
labelBaselineTab[position] = computator.getContentRectMinusAxesMargins().left - axisMargin;
nameBaselineTab[position] = labelBaselineTab[position] - axisMargin
- labelTextDescentTab[position] - labelDimensionForMarginsTab[position];
}
separationLineTab[position] = computator.getContentRectMinusAllMargins().left;
} else if (RIGHT == position) {
if (axis.isInside()) {
labelBaselineTab[position] = computator.getContentRectMinusAxesMargins().right - axisMargin;
nameBaselineTab[position] = computator.getContentRectMinusAxesMargins().right + axisMargin
+ labelTextAscentTab[position];
} else {
labelBaselineTab[position] = computator.getContentRectMinusAxesMargins().right + axisMargin;
nameBaselineTab[position] = labelBaselineTab[position] + axisMargin
+ labelTextAscentTab[position] + labelDimensionForMarginsTab[position];
}
separationLineTab[position] = computator.getContentRectMinusAllMargins().right;
} else if (BOTTOM == position) {
if (axis.isInside()) {
labelBaselineTab[position] = computator.getContentRectMinusAxesMargins().bottom - axisMargin
- labelTextDescentTab[position];
nameBaselineTab[position] = computator.getContentRectMinusAxesMargins().bottom + axisMargin
+ labelTextAscentTab[position];
} else {
labelBaselineTab[position] = computator.getContentRectMinusAxesMargins().bottom + axisMargin
+ labelTextAscentTab[position];
nameBaselineTab[position] = labelBaselineTab[position] + axisMargin +
labelDimensionForMarginsTab[position];
}
separationLineTab[position] = computator.getContentRectMinusAllMargins().bottom;
} else if (TOP == position) {
if (axis.isInside()) {
labelBaselineTab[position] = computator.getContentRectMinusAxesMargins().top + axisMargin
+ labelTextAscentTab[position];
nameBaselineTab[position] = computator.getContentRectMinusAxesMargins().top - axisMargin
- labelTextDescentTab[position];
} else {
labelBaselineTab[position] = computator.getContentRectMinusAxesMargins().top - axisMargin
- labelTextDescentTab[position];
nameBaselineTab[position] = labelBaselineTab[position] - axisMargin -
labelDimensionForMarginsTab[position];
}
separationLineTab[position] = computator.getContentRectMinusAllMargins().top;
} else {
throw new IllegalArgumentException("Invalid axis position: " + position);
}
}
/**
* Prepare axes coordinates and draw axes lines(if enabled) in the background.
*
* @param canvas
*/
public void drawInBackground(Canvas canvas) {
Axis axis = chart.getChartData().getAxisYLeft();
if (null != axis) {
prepareAxisToDraw(axis, LEFT);
drawAxisLines(canvas, axis, LEFT);
}
axis = chart.getChartData().getAxisYRight();
if (null != axis) {
prepareAxisToDraw(axis, RIGHT);
drawAxisLines(canvas, axis, RIGHT);
}
axis = chart.getChartData().getAxisXBottom();
if (null != axis) {
prepareAxisToDraw(axis, BOTTOM);
drawAxisLines(canvas, axis, BOTTOM);
}
axis = chart.getChartData().getAxisXTop();
if (null != axis) {
prepareAxisToDraw(axis, TOP);
drawAxisLines(canvas, axis, TOP);
}
}
private void prepareAxisToDraw(Axis axis, int position) {
if (axis.isAutoGenerated()) {
prepareAutoGeneratedAxis(axis, position);
} else {
prepareCustomAxis(axis, position);
}
}
/**
* Draw axes labels and names in the foreground.
*
* @param canvas
*/
public void drawInForeground(Canvas canvas) {
Axis axis = chart.getChartData().getAxisYLeft();
if (null != axis) {
drawAxisLabelsAndName(canvas, axis, LEFT);
}
axis = chart.getChartData().getAxisYRight();
if (null != axis) {
drawAxisLabelsAndName(canvas, axis, RIGHT);
}
axis = chart.getChartData().getAxisXBottom();
if (null != axis) {
drawAxisLabelsAndName(canvas, axis, BOTTOM);
}
axis = chart.getChartData().getAxisXTop();
if (null != axis) {
drawAxisLabelsAndName(canvas, axis, TOP);
}
}
private void prepareCustomAxis(Axis axis, int position) {
final Viewport maxViewport = computator.getMaximumViewport();
final Viewport visibleViewport = computator.getVisibleViewport();
final Rect contentRect = computator.getContentRectMinusAllMargins();
boolean isAxisVertical = isAxisVertical(position);
float scale, viewportMin, viewportMax;
if (isAxisVertical) {
scale = contentRect.height() * (maxViewport.height() / visibleViewport.height());
viewportMin = visibleViewport.bottom;
viewportMax = visibleViewport.top;
} else {
scale = contentRect.width() * (maxViewport.width() / visibleViewport.width());
viewportMin = visibleViewport.left;
viewportMax = visibleViewport.right;
}
int module = (int) Math.max(1,
Math.ceil((axis.getValues().size() * labelDimensionForStepsTab[position] * 1.5) / scale));
//Reinitialize tab to hold lines coordinates.
if (axis.hasLines() && (linesDrawBufferTab[position].length < axis.getValues().size() * 4)) {
linesDrawBufferTab[position] = new float[axis.getValues().size() * 4];
}
//Reinitialize tabs to hold all raw values to draw.
if (rawValuesTab[position].length < axis.getValues().size()) {
rawValuesTab[position] = new float[axis.getValues().size()];
valuesToDrawTab[position] = new AxisValue[axis.getValues().size()];
}
float rawValue;
int valueIndex = 0;
int valueToDrawIndex = 0;
for (AxisValue axisValue : axis.getValues()) {
// Draw axis values that are within visible viewport.
final float value = axisValue.getValue();
if (value >= viewportMin && value <= viewportMax) {
// Draw axis values that have 0 module value, this will hide some labels if there is no place for them.
if (0 == valueIndex % module) {
if (isAxisVertical) {
rawValue = computator.computeRawY(value);
} else {
rawValue = computator.computeRawX(value);
}
if (checkRawValue(contentRect, rawValue, axis.isInside(), position, isAxisVertical)) {
rawValuesTab[position][valueToDrawIndex] = rawValue;
valuesToDrawTab[position][valueToDrawIndex] = axisValue;
++valueToDrawIndex;
}
}
// If within viewport - increment valueIndex;
++valueIndex;
}
}
valuesToDrawNumTab[position] = valueToDrawIndex;
}
private void prepareAutoGeneratedAxis(Axis axis, int position) {
final Viewport visibleViewport = computator.getVisibleViewport();
final Rect contentRect = computator.getContentRectMinusAllMargins();
boolean isAxisVertical = isAxisVertical(position);
float start, stop;
int contentRectDimension;
if (isAxisVertical) {
start = visibleViewport.bottom;
stop = visibleViewport.top;
contentRectDimension = contentRect.height();
} else {
start = visibleViewport.left;
stop = visibleViewport.right;
contentRectDimension = contentRect.width();
}
FloatUtils.computeAutoGeneratedAxisValues(start, stop, contentRectDimension /
labelDimensionForStepsTab[position] / 2, autoValuesBufferTab[position]);
//Reinitialize tab to hold lines coordinates.
if (axis.hasLines()
&& (linesDrawBufferTab[position].length < autoValuesBufferTab[position].valuesNumber * 4)) {
linesDrawBufferTab[position] = new float[autoValuesBufferTab[position].valuesNumber * 4];
}
//Reinitialize tabs to hold all raw and auto values.
if (rawValuesTab[position].length < autoValuesBufferTab[position].valuesNumber) {
rawValuesTab[position] = new float[autoValuesBufferTab[position].valuesNumber];
autoValuesToDrawTab[position] = new float[autoValuesBufferTab[position].valuesNumber];
}
float rawValue;
int valueToDrawIndex = 0;
for (int i = 0; i < autoValuesBufferTab[position].valuesNumber; ++i) {
if (isAxisVertical) {
rawValue = computator.computeRawY(autoValuesBufferTab[position].values[i]);
} else {
rawValue = computator.computeRawX(autoValuesBufferTab[position].values[i]);
}
if (checkRawValue(contentRect, rawValue, axis.isInside(), position, isAxisVertical)) {
rawValuesTab[position][valueToDrawIndex] = rawValue;
autoValuesToDrawTab[position][valueToDrawIndex] = autoValuesBufferTab[position].values[i];
++valueToDrawIndex;
}
}
valuesToDrawNumTab[position] = valueToDrawIndex;
}
private boolean checkRawValue(Rect rect, float rawValue, boolean axisInside, int position, boolean isVertical) {
if (axisInside) {
if (isVertical) {
float marginBottom = labelTextAscentTab[BOTTOM] + axisMargin;
float marginTop = labelTextAscentTab[TOP] + axisMargin;
if (rawValue <= rect.bottom - marginBottom && rawValue >= rect.top + marginTop) {
return true;
} else {
return false;
}
} else {
float margin = labelWidthTab[position] / 2;
if (rawValue >= rect.left + margin && rawValue <= rect.right - margin) {
return true;
} else {
return false;
}
}
}
return true;
}
private void drawAxisLines(Canvas canvas, Axis axis, int position) {
final Rect contentRectMargins = computator.getContentRectMinusAxesMargins();
float separationX1, separationY1, separationX2, separationY2;
separationX1 = separationY1 = separationX2 = separationY2 = 0;
float lineX1, lineY1, lineX2, lineY2;
lineX1 = lineY1 = lineX2 = lineY2 = 0;
boolean isAxisVertical = isAxisVertical(position);
if (LEFT == position || RIGHT == position) {
separationX1 = separationX2 = separationLineTab[position];
separationY1 = contentRectMargins.bottom;
separationY2 = contentRectMargins.top;
lineX1 = contentRectMargins.left;
lineX2 = contentRectMargins.right;
} else if (TOP == position || BOTTOM == position) {
separationX1 = contentRectMargins.left;
separationX2 = contentRectMargins.right;
separationY1 = separationY2 = separationLineTab[position];
lineY1 = contentRectMargins.top;
lineY2 = contentRectMargins.bottom;
}
// Draw separation line with the same color as axis labels and name.
if (axis.hasSeparationLine()) {
canvas.drawLine(separationX1, separationY1, separationX2, separationY2, labelPaintTab[position]);
}
if (axis.hasLines()) {
int valueToDrawIndex = 0;
for (; valueToDrawIndex < valuesToDrawNumTab[position]; ++valueToDrawIndex) {
if (isAxisVertical) {
lineY1 = lineY2 = rawValuesTab[position][valueToDrawIndex];
} else {
lineX1 = lineX2 = rawValuesTab[position][valueToDrawIndex];
}
linesDrawBufferTab[position][valueToDrawIndex * 4 + 0] = lineX1;
linesDrawBufferTab[position][valueToDrawIndex * 4 + 1] = lineY1;
linesDrawBufferTab[position][valueToDrawIndex * 4 + 2] = lineX2;
linesDrawBufferTab[position][valueToDrawIndex * 4 + 3] = lineY2;
}
canvas.drawLines(linesDrawBufferTab[position], 0, valueToDrawIndex * 4, linePaintTab[position]);
}
}
private void drawAxisLabelsAndName(Canvas canvas, Axis axis, int position) {
float labelX, labelY;
labelX = labelY = 0;
boolean isAxisVertical = isAxisVertical(position);
if (LEFT == position || RIGHT == position) {
labelX = labelBaselineTab[position];
} else if (TOP == position || BOTTOM == position) {
labelY = labelBaselineTab[position];
}
for (int valueToDrawIndex = 0; valueToDrawIndex < valuesToDrawNumTab[position]; ++valueToDrawIndex) {
int charsNumber = 0;
if (axis.isAutoGenerated()) {
final float value = autoValuesToDrawTab[position][valueToDrawIndex];
charsNumber = axis.getFormatter().formatValueForAutoGeneratedAxis(labelBuffer, value,
autoValuesBufferTab[position].decimals);
} else {
AxisValue axisValue = valuesToDrawTab[position][valueToDrawIndex];
charsNumber = axis.getFormatter().formatValueForManualAxis(labelBuffer, axisValue);
}
if (isAxisVertical) {
labelY = rawValuesTab[position][valueToDrawIndex];
} else {
labelX = rawValuesTab[position][valueToDrawIndex];
}
if (axis.hasTiltedLabels()) {
canvas.save();
canvas.translate(tiltedLabelXTranslation[position], tiltedLabelYTranslation[position]);
canvas.rotate(-45, labelX, labelY);
canvas.drawText(labelBuffer, labelBuffer.length - charsNumber, charsNumber, labelX, labelY,
labelPaintTab[position]);
canvas.restore();
} else {
canvas.drawText(labelBuffer, labelBuffer.length - charsNumber, charsNumber, labelX, labelY,
labelPaintTab[position]);
}
}
// Drawing axis name
final Rect contentRectMargins = computator.getContentRectMinusAxesMargins();
if (!TextUtils.isEmpty(axis.getName())) {
if (isAxisVertical) {
canvas.save();
canvas.rotate(-90, contentRectMargins.centerY(), contentRectMargins.centerY());
canvas.drawText(axis.getName(), contentRectMargins.centerY(), nameBaselineTab[position],
namePaintTab[position]);
canvas.restore();
} else {
canvas.drawText(axis.getName(), contentRectMargins.centerX(), nameBaselineTab[position],
namePaintTab[position]);
}
}
}
private boolean isAxisVertical(int position) {
if (LEFT == position || RIGHT == position) {
return true;
} else if (TOP == position || BOTTOM == position) {
return false;
} else {
throw new IllegalArgumentException("Invalid axis position " + position);
}
}
}
|
package com.opengamma.bloombergexample.loader;
import static com.opengamma.engine.value.ValuePropertyNames.CURRENCY;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE_CALCULATION_CONFIG;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE_CURRENCY;
import static com.opengamma.engine.value.ValuePropertyNames.AGGREGATION;
import static com.opengamma.engine.value.ValueRequirementNames.PAR_RATE;
import static com.opengamma.engine.value.ValueRequirementNames.PRESENT_VALUE;
import static com.opengamma.engine.value.ValueRequirementNames.PV01;
import static com.opengamma.engine.value.ValueRequirementNames.YIELD_CURVE;
import static com.opengamma.engine.value.ValueRequirementNames.YIELD_CURVE_NODE_SENSITIVITIES;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.bloombergexample.tool.ExampleDatabasePopulator;
import com.opengamma.component.tool.AbstractTool;
import com.opengamma.core.config.impl.ConfigItem;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.view.ViewCalculationConfiguration;
import com.opengamma.engine.view.ViewDefinition;
import com.opengamma.financial.analytics.MissingInputsFunction;
import com.opengamma.financial.security.equity.EquitySecurity;
import com.opengamma.financial.security.option.EquityOptionSecurity;
import com.opengamma.financial.security.option.FXBarrierOptionSecurity;
import com.opengamma.financial.security.option.FXDigitalOptionSecurity;
import com.opengamma.financial.security.option.FXOptionSecurity;
import com.opengamma.financial.security.swap.SwapSecurity;
import com.opengamma.id.UniqueId;
import com.opengamma.integration.tool.IntegrationToolContext;
import com.opengamma.livedata.UserPrincipal;
import com.opengamma.master.config.ConfigMasterUtils;
import com.opengamma.master.portfolio.PortfolioSearchRequest;
import com.opengamma.master.portfolio.PortfolioSearchResult;
import com.opengamma.util.generate.scripts.Scriptable;
import com.opengamma.util.money.Currency;
/**
* Example code to create a set of example views.
* <p>
* It is designed to run against the HSQLDB example database.
*/
@Scriptable
public class ExampleViewsPopulator extends AbstractTool<IntegrationToolContext> {
private static final String[] s_curveConfigNames = new String[] {"DefaultTwoCurveUSDConfig", "DefaultTwoCurveGBPConfig", "DefaultTwoCurveEURConfig",
"DefaultTwoCurveJPYConfig", "DefaultTwoCurveCHFConfig"};
private static final Currency[] s_swapCurrencies = new Currency[] {Currency.USD, Currency.GBP, Currency.EUR, Currency.JPY, Currency.CHF};
private static final String FORWARD_3M = "Forward3M";
private static final String FORWARD_6M = "Forward6M";
private static final String FUNDING = "Discounting";
private static final String OLD_FORWARD_3M = "FORWARD_3M";
private static final String OLD_FORWARD_6M = "FORWARD_6M";
private static final String OLD_FUNDING = "FUNDING";
private static final String FX_SURFACE = "DEFAULT";
private static final String DEFAULT_CALC_CONFIG = "Default";
/** Logger. */
private static final Logger s_logger = LoggerFactory.getLogger(ExampleViewsPopulator.class);
private static final String MISSING_INPUTS = MissingInputsFunction.AGGREGATION_STYLE_MISSING;
/**
* Main method to run the tool.
* No arguments are needed.
*
* @param args the arguments, unused
*/
public static void main(final String[] args) { // CSIGNORE
new ExampleViewsPopulator().initAndRun(args, IntegrationToolContext.class);
System.exit(0);
}
@Override
protected void doRun() {
storeViewDefinition(getEquityViewDefinition(ExampleEquityPortfolioLoader.PORTFOLIO_NAME));
//storeViewDefinition(getFXViewDefinition(ExampleDatabasePopulator.FX_PORTFOLIO_NAME));
storeViewDefinition(getMultiCurrencySwapViewDefinition(ExampleMultiCurrencySwapPortfolioLoader.PORTFOLIO_NAME));
storeViewDefinition(getEquityOptionViewDefinition(DemoEquityOptionCollarPortfolioLoader.PORTFOLIO_NAME));
}
private void addEquityRequirements(final ViewDefinition viewDefinition) {
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquitySecurity.SECURITY_TYPE, ValueRequirementNames.CAPM_BETA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
//viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquitySecurity.SECURITY_TYPE, ValueRequirementNames.DAILY_PNL, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquitySecurity.SECURITY_TYPE, ValueRequirementNames.FAIR_VALUE, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquitySecurity.SECURITY_TYPE, ValueRequirementNames.HISTORICAL_VAR, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquitySecurity.SECURITY_TYPE, ValueRequirementNames.HISTORICAL_VAR_STDDEV, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquitySecurity.SECURITY_TYPE, ValueRequirementNames.JENSENS_ALPHA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquitySecurity.SECURITY_TYPE, ValueRequirementNames.PNL_SERIES, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquitySecurity.SECURITY_TYPE, ValueRequirementNames.SHARPE_RATIO, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquitySecurity.SECURITY_TYPE, ValueRequirementNames.TOTAL_RISK_ALPHA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquitySecurity.SECURITY_TYPE, ValueRequirementNames.TREYNOR_RATIO, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquitySecurity.SECURITY_TYPE, ValueRequirementNames.SECURITY_MARKET_PRICE, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
}
private void addEquityOptionRequirements(final ViewDefinition viewDefinition) {
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.CARRY_RHO, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
//viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.DAILY_PNL, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.DELTA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.DELTA_BLEED, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.DRIFTLESS_THETA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.ELASTICITY, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.FAIR_VALUE, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.GAMMA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.GAMMA_BLEED, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.GAMMA_P, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.GAMMA_P_BLEED, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.HISTORICAL_VAR, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.HISTORICAL_VAR_STDDEV, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.JENSENS_ALPHA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.PNL_SERIES, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.PHI, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.RHO, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.SECURITY_MARKET_PRICE, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.SPEED, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.SPEED_P, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.STRIKE_DELTA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.STRIKE_GAMMA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.THETA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.ULTIMA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VALUE_DELTA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VALUE_GAMMA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VANNA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VARIANCE_ULTIMA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VARIANCE_VANNA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VARIANCE_VEGA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VARIANCE_VOMMA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VEGA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VEGA_BLEED, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VEGA_P, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VOMMA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VOMMA_P, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.ZETA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.ZETA_BLEED, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.ZOMMA, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.ZOMMA_P, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.DVANNA_DVOL, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
viewDefinition.addPortfolioRequirement(DEFAULT_CALC_CONFIG, EquityOptionSecurity.SECURITY_TYPE, ValueRequirementNames.DZETA_DVOL, ValueProperties.with(CURVE, FUNDING).withOptional(CURVE).with(AGGREGATION, MISSING_INPUTS).withOptional(AGGREGATION).get());
}
private ViewDefinition getEquityOptionViewDefinition(final String portfolioName) {
final UniqueId portfolioId = getPortfolioId(portfolioName).toLatest();
final ViewDefinition viewDefinition = new ViewDefinition(portfolioName + " View", portfolioId, UserPrincipal.getTestUser());
viewDefinition.setDefaultCurrency(Currency.USD);
viewDefinition.setMaxFullCalculationPeriod(30000L);
viewDefinition.setMinFullCalculationPeriod(500L);
viewDefinition.setMinDeltaCalculationPeriod(500L);
viewDefinition.setMaxDeltaCalculationPeriod(30000L);
addEquityRequirements(viewDefinition);
addEquityOptionRequirements(viewDefinition);
return viewDefinition;
}
private ViewDefinition getEquityViewDefinition(final String portfolioName) {
final UniqueId portfolioId = getPortfolioId(portfolioName).toLatest();
final ViewDefinition viewDefinition = new ViewDefinition(portfolioName + " View", portfolioId, UserPrincipal.getTestUser());
viewDefinition.setDefaultCurrency(Currency.USD);
viewDefinition.setMaxFullCalculationPeriod(30000L);
viewDefinition.setMinFullCalculationPeriod(500L);
viewDefinition.setMinDeltaCalculationPeriod(500L);
viewDefinition.setMaxDeltaCalculationPeriod(30000L);
addEquityRequirements(viewDefinition);
return viewDefinition;
}
private UniqueId getPortfolioId(final String portfolioName) {
final PortfolioSearchRequest searchRequest = new PortfolioSearchRequest();
searchRequest.setName(portfolioName);
final PortfolioSearchResult searchResult = getToolContext().getPortfolioMaster().search(searchRequest);
if (searchResult.getFirstPortfolio() == null) {
s_logger.error("Couldn't find portfolio {}", portfolioName);
throw new OpenGammaRuntimeException("Couldn't find portfolio" + portfolioName);
}
return searchResult.getFirstPortfolio().getUniqueId();
}
// private ViewDefinition getMultiCurrencySwapViewDefinition(final String portfolioName) {
// final UniqueId portfolioId = getPortfolioId(portfolioName).toLatest();
// final ViewDefinition viewDefinition = new ViewDefinition(portfolioName + " View", portfolioId, UserPrincipal.getTestUser());
// viewDefinition.setDefaultCurrency(Currency.USD);
// viewDefinition.setMaxDeltaCalculationPeriod(500L);
// viewDefinition.setMaxFullCalculationPeriod(500L);
// viewDefinition.setMinDeltaCalculationPeriod(500L);
// viewDefinition.setMinFullCalculationPeriod(500L);
// final ViewCalculationConfiguration defaultCalc = new ViewCalculationConfiguration(viewDefinition, "Default");
// final ValueProperties defaultProperties = ValueProperties.with("ForwardCurve", "DEFAULT").with("FundingCurve", "DEFAULT").with("Currency", "USD").get();
// defaultCalc.setDefaultProperties(defaultProperties);
// final ValueProperties fundingCurveSpecificProperties = ValueProperties.with("Curve", FUNDING).get();
// final ValueProperties forwardCurve3MSpecificProperties = ValueProperties.with("Curve", FORWARD_3M).get();
// final ValueProperties forwardCurve6MSpecificProperties = ValueProperties.with("Curve", FORWARD_6M).get();
// defaultCalc.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, ValueRequirementNames.PV01, fundingCurveSpecificProperties);
// defaultCalc.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, ValueRequirementNames.PV01, forwardCurve3MSpecificProperties);
// defaultCalc.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, ValueRequirementNames.PV01, forwardCurve6MSpecificProperties);
// defaultCalc.addPortfolioRequirementName(SwapSecurity.SECURITY_TYPE, ValueRequirementNames.PRESENT_VALUE);
// defaultCalc.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, ValueRequirementNames.YIELD_CURVE_NODE_SENSITIVITIES, fundingCurveSpecificProperties);
// defaultCalc.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, ValueRequirementNames.YIELD_CURVE_NODE_SENSITIVITIES, forwardCurve3MSpecificProperties);
// defaultCalc.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, ValueRequirementNames.YIELD_CURVE_NODE_SENSITIVITIES, forwardCurve6MSpecificProperties);
// for (final Currency ccy : ExampleMultiCurrencySwapPortfolioLoader.s_currencies) {
// defaultCalc.addSpecificRequirement(new ValueRequirement(
// ValueRequirementNames.YIELD_CURVE,
// ComputationTargetType.PRIMITIVE,
// UniqueId.of("CurrencyISO", ccy.getCode()),
// ValueProperties.with("Curve", FUNDING).get()));
// viewDefinition.addViewCalculationConfiguration(defaultCalc);
// return viewDefinition;
private ViewDefinition getMultiCurrencySwapViewDefinition(final String portfolioName) {
final UniqueId portfolioId = getPortfolioId(portfolioName).toLatest();
final ViewDefinition viewDefinition = new ViewDefinition(portfolioName + " View", portfolioId, UserPrincipal.getTestUser());
viewDefinition.setDefaultCurrency(Currency.USD);
viewDefinition.setMaxDeltaCalculationPeriod(500L);
viewDefinition.setMaxFullCalculationPeriod(500L);
viewDefinition.setMinDeltaCalculationPeriod(500L);
viewDefinition.setMinFullCalculationPeriod(500L);
final ViewCalculationConfiguration defaultCalConfig = new ViewCalculationConfiguration(viewDefinition, DEFAULT_CALC_CONFIG);
defaultCalConfig.addPortfolioRequirementName(SwapSecurity.SECURITY_TYPE, PAR_RATE);
defaultCalConfig.addPortfolioRequirementName(SwapSecurity.SECURITY_TYPE, PRESENT_VALUE);
defaultCalConfig.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, PRESENT_VALUE,
ValueProperties.with(CURRENCY, "USD").get());
for (int i = 0; i < s_swapCurrencies.length; i++) {
final String ccyName = s_swapCurrencies[i].getCode();
final ComputationTargetSpecification ccyTarget = ComputationTargetSpecification.of(s_swapCurrencies[i]);
defaultCalConfig.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, PV01,
ValueProperties.with(CURVE, "Discounting").with(CURVE_CURRENCY, ccyName)
.with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalConfig.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, YIELD_CURVE_NODE_SENSITIVITIES,
ValueProperties.with(CURVE, "Discounting").with(CURVE_CURRENCY, ccyName)
.with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalConfig.addSpecificRequirement(new ValueRequirement(YIELD_CURVE, ccyTarget,
ValueProperties.with(CURVE, "Discounting").with(CURVE_CALCULATION_CONFIG, s_curveConfigNames[i])
.with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get()));
if (ccyName.equals("USD")) {
defaultCalConfig.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, YIELD_CURVE_NODE_SENSITIVITIES,
ValueProperties.with(CURVE, "Forward3M").with(CURVE_CURRENCY, ccyName)
.with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalConfig.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, PV01,
ValueProperties.with(CURVE, "Forward3M").with(CURVE_CURRENCY, ccyName)
.with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalConfig.addSpecificRequirement(new ValueRequirement(YIELD_CURVE, ccyTarget,
ValueProperties.with(CURVE, "Forward3M").with(CURVE_CALCULATION_CONFIG, s_curveConfigNames[i])
.with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get()));
} else {
defaultCalConfig.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, PV01,
ValueProperties.with(CURVE, "Forward6M").with(CURVE_CURRENCY, ccyName)
.with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalConfig.addPortfolioRequirement(SwapSecurity.SECURITY_TYPE, YIELD_CURVE_NODE_SENSITIVITIES,
ValueProperties.with(CURVE, "Forward6M").with(ValuePropertyNames.CURVE_CURRENCY, ccyName)
.with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalConfig.addSpecificRequirement(new ValueRequirement(YIELD_CURVE, ccyTarget,
ValueProperties.with(CURVE, "Forward6M").with(CURVE_CALCULATION_CONFIG, s_curveConfigNames[i])
.with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get()));
}
}
viewDefinition.addViewCalculationConfiguration(defaultCalConfig);
return viewDefinition;
}
private ViewDefinition getFXViewDefinition(final String portfolioName) {
final UniqueId portfolioId = getPortfolioId(portfolioName).toLatest();
final ViewDefinition viewDefinition = new ViewDefinition(portfolioName + " View", portfolioId, UserPrincipal.getTestUser());
viewDefinition.setDefaultCurrency(Currency.USD);
viewDefinition.setMaxDeltaCalculationPeriod(500L);
viewDefinition.setMaxFullCalculationPeriod(500L);
viewDefinition.setMinDeltaCalculationPeriod(500L);
viewDefinition.setMinFullCalculationPeriod(500L);
final ViewCalculationConfiguration defaultCalc = new ViewCalculationConfiguration(viewDefinition, DEFAULT_CALC_CONFIG);
defaultCalc.addPortfolioRequirement(FXOptionSecurity.SECURITY_TYPE, ValueRequirementNames.PRESENT_VALUE,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXBarrierOptionSecurity.SECURITY_TYPE, ValueRequirementNames.PRESENT_VALUE,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXDigitalOptionSecurity.SECURITY_TYPE, ValueRequirementNames.PRESENT_VALUE,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXOptionSecurity.SECURITY_TYPE, ValueRequirementNames.FX_CURRENCY_EXPOSURE,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXBarrierOptionSecurity.SECURITY_TYPE, ValueRequirementNames.FX_CURRENCY_EXPOSURE,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXDigitalOptionSecurity.SECURITY_TYPE, ValueRequirementNames.FX_CURRENCY_EXPOSURE,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VEGA_MATRIX,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXBarrierOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VEGA_MATRIX,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXDigitalOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VEGA_MATRIX,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VEGA_QUOTE_MATRIX,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXBarrierOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VEGA_QUOTE_MATRIX,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXDigitalOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VEGA_QUOTE_MATRIX,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VALUE_VEGA,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXBarrierOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VALUE_VEGA,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
defaultCalc.addPortfolioRequirement(FXDigitalOptionSecurity.SECURITY_TYPE, ValueRequirementNames.VALUE_VEGA,
ValueProperties.with(ValuePropertyNames.SURFACE, FX_SURFACE).with(ValuePropertyNames.AGGREGATION, MISSING_INPUTS).withOptional(ValuePropertyNames.AGGREGATION).get());
viewDefinition.addViewCalculationConfiguration(defaultCalc);
return viewDefinition;
}
private void storeViewDefinition(final ViewDefinition viewDefinition) {
final ConfigItem<ViewDefinition> configItem = ConfigItem.of(viewDefinition, viewDefinition.getName(), ViewDefinition.class);
ConfigMasterUtils.storeByName(getToolContext().getConfigMaster(), configItem);
}
}
|
package com.hbasebook.hush.servlet.filter;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hbasebook.hush.ResourceManager;
import com.hbasebook.hush.model.ShortUrl;
import com.hbasebook.hush.servlet.RequestInfo;
/**
* The filter handles the short Id to URL redirects.
*/
public class RedirectFilter implements Filter {
public static final String QR_EXTENSION = ".q";
public static final String DETAILS_EXTENSION = "+";
/**
* Initialized the filter instance.
*
* @param filterConfig The filter configuration.
* @throws ServletException When initializing the filter fails.
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// not used
}
/**
* Called when the filter is decommissioned.
*/
@Override
public void destroy() {
// not used
}
/**
* Filter the requests. Used to detect actual pages versus shortened URL Ids.
*
* @param request The current request.
* @param response The response to write to.
* @param chain The filter chain instance.
* @throws IOException When handling the in- or output fails.
* @throws ServletException Might be thrown when there is an internal issue.
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
String uri = httpRequest.getRequestURI();
// check if the request shall pass
if (uri.equals("/") || uri.startsWith("/user") ||
uri.startsWith("/admin") || uri.endsWith(".jsp") ||
uri.endsWith(".css")) {
chain.doFilter(request, response);
} else if (uri.endsWith(DETAILS_EXTENSION)) {
String shortId = uri.substring(1, uri.length() -
DETAILS_EXTENSION.length());
httpRequest.setAttribute("sid", shortId);
RequestDispatcher dispatcher =
httpRequest.getRequestDispatcher("/details.jsp");
if (dispatcher != null) {
dispatcher.forward(request, response);
}
} else {
// otherwise assume it is a short Id
ResourceManager rm = ResourceManager.getInstance();
boolean isQrCode = uri.endsWith(QR_EXTENSION);
String shortId = isQrCode ? uri.substring(1, uri.length() -
QR_EXTENSION.length()) : uri.substring(1);
ShortUrl surl = rm.getUrlManager().getShortUrl(shortId);
if (surl == null) {
// if the short Id was bogus show a "shush" (our fail whale)
httpResponse.sendError(404);
} else if (isQrCode) {
// show QRCode if requested
sendQRCode(httpResponse, surl.getLongUrl());
} else {
// increment counters and redirect!
rm.getCounters().incrementUsage(shortId, new RequestInfo(httpRequest));
String refShortId = surl.getRefShortId();
if (refShortId != null) {
// increment the aggregate link
rm.getCounters().incrementUsage(refShortId,
new RequestInfo(httpRequest));
}
httpResponse.sendRedirect(surl.getLongUrl());
}
}
}
/**
* Copies a Google Chart API QRCode image to the output stream.
*
* @param response The response instance to use.
* @param url The URL to encode.
* @throws IOException When reading or writing the image fails.
*/
private void sendQRCode(HttpServletResponse response, String url)
throws IOException {
URL qrUrl = new URL("http://chart.apis.google.com/chart?" +
"chs=100x100&cht=qr&chl=" + response.encodeURL(url));
InputStream in = new BufferedInputStream(qrUrl.openStream());
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int contentLength = 0;
while (true) {
int length = in.read(buf);
if (length < 0) {
break;
}
out.write(buf, 0, length);
contentLength += length;
}
response.setContentType("image/png");
response.setContentLength(contentLength);
out.flush();
}
}
|
package it.unibz.krdb.obda.owlrefplatform.core.abox;
import it.unibz.krdb.obda.model.Predicate.COL_TYPE;
import it.unibz.krdb.obda.owlrefplatform.core.dagjgrapht.Interval;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class SemanticIndexViewsManager {
private final Map<SemanticIndexViewID, Set<Integer>> nonEmptyEntityRecord = new HashMap<>();
public static SemanticIndexViewID getViewId(COL_TYPE t1, COL_TYPE t2) {
SemanticIndexViewID viewId = new SemanticIndexViewID(COLTYPEtoSITable.get(t2).ordinal(), COLTYPEtoInt(t1), COLTYPEtoInt(t2));
return viewId;
}
public static SemanticIndexViewID getViewId(COL_TYPE t1) {
SemanticIndexViewID viewId = new SemanticIndexViewID(SITable.CLASS.ordinal(), COLTYPEtoInt(t1), OBJ_TYPE_BNode);
return viewId;
}
public boolean isViewEmpty(SemanticIndexViewID viewId, List<Interval> intervals) {
Set<Integer> set = nonEmptyEntityRecord.get(viewId);
if (set == null)
return true; // the set if empty
for (Interval interval : intervals)
for (Integer i = interval.getStart(); i <= interval.getEnd(); i++)
if (set.contains(i))
return false;
return true;
}
public void addIndexToView(SemanticIndexViewID viewId, Integer idx) {
Set<Integer> set = nonEmptyEntityRecord.get(viewId);
if (set == null) {
set = new HashSet<>();
nonEmptyEntityRecord.put(viewId, set);
}
set.add(idx);
}
public String constructSqlSource(COL_TYPE type) {
StringBuilder sql = new StringBuilder();
sql.append(RDBMSSIRepositoryManager.classTable.selectCommand);
/*
* If the mapping is for something of type Literal we need to add IS
* NULL or IS NOT NULL to the language column. IS NOT NULL might be
* redundant since we have another stage in Quest where we add IS NOT
* NULL for every variable in the head of a mapping.
*/
if (type == COL_TYPE.BNODE)
sql.append("ISBNODE = TRUE AND ");
else {
assert (type == COL_TYPE.OBJECT);
sql.append("ISBNODE = FALSE AND ");
}
return sql.toString();
}
public String constructSqlSource(COL_TYPE type1, COL_TYPE type2) {
StringBuilder sql = new StringBuilder();
switch (type2) {
case OBJECT:
case BNODE:
sql.append(RDBMSSIRepositoryManager.roleTable.selectCommand);
break;
case LITERAL:
case LITERAL_LANG:
sql.append(RDBMSSIRepositoryManager.attributeTable.get(COL_TYPE.LITERAL).selectCommand);
break;
default:
sql.append(RDBMSSIRepositoryManager.attributeTable.get(type2).selectCommand);
}
/*
* If the mapping is for something of type Literal we need to add IS
* NULL or IS NOT NULL to the language column. IS NOT NULL might be
* redundant since we have another stage in Quest where we add IS NOT
* NULL for every variable in the head of a mapping.
*/
if (type1 == COL_TYPE.BNODE)
sql.append("ISBNODE = TRUE AND ");
else {
assert (type1 == COL_TYPE.OBJECT);
sql.append("ISBNODE = FALSE AND ");
}
if (type2 == COL_TYPE.BNODE)
sql.append("ISBNODE2 = TRUE AND ");
else if (type2 == COL_TYPE.OBJECT)
sql.append("ISBNODE2 = FALSE AND ");
else if (type2 == COL_TYPE.LITERAL)
sql.append("LANG IS NULL AND ");
else if (type2 == COL_TYPE.LITERAL_LANG)
sql.append("LANG IS NOT NULL AND ");
return sql.toString();
}
// the order provides datatype codes that are stored in DB (starts with 0)
private static enum SITable {
CLASS,
OPROP,
DPROPLite,
DPROPStri,
DPROPInte,
DPROPLong,
DPROPDeci,
DPROPDoub,
DPROPDate,
DPROPInt,
DPROPUnsignedInt,
DPROPNegInte,
DPROPNonNegInte,
DPROPPosInte,
DPROPNonPosInte,
DPROPFloat,
DPROPBool,
DPROPDateStamp,
DPROPLiteLang
}
private static final int OBJ_TYPE_URI = 0;
private static final int OBJ_TYPE_BNode = 1;
private static int COLTYPEtoInt(COL_TYPE t) {
return (t == COL_TYPE.BNODE) ? OBJ_TYPE_BNode : OBJ_TYPE_URI;
}
private static Map<COL_TYPE, SITable> COLTYPEtoSITable = new HashMap<>();
static {
COLTYPEtoSITable.put(COL_TYPE.OBJECT, SITable.OPROP);
COLTYPEtoSITable.put(COL_TYPE.BNODE, SITable.OPROP);
COLTYPEtoSITable.put(COL_TYPE.LITERAL, SITable.DPROPLite);
COLTYPEtoSITable.put(COL_TYPE.LITERAL_LANG, SITable.DPROPLiteLang);
COLTYPEtoSITable.put(COL_TYPE.STRING, SITable.DPROPStri);
COLTYPEtoSITable.put(COL_TYPE.INTEGER, SITable.DPROPInte);
COLTYPEtoSITable.put(COL_TYPE.INT, SITable.DPROPInt);
COLTYPEtoSITable.put(COL_TYPE.UNSIGNED_INT, SITable.DPROPUnsignedInt);
COLTYPEtoSITable.put(COL_TYPE.NEGATIVE_INTEGER, SITable.DPROPNegInte);
COLTYPEtoSITable.put(COL_TYPE.NON_NEGATIVE_INTEGER, SITable.DPROPNonNegInte);
COLTYPEtoSITable.put(COL_TYPE.POSITIVE_INTEGER, SITable.DPROPPosInte);
COLTYPEtoSITable.put(COL_TYPE.NON_POSITIVE_INTEGER, SITable.DPROPNonPosInte);
COLTYPEtoSITable.put(COL_TYPE.FLOAT, SITable.DPROPFloat);
COLTYPEtoSITable.put(COL_TYPE.LONG, SITable.DPROPLong);
COLTYPEtoSITable.put(COL_TYPE.DECIMAL, SITable.DPROPDeci);
COLTYPEtoSITable.put(COL_TYPE.DOUBLE, SITable.DPROPDoub);
COLTYPEtoSITable.put(COL_TYPE.DATETIME, SITable.DPROPDate);
COLTYPEtoSITable.put(COL_TYPE.BOOLEAN, SITable.DPROPBool);
COLTYPEtoSITable.put(COL_TYPE.DATETIME_STAMP, SITable.DPROPDateStamp);
}
/**
* checks that type is one of the two valid values
*
* @param type
* @throws RuntimeException if type is not valid
*/
private static void checkTypeValue(int type) {
if (type != OBJ_TYPE_URI && type != OBJ_TYPE_BNode)
throw new RuntimeException("Unknown OBJ_TYPE:" + type);
}
/**
* checks that table is one of the valid values
*
* @param table
* @throws RuntimeException if table is not valid
*/
private static void checkSITableValue(int table) {
SITable sitable = null;
for (SITable t : SITable.values())
if (t.ordinal() == table)
sitable = t;
if (sitable == null)
throw new RuntimeException("Unknown SITable: " + table);
}
/**
* Stores the emptiness index in the database
* @throws SQLException
*/
public void store(Connection conn) throws SQLException {
try (PreparedStatement stm = conn.prepareStatement(RDBMSSIRepositoryManager.emptinessIndexTable.insertCommand)) {
for (Entry<SemanticIndexViewID, Set<Integer>> record : nonEmptyEntityRecord.entrySet()) {
if (record.getValue() != null) {
SemanticIndexViewID viewId = record.getKey();
for (Integer idx : record.getValue()) {
stm.setInt(1, viewId.getTable());
stm.setInt(2, idx);
stm.setInt(3, viewId.getType1());
stm.setInt(4, viewId.getType2());
stm.addBatch();
}
}
}
stm.executeBatch();
}
}
/**
* Restoring the emptiness index from the database
* @throws SQLException
*/
public void load(Connection conn) throws SQLException {
try (Statement st = conn.createStatement()) {
ResultSet res = st.executeQuery("SELECT * FROM " + RDBMSSIRepositoryManager.emptinessIndexTable.tableName);
while (res.next()) {
int sitable = res.getInt(1);
int type1 = res.getInt(3);
int type2 = res.getInt(4);
int idx = res.getInt(2);
checkTypeValue(type1);
checkTypeValue(type2);
checkSITableValue(sitable);
SemanticIndexViewID viewId = new SemanticIndexViewID(sitable, type1, type2);
addIndexToView(viewId, idx);
}
}
}
}
|
package net.sf.taverna.t2.workbench.views.results.workflow;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import net.sf.taverna.t2.facade.ResultListener;
import net.sf.taverna.t2.facade.WorkflowInstanceFacade;
import net.sf.taverna.t2.invocation.InvocationContext;
import net.sf.taverna.t2.invocation.WorkflowDataToken;
import net.sf.taverna.t2.invocation.impl.InvocationContextImpl;
import net.sf.taverna.t2.lang.ui.DialogTextArea;
import net.sf.taverna.t2.provenance.api.ProvenanceAccess;
import net.sf.taverna.t2.provenance.lineageservice.utils.DataflowInvocation;
import net.sf.taverna.t2.provenance.lineageservice.utils.Port;
import net.sf.taverna.t2.reference.ReferenceService;
import net.sf.taverna.t2.reference.T2Reference;
import net.sf.taverna.t2.workbench.MainWindow;
import net.sf.taverna.t2.workbench.helper.HelpEnabledDialog;
import net.sf.taverna.t2.workbench.icons.WorkbenchIcons;
import net.sf.taverna.t2.workbench.reference.config.DataManagementConfiguration;
import net.sf.taverna.t2.workbench.ui.impl.Workbench;
import net.sf.taverna.t2.workbench.ui.zaria.UIComponentSPI;
// import net.sf.taverna.t2.workbench.views.results.saveactions.SaveAllResultsAsOPM;
import net.sf.taverna.t2.workbench.views.results.saveactions.SaveAllResultsAsOPM;
import net.sf.taverna.t2.workbench.views.results.saveactions.SaveAllResultsSPI;
import net.sf.taverna.t2.workbench.views.results.saveactions.SaveAllResultsSPIRegistry;
import net.sf.taverna.t2.workflowmodel.Dataflow;
import net.sf.taverna.t2.workflowmodel.DataflowInputPort;
import net.sf.taverna.t2.workflowmodel.DataflowOutputPort;
import net.sf.taverna.t2.workflowmodel.EditException;
//import org.apache.log4j.Logger;
/**
* This component contains a tabbed pane, where each tab displays results for one of
* the output ports of a workflow, and a set of 'save results' buttons that save results
* from all ports in a certain format.
*
* @author David Withers
* @author Alex Nenadic
*
*/
public class WorkflowResultsComponent extends JPanel implements UIComponentSPI, ResultListener {
// private static Logger logger = Logger
// .getLogger(WorkflowResultsComponent.class);
private static final long serialVersionUID = 988812623494396366L;
// Invocation context
private InvocationContext context = null;
// The map contains a mapping for each port to a T2Reference pointing to the port's result(s)
private HashMap<String, T2Reference> resultReferencesMap = new HashMap<String, T2Reference>();
// Per-port boolean values indicating if all results have been received per port
private HashMap<String, Boolean> receivedAllResultsForPort = new HashMap<String, Boolean>();
// Tabbed pane - each tab contains a results tree and a RenderedResultComponent,
// which in turn contains the currently selected result node rendered according
// to its mime type and a button for saving the selected individual result
private JTabbedPane tabbedPane;
// Panel containing the save buttons
private JPanel saveButtonsPanel;
private WorkflowInstanceFacade facade;
private Dataflow dataflow;
private JButton saveButton;
private String runId;
private ReferenceService referenceService;
// This is needed for "Save data as OPM" action so that we know if
// we should try to get the OPM graph or not (if provanance was not
// enabled there is no point in trying to save data as OPM as it will be missing)
private boolean isProvenanceEnabledForRun;
// Registry of all existing 'save results' actions, each one can save results
// in a different format
private static SaveAllResultsSPIRegistry saveAllResultsRegistry = SaveAllResultsSPIRegistry.getInstance();
private HashMap<String, PortResultsViewTab> inputPortTabMap = new HashMap<String, PortResultsViewTab>();
private HashMap<String, PortResultsViewTab> outputPortTabMap = new HashMap<String, PortResultsViewTab>();
private HashMap<String, Object> inputPortObjectMap = new HashMap<String, Object> ();
private HashMap<String, Object> outputPortObjectMap = new HashMap<String, Object> ();
public WorkflowResultsComponent() {
super(new BorderLayout());
setBorder(new EtchedBorder());
tabbedPane = new JTabbedPane();
saveButtonsPanel = new JPanel(new GridBagLayout());
add(saveButtonsPanel, BorderLayout.NORTH);
add(tabbedPane, BorderLayout.CENTER);
}
// Constructor used for showing results for an old run when data
// is obtained from provenance
public WorkflowResultsComponent(Dataflow dataflow, String runId,
ReferenceService referenceService) {
this();
this.dataflow = dataflow;
this.runId = runId;
this.referenceService = referenceService;
this.isProvenanceEnabledForRun = true; // for a previous run provenance is always turned on
populateResultsFromProvenance();
}
public ImageIcon getIcon() {
return null;
}
public String getName() {
return "Results View Component";
}
public void onDisplay() {
}
public void onDispose() {
}
public void register(WorkflowInstanceFacade facade, boolean isProvenanceEnabledForRun)
throws EditException {
clear();
this.facade = facade;
this.dataflow = facade.getDataflow();
this.runId = facade.getWorkflowRunId();
this.isProvenanceEnabledForRun = isProvenanceEnabledForRun;
saveButton = new JButton(new SaveAllAction("Save all values", this));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0,10,0,0);
saveButtonsPanel.add(new JLabel("Workflow results"), gbc);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.0;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
saveButtonsPanel.add(saveButton, gbc);
// Input ports
List<DataflowInputPort> dataflowInputPorts = new ArrayList<DataflowInputPort>(facade
.getDataflow().getInputPorts());
Collections.sort(dataflowInputPorts, new Comparator<DataflowInputPort>() {
public int compare(DataflowInputPort o1, DataflowInputPort o2) {
return o1.getName().compareTo(o2.getName());
}});
for (DataflowInputPort dataflowInputPort : dataflowInputPorts) {
String portName = dataflowInputPort.getName();
// Create a tab containing a tree view of per-port results and a rendering
// component for displaying individual results
PortResultsViewTab resultTab = new PortResultsViewTab(dataflowInputPort.getName(), dataflowInputPort.getDepth());
inputPortTabMap.put(portName, resultTab);
tabbedPane.addTab(portName, WorkbenchIcons.inputIcon, resultTab, "Input port " + portName);
}
// Output ports
List<DataflowOutputPort> dataflowOutputPorts = new ArrayList<DataflowOutputPort>(facade
.getDataflow().getOutputPorts());
Collections.sort(dataflowOutputPorts, new Comparator<DataflowOutputPort>() {
public int compare(DataflowOutputPort o1, DataflowOutputPort o2) {
return o1.getName().compareTo(o2.getName());
}});
for (DataflowOutputPort dataflowOutputPort : dataflowOutputPorts) {
String portName = dataflowOutputPort.getName();
// Initially we have no results for a port
receivedAllResultsForPort.put(portName, new Boolean(Boolean.FALSE));
// Create a tab containing a tree view of per-port results and a rendering
// component for displaying individual results
PortResultsViewTab resultTab = new PortResultsViewTab(dataflowOutputPort.getName(),
dataflowOutputPort.getDepth());
outputPortTabMap.put(portName, resultTab);
// Per-port tree model listens for results coming out of the data facade
facade.addResultListener(resultTab.getResultModel());
// This component also listens to the results coming out in order to know
// when receiving of results has finished
facade.addResultListener(this);
tabbedPane.addTab(portName, WorkbenchIcons.outputIcon, resultTab, "Output port " + portName);
}
// Select the first output port tab
if (!dataflowOutputPorts.isEmpty()){
PortResultsViewTab tab = outputPortTabMap.get(dataflowOutputPorts.get(0).getName());
tabbedPane.setSelectedComponent(tab);
}
revalidate();
}
public void populateResultsFromProvenance() {
String connectorType = DataManagementConfiguration.getInstance().getConnectorType();
ProvenanceAccess provenanceAccess = new ProvenanceAccess(connectorType);
InvocationContext dummyContext = new InvocationContextImpl(referenceService, null);
context = dummyContext;
saveButton = new JButton(new SaveAllAction("Save all values", this));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0,10,0,0);
saveButtonsPanel.add(new JLabel("Workflow results"), gbc);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.0;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
saveButtonsPanel.add(saveButton, gbc);
// Get data for inputs and outputs ports
DataflowInvocation dataflowInvocation = provenanceAccess.getDataflowInvocation(runId);
String inputsDataBindingId = dataflowInvocation.getInputsDataBindingId();
String outputsDataBindingId = dataflowInvocation.getOutputsDataBindingId();
Map<Port, T2Reference> dataBindings = new HashMap<Port, T2Reference>();
if (inputsDataBindingId != null){
dataBindings.putAll(provenanceAccess
.getDataBindings(inputsDataBindingId));
}
if (outputsDataBindingId != null && !outputsDataBindingId.equals(inputsDataBindingId)){
dataBindings.putAll(provenanceAccess
.getDataBindings(outputsDataBindingId));
}
// Input ports
List<DataflowInputPort> dataflowInputPorts = new ArrayList<DataflowInputPort>(dataflow.getInputPorts());
Collections.sort(dataflowInputPorts, new Comparator<DataflowInputPort>() {
public int compare(DataflowInputPort o1, DataflowInputPort o2) {
return o1.getName().compareTo(o2.getName());
}});
for (DataflowInputPort dataflowInputPort : dataflowInputPorts) {
String portName = dataflowInputPort.getName();
// Create a tab containing a tree view of per-port results and a rendering
// component for displaying individual results
PortResultsViewTab resultTab = new PortResultsViewTab(dataflowInputPort.getName(), dataflowInputPort.getDepth());
inputPortTabMap.put(portName, resultTab);
tabbedPane.addTab(portName, WorkbenchIcons.inputIcon, resultTab, "Input port " + portName);
}
// Output ports
List<DataflowOutputPort> dataflowOutputPorts = new ArrayList<DataflowOutputPort>(dataflow.getOutputPorts());
Collections.sort(dataflowOutputPorts, new Comparator<DataflowOutputPort>() {
public int compare(DataflowOutputPort o1, DataflowOutputPort o2) {
return o1.getName().compareTo(o2.getName());
}});
for (DataflowOutputPort dataflowOutputPort : dataflowOutputPorts) {
String portName = dataflowOutputPort.getName();
// Create a tab containing a tree view of per-port results and a rendering
// component for displaying individual results
PortResultsViewTab resultTab = new PortResultsViewTab(dataflowOutputPort.getName(), dataflowOutputPort.getDepth());
outputPortTabMap.put(portName, resultTab);
tabbedPane.addTab(portName, WorkbenchIcons.outputIcon, resultTab, "Output port " + portName);
}
// Select the first output port tab
if (!dataflowOutputPorts.isEmpty()){
PortResultsViewTab tab = outputPortTabMap.get(dataflowOutputPorts.get(0).getName());
tabbedPane.setSelectedComponent(tab);
}
for (java.util.Map.Entry<Port, T2Reference> entry : dataBindings
.entrySet()) {
if (entry.getKey().isInputPort()) { // input port
PortResultsViewTab resultTab = inputPortTabMap.get(entry.getKey().getPortName());
WorkflowResultTreeModel treeModel = resultTab.getResultModel();
treeModel.createTree(entry.getValue(), dummyContext, ((WorkflowResultTreeNode) treeModel.getRoot()));
// Need to refresh the tree model we have just changed by adding result nodes
treeModel.reload();
resultTab.expandTree(); // tree will be collapsed after reloading
}
else{ // output port
PortResultsViewTab resultTab = outputPortTabMap.get(entry.getKey().getPortName());
WorkflowResultTreeModel treeModel = resultTab.getResultModel();
treeModel.createTree(entry.getValue(), dummyContext, ((WorkflowResultTreeNode) treeModel.getRoot()));
// Need to refresh the tree model we have just changed by adding result nodes
treeModel.reload();
resultTab.expandTree(); // tree will be collapsed after reloading
}
}
}
public void clear() {
saveButtonsPanel.removeAll();
tabbedPane.removeAll();
}
public void resultTokenProduced(WorkflowDataToken token, String portName) {
// Set the invocation context the first time you get the chance
if (context == null)
context = token.getContext();
// If we have finished receiving results - token.getIndex().length is 0
if (token.getIndex().length == 0){
receivedAllResultsForPort.put(portName, new Boolean(Boolean.TRUE));
// We know that at this point the token.getData() contains a T2Reference to
// all result(s)
T2Reference resultsRef = token.getData();
// Put the resultsRef in the resultReferencesMap
resultReferencesMap.put(portName, resultsRef);
}
// If this is the last token for all ports - update the save buttons' state
boolean receivedAll = true;
for (String pName : receivedAllResultsForPort.keySet()){
if (!receivedAllResultsForPort.get(pName).booleanValue()){
receivedAll = false;
break;
}
}
if (receivedAll){
HashMap<String, T2Reference> inputValuesMap = new HashMap<String, T2Reference> ();
for (DataflowInputPort dataflowInputPort : dataflow.getInputPorts()) {
String name = dataflowInputPort.getName();
inputValuesMap.put(name, facade.getPushedDataMap().get(name));
}
saveButton.setEnabled(true);
saveButton.setFocusable(false);
}
}
@SuppressWarnings("serial")
private class SaveAllAction extends AbstractAction {
//private WorkflowResultsComponent parent;
public SaveAllAction(String name, WorkflowResultsComponent resultViewComponent) {
super(name);
//this.parent = resultViewComponent;
putValue(SMALL_ICON, WorkbenchIcons.saveAllIcon);
}
public void actionPerformed(ActionEvent e) {
String title = "Workflow run data saver";
final JDialog dialog = new HelpEnabledDialog(MainWindow.getMainWindow(), title, true);
dialog.setResizable(false);
dialog.setLocationRelativeTo(MainWindow.getMainWindow());
JPanel panel = new JPanel(new BorderLayout());
DialogTextArea explanation = new DialogTextArea();
explanation.setText("Select the workflow input and output ports to save the associated data");
explanation.setColumns(40);
explanation.setEditable(false);
explanation.setOpaque(false);
explanation.setBorder(new EmptyBorder(5, 20, 5, 20));
explanation.setFocusable(false);
explanation.setFont(new JLabel().getFont()); // make the font the same as for other components in the dialog
panel.add(explanation, BorderLayout.NORTH);
final Map<String, JCheckBox> inputChecks = new HashMap<String, JCheckBox> ();
final Map<String, JCheckBox> outputChecks = new HashMap<String, JCheckBox> ();
final Map<JCheckBox, Object> checkReferences =
new HashMap<JCheckBox, Object>();
final Map<String, Object> chosenReferences =
new HashMap<String, Object> ();
final Set<SaveAllResultsSPI> actionSet = new HashSet<SaveAllResultsSPI>();
ItemListener listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
JCheckBox source = (JCheckBox) e.getItemSelectable();
if (inputChecks.containsValue(source)) {
if (source.isSelected()) {
if (outputChecks.containsKey(source.getText())) {
outputChecks.get(source.getText()).setSelected(false);
}
}
}
if (outputChecks.containsValue(source)) {
if (source.isSelected()) {
if (inputChecks.containsKey(source.getText())) {
inputChecks.get(source.getText()).setSelected(false);
}
}
}
chosenReferences.clear();
for (JCheckBox checkBox : checkReferences.keySet()) {
if (checkBox.isSelected()) {
chosenReferences.put(checkBox.getText(),
checkReferences.get(checkBox));
}
}
}
};
JPanel portsPanel = new JPanel();
portsPanel.setBorder(new CompoundBorder(new EmptyBorder(new Insets(5,10,5,10)), new EtchedBorder(EtchedBorder.LOWERED)));
portsPanel.setLayout(new GridBagLayout());
if (!dataflow.getInputPorts().isEmpty()) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
gbc.insets = new Insets(5,10,5,10);
portsPanel.add(new JLabel("Workflow inputs:"), gbc);
//JPanel inputsPanel = new JPanel();
//WeakHashMap<String, T2Reference> pushedDataMap = null;
TreeMap<String, JCheckBox> sortedBoxes = new TreeMap<String, JCheckBox>();
for (DataflowInputPort port : dataflow.getInputPorts()) {
String portName = port.getName();
Object o = inputPortObjectMap.get(portName);
if (o == null) {
WorkflowResultTreeNode root = (WorkflowResultTreeNode) inputPortTabMap.get(portName).getResultModel().getRoot();
o = root.getAsObject();
inputPortObjectMap.put(portName, o);
}
JCheckBox checkBox = new JCheckBox(portName);
checkBox
.setSelected(!resultReferencesMap.containsKey(portName));
checkBox.addItemListener(listener);
inputChecks.put(portName, checkBox);
sortedBoxes.put(portName, checkBox);
checkReferences.put(checkBox, o);
}
gbc.insets = new Insets(0,10,0,10);
for (String portName : sortedBoxes.keySet()) {
gbc.gridy++;
portsPanel.add(sortedBoxes.get(portName), gbc);
gbc.gridy++;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(5,10,5,10);
portsPanel.add(new JLabel(""), gbc); // empty space
}
}
if (!dataflow.getOutputPorts().isEmpty()) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
gbc.insets = new Insets(5,10,5,10);
portsPanel.add(new JLabel("Workflow outputs:"), gbc);
TreeMap<String, JCheckBox> sortedBoxes = new TreeMap<String, JCheckBox>();
for (DataflowOutputPort port : dataflow.getOutputPorts()) {
String portName = port.getName();
Object o = outputPortObjectMap.get(portName);
if (o == null) {
WorkflowResultTreeNode root = (WorkflowResultTreeNode) outputPortTabMap.get(portName).getResultModel().getRoot();
o = root.getAsObject();
outputPortObjectMap.put(portName, o);
}
resultReferencesMap.put(portName, null);
JCheckBox checkBox = new JCheckBox(portName);
checkBox
.setSelected(true);
checkReferences.put(checkBox, o);
checkBox.addItemListener(listener);
outputChecks.put(portName, checkBox);
sortedBoxes.put(portName, checkBox);
}
gbc.insets = new Insets(0,10,0,10);
for (String portName : sortedBoxes.keySet()) {
gbc.gridy++;
portsPanel.add(sortedBoxes.get(portName), gbc);
}
gbc.gridy++;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(5,10,5,10);
portsPanel.add(new JLabel(""), gbc); // empty space
}
panel.add(portsPanel, BorderLayout.CENTER);
chosenReferences.clear();
for (JCheckBox checkBox : checkReferences.keySet()) {
if (checkBox.isSelected()) {
chosenReferences.put(checkBox.getText(),
checkReferences.get(checkBox));
}
}
JPanel buttonsBar = new JPanel();
buttonsBar.setLayout(new FlowLayout());
// Get all existing 'Save result' actions
List<SaveAllResultsSPI> saveActions = saveAllResultsRegistry.getSaveResultActions();
for (SaveAllResultsSPI spi : saveActions){
if (spi instanceof SaveAllResultsAsOPM){
((SaveAllResultsAsOPM)spi).setIsProvenanceEnabledForRun(isProvenanceEnabledForRun);
((SaveAllResultsAsOPM)spi).setRunId(runId);
((SaveAllResultsAsOPM)spi).setDataflow(dataflow);
}
SaveAllResultsSPI action = (SaveAllResultsSPI) spi.getAction();
actionSet.add(action);
JButton saveButton = new JButton((AbstractAction) action);
action.setChosenReferences(chosenReferences);
action.setParent(dialog);
//saveButton.setEnabled(true);
buttonsBar.add(saveButton);
}
JButton cancelButton = new JButton("Cancel", WorkbenchIcons.closeIcon);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
});
buttonsBar.add(cancelButton);
panel.add(buttonsBar, BorderLayout.SOUTH);
panel.revalidate();
dialog.add(panel);
dialog.pack();
dialog.setVisible(true);
}
}
public void pushInputData(WorkflowDataToken token, String portName) {
WorkflowResultTreeModel model = inputPortTabMap.get(portName).getResultModel();
if (model != null) {
model.resultTokenProduced(token, portName);
}
}
// private class ReloadWorkflowAction extends AbstractAction {
// private Dataflow dataflow;
// private Date date;
// PerspectiveSPI designPerspective = null;
// public ReloadWorkflowAction(String name, Dataflow dataflow, Date date) {
// super(name);
// this.dataflow = dataflow;
// this.date = date;
// public void actionPerformed(ActionEvent e) {
// XMLSerializer serialiser = new XMLSerializerImpl();
// XMLDeserializer deserialiser = new XMLDeserializerImpl();
// try {
// FileManager manager = FileManager.getInstance();
// String newName = dataflow.getLocalName() + "_"
// + DateFormat.getDateTimeInstance().format(date);
// newName = sanitiseName(newName);
// Dataflow alreadyOpened = null;
// for (Dataflow d : manager.getOpenDataflows()) {
// if (d.getLocalName().equals(newName)) {
// alreadyOpened = d;
// break;
// if (alreadyOpened != null) {
// manager.setCurrentDataflow(alreadyOpened);
// switchToDesignPerspective();
// } else {
// DataflowImpl dataflowCopy = (DataflowImpl) deserialiser.deserializeDataflow(serialiser
// .serializeDataflow(dataflow));
// dataflowCopy.setLocalName(newName);
// manager.openDataflow(dataflowCopy);
// } catch (SerializationException e1) {
// logger.error("Unable to copy workflow", e1);
// } catch (DeserializationException e1) {
// logger.error("Unable to copy workflow", e1);
// } catch (EditException e1) {
// logger.error("Unable to copy workflow", e1);
// private void switchToDesignPerspective() {
// if (designPerspective == null) {
// for (PerspectiveSPI perspective : Workbench.getInstance()
// .getPerspectives().getPerspectives()) {
// if (perspective.getText().equalsIgnoreCase("design")) {
// designPerspective = perspective;
// break;
// if (designPerspective != null) {
// ModelMap.getInstance().setModel(
// ModelMapConstants.CURRENT_PERSPECTIVE, designPerspective);
// /**
// * Checks that the name does not have any characters that are invalid for a
// * processor name.
// *
// * The name must contain only the chars[A-Za-z_0-9].
// *
// * @param name
// * the original name
// * @return the sanitised name
// */
// private static String sanitiseName(String name) {
// String result = name;
// if (Pattern.matches("\\w++", name) == false) {
// result = "";
// for (char c : name.toCharArray()) {
// result += c;
// } else {
// result += "_";
// return result;
}
|
package com.alibaba.rocketmq.client.producer.concurrent;
import com.alibaba.fastjson.JSON;
import com.alibaba.rocketmq.client.log.ClientLogger;
import com.alibaba.rocketmq.common.ThreadFactoryImpl;
import com.alibaba.rocketmq.common.message.Message;
import org.slf4j.Logger;
import java.io.*;
import java.util.Properties;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
public class DefaultLocalMessageStore implements LocalMessageStore {
private static final Logger LOGGER = ClientLogger.getLog();
private static final int MESSAGES_PER_FILE = 100000;
private final AtomicLong writeIndex = new AtomicLong(0L);
private final AtomicLong writeOffSet = new AtomicLong(0L);
private final AtomicLong readIndex = new AtomicLong(0L);
private final AtomicLong readOffSet = new AtomicLong(0L);
private static final String STORE_LOCATION = System.getProperty("defaultLocalMessageStoreLocation",
System.getProperty("user.home") + File.separator + ".localMessageStore");
private File localMessageStoreDirectory;
private ConcurrentHashMap<Long, File> messageStoreNameFileMapping = new ConcurrentHashMap<Long, File>();
private File configFile;
private RandomAccessFile randomAccessFile;
private ReentrantLock lock = new ReentrantLock();
private LinkedBlockingQueue<Message> messageQueue = new LinkedBlockingQueue<Message>(50000);
private ScheduledExecutorService flushConfigAtFixedRateExecutorService;
private ScheduledExecutorService flushConfigAtFixedDirtyMessageNumberExecutorService;
private volatile boolean ready = false;
private static final int MAXIMUM_NUMBER_OF_DIRTY_MESSAGE_IN_QUEUE = 1000;
public DefaultLocalMessageStore(String producerGroup) {
localMessageStoreDirectory = new File(STORE_LOCATION, producerGroup);
if (!localMessageStoreDirectory.exists()) {
if (!localMessageStoreDirectory.mkdirs()) {
throw new RuntimeException("Local message store directory does not exist and unable to create one");
}
}
loadConfig();
flushConfigAtFixedRateExecutorService = Executors
.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("LocalMessageStoreFlushServiceFixedRate"));
flushConfigAtFixedRateExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
flush();
}
}, 0, 1000, TimeUnit.MILLISECONDS);
flushConfigAtFixedDirtyMessageNumberExecutorService = Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryImpl("LocalMessageStoreFlushServiceFixedDirtyMessageNumber"));
flushConfigAtFixedDirtyMessageNumberExecutorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
if (messageQueue.size() > MAXIMUM_NUMBER_OF_DIRTY_MESSAGE_IN_QUEUE) {
flush();
}
}
}, 50, 100, TimeUnit.MILLISECONDS);
ready = true;
}
/**
* This method will execute on startup.
*/
private void loadConfig() {
configFile = new File(localMessageStoreDirectory, ".config");
if (configFile.exists() && configFile.canRead()) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(configFile);
Properties properties = new Properties();
properties.load(inputStream);
writeIndex.set(null == properties.getProperty("writeIndex") ? 0L :
Long.parseLong(properties.getProperty("writeIndex")));
writeOffSet.set(null == properties.getProperty("writeOffSet") ? 0L :
Long.parseLong(properties.getProperty("writeOffSet")));
readIndex.set(null == properties.getProperty("readIndex") ? 0L :
Long.parseLong(properties.getProperty("readIndex")));
readOffSet.set(null == properties.getProperty("readOffSet") ? 0L :
Long.parseLong(properties.getProperty("readOffSet")));
String[] dataFiles = localMessageStoreDirectory.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return (!".config".equals(name)) && name.matches("\\d+");
}
});
for (String dataFile : dataFiles) {
messageStoreNameFileMapping.putIfAbsent(Long.parseLong(dataFile),
new File(localMessageStoreDirectory, dataFile));
}
File lastWrittenFileName = messageStoreNameFileMapping
.get(writeIndex.longValue() / MESSAGES_PER_FILE * MESSAGES_PER_FILE + 1);
if (null == lastWrittenFileName && writeIndex.longValue() % MESSAGES_PER_FILE != 0) {
throw new RuntimeException("Data corrupted");
}
if (null != lastWrittenFileName) {
randomAccessFile = new RandomAccessFile(lastWrittenFileName, "rw");
if (writeOffSet.longValue() > 0) {
randomAccessFile.seek(writeOffSet.longValue());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
//ignore.
}
}
}
}
}
/**
* This method is synchronized as there may be multiple threads executing this thread.
*/
private synchronized void updateConfig() {
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter(configFile, false));
bufferedWriter.write("writeIndex=" + writeIndex.longValue());
bufferedWriter.newLine();
bufferedWriter.write("writeOffSet=" + writeOffSet.longValue());
bufferedWriter.newLine();
bufferedWriter.write("readIndex=" + readIndex.longValue());
bufferedWriter.newLine();
bufferedWriter.write("readOffSet=" + readOffSet.longValue());
bufferedWriter.newLine();
bufferedWriter.flush();
} catch (IOException e) {
LOGGER.error("Unable to update config file", e.getMessage());
e.printStackTrace();
} finally {
if (null != bufferedWriter) {
try {
bufferedWriter.close();
} catch (IOException e) {
//ignore.
}
}
}
}
/**
* This method is assumed to execute concurrently.
*
* @param message Message to stash.
*/
@Override
public void stash(Message message) {
if (!ready) {
throw new RuntimeException("Message store is not ready. You may have closed it already.");
}
try {
//Block if no space available.
messageQueue.put(message);
} catch (InterruptedException e) {
LOGGER.error("Unable to stash message locally.", e);
}
}
private void flush() {
LOGGER.info("Local message store starts to flush.");
try {
if (!lock.tryLock()) {
lock.lockInterruptibly();
}
Message message = messageQueue.poll();
int numberOfMessageToCommit = 0;
while (null != message) {
writeIndex.incrementAndGet();
long currentWriteIndex = writeIndex.longValue();
if (1 == currentWriteIndex ||
(currentWriteIndex - 1) / MESSAGES_PER_FILE > (currentWriteIndex - 2) / MESSAGES_PER_FILE) {
//we need to create a new file.
File newMessageStoreFile = new File(localMessageStoreDirectory, String.valueOf(currentWriteIndex));
if (!newMessageStoreFile.createNewFile()) {
throw new RuntimeException("Unable to create new local message store file");
}
messageStoreNameFileMapping.putIfAbsent(currentWriteIndex, newMessageStoreFile);
//close previous file.
if (null != randomAccessFile) {
randomAccessFile.close();
}
File dataFile = messageStoreNameFileMapping.get(currentWriteIndex);
randomAccessFile = new RandomAccessFile(dataFile, "rw");
}
if (null == randomAccessFile) {
File currentWritingDataFile = messageStoreNameFileMapping
.get(writeIndex.longValue() / MESSAGES_PER_FILE * MESSAGES_PER_FILE + 1);
randomAccessFile = new RandomAccessFile(currentWritingDataFile, "rw");
}
byte[] msgData = JSON.toJSONString(message).getBytes();
randomAccessFile.writeLong(msgData.length);
randomAccessFile.write(msgData);
writeOffSet.set(randomAccessFile.getFilePointer());
if (writeIndex.longValue() % MESSAGES_PER_FILE == 0) {
writeOffSet.set(0L);
}
if(++numberOfMessageToCommit % MAXIMUM_NUMBER_OF_DIRTY_MESSAGE_IN_QUEUE == 0) {
updateConfig();
}
//Take message from tail.
message = messageQueue.poll();
}
updateConfig();
} catch (InterruptedException e) {
e.printStackTrace();
throw new RuntimeException("Lock exception", e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("IO Error", e);
} finally {
LOGGER.info("Local message store flushing completes.");
lock.unlock();
}
}
@Override
public Message[] pop(int n) {
if (n < 0) {
throw new IllegalArgumentException("n should be positive");
}
if (!ready) {
throw new RuntimeException("Message store is not ready. You may have closed it already.");
}
try {
if (!lock.tryLock()) {
lock.lockInterruptibly();
}
int messageToRead = Math.min(getNumberOfMessageStashed(), n);
Message[] messages = new Message[messageToRead];
if (messageToRead == 0) {
return messages;
}
int messageRead = 0;
//First to retrieve messages from message queue, beginning from head side, which is held in memory.
Message message = messageQueue.poll();
while (null != message) {
messages[messageRead++] = message;
if (messageRead == messageToRead) { //We've already got all messages we want to pop.
return messages;
}
message = messageQueue.poll();
}
//In case we need more messages, read from local files.
RandomAccessFile readRandomAccessFile = null;
File currentReadFile = null;
while (messageRead < messageToRead && readIndex.longValue() <= writeIndex.longValue()) {
if (null == readRandomAccessFile) {
currentReadFile = messageStoreNameFileMapping
.get(readIndex.longValue() / MESSAGES_PER_FILE * MESSAGES_PER_FILE + 1);
if (null == currentReadFile || !currentReadFile.exists()) {
throw new RuntimeException("Data file corrupted");
}
readRandomAccessFile = new RandomAccessFile(currentReadFile, "rw");
if (readOffSet.longValue() > 0) {
readRandomAccessFile.seek(readOffSet.longValue());
}
}
long messageSize = readRandomAccessFile.readLong();
byte[] data = new byte[(int) messageSize];
readRandomAccessFile.read(data);
messages[messageRead++] = JSON.parseObject(data, Message.class);
readIndex.incrementAndGet();
readOffSet.set(readRandomAccessFile.getFilePointer());
if (readIndex.longValue() % MESSAGES_PER_FILE == 0 && currentReadFile.exists()) {
readRandomAccessFile.close();
readRandomAccessFile = null;
readOffSet.set(0L);
messageStoreNameFileMapping.remove((readIndex.longValue() - 1) / MESSAGES_PER_FILE * MESSAGES_PER_FILE + 1);
if (!currentReadFile.delete()) {
LOGGER.warn("Unable to delete used data file: {}", currentReadFile.getAbsolutePath());
}
}
}
return messages;
} catch (InterruptedException e) {
LOGGER.error("Pop message error, caused by {}", e.getMessage());
e.printStackTrace();
} catch (FileNotFoundException e) {
LOGGER.error("Pop message error, caused by {}", e.getMessage());
e.printStackTrace();
} catch (IOException e) {
LOGGER.error("Pop message error, caused by {}", e.getMessage());
e.printStackTrace();
} finally {
lock.unlock();
}
return null;
}
public int getNumberOfMessageStashed() {
synchronized (DefaultLocalMessageStore.class) {
return writeIndex.intValue() - readIndex.intValue() + messageQueue.size();
}
}
public void close() throws InterruptedException {
if (ready) {
flush();
flushConfigAtFixedRateExecutorService.shutdown();
flushConfigAtFixedDirtyMessageNumberExecutorService.shutdown();
flushConfigAtFixedRateExecutorService.awaitTermination(30, TimeUnit.SECONDS);
flushConfigAtFixedDirtyMessageNumberExecutorService.awaitTermination(30, TimeUnit.SECONDS);
}
ready = false;
LOGGER.info("Default local message store shutdown complete");
}
}
|
package org.ow2.proactive.scheduler.examples;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.log4j.Logger;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.transfer.Transfer;
import com.amazonaws.services.s3.transfer.TransferProgress;
/**
* SelectionUtils provides static methods for scheduler examples.
*
* @author ActiveEon Team
* @since 17/05/2018
*/
public class SchedulerExamplesUtils {
private static final Logger logger = Logger.getLogger(SchedulerExamplesUtils.class);
private SchedulerExamplesUtils() {
}
/**
* waits for the transfer to complete, catching any exceptions that occur.
* @param xfer
*/
protected static void waitForCompletion(Transfer xfer) {
try {
xfer.waitForCompletion();
} catch (AmazonServiceException e) {
logger.error("Amazon service error: " + e.getMessage());
System.exit(1);
} catch (AmazonClientException e) {
logger.error("Amazon client error: " + e.getMessage());
System.exit(1);
} catch (InterruptedException e) {
logger.error("Transfer interrupted: " + e.getMessage());
Thread.currentThread().interrupt();
System.exit(1);
}
}
/**
* Prints progress while waiting for the transfer to finish.
* @param xfer
*/
protected static void showTransferProgress(Transfer xfer) {
// print the transfer's human-readable description
logger.info(xfer.getDescription());
// print an empty progress bar...
printProgressBar(0.0);
// update the progress bar while the xfer is ongoing.
do {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
// Note: so_far and total aren't used, they're just for
// documentation purposes.
TransferProgress progress = xfer.getProgress();
double pct = progress.getPercentTransferred();
eraseProgressBar();
printProgressBar(pct);
} while (!xfer.isDone());
// print the final state of the transfer.
Transfer.TransferState xferState = xfer.getState();
logger.info(": " + xferState);
}
protected static void printProgressBar(double pct) {
// if bar_size changes, then change erase_bar (in eraseProgressBar) to
// match.
final int bar_size = 40;
final String empty_bar = " ";
final String filled_bar = "
int amtFull = (int) (bar_size * (pct / 100.0));
final String logMsg = String.format(" [%s%s]",
filled_bar.substring(0, amtFull),
empty_bar.substring(0, bar_size - amtFull));
logger.info(logMsg);
}
/**
* erases the progress bar.
*/
protected static void eraseProgressBar() {
// erase_bar is bar_size (from printProgressBar) + 4 chars.
final String erase_bar = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
logger.info(erase_bar);
}
/**
* List recursively the contents of a directory
* @param dir
* @param filesRelativePathName
* @return List of Files' names of the given directory
* @throws IOException
*/
protected static List<String> listDirectoryContents(File dir, List<String> filesRelativePathName)
throws IOException {
File[] files = dir.listFiles();
if (files == null) {
throw new IOException("Downloading process failed. Please check the remote path (the key name) in the given S3 Url");
}
for (File file : files) {
if (file.isDirectory()) {
listDirectoryContents(file, filesRelativePathName);
} else {
filesRelativePathName.add(file.getCanonicalPath());
}
}
return filesRelativePathName;
}
}
|
package solutions.digamma.damas.config;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Default configuration manager implementation.
*
* @author Ahmad Shahwan
*/
public class DefaultConfigurationManager implements ConfigurationManager {
/**
* Home directory system property.
*/
public static final String HOME_DIR = "home.dir";
/**
* Default home directory.
*/
private static final String DEFAULT_HOME_DIR = ".";
private static final String CONF_FILE_NAME = "conf.properties";
@Inject
private Logger logger;
private Properties properties;
/**
* No-args constructor.
*/
public DefaultConfigurationManager() {
}
/**
* Initialize manager.
*/
@PostConstruct
public void init() {
this.logger.info("Initializing configuration service.");
File homeDir = getHomeDir();
File confFile = new File(homeDir, CONF_FILE_NAME);
this.properties = new Properties();
if (confFile.isFile()) {
this.logger.info(() -> String.format(
"Configuration file found at %s.", confFile.getPath()));
try {
this.properties.load(new FileReader(confFile));
this.logger.info(() -> String.format(
"%d configs loaded from file", this.properties.size()));
} catch (IOException e) {
this.logger.log(Level.SEVERE, "Error reading conf file.", e);
}
} else {
this.logger.info(() -> String.format(
"No configuration file found at %s.", confFile.getPath()));
}
this.properties.putAll(System.getenv());
this.properties.putAll(System.getProperties());
this.properties.put(Configurations.HOME, homeDir.getAbsolutePath());
this.logger.info("System properties added to configurations.");
}
@Override
public String getString(String key) {
return this.properties.getProperty(key);
}
@Override
public Integer getInteger(String key) {
if (!this.properties.contains(key)) {
return null;
}
try {
return Integer.parseInt(this.properties.getProperty(key));
} catch (NumberFormatException e) {
return null;
}
}
@Override
public Map<String, Object> getConfigurations(String postfix) {
return this.properties
.entrySet()
.stream()
.filter(e -> e.getKey().toString().startsWith(postfix))
.collect(Collectors.toMap(
p -> p.getKey().toString(),
Map.Entry::getValue));
}
/**
* Obtain home directory.
*
* @return home directory file
*/
private File getHomeDir() {
String homePath = System.getProperty(HOME_DIR);
if (homePath != null) {
File homeDir = new File(homePath);
if (homeDir.isDirectory()) {
this.logger.info(() -> String.format(
"Home directory at %s.", homeDir.getPath()));
return homeDir;
}
}
this.logger.info("Home directory defaults to current directory.");
return new File(DEFAULT_HOME_DIR);
}
}
|
package org.objectweb.proactive.core.component.adl.implementations;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.objectweb.fractal.adl.ADLException;
import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.Type;
import org.objectweb.fractal.api.control.BindingController;
import org.objectweb.fractal.api.type.ComponentType;
import org.objectweb.fractal.util.Fractal;
import org.objectweb.proactive.core.component.Constants;
import org.objectweb.proactive.core.component.ContentDescription;
import org.objectweb.proactive.core.component.ControllerDescription;
import org.objectweb.proactive.core.component.adl.RegistryManager;
import org.objectweb.proactive.core.component.adl.nodes.VirtualNode;
import org.objectweb.proactive.core.component.adl.vnexportation.ExportedVirtualNodesList;
import org.objectweb.proactive.core.component.adl.vnexportation.LinkedVirtualNode;
import org.objectweb.proactive.core.component.factory.ProActiveGenericFactory;
import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor;
import org.objectweb.proactive.core.group.Group;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
//import org.objectweb.proactive.extra.gcmdeployment.GCMApplication.GCMApplication;
//import org.objectweb.proactive.extra.gcmdeployment.core.GCMVirtualNode;
/**
* @author The ProActive Team
*/
public class ProActiveImplementationBuilderImpl implements ProActiveImplementationBuilder, BindingController {
public final static String REGISTRY_BINDING = "registry";
public RegistryManager registry;
protected static Logger logger = ProActiveLogger.getLogger(Loggers.COMPONENTS_ADL);
// Implementation of the BindingController interface
public String[] listFc() {
return new String[] { REGISTRY_BINDING };
}
public Object lookupFc(final String itf) {
if (itf.equals(REGISTRY_BINDING)) {
return registry;
}
return null;
}
public void bindFc(final String itf, final Object value) {
if (itf.equals(REGISTRY_BINDING)) {
registry = (RegistryManager) value;
}
}
public void unbindFc(final String itf) {
if (itf.equals(REGISTRY_BINDING)) {
registry = null;
}
}
// Implementation of the Implementation Builder and ProActiveImplementationBuilder interfaces
public Object createComponent(Object arg0, String arg1, String arg2, Object arg3, Object arg4, Object arg5)
throws Exception {
return null;
}
public Object createComponent(Object type, String name, String definition,
ControllerDescription controllerDesc, ContentDescription contentDesc, VirtualNode adlVN,
Map context) throws Exception {
ObjectsContainer obj = commonCreation(type, name, definition, contentDesc, adlVN, context);
return createFComponent(type, obj.getDvn(), controllerDesc, contentDesc, adlVN, obj
.getBootstrapComponent());
}
protected ObjectsContainer commonCreation(Object type, String name, String definition,
ContentDescription contentDesc, VirtualNode adlVN, Map context) throws Exception {
Component bootstrap = null;
if (context != null) {
bootstrap = (Component) context.get("bootstrap");
}
if (bootstrap == null) {
bootstrap = Fractal.getBootstrapComponent();
}
ObjectsContainer result = null;
if (adlVN != null) {
// consider exported virtual nodes
LinkedVirtualNode exported = ExportedVirtualNodesList.instance().getNode(name, adlVN.getName(),
false);
if (exported != null) {
adlVN.setName(exported.getExportedVirtualNodeNameAfterComposition());
adlVN.setCardinality(exported.isMultiple() ? VirtualNode.MULTIPLE : VirtualNode.SINGLE);
} else {
// TODO add self exported virtual node ?
// for the moment, just add a leaf to the linked vns
ExportedVirtualNodesList.instance().addLeafVirtualNode(name, adlVN.getName(),
adlVN.getCardinality()); // TODO_M check this
}
Object deploymentDescriptor = context.get("deployment-descriptor");
if (deploymentDescriptor != null) {
/*
* if (deploymentDescriptor instanceof GCMApplication) { // // New deployment //
* GCMApplication gcmApplication = (GCMApplication) deploymentDescriptor;
*
* GCMVirtualNode virtualNode = gcmApplication.getVirtualNode(adlVN.getName());
*
* result = new ObjectsContainer(virtualNode, bootstrap); } else
*/
if (deploymentDescriptor instanceof ProActiveDescriptor) {
// Old deployment
org.objectweb.proactive.core.descriptor.data.VirtualNodeInternal deploymentVN = null;
ProActiveDescriptor proactiveDecriptor = (ProActiveDescriptor) deploymentDescriptor;
org.objectweb.proactive.core.descriptor.data.VirtualNode vn = ((ProActiveDescriptor) context
.get("deployment-descriptor")).getVirtualNode(adlVN.getName());
if (vn != null) {
deploymentVN = vn.getVirtualNodeInternal();
}
if (deploymentVN == null) {
if (adlVN.getName().equals("null")) {
logger
.info(name +
" will be instantiated in the current virtual machine (\"null\" was specified as the virtual node name)");
} else {
throw new ADLException("Could not find virtual node " + adlVN.getName() +
" in the deployment descriptor", null);
}
} else {
if (deploymentVN.isMultiple() && (adlVN.getCardinality().equals(VirtualNode.SINGLE))) {
// there will be only one instance of the component, on one node of the virtual node
contentDesc.forceSingleInstance();
} else if (!(deploymentVN.isMultiple()) &&
(adlVN.getCardinality().equals(VirtualNode.MULTIPLE))) {
throw new ADLException(
"Cannot deploy on a single virtual node when the cardinality of this virtual node named " +
adlVN.getName() + " in the ADL is set to multiple", null);
}
}
result = new ObjectsContainer(deploymentVN, bootstrap);
}
}
}
return new ObjectsContainer(null, bootstrap);
}
private Component createFComponent(Object type,
org.objectweb.proactive.core.descriptor.data.VirtualNode deploymentVN,
ControllerDescription controllerDesc, ContentDescription contentDesc, VirtualNode adlVN,
Component bootstrap) throws Exception {
Component result;
// FIXME : exhaustively specify the behaviour
if ((deploymentVN != null) && VirtualNode.MULTIPLE.equals(adlVN.getCardinality()) &&
controllerDesc.getHierarchicalType().equals(Constants.PRIMITIVE) && !contentDesc.uniqueInstance()) {
Group fcInstance = (Group) newFcInstanceAsList(bootstrap, (ComponentType) type, controllerDesc,
contentDesc, deploymentVN);
result = (Component) fcInstance.getGroupByType();
} else {
result = newFcInstance(bootstrap, (ComponentType) type, controllerDesc, contentDesc, deploymentVN);
}
// registry.addComponent(result); // the registry can handle groups
return result;
}
protected class ObjectsContainer {
// private GCMVirtualNode gcmDeploymentVN;
private org.objectweb.proactive.core.descriptor.data.VirtualNode deploymentVN;
private Component bootstrap;
public ObjectsContainer(org.objectweb.proactive.core.descriptor.data.VirtualNode dVn, Component bstrp) {
deploymentVN = dVn;
bootstrap = bstrp;
}
// public ObjectsContainer(GCMVirtualNode gcmVn, Component bstrp) {
// gcmDeploymentVN = gcmVn;
// bootstrap = bstrp;
public org.objectweb.proactive.core.descriptor.data.VirtualNode getDvn() {
return deploymentVN;
}
public Component getBootstrapComponent() {
return bootstrap;
}
}
private List<Component> newFcInstanceAsList(Component bootstrap, Type type,
ControllerDescription controllerDesc, ContentDescription contentDesc,
org.objectweb.proactive.core.descriptor.data.VirtualNode virtualNode) throws Exception {
ProActiveGenericFactory genericFactory = (ProActiveGenericFactory) Fractal
.getGenericFactory(bootstrap);
if (virtualNode == null) {
return genericFactory.newFcInstanceAsList(type, controllerDesc, contentDesc, (Node[]) null);
}
try {
virtualNode.activate();
return genericFactory.newFcInstanceAsList(type, controllerDesc, contentDesc, virtualNode
.getNodes());
} catch (NodeException e) {
throw new InstantiationException(
"could not instantiate components due to a deployment problem : " + e.getMessage());
}
}
public Component newFcInstance(Component bootstrap, Type type, ControllerDescription controllerDesc,
ContentDescription contentDesc,
org.objectweb.proactive.core.descriptor.data.VirtualNode virtualNode) throws Exception {
ProActiveGenericFactory genericFactory = (ProActiveGenericFactory) Fractal
.getGenericFactory(bootstrap);
if (virtualNode == null) {
return genericFactory.newFcInstance(type, controllerDesc, contentDesc, (Node) null);
}
try {
virtualNode.activate();
if (virtualNode.getNodes().length == 0) {
throw new InstantiationException(
"Cannot create component on virtual node as no node is associated with this virtual node");
}
return genericFactory.newFcInstance(type, controllerDesc, contentDesc, virtualNode.getNode());
} catch (NodeException e) {
throw new InstantiationException(
"could not instantiate components due to a deployment problem : " + e.getMessage());
}
}
}
|
package com.cwctravel.hudson.plugins.extended_choice_parameter;
import hudson.Extension;
import hudson.model.ParameterValue;
import hudson.model.ParameterDefinition;
import hudson.util.FormValidation;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Property;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
public class ExtendedChoiceParameterDefinition extends ParameterDefinition {
private static final long serialVersionUID = -2946187268529865645L;
public static final String PARAMETER_TYPE_SINGLE_SELECT = "PT_SINGLE_SELECT";
public static final String PARAMETER_TYPE_MULTI_SELECT = "PT_MULTI_SELECT";
public static final String PARAMETER_TYPE_CHECK_BOX = "PT_CHECKBOX";
public static final String PARAMETER_TYPE_RADIO = "PT_RADIO";
public static final String PARAMETER_TYPE_TEXT_BOX = "PT_TEXTBOX";
@Extension
public static class DescriptorImpl extends ParameterDescriptor {
@Override
public String getDisplayName() {
return Messages.ExtendedChoiceParameterDefinition_DisplayName();
}
public FormValidation doCheckPropertyFile(@QueryParameter final String propertyFile, @QueryParameter final String propertyKey) throws IOException, ServletException {
if(StringUtils.isBlank(propertyFile)) {
return FormValidation.ok();
}
Project project = new Project();
Property property = new Property();
property.setProject(project);
File prop = new File(propertyFile);
try {
if(prop.exists()) {
property.setFile(prop);
}
else {
URL propertyFileUrl = new URL(propertyFile);
property.setUrl(propertyFileUrl);
}
property.execute();
}
catch(Exception e) {
return FormValidation.warning(Messages.ExtendedChoiceParameterDefinition_PropertyFileDoesntExist(), propertyFile);
}
if(StringUtils.isNotBlank(propertyKey)) {
if(project.getProperty(propertyKey) != null) {
return FormValidation.ok();
}
else {
return FormValidation.warning(Messages.ExtendedChoiceParameterDefinition_PropertyFileExistsButProvidedKeyIsInvalid(), propertyFile, propertyKey);
}
}
else {
return FormValidation.warning(Messages.ExtendedChoiceParameterDefinition_PropertyFileExistsButNoProvidedKey(), propertyFile);
}
}
public FormValidation doCheckPropertyKey(@QueryParameter final String propertyFile, @QueryParameter final String propertyKey) throws IOException, ServletException {
return doCheckPropertyFile(propertyFile, propertyKey);
}
public FormValidation doCheckDefaultPropertyFile(@QueryParameter final String defaultPropertyFile,
@QueryParameter final String defaultPropertyKey) throws IOException, ServletException {
return doCheckPropertyFile(defaultPropertyFile, defaultPropertyKey);
}
public FormValidation doCheckDefaultPropertyKey(@QueryParameter final String defaultPropertyFile,
@QueryParameter final String defaultPropertyKey) throws IOException, ServletException {
return doCheckPropertyFile(defaultPropertyFile, defaultPropertyKey);
}
}
private boolean quoteValue;
private int visibleItemCount;
private String type;
private String value;
private String propertyFile;
private String propertyKey;
private String defaultValue;
private String defaultPropertyFile;
private String defaultPropertyKey;
private String multiSelectDelimiter = ",";
@DataBoundConstructor
public ExtendedChoiceParameterDefinition(String name, String type, String value, String propertyFile, String propertyKey, String defaultValue,
String defaultPropertyFile, String defaultPropertyKey, boolean quoteValue, int visibleItemCount, String description,
String multiSelectDelimiter) {
super(name, description);
this.type = type;
this.propertyFile = propertyFile;
this.propertyKey = propertyKey;
this.defaultPropertyFile = defaultPropertyFile;
this.defaultPropertyKey = defaultPropertyKey;
this.value = value;
this.defaultValue = defaultValue;
this.quoteValue = quoteValue;
if(visibleItemCount == 0) {
visibleItemCount = 5;
}
this.visibleItemCount = visibleItemCount;
if(multiSelectDelimiter.equals("")) {
multiSelectDelimiter = ",";
}
this.multiSelectDelimiter = multiSelectDelimiter;
}
private Map<String, Boolean> computeDefaultValueMap() {
Map<String, Boolean> defaultValueMap = null;
String effectiveDefaultValue = getEffectiveDefaultValue();
if(!StringUtils.isBlank(effectiveDefaultValue)) {
defaultValueMap = new HashMap<String, Boolean>();
String[] defaultValues = StringUtils.split(effectiveDefaultValue, ',');
for(String value: defaultValues) {
defaultValueMap.put(StringUtils.trim(value), true);
}
}
return defaultValueMap;
}
@Override
public ParameterValue createValue(StaplerRequest request) {
String[] requestValues = request.getParameterValues(getName());
if(requestValues == null || requestValues.length == 0) {
return getDefaultParameterValue();
}
if(PARAMETER_TYPE_TEXT_BOX.equals(type)) {
return new ExtendedChoiceParameterValue(getName(), requestValues[0]);
}
else {
String valueStr = getEffectiveValue();
if(valueStr != null) {
List<String> result = new ArrayList<String>();
String[] values = valueStr.split(",");
Set<String> valueSet = new HashSet<String>();
for(String value: values) {
valueSet.add(value);
}
for(String requestValue: requestValues) {
if(valueSet.contains(requestValue)) {
result.add(requestValue);
}
}
return new ExtendedChoiceParameterValue(getName(), StringUtils.join(result, getMultiSelectDelimiter()));
}
}
return null;
}
@Override
public ParameterValue createValue(StaplerRequest request, JSONObject jO) {
Object value = jO.get("value");
String strValue = "";
if(value instanceof String) {
strValue = (String)value;
}
else if(value instanceof JSONArray) {
JSONArray jsonValues = (JSONArray)value;
strValue = StringUtils.join(jsonValues.iterator(), getMultiSelectDelimiter());
}
if(quoteValue) {
strValue = "\"" + strValue + "\"";
}
return new ExtendedChoiceParameterValue(getName(), strValue);
}
@Override
public ParameterValue getDefaultParameterValue() {
String defaultValue = getEffectiveDefaultValue();
if(!StringUtils.isBlank(defaultValue)) {
if(quoteValue) {
defaultValue = "\"" + defaultValue + "\"";
}
return new ExtendedChoiceParameterValue(getName(), defaultValue);
}
return super.getDefaultParameterValue();
}
private String computeValue(String value, String propertyFilePath, String propertyKey) {
if(!StringUtils.isBlank(propertyFile) && !StringUtils.isBlank(propertyKey)) {
try {
Project project = new Project();
Property property = new Property();
property.setProject(project);
File propertyFile = new File(propertyFilePath);
if(propertyFile.exists()) {
property.setFile(propertyFile);
}
else {
URL propertyFileUrl = new URL(propertyFilePath);
property.setUrl(propertyFileUrl);
}
property.execute();
return project.getProperty(propertyKey);
}
catch(Exception e) {
}
}
else if(!StringUtils.isBlank(value)) {
return value;
}
return null;
}
@Override
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getEffectiveDefaultValue() {
return computeValue(defaultValue, defaultPropertyFile, defaultPropertyKey);
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public String getPropertyFile() {
return propertyFile;
}
public void setPropertyFile(String propertyFile) {
this.propertyFile = propertyFile;
}
public String getDefaultPropertyKey() {
return defaultPropertyKey;
}
public void setDefaultPropertyKey(String defaultPropertyKey) {
this.defaultPropertyKey = defaultPropertyKey;
}
public String getEffectiveValue() {
return computeValue(value, propertyFile, propertyKey);
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getPropertyKey() {
return propertyKey;
}
public void setPropertyKey(String propertyKey) {
this.propertyKey = propertyKey;
}
public String getDefaultPropertyFile() {
return defaultPropertyFile;
}
public boolean isQuoteValue() {
return quoteValue;
}
public void setQuoteValue(boolean quoteValue) {
this.quoteValue = quoteValue;
}
public int getVisibleItemCount() {
return visibleItemCount;
}
public void setVisibleItemCount(int visibleItemCount) {
this.visibleItemCount = visibleItemCount;
}
public String getMultiSelectDelimiter() {
return this.multiSelectDelimiter;
}
public void setMultiSelectDelimiter(final String multiSelectDelimiter) {
this.multiSelectDelimiter = multiSelectDelimiter;
}
public void setDefaultPropertyFile(String defaultPropertyFile) {
this.defaultPropertyFile = defaultPropertyFile;
}
public Map<String, Boolean> getDefaultValueMap() {
return computeDefaultValueMap();
}
}
|
package net.finmath.montecarlo.automaticdifferentiation.backward;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.DoubleBinaryOperator;
import java.util.function.DoubleUnaryOperator;
import java.util.function.IntToDoubleFunction;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import net.finmath.functions.DoubleTernaryOperator;
import net.finmath.montecarlo.RandomVariable;
import net.finmath.montecarlo.automaticdifferentiation.RandomVariableDifferentiableInterface;
import net.finmath.stochastic.ConditionalExpectationEstimatorInterface;
import net.finmath.stochastic.RandomVariableInterface;
public class RandomVariableDifferentiableAAD implements RandomVariableDifferentiableInterface {
private static final long serialVersionUID = 2459373647785530657L;
private static AtomicLong indexOfNextRandomVariable = new AtomicLong(0);
private static enum OperatorType {
ADD, MULT, DIV, SUB, SQUARED, SQRT, LOG, SIN, COS, EXP, INVERT, CAP, FLOOR, ABS,
ADDPRODUCT, ADDRATIO, SUBRATIO, BARRIER, DISCOUNT, ACCRUE, POW, MIN, MAX, AVERAGE, VARIANCE,
STDEV, STDERROR, SVARIANCE, AVERAGE2, VARIANCE2,
STDEV2, STDERROR2, CONDITIONAL_EXPECTATION
}
private static class OperatorTreeNode {
private final Long id;
private final OperatorType operatorType;
private final List<OperatorTreeNode> arguments;
private final List<RandomVariableInterface> argumentValues;
private final Object operator;
public OperatorTreeNode(OperatorType operatorType, List<RandomVariableInterface> arguments, Object operator) {
this(operatorType,
arguments != null ? arguments.stream().map((RandomVariableInterface x) -> {
return (x != null && x instanceof RandomVariableDifferentiableAAD) ? ((RandomVariableDifferentiableAAD)x).getOperatorTreeNode(): null;
}).collect(Collectors.toList()) : null,
arguments != null ? arguments.stream().map((RandomVariableInterface x) -> {
return (x != null && x instanceof RandomVariableDifferentiableAAD) ? ((RandomVariableDifferentiableAAD)x).getValues() : x;
}).collect(Collectors.toList()) : null,
operator
);
}
public OperatorTreeNode(OperatorType operatorType, List<OperatorTreeNode> arguments, List<RandomVariableInterface> argumentValues, Object operator) {
super();
this.id = indexOfNextRandomVariable.getAndIncrement();
this.operatorType = operatorType;
this.arguments = arguments;
// This is the simple modification which reduces memory requirements.
this.argumentValues = (operatorType != null && operatorType.equals(OperatorType.ADD)) ? null: argumentValues;
this.operator = operator;
if(operatorType != null && (operatorType.equals(OperatorType.ADD) || operatorType.equals(OperatorType.SUB))) {
// Addition does not need to retain arguments
argumentValues = null;
}
else if(operatorType != null && operatorType.equals(OperatorType.AVERAGE)) {
// Average does not need to retain arguments
argumentValues = null;
}
else if(operatorType != null && operatorType.equals(OperatorType.MULT)) {
// Product only needs to retain factors on differentiables
if(arguments.get(0) == null) argumentValues.set(1, null);
if(arguments.get(1) == null) argumentValues.set(0, null);
}
else if(operatorType != null && operatorType.equals(OperatorType.ADDPRODUCT)) {
// Addition does not need to retain arguments
argumentValues.set(0, null);
// Addition of product only needs to retain factors on differentiables
if(arguments.get(1) == null) argumentValues.set(2, null);
if(arguments.get(2) == null) argumentValues.set(1, null);
}
else if(operatorType != null && operatorType.equals(OperatorType.ACCRUE)) {
// Addition of product only needs to retain factors on differentiables
if(arguments.get(1) == null && arguments.get(2) == null) argumentValues.set(0, null);
if(arguments.get(0) == null && arguments.get(1) == null) argumentValues.set(1, null);
if(arguments.get(0) == null && arguments.get(2) == null) argumentValues.set(2, null);
}
else if(operatorType != null && operatorType.equals(OperatorType.BARRIER)) {
if(arguments.get(0) == null) {
argumentValues.set(1, null);
argumentValues.set(2, null);
}
}
}
private void propagateDerivativesFromResultToArgument(Map<Long, RandomVariableInterface> derivatives) {
for(OperatorTreeNode argument : arguments) {
if(argument != null) {
Long argumentID = argument.id;
if(!derivatives.containsKey(argumentID)) derivatives.put(argumentID, new RandomVariable(0.0));
RandomVariableInterface partialDerivative = getPartialDerivative(argument);
RandomVariableInterface derivative = derivatives.get(id);
RandomVariableInterface argumentDerivative = derivatives.get(argumentID);
if(operatorType == OperatorType.AVERAGE) {
derivative = derivative.average();
}
if(operatorType == OperatorType.CONDITIONAL_EXPECTATION) {
ConditionalExpectationEstimatorInterface estimator = (ConditionalExpectationEstimatorInterface)operator;
// derivative = estimator.getConditionalExpectation(derivative);
}
argumentDerivative = argumentDerivative.addProduct(partialDerivative, derivative);
derivatives.put(argumentID, argumentDerivative);
}
}
}
private RandomVariableInterface getPartialDerivative(OperatorTreeNode differential){
if(!arguments.contains(differential)) return new RandomVariable(0.0);
int differentialIndex = arguments.indexOf(differential);
RandomVariableInterface X = arguments.size() > 0 && argumentValues != null ? argumentValues.get(0) : null;
RandomVariableInterface Y = arguments.size() > 1 && argumentValues != null ? argumentValues.get(1) : null;
RandomVariableInterface Z = arguments.size() > 2 && argumentValues != null ? argumentValues.get(2) : null;
RandomVariableInterface resultrandomvariable = null;
switch(operatorType) {
/* functions with one argument */
case SQUARED:
resultrandomvariable = X.mult(2.0);
break;
case SQRT:
resultrandomvariable = X.sqrt().invert().mult(0.5);
break;
case EXP:
resultrandomvariable = X.exp();
break;
case LOG:
resultrandomvariable = X.invert();
break;
case SIN:
resultrandomvariable = X.cos();
break;
case COS:
resultrandomvariable = X.sin().mult(-1.0);
break;
case AVERAGE:
resultrandomvariable = new RandomVariable(1.0);
break;
case CONDITIONAL_EXPECTATION:
resultrandomvariable = new RandomVariable(1.0);
break;
case VARIANCE:
resultrandomvariable = X.sub(X.getAverage()*(2.0*X.size()-1.0)/X.size()).mult(2.0/X.size());
break;
case STDEV:
resultrandomvariable = X.sub(X.getAverage()*(2.0*X.size()-1.0)/X.size()).mult(2.0/X.size()).mult(0.5).div(Math.sqrt(X.getVariance()));
break;
case MIN:
double min = X.getMin();
resultrandomvariable = X.apply(x -> (x == min) ? 1.0 : 0.0);
break;
case MAX:
double max = X.getMax();
resultrandomvariable = X.apply(x -> (x == max) ? 1.0 : 0.0);
break;
case ABS:
resultrandomvariable = X.barrier(X, new RandomVariable(1.0), new RandomVariable(-1.0));
break;
case STDERROR:
resultrandomvariable = X.sub(X.getAverage()*(2.0*X.size()-1.0)/X.size()).mult(2.0/X.size()).mult(0.5).div(Math.sqrt(X.getVariance() * X.size()));
break;
case SVARIANCE:
resultrandomvariable = X.sub(X.getAverage()*(2.0*X.size()-1.0)/X.size()).mult(2.0/(X.size()-1));
break;
case ADD:
resultrandomvariable = new RandomVariable(1.0);
break;
case SUB:
resultrandomvariable = new RandomVariable(differentialIndex == 0 ? 1.0 : -1.0);
break;
case MULT:
resultrandomvariable = differentialIndex == 0 ? Y : X;
break;
case DIV:
resultrandomvariable = differentialIndex == 0 ? Y.invert() : X.div(Y.squared()).mult(-1);
break;
case CAP:
if(differentialIndex == 0) {
resultrandomvariable = X.barrier(X.sub(Y), new RandomVariable(0.0), new RandomVariable(1.0));
}
else {
resultrandomvariable = X.barrier(X.sub(Y), new RandomVariable(1.0), new RandomVariable(0.0));
}
break;
case FLOOR:
if(differentialIndex == 0) {
resultrandomvariable = X.barrier(X.sub(Y), new RandomVariable(1.0), new RandomVariable(0.0));
}
else {
resultrandomvariable = X.barrier(X.sub(Y), new RandomVariable(0.0), new RandomVariable(1.0));
}
break;
case AVERAGE2:
resultrandomvariable = differentialIndex == 0 ? Y : X;
break;
case VARIANCE2:
resultrandomvariable = differentialIndex == 0 ? Y.mult(2.0).mult(X.mult(Y.add(X.getAverage(Y)*(X.size()-1)).sub(X.getAverage(Y)))) :
X.mult(2.0).mult(Y.mult(X.add(Y.getAverage(X)*(X.size()-1)).sub(Y.getAverage(X))));
break;
case STDEV2:
resultrandomvariable = differentialIndex == 0 ? Y.mult(2.0).mult(X.mult(Y.add(X.getAverage(Y)*(X.size()-1)).sub(X.getAverage(Y)))).div(Math.sqrt(X.getVariance(Y))) :
X.mult(2.0).mult(Y.mult(X.add(Y.getAverage(X)*(X.size()-1)).sub(Y.getAverage(X)))).div(Math.sqrt(Y.getVariance(X)));
break;
case STDERROR2:
resultrandomvariable = differentialIndex == 0 ? Y.mult(2.0).mult(X.mult(Y.add(X.getAverage(Y)*(X.size()-1)).sub(X.getAverage(Y)))).div(Math.sqrt(X.getVariance(Y) * X.size())) :
X.mult(2.0).mult(Y.mult(X.add(Y.getAverage(X)*(X.size()-1)).sub(Y.getAverage(X)))).div(Math.sqrt(Y.getVariance(X) * Y.size()));
break;
case POW:
/* second argument will always be deterministic and constant! */
resultrandomvariable = (differentialIndex == 0) ? Y.mult(X.pow(Y.getAverage() - 1.0)) : new RandomVariable(0.0);
break;
case ADDPRODUCT:
if(differentialIndex == 0) {
resultrandomvariable = new RandomVariable(1.0);
} else if(differentialIndex == 1) {
resultrandomvariable = Z;
} else {
resultrandomvariable = Y;
}
break;
case ADDRATIO:
if(differentialIndex == 0) {
resultrandomvariable = new RandomVariable(1.0);
} else if(differentialIndex == 1) {
resultrandomvariable = Z.invert();
} else {
resultrandomvariable = Y.div(Z.squared()).mult(-1.0);
}
break;
case SUBRATIO:
if(differentialIndex == 0) {
resultrandomvariable = new RandomVariable(1.0);
} else if(differentialIndex == 1) {
resultrandomvariable = Z.invert().mult(-1.0);
} else {
resultrandomvariable = Y.div(Z.squared());
}
break;
case ACCRUE:
if(differentialIndex == 0) {
resultrandomvariable = Y.mult(Z).add(1.0);
} else if(differentialIndex == 1) {
resultrandomvariable = X.mult(Z);
} else {
resultrandomvariable = X.mult(Y);
}
break;
case DISCOUNT:
if(differentialIndex == 0) {
resultrandomvariable = Y.mult(Z).add(1.0).invert();
} else if(differentialIndex == 1) {
resultrandomvariable = X.mult(Z).div(Y.mult(Z).add(1.0).squared()).mult(-1.0);
} else {
resultrandomvariable = X.mult(Y).div(Y.mult(Z).add(1.0).squared()).mult(-1.0);
}
break;
case BARRIER:
if(differentialIndex == 0) {
/*
* Experimental version - This should be specified as a parameter.
*/
resultrandomvariable = Y.sub(Z);
double epsilon = 0.2*X.getStandardDeviation();
resultrandomvariable = resultrandomvariable.mult(X.barrier(X.add(epsilon/2), new RandomVariable(1.0), new RandomVariable(0.0)));
resultrandomvariable = resultrandomvariable.mult(X.barrier(X.sub(epsilon/2), new RandomVariable(0.0), new RandomVariable(1.0)));
resultrandomvariable = resultrandomvariable.div(epsilon);
} else if(differentialIndex == 1) {
resultrandomvariable = X.barrier(X, new RandomVariable(1.0), new RandomVariable(0.0));
} else {
resultrandomvariable = X.barrier(X, new RandomVariable(0.0), new RandomVariable(1.0));
}
default:
break;
}
return resultrandomvariable;
}
}
private final RandomVariableInterface values;
private final OperatorTreeNode operatorTreeNode;
public static RandomVariableDifferentiableAAD of(double value) {
return new RandomVariableDifferentiableAAD(value);
}
public static RandomVariableDifferentiableAAD of(RandomVariableInterface randomVariable) {
return new RandomVariableDifferentiableAAD(randomVariable);
}
public RandomVariableDifferentiableAAD(double value) {
this(new RandomVariable(value), null, null);
}
public RandomVariableDifferentiableAAD(double time, double[] realisations) {
this(new RandomVariable(time, realisations), null, null);
}
public RandomVariableDifferentiableAAD(RandomVariableInterface randomVariable) {
this(randomVariable, null, null);
}
private RandomVariableDifferentiableAAD(RandomVariableInterface values, List<RandomVariableInterface> arguments, OperatorType operator) {
super();
this.values = values;
this.operatorTreeNode = new OperatorTreeNode(operator, arguments, null);
}
public RandomVariableDifferentiableAAD(RandomVariableInterface values, List<RandomVariableInterface> arguments, ConditionalExpectationEstimatorInterface estimator,
OperatorType operator) {
super();
this.values = values;
this.operatorTreeNode = new OperatorTreeNode(operator, arguments, estimator);
}
public RandomVariableInterface getRandomVariable() {
return values;
}
public OperatorTreeNode getOperatorTreeNode() {
return operatorTreeNode;
}
public Long getID(){
return getOperatorTreeNode().id;
}
public Map<Long, RandomVariableInterface> getGradient() {
// The map maintaining the derivatives id -> derivative
Map<Long, RandomVariableInterface> derivatives = new HashMap<Long, RandomVariableInterface>();
// Put derivative of this node w.r.t. itself
derivatives.put(getID(), new RandomVariable(1.0));
// The set maintaining the independents. Note: TreeMap is maintaining a sort on the keys.
TreeMap<Long, OperatorTreeNode> independents = new TreeMap<Long, OperatorTreeNode>();
independents.put(getID(), getOperatorTreeNode());
while(independents.size() > 0) {
// Process node with the highest id in independents
Map.Entry<Long, OperatorTreeNode> independentEntry = independents.lastEntry();
Long id = independentEntry.getKey();
OperatorTreeNode independent = independentEntry.getValue();
// Get arguments of this node and propagate derivative to arguments
List<OperatorTreeNode> arguments = independent.arguments;
if(arguments != null && arguments.size() > 0) {
independent.propagateDerivativesFromResultToArgument(derivatives);
// Add all non constant arguments to the list of independents
for(OperatorTreeNode argument : arguments) {
if(argument != null) {
Long argumentId = argument.id;
independents.put(argumentId, argument);
}
}
// Remove id from derivatives - keep only leaf nodes.
derivatives.remove(id);
}
// Done with processing. Remove from map.
independents.remove(id);
}
return derivatives;
}
/* for all functions that need to be differentiated and are returned as double in the Interface, write a method to return it as RandomVariableAAD
* that is deterministic by its nature. For their double-returning pendant just return the average of the deterministic RandomVariableAAD */
public RandomVariableInterface getAverageAsRandomVariableAAD(RandomVariableInterface probabilities) {
/*returns deterministic AAD random variable */
return new RandomVariableDifferentiableAAD(
new RandomVariable(getAverage(probabilities)),
Arrays.asList(new RandomVariableInterface[]{ this, new RandomVariable(probabilities) }),
OperatorType.AVERAGE2);
}
public RandomVariableInterface getVarianceAsRandomVariableAAD(RandomVariableInterface probabilities){
/*returns deterministic AAD random variable */
return new RandomVariableDifferentiableAAD(
new RandomVariable(getVariance(probabilities)),
Arrays.asList(new RandomVariableInterface[]{ this, new RandomVariable(probabilities) }),
OperatorType.VARIANCE2);
}
public RandomVariableInterface getStandardDeviationAsRandomVariableAAD(RandomVariableInterface probabilities){
/*returns deterministic AAD random variable */
return new RandomVariableDifferentiableAAD(
new RandomVariable(getStandardDeviation(probabilities)),
Arrays.asList(new RandomVariableInterface[]{ this, new RandomVariable(probabilities) }),
OperatorType.STDEV2);
}
public RandomVariableInterface getStandardErrorAsRandomVariableAAD(RandomVariableInterface probabilities){
/*returns deterministic AAD random variable */
return new RandomVariableDifferentiableAAD(
new RandomVariable(getStandardError(probabilities)),
Arrays.asList(new RandomVariableInterface[]{ this, new RandomVariable(probabilities) }),
OperatorType.STDERROR2);
}
public RandomVariableInterface getAverageAsRandomVariableAAD(){
/*returns deterministic AAD random variable */
return new RandomVariableDifferentiableAAD(
new RandomVariable(getAverage()),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.AVERAGE);
}
public RandomVariableInterface getVarianceAsRandomVariableAAD(){
/*returns deterministic AAD random variable */
return new RandomVariableDifferentiableAAD(
new RandomVariable(getVariance()),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.VARIANCE);
}
public RandomVariableInterface getSampleVarianceAsRandomVariableAAD() {
/*returns deterministic AAD random variable */
return new RandomVariableDifferentiableAAD(
new RandomVariable(getSampleVariance()),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.SVARIANCE);
}
public RandomVariableInterface getStandardDeviationAsRandomVariableAAD(){
/*returns deterministic AAD random variable */
return new RandomVariableDifferentiableAAD(
new RandomVariable(getStandardDeviation()),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.STDEV);
}
public RandomVariableInterface getStandardErrorAsRandomVariableAAD(){
/*returns deterministic AAD random variable */
return new RandomVariableDifferentiableAAD(
new RandomVariable(getStandardError()),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.STDERROR);
}
public RandomVariableInterface getMinAsRandomVariableAAD(){
/*returns deterministic AAD random variable */
return new RandomVariableDifferentiableAAD(
new RandomVariable(getMin()),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.MIN);
}
public RandomVariableInterface getMaxAsRandomVariableAAD(){
/*returns deterministic AAD random variable */
return new RandomVariableDifferentiableAAD(
new RandomVariable(getMax()),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.MAX);
}
private RandomVariableInterface getValues(){
return values;
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#equals(net.finmath.stochastic.RandomVariableInterface)
*/
@Override
public boolean equals(RandomVariableInterface randomVariable) {
return getValues().equals(randomVariable);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getFiltrationTime()
*/
@Override
public double getFiltrationTime() {
return getValues().getFiltrationTime();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#get(int)
*/
@Override
public double get(int pathOrState) {
return getValues().get(pathOrState);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#size()
*/
@Override
public int size() {
return getValues().size();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#isDeterministic()
*/
@Override
public boolean isDeterministic() {
return getValues().isDeterministic();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getRealizations()
*/
@Override
public double[] getRealizations() {
return getValues().getRealizations();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getRealizations(int)
*/
@Override
public double[] getRealizations(int numberOfPaths) {
return getValues().getRealizations(numberOfPaths);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getMin()
*/
@Override
public double getMin() {
return getValues().getMin();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getMax()
*/
@Override
public double getMax() {
return getValues().getMax();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getAverage()
*/
@Override
public double getAverage() {
return getValues().getAverage();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getAverage(net.finmath.stochastic.RandomVariableInterface)
*/
@Override
public double getAverage(RandomVariableInterface probabilities) {
return getValues().getAverage(probabilities);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getVariance()
*/
@Override
public double getVariance() {
return getValues().getVariance();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getVariance(net.finmath.stochastic.RandomVariableInterface)
*/
@Override
public double getVariance(RandomVariableInterface probabilities) {
return getValues().getVariance(probabilities);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getSampleVariance()
*/
@Override
public double getSampleVariance() {
return getValues().getSampleVariance();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getStandardDeviation()
*/
@Override
public double getStandardDeviation() {
return getValues().getStandardDeviation();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getStandardDeviation(net.finmath.stochastic.RandomVariableInterface)
*/
@Override
public double getStandardDeviation(RandomVariableInterface probabilities) {
return getValues().getStandardDeviation(probabilities);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getStandardError()
*/
@Override
public double getStandardError() {
return getValues().getStandardError();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getStandardError(net.finmath.stochastic.RandomVariableInterface)
*/
@Override
public double getStandardError(RandomVariableInterface probabilities) {
return getValues().getStandardError(probabilities);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getQuantile(double)
*/
@Override
public double getQuantile(double quantile) {
return getValues().getQuantile(quantile);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getQuantile(double, net.finmath.stochastic.RandomVariableInterface)
*/
@Override
public double getQuantile(double quantile, RandomVariableInterface probabilities) {
return ((RandomVariableDifferentiableAAD) getValues()).getValues().getQuantile(quantile, probabilities);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getQuantileExpectation(double, double)
*/
@Override
public double getQuantileExpectation(double quantileStart, double quantileEnd) {
return ((RandomVariableDifferentiableAAD) getValues()).getValues().getQuantileExpectation(quantileStart, quantileEnd);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getHistogram(double[])
*/
@Override
public double[] getHistogram(double[] intervalPoints) {
return getValues().getHistogram(intervalPoints);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#getHistogram(int, double)
*/
@Override
public double[][] getHistogram(int numberOfPoints, double standardDeviations) {
return getValues().getHistogram(numberOfPoints, standardDeviations);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#cache()
*/
@Override
public RandomVariableInterface cache() {
return this;
}
@Override
public RandomVariableInterface cap(double cap) {
return new RandomVariableDifferentiableAAD(
getValues().cap(cap),
Arrays.asList(new RandomVariableInterface[]{ this, new RandomVariable(cap) }),
OperatorType.CAP);
}
@Override
public RandomVariableInterface floor(double floor) {
return new RandomVariableDifferentiableAAD(
getValues().floor(floor),
Arrays.asList(new RandomVariableInterface[]{ this, new RandomVariable(floor) }),
OperatorType.FLOOR);
}
@Override
public RandomVariableInterface add(double value) {
return new RandomVariableDifferentiableAAD(
getValues().add(value),
Arrays.asList(new RandomVariableInterface[]{ this, new RandomVariable(value) }),
OperatorType.ADD);
}
@Override
public RandomVariableInterface sub(double value) {
return new RandomVariableDifferentiableAAD(
getValues().sub(value),
Arrays.asList(new RandomVariableInterface[]{ this, new RandomVariable(value) }),
OperatorType.SUB);
}
@Override
public RandomVariableInterface mult(double value) {
return new RandomVariableDifferentiableAAD(
getValues().mult(value),
Arrays.asList(new RandomVariableInterface[]{ this, new RandomVariable(value) }),
OperatorType.MULT);
}
@Override
public RandomVariableInterface div(double value) {
return new RandomVariableDifferentiableAAD(
getValues().div(value),
Arrays.asList(new RandomVariableInterface[]{ this, new RandomVariable(value) }),
OperatorType.DIV);
}
@Override
public RandomVariableInterface pow(double exponent) {
return new RandomVariableDifferentiableAAD(
getValues().pow(exponent),
Arrays.asList(new RandomVariableInterface[]{ this, new RandomVariable(exponent) }),
OperatorType.POW);
}
@Override
public RandomVariableInterface average() {
return new RandomVariableDifferentiableAAD(
getValues().average(),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.AVERAGE);
}
public RandomVariableInterface getConditionalExpectation(ConditionalExpectationEstimatorInterface estimator) {
return new RandomVariableDifferentiableAAD(
getValues().average(),
Arrays.asList(new RandomVariableInterface[]{ this }),
estimator,
OperatorType.CONDITIONAL_EXPECTATION);
}
@Override
public RandomVariableInterface squared() {
return new RandomVariableDifferentiableAAD(
getValues().squared(),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.SQUARED);
}
@Override
public RandomVariableInterface sqrt() {
return new RandomVariableDifferentiableAAD(
getValues().sqrt(),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.SQRT);
}
@Override
public RandomVariableInterface exp() {
return new RandomVariableDifferentiableAAD(
getValues().exp(),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.EXP);
}
@Override
public RandomVariableInterface log() {
return new RandomVariableDifferentiableAAD(
getValues().log(),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.LOG);
}
@Override
public RandomVariableInterface sin() {
return new RandomVariableDifferentiableAAD(
getValues().sin(),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.SIN);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#cos()
*/
@Override
public RandomVariableInterface cos() {
return new RandomVariableDifferentiableAAD(
getValues().cos(),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.COS);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#add(net.finmath.stochastic.RandomVariableInterface)
*/
@Override
public RandomVariableInterface add(RandomVariableInterface randomVariable) {
return new RandomVariableDifferentiableAAD(
getValues().add(randomVariable),
Arrays.asList(new RandomVariableInterface[]{ this, randomVariable }),
OperatorType.ADD);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#sub(net.finmath.stochastic.RandomVariableInterface)
*/
@Override
public RandomVariableInterface sub(RandomVariableInterface randomVariable) {
return new RandomVariableDifferentiableAAD(
getValues().sub(randomVariable),
Arrays.asList(new RandomVariableInterface[]{ this, randomVariable }),
OperatorType.SUB);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#mult(net.finmath.stochastic.RandomVariableInterface)
*/
@Override
public RandomVariableDifferentiableInterface mult(RandomVariableInterface randomVariable) {
return new RandomVariableDifferentiableAAD(
getValues().mult(randomVariable),
Arrays.asList(new RandomVariableInterface[]{ this, randomVariable }),
OperatorType.MULT);
}
@Override
public RandomVariableInterface div(RandomVariableInterface randomVariable) {
return new RandomVariableDifferentiableAAD(
getValues().div(randomVariable),
Arrays.asList(new RandomVariableInterface[]{ this, randomVariable }),
OperatorType.DIV);
}
@Override
public RandomVariableInterface cap(RandomVariableInterface cap) {
return new RandomVariableDifferentiableAAD(
getValues().cap(cap),
Arrays.asList(new RandomVariableInterface[]{ this, cap }),
OperatorType.CAP);
}
@Override
public RandomVariableInterface floor(RandomVariableInterface floor) {
return new RandomVariableDifferentiableAAD(
getValues().cap(floor),
Arrays.asList(new RandomVariableInterface[]{ this, floor }),
OperatorType.FLOOR);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#accrue(net.finmath.stochastic.RandomVariableInterface, double)
*/
@Override
public RandomVariableInterface accrue(RandomVariableInterface rate, double periodLength) {
return new RandomVariableDifferentiableAAD(
getValues().accrue(rate, periodLength),
Arrays.asList(new RandomVariableInterface[]{ this, rate, new RandomVariable(periodLength) }),
OperatorType.ACCRUE);
}
@Override
public RandomVariableInterface discount(RandomVariableInterface rate, double periodLength) {
return new RandomVariableDifferentiableAAD(
getValues().discount(rate, periodLength),
Arrays.asList(new RandomVariableInterface[]{ this, rate, new RandomVariable(periodLength) }),
OperatorType.DISCOUNT);
}
@Override
public RandomVariableInterface barrier(RandomVariableInterface trigger, RandomVariableInterface valueIfTriggerNonNegative, RandomVariableInterface valueIfTriggerNegative) {
RandomVariableInterface triggerValues = trigger instanceof RandomVariableDifferentiableAAD ? ((RandomVariableDifferentiableAAD)trigger).getValues() : trigger;
return new RandomVariableDifferentiableAAD(
getValues().barrier(triggerValues, valueIfTriggerNonNegative, valueIfTriggerNegative),
Arrays.asList(new RandomVariableInterface[]{ trigger, valueIfTriggerNonNegative, valueIfTriggerNegative }),
OperatorType.BARRIER);
}
@Override
public RandomVariableInterface barrier(RandomVariableInterface trigger, RandomVariableInterface valueIfTriggerNonNegative, double valueIfTriggerNegative) {
RandomVariableInterface triggerValues = trigger instanceof RandomVariableDifferentiableAAD ? ((RandomVariableDifferentiableAAD)trigger).getValues() : trigger;
return new RandomVariableDifferentiableAAD(
getValues().barrier(triggerValues, valueIfTriggerNonNegative, valueIfTriggerNegative),
Arrays.asList(new RandomVariableInterface[]{ trigger, valueIfTriggerNonNegative, new RandomVariable(valueIfTriggerNegative) }),
OperatorType.BARRIER);
}
@Override
public RandomVariableInterface invert() {
return new RandomVariableDifferentiableAAD(
getValues().invert(),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.INVERT);
}
@Override
public RandomVariableInterface abs() {
return new RandomVariableDifferentiableAAD(
getValues().abs(),
Arrays.asList(new RandomVariableInterface[]{ this }),
OperatorType.ABS);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariableInterface#addProduct(net.finmath.stochastic.RandomVariableInterface, double)
*/
@Override
public RandomVariableInterface addProduct(RandomVariableInterface factor1, double factor2) {
return new RandomVariableDifferentiableAAD(
getValues().addProduct(factor1, factor2),
Arrays.asList(new RandomVariableInterface[]{ this, factor1, new RandomVariable(factor2) }),
OperatorType.ADDPRODUCT);
}
@Override
public RandomVariableInterface addProduct(RandomVariableInterface factor1, RandomVariableInterface factor2) {
return new RandomVariableDifferentiableAAD(
getValues().addProduct(factor1, factor2),
Arrays.asList(new RandomVariableInterface[]{ this, factor1, factor2 }),
OperatorType.ADDPRODUCT);
}
@Override
public RandomVariableInterface addRatio(RandomVariableInterface numerator, RandomVariableInterface denominator) {
return new RandomVariableDifferentiableAAD(
getValues().addRatio(numerator, denominator),
Arrays.asList(new RandomVariableInterface[]{ this, numerator, denominator }),
OperatorType.ADDRATIO);
}
@Override
public RandomVariableInterface subRatio(RandomVariableInterface numerator, RandomVariableInterface denominator) {
return new RandomVariableDifferentiableAAD(
getValues().subRatio(numerator, denominator),
Arrays.asList(new RandomVariableInterface[]{ this, numerator, denominator }),
OperatorType.SUBRATIO);
}
@Override
public RandomVariableInterface isNaN() {
return getValues().isNaN();
}
@Override
public RandomVariableInterface getMutableCopy() {
return this;
}
@Override
public IntToDoubleFunction getOperator() {
return getValues().getOperator();
}
@Override
public DoubleStream getRealizationsStream() {
return getValues().getRealizationsStream();
}
@Override
public RandomVariableInterface apply(DoubleUnaryOperator operator) {
throw new UnsupportedOperationException("Applying functions is not supported.");
}
@Override
public RandomVariableInterface apply(DoubleBinaryOperator operator, RandomVariableInterface argument) {
throw new UnsupportedOperationException("Applying functions is not supported.");
}
@Override
public RandomVariableInterface apply(DoubleTernaryOperator operator, RandomVariableInterface argument1, RandomVariableInterface argument2) {
throw new UnsupportedOperationException("Applying functions is not supported.");
}
}
|
package org.spongepowered.common.mixin.api.mcp.command.arguments;
import com.google.common.base.Preconditions;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap;
import net.minecraft.advancements.criterion.MinMaxBounds;
import net.minecraft.advancements.criterion.MinMaxBoundsWrapped;
import net.minecraft.command.arguments.EntitySelector;
import net.minecraft.command.arguments.EntitySelectorParser;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.util.registry.Registry;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.advancement.Advancement;
import org.spongepowered.api.advancement.criteria.AdvancementCriterion;
import org.spongepowered.api.command.selector.Selector;
import org.spongepowered.api.command.selector.SelectorSortAlgorithm;
import org.spongepowered.api.command.selector.SelectorType;
import org.spongepowered.api.data.persistence.DataFormats;
import org.spongepowered.api.data.persistence.DataView;
import org.spongepowered.api.entity.EntityType;
import org.spongepowered.api.entity.living.player.gamemode.GameMode;
import org.spongepowered.api.registry.RegistryTypes;
import org.spongepowered.api.scoreboard.Score;
import org.spongepowered.api.scoreboard.Team;
import org.spongepowered.api.util.Range;
import org.spongepowered.api.util.Tristate;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.accessor.advancements.criterion.MinMaxBounds_FloatBoundAccessor;
import org.spongepowered.common.accessor.advancements.criterion.MinMaxBounds_IntBoundAccessor;
import org.spongepowered.common.bridge.command.arguments.EntitySelectorParserBridge;
import org.spongepowered.common.command.selector.SpongeSelectorSortAlgorithm;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
@Mixin(EntitySelectorParser.class)
public abstract class EntitySelectorParserMixin_API implements Selector.Builder {
// @formatter:off
@Shadow @Final private StringReader reader;
@Shadow private int maxResults;
@Shadow private BiConsumer<Vector3d, List<? extends Entity>> order;
@Shadow private MinMaxBounds.FloatBound distance;
@Shadow private MinMaxBounds.IntBound level;
@Shadow private boolean includesEntities;
@Shadow private boolean worldLimited;
@Shadow @Nullable private Double x;
@Shadow @Nullable private Double y;
@Shadow @Nullable private Double z;
@Shadow @Nullable private Double deltaX;
@Shadow @Nullable private Double deltaY;
@Shadow @Nullable private Double deltaZ;
@Shadow private MinMaxBoundsWrapped rotX = MinMaxBoundsWrapped.ANY;
@Shadow private MinMaxBoundsWrapped rotY = MinMaxBoundsWrapped.ANY;
@Shadow private Predicate<Entity> predicate;
@Shadow private boolean currentEntity;
@Shadow @Nullable private String playerName;
@Shadow private int startPosition;
@Shadow @Nullable private UUID entityUUID;
@Shadow private BiFunction<SuggestionsBuilder, Consumer<SuggestionsBuilder>, CompletableFuture<Suggestions>> suggestions;
@Shadow private boolean hasNameEquals;
@Shadow private boolean hasNameNotEquals;
@Shadow private boolean isLimited;
@Shadow private boolean isSorted;
@Shadow private boolean hasGamemodeEquals;
@Shadow private boolean hasGamemodeNotEquals;
@Shadow private boolean hasTeamEquals;
@Shadow private boolean hasTeamNotEquals;
@Shadow private net.minecraft.entity.@Nullable EntityType<?> type;
@Shadow private boolean typeInverse;
@Shadow private boolean hasScores;
@Shadow private boolean hasAdvancements;
@Shadow private boolean usesSelectors;
@Shadow public abstract void shadow$setLimited(boolean value);
@Shadow public abstract void shadow$setSorted(boolean value);
@Shadow public abstract void shadow$setX(double xIn);
@Shadow public abstract void shadow$setY(double yIn);
@Shadow public abstract void shadow$setZ(double zIn);
@Shadow public abstract void shadow$setDeltaX(double dxIn);
@Shadow public abstract void shadow$setDeltaY(double dyIn);
@Shadow public abstract void shadow$setDeltaZ(double dzIn);
@Shadow public abstract void shadow$setIncludesEntities(boolean includeNonPlayers);
@Shadow public abstract EntitySelector shadow$getSelector();
@Shadow public abstract void shadow$addPredicate(Predicate<Entity> p_197401_1_);
// @formatter:on
@Nullable private Map<String, Range<@NonNull Integer>> api$scores;
@Nullable private Object2BooleanOpenHashMap<String> api$advancement;
@Nullable private Map<String, Object2BooleanOpenHashMap<String>> api$criterion;
private boolean api$forceSelf;
@Override
public Selector.@NonNull Builder applySelectorType(final Supplier<? extends SelectorType> selectorType) {
return this.applySelectorType(selectorType.get());
}
@Override
public Selector.@NonNull Builder applySelectorType(@NonNull final SelectorType selectorType) {
try {
((EntitySelectorParserBridge) this).bridge$parseSelector(selectorType);
} catch (final CommandSyntaxException commandSyntaxException) {
throw new IllegalArgumentException("Could not parse provided SelectorType", commandSyntaxException);
}
return this;
}
@Override
public Selector.@NonNull Builder includeSelf() {
this.api$forceSelf = true;
return this;
}
@Override
public Selector.@NonNull Builder setLimit(final int limit) {
this.maxResults = limit;
this.shadow$setLimited(limit != Integer.MAX_VALUE);
return this;
}
@Override
public Selector.@NonNull Builder setDistance(@NonNull final Range<@NonNull Double> range) {
Preconditions.checkArgument(range.getMin() == null || range.getMin() >= 0, "min must be non-negative");
Preconditions.checkArgument(range.getMax() == null || range.getMax() >= 0, "max must be non-negative");
this.distance = MinMaxBounds_FloatBoundAccessor.invoker$new(
this.api$floatFromDouble(range.getMin(), Function.identity()),
this.api$floatFromDouble(range.getMax(), Function.identity()));
return this;
}
@Override
public Selector.@NonNull Builder setVolume(final org.spongepowered.math.vector.@NonNull Vector3d corner1,
final org.spongepowered.math.vector.@NonNull Vector3d corner2) {
final org.spongepowered.math.vector.Vector3d minPoint = corner1.min(corner2);
final org.spongepowered.math.vector.Vector3d distance = corner1.max(corner2).sub(minPoint);
this.shadow$setX(minPoint.getX());
this.shadow$setY(minPoint.getY());
this.shadow$setZ(minPoint.getZ());
this.shadow$setDeltaX(distance.getX());
this.shadow$setDeltaY(distance.getY());
this.shadow$setDeltaZ(distance.getZ());
return this;
}
@Override
public Selector.@NonNull Builder setSortAlgorithm(@NonNull final Supplier<? extends SelectorSortAlgorithm> algorithm) {
return this.setSortAlgorithm(algorithm.get());
}
@Override
public Selector.@NonNull Builder setSortAlgorithm(@NonNull final SelectorSortAlgorithm algorithm) {
Preconditions.checkArgument(algorithm instanceof SpongeSelectorSortAlgorithm, "Must be a SpongeSelectorSortAlgorithm");
this.shadow$setSorted(true);
this.order = ((SpongeSelectorSortAlgorithm) algorithm).getSortAlgorithm();
return this;
}
@Override
public Selector.@NonNull Builder advancement(@NonNull final Advancement advancement) {
return this.api$advancement(advancement, false);
}
@Override
public Selector.@NonNull Builder notAdvancement(@NonNull final Advancement advancement) {
return this.api$advancement(advancement, true);
}
@Override
public Selector.@NonNull Builder advancementCriterion(@NonNull final Advancement advancement, @NonNull final AdvancementCriterion criterion) {
return this.api$advancementCriterion(advancement, criterion, false);
}
@Override
public Selector.@NonNull Builder notAdvancementCriterion(@NonNull final Advancement advancement, @NonNull final AdvancementCriterion criterion) {
return this.api$advancementCriterion(advancement, criterion, true);
}
@Override
public Selector.@NonNull Builder setDataView(@NonNull final DataView view) {
try {
// TODO: ensure this works as expected
final String json = DataFormats.JSON.get().write(view);
this.api$handle("nbt", json);
return this;
} catch (@NonNull final IOException e) {
throw new RuntimeException("Could not create JSON representation of DataView", e);
}
}
@Override
public Selector.@NonNull Builder notEntityType(@NonNull final Supplier<@NonNull EntityType<@NonNull ?>> type) {
return this.notEntityType(type.get());
}
@Override
public Selector.@NonNull Builder notEntityType(@NonNull final EntityType<@NonNull ?> type) {
final ResourceKey key = (ResourceKey) (Object) Registry.ENTITY_TYPE.getKey((net.minecraft.entity.EntityType<?>) type);
this.api$handle("type", "!" + key.asString());
return this;
}
@Override
public Selector.@NonNull Builder entityType(@NonNull final Supplier<@NonNull EntityType<@NonNull ?>> type, final boolean inherit) {
return this.entityType(type.get(), inherit);
}
@Override
public Selector.@NonNull Builder entityType(@NonNull final EntityType<@NonNull ?> type, final boolean inherit) {
final ResourceKey key = (ResourceKey) (Object) Registry.ENTITY_TYPE.getKey((net.minecraft.entity.EntityType<?>) type);
this.api$handle("type", String.format("%s%s", inherit ? "#" : "", key.asString()));
return this;
}
@Override
public Selector.@NonNull Builder setExperienceLevel(@NonNull final Range<@NonNull Integer> range) {
Preconditions.checkArgument(range.getMin() == null || range.getMin() >= 0, "min must be non-negative");
Preconditions.checkArgument(range.getMax() == null || range.getMax() >= 0, "max must be non-negative");
this.level = MinMaxBounds_IntBoundAccessor.invoker$new(range.getMin(), range.getMax());
this.shadow$setIncludesEntities(false);
return this;
}
@Override
public Selector.@NonNull Builder gameMode(@NonNull final Supplier<? extends GameMode> mode) {
return this.gameMode(mode.get());
}
@Override
public Selector.@NonNull Builder gameMode(@NonNull final GameMode mode) {
final ResourceKey key = Sponge.getGame().registries().registry(RegistryTypes.GAME_MODE).valueKey(mode);
this.api$handle("gamemode", key.getValue(), Tristate.FALSE);
return this;
}
@Override
public Selector.@NonNull Builder notGameMode(@NonNull final Supplier<? extends GameMode> mode) {
return this.notGameMode(mode.get());
}
@Override
public Selector.@NonNull Builder notGameMode(@NonNull final GameMode mode) {
final ResourceKey key = Sponge.getGame().registries().registry(RegistryTypes.GAME_MODE).valueKey(mode);
this.api$handle("gamemode", key.getValue(), Tristate.TRUE);
return this;
}
@Override
public Selector.@NonNull Builder noTeam() {
this.api$handle("team", "", Tristate.TRUE);
return this;
}
@Override
public Selector.@NonNull Builder anyTeam() {
this.api$handle("team", "", Tristate.FALSE);
return this;
}
@Override
public Selector.@NonNull Builder team(@NonNull final Team team) {
this.api$handle("team", team.getName(), Tristate.FALSE);
return this;
}
@Override
public Selector.@NonNull Builder notTeam(@NonNull final Team team) {
this.api$handle("team", team.getName(), Tristate.TRUE);
return this;
}
@Override
public Selector.@NonNull Builder name(@NonNull final String name) {
this.api$handle("name", name, Tristate.FALSE);
return this;
}
@Override
public Selector.@NonNull Builder notName(@NonNull final String name) {
this.api$handle("name", name, Tristate.TRUE);
return this;
}
@Override
public Selector.@NonNull Builder score(@NonNull final Score score, @NonNull final Range<@NonNull Integer> range) {
if (this.api$scores == null) {
this.api$scores = new HashMap<>();
}
// TODO: Check this is right.
this.api$scores.put(score.getName().toString(), range);
return this;
}
@Override
public Selector.@NonNull Builder tag(@NonNull final String tag) {
this.api$handle("tag", tag, Tristate.FALSE);
return this;
}
@Override
public Selector.@NonNull Builder notTag(@NonNull final String tag) {
this.api$handle("tag", tag, Tristate.TRUE);
return this;
}
@Override
public Selector.@NonNull Builder setPitch(@NonNull final Range<@NonNull Double> range) {
this.rotX = this.api$getWrappedBounds(range);
return this;
}
@Override
public Selector.@NonNull Builder setYaw(@NonNull final Range<@NonNull Double> range) {
this.rotY = this.api$getWrappedBounds(range);
return this;
}
@Override
public Selector.@NonNull Builder filter(@NonNull final Predicate<org.spongepowered.api.entity.@NonNull Entity> filter) {
this.shadow$addPredicate((Predicate<Entity>) (Object) filter);
return this;
}
@Override
@NonNull
public Selector build() throws IllegalStateException {
// Advancements and criteria
if (this.api$advancement != null || this.api$criterion != null) {
final List<String> entries = new ArrayList<>();
if (this.api$advancement != null) {
this.api$advancement.object2BooleanEntrySet().fastForEach(x -> entries.add(x.getKey() + "=" + x.getBooleanValue()));
}
if (this.api$criterion != null) {
this.api$criterion.forEach((key, value) ->
value.object2BooleanEntrySet().fastForEach(x -> entries.add(key + "={" + x.getKey() + "=" + x.getBooleanValue() + "}")));
}
this.api$handle("advancements", "{" + String.join(",", entries) + "}");
this.api$advancement = null;
this.api$criterion = null;
}
if (this.api$scores != null) {
final List<String> entries = new ArrayList<>();
this.api$scores.forEach((key, range) -> entries.add(key + "=" + this.api$intRangeToStringRepresentation(range)));
this.api$handle("scores", "{" + String.join(",", entries) + "}");
this.api$scores = null;
}
if (this.api$forceSelf) {
this.currentEntity = true;
}
return (Selector) this.shadow$getSelector();
}
@Override
public Selector.@NonNull Builder reset() {
this.order = EntitySelectorParser.ORDER_ARBITRARY;
this.distance = MinMaxBounds.FloatBound.ANY;
this.level = MinMaxBounds.IntBound.ANY;
this.includesEntities = false;
this.worldLimited = false;
this.x = null;
this.y = null;
this.z = null;
this.deltaX = null;
this.deltaY = null;
this.deltaZ = null;
this.rotX = MinMaxBoundsWrapped.ANY;
this.rotY = MinMaxBoundsWrapped.ANY;
this.predicate = x -> true;
this.currentEntity = false;
this.playerName = null;
this.startPosition = 0;
this.entityUUID = null;
this.hasNameEquals = false;
this.hasNameNotEquals = false;
this.isLimited = false;
this.isSorted = false;
this.hasGamemodeEquals = false;
this.hasGamemodeNotEquals = false;
this.hasTeamEquals = false;
this.hasTeamNotEquals = false;
this.type = null;
this.typeInverse = false;
this.hasScores = false;
this.hasAdvancements = false;
this.usesSelectors = false;
this.reader.setCursor(0);
this.suggestions = EntitySelectorParser.SUGGEST_NOTHING;
this.api$forceSelf = false;
return this;
}
private Selector.@NonNull Builder api$advancement(@NonNull final Advancement advancement, final boolean inverted) {
if (this.api$advancement == null) {
this.api$advancement = new Object2BooleanOpenHashMap<>();
}
this.api$advancement.put(advancement.getKey().asString(), inverted);
return this;
}
private Selector.@NonNull Builder api$advancementCriterion(@NonNull final Advancement advancement, @NonNull final AdvancementCriterion criterion,
final boolean inverted) {
if (this.api$criterion == null) {
this.api$criterion = new HashMap<>();
}
this.api$criterion.computeIfAbsent(advancement.getKey().toString(), k -> new Object2BooleanOpenHashMap<>()).put(criterion.getName(), inverted);
return this;
}
private void api$handle(@NonNull final String name, @NonNull final String value) {
this.api$handle(name, value, Tristate.UNDEFINED);
}
private void api$handle(@NonNull final String name, @NonNull final String value, @NonNull final Tristate invert) {
try {
((EntitySelectorParserBridge) this).bridge$handleValue(name, value, invert);
} catch (final CommandSyntaxException ex) {
throw new IllegalArgumentException("Could not create selector criteria based on input", ex);
}
}
@Nullable
private Float api$floatFromDouble(@Nullable final Double d, final Function<Float, Float> mapping) {
if (d == null) {
return null;
}
return mapping.apply(d.floatValue());
}
private MinMaxBoundsWrapped api$getWrappedBounds(final Range<@NonNull Double> range) {
final Float a = this.api$floatFromDouble(range.getMin(), MathHelper::wrapDegrees);
final Float b = this.api$floatFromDouble(range.getMax(), MathHelper::wrapDegrees);
if (a == null) {
return new MinMaxBoundsWrapped(null, b);
}
if (b == null) {
return new MinMaxBoundsWrapped(a, null);
}
if (a <= b) {
return new MinMaxBoundsWrapped(a, b);
}
return new MinMaxBoundsWrapped(b, a);
}
private String api$intRangeToStringRepresentation(@NonNull final Range<@NonNull Integer> range) {
if (range.getMin() != null && range.getMax() != null && range.getMin().intValue() == range.getMax().intValue()) {
return String.valueOf(range.getMax().intValue());
}
return String.format("%s..%s",
range.getMin() == null ? "" : String.valueOf(range.getMin().intValue()),
range.getMax() == null ? "" : String.valueOf(range.getMax().intValue()));
}
}
|
package fr.moreaubenjamin.imageloader;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.ImageView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import fr.moreaubenjamin.imageloader.settings.ImageLoaderSettings;
public class ImageLoader {
private Context mContext;
private MemoryCache mMemoryCache;
private FileCache mFileCache;
private Map<ImageView, String> mImageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String> ());
private ExecutorService mExecutorService;
private Handler mHandler = new Handler();
private int mLoadingPictureResource;
private int mNoPictureResource;
private ImageView.ScaleType mLoadingScaleType;
public ImageLoader(Context context, String pathExtension, String cacheFolderName, int loadingPictureResource, int noPictureResource, ImageView.ScaleType loadingScaleType) {
mContext = context;
mMemoryCache = new MemoryCache(mContext);
mFileCache = new FileCache(mContext, pathExtension, cacheFolderName);
mExecutorService = Executors.newFixedThreadPool(ImageLoaderSettings.THREAD_NUMBER);
mLoadingPictureResource = (loadingPictureResource == -1) ? R.drawable.ic_launcher : loadingPictureResource;
mNoPictureResource = (noPictureResource == -1) ? R.drawable.ic_launcher : noPictureResource;
mLoadingScaleType = (loadingScaleType == null) ? ImageView.ScaleType.FIT_CENTER : loadingScaleType;
}
public void displayImage(String url, ImageView imageView, int requiredSize, ImageView.ScaleType scaleType) {
if (!TextUtils.isEmpty(url) && url.startsWith("http:
url += ImageLoaderSettings.SEPARATOR + requiredSize;
mImageViews.put(imageView, url);
Bitmap bitmap = mMemoryCache.get(url);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
imageView.setScaleType(scaleType);
} else {
queuePhoto(url, imageView, requiredSize, scaleType);
imageView.setImageResource(mLoadingPictureResource);
imageView.setScaleType(mLoadingScaleType);
}
} else {
imageView.setImageResource(mNoPictureResource);
imageView.setScaleType(scaleType);
}
}
private void queuePhoto(String url, ImageView imageView, int requiredSize, ImageView.ScaleType scaleType) {
PhotoToLoad photoToLoad = new PhotoToLoad(url, imageView, requiredSize, scaleType);
mExecutorService.submit(new PhotosLoader(photoToLoad));
}
private class PhotoToLoad {
public String mUrl;
public ImageView mImageView;
public int mRequiredSize;
public ImageView.ScaleType mScaleType;
public PhotoToLoad(String url, ImageView imageView, int requiredSize, ImageView.ScaleType scaleType) {
mUrl = url;
mImageView = imageView;
mRequiredSize = requiredSize;
mScaleType = scaleType;
}
}
private class PhotosLoader implements Runnable {
private PhotoToLoad mPhotoToLoad;
public PhotosLoader(PhotoToLoad photoToLoad) {
mPhotoToLoad = photoToLoad;
}
@Override
public void run() {
try {
if (imageViewReused(mPhotoToLoad)) {
return;
}
String url = mPhotoToLoad.mUrl;
if (url.contains(ImageLoaderSettings.SEPARATOR)) {
StringTokenizer tokens = new StringTokenizer(url, ImageLoaderSettings.SEPARATOR);
url = tokens.nextToken();
}
Bitmap bitmap = getBitmap(url, mPhotoToLoad.mRequiredSize);
mMemoryCache.put(mPhotoToLoad.mUrl, bitmap);
if (imageViewReused(mPhotoToLoad)) {
return;
}
BitmapDisplayer bitmapDisplayer = new BitmapDisplayer(bitmap, mPhotoToLoad);
mHandler.post(bitmapDisplayer);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = mImageViews.get(photoToLoad.mImageView);
return (tag == null) || !tag.equals(photoToLoad.mUrl);
}
private Bitmap getBitmap(String url, int requiredSize) {
File file = mFileCache.getFile(url);
Bitmap bitmap1 = decodeFile(file, requiredSize);
if (bitmap1 != null) {
return bitmap1;
}
try {
Bitmap bitmap2;
URL imageURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) imageURL.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setInstanceFollowRedirects(true);
InputStream inputStream = connection.getInputStream();
OutputStream outputStream = new FileOutputStream(file);
copyStream(inputStream, outputStream);
outputStream.close();
bitmap2 = decodeFile(file, requiredSize);
return bitmap2;
} catch (Throwable ex) {
ex.printStackTrace();;
if (ex instanceof OutOfMemoryError) {
mMemoryCache.clear();
}
return null;
}
}
private Bitmap decodeFile(File file, int requiredSize) {
try {
BitmapFactory.Options options1 = new BitmapFactory.Options();
options1.inJustDecodeBounds = true;
FileInputStream inputStream1 = new FileInputStream(file);
BitmapFactory.decodeStream(inputStream1, null, options1);
inputStream1.close();
int widthTmp = options1.outWidth;
int heightTmp = options1.outHeight;
int scale = 1;
if (requiredSize > -1) {
while (true) {
if (((widthTmp / 2) < requiredSize) || ((heightTmp / 2) < requiredSize)) {
break;
}
widthTmp /= 2;
heightTmp /= 2;
scale *= 2;
}
}
BitmapFactory.Options options2 = new BitmapFactory.Options();
options2.inSampleSize = scale;
FileInputStream inputStream2 = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream2, null, options2);
inputStream2.close();
return bitmap;
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
private void copyStream(InputStream inputStream, OutputStream outputStream) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for( ; ; ) {
int count = inputStream.read(bytes, 0, buffer_size);
if (count == -1) {
break;
}
outputStream.write(bytes, 0, count);
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
private class BitmapDisplayer implements Runnable {
private Bitmap mBitmap;
private PhotoToLoad mPhotoToLoad;
public BitmapDisplayer(Bitmap bitmap, PhotoToLoad photoToLoad) {
mBitmap = bitmap;
mPhotoToLoad = photoToLoad;
}
@Override
public void run() {
if (imageViewReused(mPhotoToLoad)) {
return;
}
if (mBitmap != null) {
mPhotoToLoad.mImageView.setImageBitmap(mBitmap);
mPhotoToLoad.mImageView.setScaleType(mPhotoToLoad.mScaleType);
} else {
mPhotoToLoad.mImageView.setImageResource(mNoPictureResource);
mPhotoToLoad.mImageView.setScaleType(mPhotoToLoad.mScaleType);
}
}
}
public void clearCache() {
mMemoryCache.clear();
mFileCache.clear();
}
}
|
package org.sagebionetworks;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sagebionetworks.client.SynapseAdminClient;
import org.sagebionetworks.client.SynapseAdminClientImpl;
import org.sagebionetworks.client.SynapseClient;
import org.sagebionetworks.client.SynapseClientImpl;
import org.sagebionetworks.client.exceptions.SynapseException;
import org.sagebionetworks.repo.model.ACCESS_TYPE;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.PaginatedResults;
import org.sagebionetworks.repo.model.Project;
import org.sagebionetworks.repo.model.RestrictableObjectDescriptor;
import org.sagebionetworks.repo.model.RestrictableObjectType;
import org.sagebionetworks.repo.model.TermsOfUseAccessRequirement;
import org.sagebionetworks.repo.model.dao.WikiPageKey;
import org.sagebionetworks.repo.model.dao.WikiPageKeyHelper;
import org.sagebionetworks.repo.model.file.FileHandle;
import org.sagebionetworks.repo.model.file.FileHandleResults;
import org.sagebionetworks.repo.model.file.PreviewFileHandle;
import org.sagebionetworks.repo.model.file.S3FileHandle;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiHeader;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiHistorySnapshot;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage;
import org.sagebionetworks.repo.model.wiki.WikiPage;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.utils.MD5ChecksumHelper;
public class ITV2WikiPageTest {
private static String FILE_NAME = "LittleImage.png";
private static String FILE_NAME2 = "profile_pic.png";
private static String MARKDOWN_NAME = "previewtest.txt.gz";
public static final long MAX_WAIT_MS = 1000*20; // 20 sec
private static SynapseAdminClient adminSynapse;
private static SynapseClient synapse;
private static Long userToDelete;
private List<WikiPageKey> toDelete = null;
private List<String> fileHandlesToDelete = null;
private S3FileHandle fileHandle;
private S3FileHandle fileHandleTwo;
private S3FileHandle markdownHandle;
private File imageFile;
private String imageFileMD5;
private File imageFileTwo;
private File markdownFile;
private Project project;
private TermsOfUseAccessRequirement accessRequirement;
@BeforeClass
public static void beforeClass() throws Exception {
// Create a user
adminSynapse = new SynapseAdminClientImpl();
SynapseClientHelper.setEndpoints(adminSynapse);
adminSynapse.setUserName(StackConfiguration.getMigrationAdminUsername());
adminSynapse.setApiKey(StackConfiguration.getMigrationAdminAPIKey());
adminSynapse.clearAllLocks();
synapse = new SynapseClientImpl();
userToDelete = SynapseClientHelper.createUser(adminSynapse, synapse);
}
@Before
public void before() throws SynapseException, IOException {
toDelete = new ArrayList<WikiPageKey>();
fileHandlesToDelete = new ArrayList<String>();
// Get image and markdown files from the classpath.
URL url = ITV2WikiPageTest.class.getClassLoader().getResource("images/"+FILE_NAME);
URL url2 = ITV2WikiPageTest.class.getClassLoader().getResource("images/" + FILE_NAME2);
URL markdownUrl = ITV2WikiPageTest.class.getClassLoader().getResource("images/"+MARKDOWN_NAME);
imageFile = new File(url.getFile().replaceAll("%20", " "));
imageFileMD5 = MD5ChecksumHelper.getMD5Checksum(imageFile);
imageFileTwo = new File(url2.getFile().replaceAll("%20", " "));
markdownFile = new File(markdownUrl.getFile().replaceAll("%20", " "));
assertNotNull(imageFile);
assertTrue(imageFile.exists());
assertNotNull(imageFileTwo);
assertTrue(imageFileTwo.exists());
assertNotNull(markdownFile);
assertTrue(markdownFile.exists());
// Create a project, this will own the wiki page.
project = new Project();
project = synapse.createEntity(project);
// Create the file handles
List<File> list = new LinkedList<File>();
list.add(imageFile);
list.add(imageFileTwo);
list.add(markdownFile);
FileHandleResults results = synapse.createFileHandles(list, project.getId());
assertNotNull(results);
assertNotNull(results.getList());
assertEquals(3, results.getList().size());
fileHandle = (S3FileHandle) results.getList().get(0);
fileHandleTwo = (S3FileHandle) results.getList().get(1);
markdownHandle = (S3FileHandle) results.getList().get(2);
// create the access requirement
accessRequirement = new TermsOfUseAccessRequirement();
RestrictableObjectDescriptor rod = new RestrictableObjectDescriptor();
rod.setId(project.getId());
rod.setType(RestrictableObjectType.ENTITY);
accessRequirement.setAccessType(ACCESS_TYPE.DOWNLOAD);
accessRequirement.setSubjectIds(Collections.singletonList(rod));
accessRequirement = adminSynapse.createAccessRequirement(accessRequirement);
}
@After
public void after() throws Exception {
if (accessRequirement != null) {
try {
synapse.deleteAccessRequirement(accessRequirement.getId());
} catch (Exception e) {
// continue
}
}
if(fileHandle != null){
try {
synapse.deleteFileHandle(fileHandle.getId());
} catch (Exception e) {}
}
if(fileHandleTwo != null){
try {
synapse.deleteFileHandle(fileHandleTwo.getId());
} catch (Exception e) {}
}
if(markdownHandle != null) {
try {
synapse.deleteFileHandle(markdownHandle.getId());
} catch (Exception e) {}
}
if(project != null){
synapse.deleteAndPurgeEntity(project);
}
for(String id: fileHandlesToDelete) {
synapse.deleteFileHandle(id);
}
for(WikiPageKey key: toDelete){
synapse.deleteV2WikiPage(key);
}
}
@AfterClass
public static void afterClass() throws Exception {
adminSynapse.deleteUser(userToDelete);
}
@Test
public void testV2WikiRoundTrip() throws SynapseException, IOException, InterruptedException, JSONObjectAdapterException{
V2WikiPage wiki = new V2WikiPage();
wiki.setAttachmentFileHandleIds(new ArrayList<String>());
wiki.getAttachmentFileHandleIds().add(fileHandle.getId());
wiki.setMarkdownFileHandleId(markdownHandle.getId());
wiki.setTitle("ITV2WikiPageTest.testWikiRoundTrip");
// Create a V2WikiPage
wiki = synapse.createV2WikiPage(project.getId(), ObjectType.ENTITY, wiki);
assertNotNull(wiki);
assertNotNull(wiki.getAttachmentFileHandleIds());
assertEquals(1, wiki.getAttachmentFileHandleIds().size());
assertEquals(fileHandle.getId(), wiki.getAttachmentFileHandleIds().get(0));
WikiPageKey key = WikiPageKeyHelper.createWikiPageKey(project.getId(), ObjectType.ENTITY, wiki.getId());
toDelete.add(key);
Date firstModifiedOn = wiki.getModifiedOn();
// Add another file attachment and change the title and update the wiki
wiki.getAttachmentFileHandleIds().add(fileHandleTwo.getId());
wiki.setTitle("Updated ITV2WikiPageTest");
wiki = synapse.updateV2WikiPage(key.getOwnerObjectId(), key.getOwnerObjectType(), wiki);
assertNotNull(wiki);
assertNotNull(wiki.getAttachmentFileHandleIds());
assertEquals(2, wiki.getAttachmentFileHandleIds().size());
assertEquals(fileHandle.getId(), wiki.getAttachmentFileHandleIds().get(0));
assertEquals(fileHandleTwo.getId(), wiki.getAttachmentFileHandleIds().get(1));
assertEquals(markdownHandle.getId(), wiki.getMarkdownFileHandleId());
assertEquals("Updated ITV2WikiPageTest", wiki.getTitle());
assertTrue(!wiki.getModifiedOn().equals(firstModifiedOn));
// test get
wiki = synapse.getV2WikiPage(key);
V2WikiPage root = synapse.getV2RootWikiPage(project.getId(), ObjectType.ENTITY);
assertEquals(wiki, root);
// get markdown file
String markdown = synapse.downloadV2WikiMarkdown(key);
assertNotNull(markdown);
String oldMarkdown = synapse.downloadVersionOfV2WikiMarkdown(key, new Long(0));
assertNotNull(oldMarkdown);
// Get the tree
PaginatedResults<V2WikiHeader> tree = synapse.getV2WikiHeaderTree(key.getOwnerObjectId(), key.getOwnerObjectType());
assertNotNull(tree);
assertNotNull(tree.getResults());
assertEquals(1, tree.getResults().size());
assertEquals(1, tree.getTotalNumberOfResults());
// Get history
PaginatedResults<V2WikiHistorySnapshot> history = synapse.getV2WikiHistory(key, new Long(10), new Long(0));
assertNotNull(history);
assertNotNull(history.getResults());
assertTrue(history.getResults().size() == 2);
// First snapshot is most recent, so we want the last snapshot, version 0 (the first entry in history)
String versionToRestore = history.getResults().get(1).getVersion();
// Get the version first
V2WikiPage firstVersion = synapse.getVersionOfV2WikiPage(key, new Long(versionToRestore));
assertEquals(1, firstVersion.getAttachmentFileHandleIds().size());
assertEquals(fileHandle.getId(), firstVersion.getAttachmentFileHandleIds().get(0));
assertEquals(firstModifiedOn, firstVersion.getModifiedOn());
// Restore wiki to first state before update
wiki = synapse.restoreV2WikiPage(key.getOwnerObjectId(), key.getOwnerObjectType(), key.getWikiPageId(), new Long(versionToRestore));
assertNotNull(wiki);
assertNotNull(wiki.getAttachmentFileHandleIds());
assertNotNull(wiki.getMarkdownFileHandleId());
// Get history again
PaginatedResults<V2WikiHistorySnapshot> history2 = synapse.getV2WikiHistory(key, new Long(10), new Long(0));
assertNotNull(history2);
assertNotNull(history2.getResults());
assertTrue(history2.getResults().size() == 3);
assertTrue(wiki.getAttachmentFileHandleIds().size() == 1);
assertEquals(fileHandle.getId(), wiki.getAttachmentFileHandleIds().get(0));
assertEquals(markdownHandle.getId(), wiki.getMarkdownFileHandleId());
assertEquals("ITV2WikiPageTest.testWikiRoundTrip", wiki.getTitle());
// Delete the wiki
synapse.deleteV2WikiPage(key);
// Now try to get it
try{
synapse.getV2WikiPage(key);
fail("This should have failed as the wiki was deleted");
}catch(SynapseException e){
// expected;
}
}
@Test
public void testAccessRequirementV2WikiRoundTrip() throws SynapseException, IOException, InterruptedException, JSONObjectAdapterException{
V2WikiPage wiki = new V2WikiPage();
wiki.setAttachmentFileHandleIds(new ArrayList<String>());
wiki.getAttachmentFileHandleIds().add(fileHandle.getId());
wiki.setMarkdownFileHandleId(markdownHandle.getId());
wiki.setTitle("ITV2WikiPageTest.testAccessRequirementWikiRoundTrip");
// Create a V2WikiPage
wiki = adminSynapse.createV2WikiPage(accessRequirement.getId().toString(), ObjectType.ACCESS_REQUIREMENT, wiki);
assertNotNull(wiki);
assertNotNull(wiki.getAttachmentFileHandleIds());
assertEquals(1, wiki.getAttachmentFileHandleIds().size());
assertEquals(fileHandle.getId(), wiki.getAttachmentFileHandleIds().get(0));
WikiPageKey key = WikiPageKeyHelper.createWikiPageKey(project.getId(), ObjectType.ACCESS_REQUIREMENT, wiki.getId());
toDelete.add(key);
Date firstModifiedOn = wiki.getModifiedOn();
// Add another file attachment and change the title and update the wiki
wiki.getAttachmentFileHandleIds().add(fileHandleTwo.getId());
wiki.setTitle("Updated ITV2AccessRequirementWikiPageTest");
wiki = adminSynapse.updateV2WikiPage(key.getOwnerObjectId(), key.getOwnerObjectType(), wiki);
assertNotNull(wiki);
assertNotNull(wiki.getAttachmentFileHandleIds());
assertEquals(2, wiki.getAttachmentFileHandleIds().size());
assertEquals(fileHandle.getId(), wiki.getAttachmentFileHandleIds().get(0));
assertEquals(fileHandleTwo.getId(), wiki.getAttachmentFileHandleIds().get(1));
assertEquals(markdownHandle.getId(), wiki.getMarkdownFileHandleId());
assertEquals("Updated ITV2AccessRequirementWikiPageTest", wiki.getTitle());
assertTrue(!wiki.getModifiedOn().equals(firstModifiedOn));
// test get
wiki = synapse.getV2WikiPage(key);
V2WikiPage root = synapse.getV2RootWikiPage(project.getId(), ObjectType.ACCESS_REQUIREMENT);
assertEquals(wiki, root);
// get markdown file
String markdown = synapse.downloadV2WikiMarkdown(key);
assertNotNull(markdown);
String oldMarkdown = synapse.downloadVersionOfV2WikiMarkdown(key, new Long(0));
assertNotNull(oldMarkdown);
// Get the tree
PaginatedResults<V2WikiHeader> tree = synapse.getV2WikiHeaderTree(key.getOwnerObjectId(), key.getOwnerObjectType());
assertNotNull(tree);
assertNotNull(tree.getResults());
assertEquals(1, tree.getResults().size());
assertEquals(1, tree.getTotalNumberOfResults());
// Get history
PaginatedResults<V2WikiHistorySnapshot> history = synapse.getV2WikiHistory(key, new Long(10), new Long(0));
assertNotNull(history);
assertNotNull(history.getResults());
assertTrue(history.getResults().size() == 2);
// First snapshot is most recent, so we want the last snapshot, version 0 (the first entry in history)
String versionToRestore = history.getResults().get(1).getVersion();
// Get the version first
V2WikiPage firstVersion = synapse.getVersionOfV2WikiPage(key, new Long(versionToRestore));
assertEquals(1, firstVersion.getAttachmentFileHandleIds().size());
assertEquals(fileHandle.getId(), firstVersion.getAttachmentFileHandleIds().get(0));
assertEquals(firstModifiedOn, firstVersion.getModifiedOn());
// Restore wiki to first state before update
wiki = adminSynapse.restoreV2WikiPage(key.getOwnerObjectId(), key.getOwnerObjectType(), key.getWikiPageId(), new Long(versionToRestore));
assertNotNull(wiki);
assertNotNull(wiki.getAttachmentFileHandleIds());
assertNotNull(wiki.getMarkdownFileHandleId());
// Get history again
PaginatedResults<V2WikiHistorySnapshot> history2 = synapse.getV2WikiHistory(key, new Long(10), new Long(0));
assertNotNull(history2);
assertNotNull(history2.getResults());
assertTrue(history2.getResults().size() == 3);
assertTrue(wiki.getAttachmentFileHandleIds().size() == 1);
assertEquals(fileHandle.getId(), wiki.getAttachmentFileHandleIds().get(0));
assertEquals(markdownHandle.getId(), wiki.getMarkdownFileHandleId());
assertEquals("ITV2WikiPageTest.testAccessRequirementWikiRoundTrip", wiki.getTitle());
// Delete the wiki
adminSynapse.deleteV2WikiPage(key);
// Now try to get it
try{
synapse.getV2WikiPage(key);
fail("This should have failed as the wiki was deleted");
}catch(SynapseException e){
// expected;
}
}
@Test
public void testV2MethodsWithV1Models() throws IOException, SynapseException, JSONObjectAdapterException {
// Create V1 Wiki
WikiPage wiki = new WikiPage();
wiki.setAttachmentFileHandleIds(new ArrayList<String>());
wiki.getAttachmentFileHandleIds().add(fileHandle.getId());
wiki.setMarkdown("markdown");
wiki.setTitle("ITV2WikiPageTest");
wiki = synapse.createV2WikiPageWithV1(project.getId(), ObjectType.ENTITY, wiki);
assertNotNull(wiki);
assertNotNull(wiki.getAttachmentFileHandleIds());
assertEquals(1, wiki.getAttachmentFileHandleIds().size());
assertEquals(fileHandle.getId(), wiki.getAttachmentFileHandleIds().get(0));
WikiPageKey key = WikiPageKeyHelper.createWikiPageKey(project.getId(), ObjectType.ENTITY, wiki.getId());
toDelete.add(key);
// Store file handle before updating to delete later
V2WikiPage wikiV2Clone = synapse.getV2WikiPage(key);
fileHandlesToDelete.add(wikiV2Clone.getMarkdownFileHandleId());
Date firstModifiedOn = wiki.getModifiedOn();
// Add another file attachment and update the wiki
wiki.getAttachmentFileHandleIds().add(fileHandleTwo.getId());
wiki.setMarkdown("updated markdown");
wiki = synapse.updateV2WikiPageWithV1(key.getOwnerObjectId(), key.getOwnerObjectType(), wiki);
assertNotNull(wiki);
assertNotNull(wiki.getAttachmentFileHandleIds());
assertEquals(2, wiki.getAttachmentFileHandleIds().size());
assertTrue(!wiki.getModifiedOn().equals(firstModifiedOn));
assertEquals("updated markdown", wiki.getMarkdown());
// Store file handle that was created during update for deletion
V2WikiPage updatedWikiV2Clone = synapse.getV2WikiPage(key);
fileHandlesToDelete.add(updatedWikiV2Clone.getMarkdownFileHandleId());
// test get
wiki = synapse.getV2WikiPageAsV1(key);
V2WikiPage root = synapse.getV2RootWikiPage(project.getId(), ObjectType.ENTITY);
// this root is in the V2 model, but should have all the same fields as "wiki"
assertEquals(root.getAttachmentFileHandleIds().size(), wiki.getAttachmentFileHandleIds().size());
String markdown = synapse.downloadV2WikiMarkdown(key);
assertEquals(markdown, wiki.getMarkdown());
// test get first version
WikiPage firstWiki = synapse.getVersionOfV2WikiPageAsV1(key, new Long(0));
assertNotNull(firstWiki.getAttachmentFileHandleIds());
assertEquals(1, firstWiki.getAttachmentFileHandleIds().size());
assertEquals("markdown", firstWiki.getMarkdown());
}
@Test
public void testGetWikiPageAttachmentsAndMarkdown() throws Exception{
V2WikiPage wiki = new V2WikiPage();
wiki.setTitle("IT055WikiPageTest.testGetWikiPageAttachmentFileHandles");
wiki.setAttachmentFileHandleIds(new LinkedList<String>());
wiki.getAttachmentFileHandleIds().add(fileHandle.getId());
wiki.setMarkdownFileHandleId(markdownHandle.getId());
// Create it
wiki = synapse.createV2WikiPage(project.getId(), ObjectType.ENTITY, wiki);
assertNotNull(wiki);
WikiPageKey key = WikiPageKeyHelper.createWikiPageKey(project.getId(), ObjectType.ENTITY, wiki.getId());
toDelete.add(key);
// Since we expect the preview file handle to be returned we need to wait for it.
waitForPreviewToBeCreated(fileHandle);
// There should be two handles for this WikiPage, one for the origin file
// and the other for the preview.
FileHandleResults results = synapse.getV2WikiAttachmentHandles(key);
assertNotNull(results);
assertNotNull(results.getList());
assertEquals(markdownHandle.getId(), wiki.getMarkdownFileHandleId());
// there should be two things on the list, the original file and its preview.
assertEquals(2, results.getList().size());
FileHandle one = results.getList().get(0);
assertTrue(one instanceof S3FileHandle);
S3FileHandle handle = (S3FileHandle) one;
FileHandle two = results.getList().get(1);
assertTrue(two instanceof PreviewFileHandle);
PreviewFileHandle preview = (PreviewFileHandle) two;
assertTrue(handle.getPreviewId().equals(preview.getId()));
URL url = synapse.getV2WikiAttachmentTemporaryUrl(key, handle.getFileName());
assertNotNull(url);
File target = File.createTempFile("test", null);
target.deleteOnExit();
synapse.downloadV2WikiAttachment(key, handle.getFileName(), target);
assertEquals(imageFileMD5, MD5ChecksumHelper.getMD5Checksum(target));
url = synapse.getVersionOfV2WikiAttachmentTemporaryUrl(key, handle.getFileName(), 0L);
assertNotNull(url);
synapse.downloadVersionOfV2WikiAttachment(key, handle.getFileName(), 0L, target);
assertEquals(imageFileMD5, MD5ChecksumHelper.getMD5Checksum(target));
url = synapse.getV2WikiAttachmentPreviewTemporaryUrl(key, handle.getFileName());
assertNotNull(url);
synapse.downloadV2WikiAttachmentPreview(key, handle.getFileName(), target);
assertTrue(target.length()>0);
url = synapse.getVersionOfV2WikiAttachmentPreviewTemporaryUrl(key, handle.getFileName(), 0L);
assertNotNull(url);
synapse.downloadVersionOfV2WikiAttachmentPreview(key, handle.getFileName(), 0L, target);
assertTrue(target.length()>0);
// Update wiki with another file handle
wiki.getAttachmentFileHandleIds().add(fileHandleTwo.getId());
wiki = synapse.updateV2WikiPage(key.getOwnerObjectId(), key.getOwnerObjectType(), wiki);
// Since we expect the preview file handle to be returned we need to wait for it.
waitForPreviewToBeCreated(fileHandleTwo);
assertNotNull(wiki);
assertNotNull(wiki.getAttachmentFileHandleIds());
assertEquals(2, wiki.getAttachmentFileHandleIds().size());
FileHandleResults resultsUpdated = synapse.getV2WikiAttachmentHandles(key);
assertEquals(4, resultsUpdated.getList().size());
// Getting first version file handles should return two.
FileHandleResults oldResults = synapse.getVersionOfV2WikiAttachmentHandles(key, new Long(0));
assertEquals(2, oldResults.getList().size());
}
/**
* Wait for a preview to be generated for the given file handle.
* @throws InterruptedException
* @throws SynapseException
*/
private void waitForPreviewToBeCreated(S3FileHandle fileHandle) throws InterruptedException,
SynapseException {
long start = System.currentTimeMillis();
while(fileHandle.getPreviewId() == null){
System.out.println("Waiting for a preview file to be created");
Thread.sleep(1000);
assertTrue("Timed out waiting for a preview to be created",(System.currentTimeMillis()-start) < MAX_WAIT_MS);
fileHandle = (S3FileHandle) synapse.getRawFileHandle(fileHandle.getId());
}
}
}
|
package org.intermine.web.logic.profile;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionMessage;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.BagState;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.ProfileManager;
import org.intermine.api.profile.ProfileManager.ApiPermission;
import org.intermine.api.profile.SavedQuery;
import org.intermine.api.util.NameUtil;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.intermine.ObjectStoreWriterInterMineImpl;
import org.intermine.sql.DatabaseUtil;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.struts.InterMineAction;
/**
* @author Xavier Watkins
*
*
* Abstract class containing the methods for login in and copying current
* history, bags,... into profile.
*
*/
public abstract class LoginHandler extends InterMineAction
{
private static final Logger LOG = Logger.getLogger(LoginHandler.class);
/**
* Log-in a user.
* @param request The HttpServletRequest
* @param username The username
* @param password The password
* @return the map containing the renamed bags the user created before they were logged in
*/
public Map<String, String> doLogin(HttpServletRequest request,
String username, String password) {
Map<String, String> renamedBags = doStaticLogin(request, username, password);
HttpSession session = request.getSession();
ProfileManager pm = SessionMethods.getInterMineAPI(session).getProfileManager();
Profile profile = pm.getProfile(username);
InterMineAPI im = SessionMethods.getInterMineAPI(session);
if (im.getBagManager().isAnyBagNotCurrentOrUpgrading(profile)) {
recordError(new ActionMessage("login.upgradeListStarted"), request);
} else if (im.getBagManager().isAnyBagToUpgrade(profile)) {
recordError(new ActionMessage("login.upgradeListManually"), request);
}
return renamedBags;
}
/**
* Merge two profiles together. This is mainly of use when a new user registers and we need
* to save their current anonymous session into their new profile.
* @param fromProfile The profile to take information from.
* @param toProfile The profile to merge into.
* @return A map of bags, from old name to new name.
*/
public static Map<String, String> mergeProfiles(Profile fromProfile, Profile toProfile) {
Map<String, SavedQuery> mergeQueries = Collections.emptyMap();
Map<String, InterMineBag> mergeBags = Collections.emptyMap();
if (fromProfile != null) {
mergeQueries = fromProfile.getHistory();
mergeBags = fromProfile.getSavedBags();
}
// Merge in anonymous query history
for (SavedQuery savedQuery : mergeQueries.values()) {
toProfile.saveHistory(savedQuery);
}
// Merge anonymous bags
Map<String, String> renamedBags = new HashMap<String, String>();
for (Map.Entry<String, InterMineBag> entry : mergeBags.entrySet()) {
InterMineBag bag = entry.getValue();
// Make sure the userId gets set to be the profile one
try {
bag.setProfileId(toProfile.getUserId());
String name = NameUtil.validateName(toProfile.getSavedBags().keySet(),
entry.getKey());
if (!entry.getKey().equals(name)) {
renamedBags.put(entry.getKey(), name);
}
bag.setName(name);
toProfile.saveBag(name, bag);
} catch (ObjectStoreException iex) {
throw new RuntimeException(iex.getMessage());
}
}
return renamedBags;
}
/**
* Main log-in logic.
* @param request The current request.
* @param username The current user's login name.
* @param password The current user's password.
* @return A map of renamed-bags from old to new name.
*/
public static Map<String, String> doStaticLogin(HttpServletRequest request,
String username, String password) {
// Merge current history into loaded profile
Profile currentProfile = SessionMethods.getProfile(request.getSession());
HttpSession session = request.getSession();
Profile profile = setUpProfile(session, username, password);
Map<String, String> renamedBags = new HashMap<String, String>();
if (currentProfile != null && StringUtils.isEmpty(currentProfile.getUsername())) {
// The current profile was for an anonymous guest.
renamedBags = mergeProfiles(currentProfile, profile);
}
return renamedBags;
}
/**
* Initialises a profile for the current user based on their user name and password.
*
* @param session HTTP session
* @param username user name
* @param password password
* @return profile, fully ready to use.
*/
public static Profile setUpProfile(HttpSession session, String username, String password) {
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile;
ProfileManager pm = SessionMethods.getInterMineAPI(session).getProfileManager();
if (pm.hasProfile(username)) {
profile = pm.getProfile(username, password, im.getClassKeys());
} else {
throw new LoginException("There is no profile for " + username);
}
return setUpProfile(session, profile);
}
public static void setUpPermission(InterMineAPI api,
ApiPermission permission) {
final ProfileManager pm = api.getProfileManager();
final Profile profile = permission.getProfile();
final String userName = profile.getUsername();
if (userName != null && userName.equals(pm.getSuperuser())) {
permission.addRole("SUPERUSER");
}
if (!api.getBagManager().isAnyBagInState(profile, BagState.UPGRADING)) {
Runnable upgrade = new UpgradeBagList(profile, api.getBagQueryRunner());
runBagUpgrade(upgrade, api, profile);
}
}
private static void runBagUpgrade(Runnable procedure, InterMineAPI api,
Profile profile) {
Connection con = null;
try {
con = ((ObjectStoreWriterInterMineImpl) api.getProfileManager()
.getProfileObjectStoreWriter()).getDatabase()
.getConnection();
if (api.getBagManager().isAnyBagNotCurrent(profile)
&& !DatabaseUtil.isBagValuesEmpty(con)) {
Thread upgrade = new Thread(procedure);
upgrade.setDaemon(true);
upgrade.start();
}
} catch (SQLException sqle) {
LOG.error("Problems retrieving the connection", sqle);
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException sqle) {
}
}
}
/**
* Sets up a profile ready for a session in InterMine.
*
* @param session http session
* @param profile the user's profile (possibly anonymous and temporary)
* @return profile The profile all cleaned up and good to go.
*/
public static Profile setUpProfile(HttpSession session, Profile profile) {
SessionMethods.setProfile(session, profile);
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
if (profile.isSuperuser()) {
session.setAttribute(Constants.IS_SUPERUSER, Boolean.TRUE);
}
Runnable upgrade = new UpgradeBagList(profile, im.getBagQueryRunner());
runBagUpgrade(upgrade, im, profile);
return profile;
}
private static final class LoginException extends RuntimeException
{
/**
* Default serial id.
*/
private static final long serialVersionUID = 1L;
private LoginException() {
super();
}
private LoginException(String message) {
super(message);
}
}
}
|
package com.oculusinfo.tile.rendering.transformations.combine;
import com.oculusinfo.binning.TilePyramid;
import com.oculusinfo.binning.io.PyramidIO;
import com.oculusinfo.binning.io.serialization.TileSerializer;
import com.oculusinfo.factory.ConfigurableFactory;
import com.oculusinfo.factory.ConfigurationException;
import com.oculusinfo.factory.properties.JSONProperty;
import com.oculusinfo.factory.properties.StringProperty;
import com.oculusinfo.factory.providers.FactoryProvider;
import com.oculusinfo.tile.rendering.transformations.tile.*;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Factory class to create the standard types of Tile Combiners
*
*/
public class TileCombinerFactory extends ConfigurableFactory<TileCombiner<?>> {
public static final List<String> DATA_PATH = Collections.unmodifiableList(Arrays.asList("data"));
public static final List<String> PYRAMID_IO_PATH = Collections.unmodifiableList( Arrays.asList( "data","pyramidio" ) );
public static final List<String> SERIALIZER_PATH = Collections.unmodifiableList( Arrays.asList( "data","serializer" ) );
public static StringProperty TILE_COMBINER_TYPE = new StringProperty("type",
"The type of Combiner desired.",
"identity");
public static final StringProperty DATA_ID = new StringProperty("id",
"The ID of the data source of the layer; exact format depends on how the layer is stored.",
null);
// There is no way to produce a Class<TileTransformer<?>> directly; the best one can do is fake it through erasure.
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Class<TileCombiner<?>> getFactoryClass () {
return (Class) TileCombiner.class;
}
public TileCombinerFactory(FactoryProvider<PyramidIO> pyramidIOFactoryProvider,
FactoryProvider<TileSerializer<?>> serializationFactoryProvider,
ConfigurableFactory<?> parent,
List<String> path) {
this(null, pyramidIOFactoryProvider, serializationFactoryProvider, parent, path);
}
public TileCombinerFactory(String name,
FactoryProvider<PyramidIO> pyramidIOFactoryProvider,
FactoryProvider<TileSerializer<?>> serializationFactoryProvider,
ConfigurableFactory<?> parent,
List<String> path) {
super(name, getFactoryClass(), parent, path);
addProperty(TILE_COMBINER_TYPE);
addProperty(DATA_ID, DATA_PATH);
addChildFactory( pyramidIOFactoryProvider.createFactory(this, PYRAMID_IO_PATH) );
addChildFactory( serializationFactoryProvider.createFactory(this, SERIALIZER_PATH) );
}
@Override
protected TileCombiner<?> create () throws ConfigurationException {
String transformerTypes = getPropertyValue(TILE_COMBINER_TYPE);
if ("normalize".equals(transformerTypes)) {
try {
PyramidIO pyramidIO = produce( PyramidIO.class );
TileSerializer<?> serializer = produce( TileSerializer.class );
String dataId = getPropertyValue(DATA_ID);
return new NormalizeTileCombiner(pyramidIO, serializer, dataId);
} catch (Exception e) {
return null;
}
} else { // 'identity' or none passed in will give the default transformer
return new IdentityTileCombiner();
}
}
}
|
package edu.cornell.mannlib.vitro.utilities.revisioninfo;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;
import edu.cornell.mannlib.vitro.utilities.revisioninfo.ProcessRunner.ProcessException;
/**
* Get release and revision information to display on screen. Put this
* information into a single line and append it to the specified file.
*
* Ask Subversion for the information. If Subversion is available, and if this
* is a working directory, then we can build the info from the responses we get
* from "svn info" and "svnversion".
*
* If that doesn't work, read the information from the "revisionInfo" file in
* the product directory. Presumably, that file was created when the source was
* exported from Subversion.
*
* If that doesn't work either, return something like this:
* "productName ~ unknown ~ unknown"
*/
public class RevisionInfoBuilder {
/**
* Indicates a problem with the command-line arguments.
*/
private static class UsageException extends Exception {
UsageException(String message) {
super(message);
}
}
/**
* An object that holds the revision information and a message about how we
* obtained it.
*/
private static class Results {
final String message;
final String infoLine;
Results(String message, String infoLine) {
this.message = message;
this.infoLine = infoLine;
}
public String toString() {
return message + ": " + infoLine;
}
}
private static final String SVN_DIRECTORY_NAME = ".svn";
private static final String[] SVNVERSION_COMMAND = { "svnversion", "." };
private static final String[] SVN_INFO_COMMAND = { "svn", "info" };
private static final String INFO_LINE_DELIMITER = " ~ ";
private static final String REVISION_INFO_FILENAME = "revisionInfo";
private final String productName;
private final File productDirectory;
private final File resultFile;
private Results results;
public RevisionInfoBuilder(String[] args) throws UsageException {
if (args.length != 3) {
throw new UsageException(
"RevisionInfoBuilder requires 3 arguments, not "
+ args.length);
}
productName = args[0];
productDirectory = new File(args[1]);
resultFile = new File(args[2]);
if (!productDirectory.isDirectory()) {
throw new UsageException("Directory '"
+ productDirectory.getAbsolutePath() + "' does not exist.");
}
if (!resultFile.getParentFile().exists()) {
throw new UsageException("Result file '"
+ resultFile.getAbsolutePath()
+ "' does not exist, and we can't create it "
+ "because it's parent directory doesn't exist either.");
}
}
private void buildInfo() {
results = buildInfoFromSubversion();
if (results == null) {
results = buildInfoFromFile();
}
if (results == null) {
results = buildDummyInfo();
}
}
private Results buildInfoFromSubversion() {
if (!isThisASubversionWorkspace()) {
System.out.println("Not a Subversion workspace");
return null;
}
String release = assembleReleaseNameFromSubversion();
if (release == null) {
System.out.println("Couldn't get release name from Subversion");
return null;
}
String revision = obtainRevisionLevelFromSubversion();
if (revision == null) {
System.out.println("Couldn't get revision level from Subversion");
return null;
}
return new Results("Info from Subversion", buildLine(release, revision));
}
private boolean isThisASubversionWorkspace() {
File svnDirectory = new File(productDirectory, SVN_DIRECTORY_NAME);
return svnDirectory.isDirectory();
}
private String assembleReleaseNameFromSubversion() {
String infoResponse = runSubProcess(SVN_INFO_COMMAND);
return new InfoResponseParser(infoResponse).parse();
}
private String obtainRevisionLevelFromSubversion() {
String response = runSubProcess(SVNVERSION_COMMAND);
return (response == null) ? null : response.trim();
}
private String runSubProcess(String[] cmdArray) {
List<String> command = Arrays.asList(cmdArray);
try {
ProcessRunner runner = new ProcessRunner();
runner.setWorkingDirectory(productDirectory);
runner.run(command);
int rc = runner.getReturnCode();
if (rc != 0) {
throw new ProcessRunner.ProcessException("Return code from "
+ command + " was " + rc);
}
String output = runner.getStdOut();
// System.err.println(command + " response was '" + output + "'");
return output;
} catch (ProcessException e) {
return null;
}
}
private Results buildInfoFromFile() {
try {
File revisionInfoFile = new File(productDirectory,
REVISION_INFO_FILENAME);
BufferedReader reader = new BufferedReader(new FileReader(
revisionInfoFile));
String release = reader.readLine();
if (release == null) {
throw new EOFException("No release line in file.");
}
String revision = reader.readLine();
if (revision == null) {
throw new EOFException("No revision line in file.");
}
return new Results("Info from file", buildLine(release, revision));
} catch (IOException e) {
System.out.println("No information from file: " + e);
return null;
}
}
private Results buildDummyInfo() {
String line = buildLine(null, null);
return new Results("Using dummy info", line);
}
private String buildLine(String release, String revision) {
if (release == null) {
release = "unknown";
}
if (revision == null) {
revision = "unknown";
}
return productName + INFO_LINE_DELIMITER + release.trim()
+ INFO_LINE_DELIMITER + revision.trim();
}
private void writeLine() throws IOException {
Writer writer = null;
writer = new FileWriter(resultFile, true);
writer.write(results.infoLine + "\n");
writer.close();
System.out.println(results);
}
public static void main(String[] args) {
try {
RevisionInfoBuilder builder = new RevisionInfoBuilder(args);
builder.buildInfo();
builder.writeLine();
} catch (UsageException e) {
System.err.println(e);
System.err.println("usage: RevisionInfoBuilder [product_name] "
+ "[product_directory] [output_file]");
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
package uk.ac.ebi.atlas.search.analyticsindex.differential;
import autovalue.shaded.com.google.common.common.collect.Maps;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.collect.TreeMultimap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.ReadContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import uk.ac.ebi.atlas.model.ExperimentType;
import uk.ac.ebi.atlas.profiles.differential.viewmodel.FoldChangeRounder;
import uk.ac.ebi.atlas.trader.ContrastTrader;
import uk.ac.ebi.atlas.trader.ExperimentTrader;
import uk.ac.ebi.atlas.utils.ColourGradient;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.*;
@Named
public class DifferentialAnalyticsFacetsReader {
private final ExperimentTrader experimentTrader;
private final ContrastTrader contrastTrader;
private final FoldChangeRounder foldChangeRounder;
private static final String[] FACET_FIELDS = {"kingdom", "species", "experimentType", "factors", "numReplicates", "regulation"};
private static final String DOCS_PATH = "$.response.docs[*]";
private static final String EXPERIMENT_TYPE_FIELD = "experimentType";
private static final String EXPERIMENT_ACCESSION_FIELD = "experimentAccession";
private static final String CONTRAST_ID_FIELD = "contrastId";
private static final String LOG2_FOLD_CHANGE_FIELD = "foldChange";
private final ColourGradient colourGradient;
@Inject
public DifferentialAnalyticsFacetsReader(ExperimentTrader experimentTrader, ContrastTrader contrastTrader, FoldChangeRounder foldChangeRounder, ColourGradient colourGradient) {
this.experimentTrader = experimentTrader;
this.contrastTrader = contrastTrader;
this.foldChangeRounder = foldChangeRounder;
this.colourGradient = colourGradient;
}
public String extractResultsAsJson(String solrResponseAsJson) {
Map<String, Object> resultsWithLevels = new HashMap<>(3);
double minUpLevel = Double.POSITIVE_INFINITY;
double maxUpLevel = 0.0;
double minDownLevel = Double.NEGATIVE_INFINITY;
double maxDownLevel = 0.0;
List<Map<String, Object>> filteredDocuments = Lists.newArrayList();
TreeMultimap<String, String> experimentContrastMap = TreeMultimap.create();
Configuration jsonPathConfiguration = Configuration.defaultConfiguration().addOptions(Option.ALWAYS_RETURN_LIST);
ReadContext jsonReadContext = JsonPath.using(jsonPathConfiguration).parse(solrResponseAsJson);
List<Map<String, Object>> documents = jsonReadContext.read(DOCS_PATH);
if(!documents.isEmpty()) {
Map<String, Set<String>> commonFacetItems = new HashMap<>();
for (String facetField : FACET_FIELDS) {
commonFacetItems.put(facetField, stringOrStringCollectionAsSet(documents.get(0).get(facetField)));
}
for (Map<String, Object> document : documents) {
String experimentAccession = (String) document.get(EXPERIMENT_ACCESSION_FIELD);
String contrastId = (String) document.get(CONTRAST_ID_FIELD);
if (experimentContrastMap.put(experimentAccession, contrastId)) {
intersectMaps(commonFacetItems, document);
ExperimentType experimentType = ExperimentType.get((String) document.get(EXPERIMENT_TYPE_FIELD));
Object foldChangeSymbol = document.get(LOG2_FOLD_CHANGE_FIELD);
double foldChange = foldChangeSymbol instanceof Double ? (double) foldChangeSymbol : Double.parseDouble((String) foldChangeSymbol);
document.put("foldChange", foldChange);
document.put("comparison", contrastTrader.getContrastFromCache(experimentAccession, experimentType, contrastId).getDisplayName());
document.put("experimentName", experimentTrader.getExperimentFromCache(experimentAccession, experimentType).getDescription());
if (foldChange > 0.0) {
minUpLevel = Math.min(minUpLevel, foldChange);
maxUpLevel = Math.max(maxUpLevel, foldChange);
} else {
minDownLevel = Math.max(minDownLevel, foldChange);
maxDownLevel = Math.min(maxDownLevel, foldChange);
}
filteredDocuments.add(document);
}
}
for (Map<String, Object> document : filteredDocuments) {
double foldChange = (Double) document.get("foldChange");
String colour = foldChange > 0.0 ? colourGradient.getGradientColour(foldChange, minUpLevel, maxUpLevel, "pink", "red") : colourGradient.getGradientColour(foldChange, minDownLevel, maxDownLevel, "lightGray", "blue");
document.put("colour", colour);
document.put("foldChange", foldChangeRounder.format(foldChange));
}
resultsWithLevels.put("maxDownLevel", foldChangeRounder.format(maxDownLevel));
resultsWithLevels.put("minDownLevel", foldChangeRounder.format(minDownLevel));
resultsWithLevels.put("minUpLevel", foldChangeRounder.format(minUpLevel));
resultsWithLevels.put("maxUpLevel", foldChangeRounder.format(maxUpLevel));
String[] keySet = commonFacetItems.keySet().toArray(new String[commonFacetItems.keySet().size()]);
for (String facetField : keySet) {
Set<String> items = commonFacetItems.remove(facetField);
commonFacetItems.put(FacetFieldMapConverter.get(facetField), items);
}
resultsWithLevels.put("commonFacetItems", commonFacetItems);
}
resultsWithLevels.put("results", filteredDocuments);
Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
return gson.toJson(resultsWithLevels);
}
private void intersectMaps(Map<String, Set<String>> thisMap, Map<String, Object> document) {
for (String key : thisMap.keySet()) {
if (!thisMap.get(key).isEmpty()) {
Set<String> otherMapValueAsStringSet = stringOrStringCollectionAsSet(document.get(key));
thisMap.get(key).retainAll(otherMapValueAsStringSet);
}
}
}
private Set<String> stringOrStringCollectionAsSet(Object stringOrStringCollection) {
Set<String> stringSet = Sets.newHashSet();
if (stringOrStringCollection instanceof String) {
stringSet.add((String) stringOrStringCollection);
} else if (stringOrStringCollection instanceof Collection) {
for (Object o : (Collection) stringOrStringCollection) {
if (o instanceof String) {
stringSet.add((String) o);
}
}
}
return stringSet;
}
public String generateFacetsTreeJson(String solrResponseAsJson) {
JsonObject facets = new JsonObject();
ReadContext jsonReadContext = JsonPath.parse(solrResponseAsJson);
for (String facetField : FACET_FIELDS) {
JsonArray facet = new JsonArray();
List<Object> facetFieldValues = jsonReadContext.read("$.." + facetField + "..val");
for (Object facetFieldValue : facetFieldValues) {
JsonObject facetItem = new JsonObject();
facetItem.addProperty("name", facetFieldValue.toString());
if(facetField.equals("experimentType")) {
facetItem.addProperty("value", ExperimentsTypeMapConverter.get(facetFieldValue.toString()));
} else {
facetItem.addProperty("value", facetFieldValue.toString().toLowerCase());
}
facet.add(facetItem);
}
facets.add(FacetFieldMapConverter.get(facetField), facet);
}
return facets.toString();
}
protected static class ExperimentsTypeMapConverter {
private static final Logger LOGGER = LogManager.getLogger(ExperimentsTypeMapConverter.class);
private static final Map<String,String> EXPERIMENTS_TYPE_MAP = ImmutableMap.<String, String>builder()
.put("rnaseq_mrna_baseline", "RNA-seq mRNA baseline")
.put("rnaseq_mrna_differential", "RNA-seq mRNA differential")
.put("proteomics_baseline", "proteomics baseline")
.put("microarray_1colour_microrna_differential", "microarray 1-colour microRNA differential")
.put("microarray_1colour_mrna_differential", "microarray 1-colour mRNA differential")
.put("microarray_2colour_mrna_differential", "microarray 2-colour mRNA differential")
.build();
public static String get(String type) {
if(EXPERIMENTS_TYPE_MAP.get(type) != null) {
return EXPERIMENTS_TYPE_MAP.get(type);
} else {
LOGGER.warn(String.format("Experiment type not found %s", type));
return type;
}
}
}
protected static class FacetFieldMapConverter {
private static final Logger LOGGER = LogManager.getLogger(FacetFieldMapConverter.class);
private static final Map<String,String> FACET_FIELDS_MAP = ImmutableMap.<String, String>builder()
.put("kingdom", "kingdom")
.put("species", "species")
.put("experimentType", "experiment type")
.put("factors", "experimental variables")
.put("numReplicates", "number of replicates")
.put("regulation", "regulation")
.build();
public static String get(String type) {
if(FACET_FIELDS_MAP.get(type) != null) {
return FACET_FIELDS_MAP.get(type);
} else {
LOGGER.warn(String.format("Facet field not found %s", type));
return type;
}
}
}
}
|
package won.utils.goals.instantiation;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.jena.query.*;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFFormat;
import org.apache.jena.shared.NotFoundException;
import org.junit.Assert;
import org.junit.Test;
import won.protocol.model.Coordinate;
import won.protocol.util.DefaultNeedModelWrapper;
import won.protocol.util.NeedModelWrapper;
import won.utils.goals.GoalInstantiationProducer;
import won.utils.goals.GoalInstantiationResult;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Collection;
import java.util.LinkedList;
public class GoalInstantiationTest {
private static final String baseFolder = "/won/utils/goals/instantiation/";
@Test
public void example1_allInfoInTwoGoals() throws IOException {
Dataset need1 = loadDataset(baseFolder + "ex1_need.trig");
Dataset need2 = loadDataset(baseFolder + "ex1_need_debug.trig");
Dataset conversation = loadDataset(baseFolder + "ex1_conversation.trig");
GoalInstantiationProducer goalInstantiation = new GoalInstantiationProducer(need1, need2, conversation, "http:
Collection<GoalInstantiationResult> results = goalInstantiation.createAllGoalCombinationInstantiationResults();
// instantiation of combined goals must be conform
Assert.assertEquals(1, results.size());
System.out.println(results.iterator().next().toString());
Assert.assertTrue(results.iterator().next().isConform());
// instantiation of goal of need1 fails cause driver is missing
NeedModelWrapper needWrapper1 = new NeedModelWrapper(need1);
Resource goal = needWrapper1.getGoals().iterator().next();
GoalInstantiationResult result = goalInstantiation.findInstantiationForGoal(goal);
System.out.println(result.toString());
Assert.assertFalse(result.isConform());
Assert.assertEquals("hasDriver", result.getShaclReportWrapper().getValidationResults().iterator().next().getResultPath().getLocalName());
// instantiation of goal of need2 fails cause 3 attributes are missing: location, time, client
NeedModelWrapper needWrapper2 = new NeedModelWrapper(need2);
goal = needWrapper2.getGoals().iterator().next();
result = goalInstantiation.findInstantiationForGoal(goal);
System.out.println(result.toString());
Assert.assertFalse(result.isConform());
Assert.assertEquals(3, result.getShaclReportWrapper().getValidationResults().size());
}
@Test
public void example2_allInfoInTwoGoalsAndMessage() throws IOException {
Dataset need1 = loadDataset(baseFolder + "ex2_need.trig");
Dataset need2 = loadDataset(baseFolder + "ex2_need_debug.trig");
Dataset conversationWithoutPickupTime = loadDataset(baseFolder + "ex1_conversation.trig");
Dataset conversationWithPickupTime = loadDataset(baseFolder + "ex2_conversation.trig");
// this conversation doas not contain the missing pickup time info so the goals cannot be fulfilled
GoalInstantiationProducer goalInstantiation = new GoalInstantiationProducer(need1, need2, conversationWithoutPickupTime, "http:
Collection<GoalInstantiationResult> results = goalInstantiation.createAllGoalCombinationInstantiationResults();
Assert.assertEquals(1, results.size());
System.out.println(results.iterator().next().toString());
Assert.assertFalse(results.iterator().next().isConform());
// this conversation contains the missing pickup info so the goals can be fulfilled
goalInstantiation = new GoalInstantiationProducer(need1, need2, conversationWithPickupTime, "http:
results = goalInstantiation.createAllGoalCombinationInstantiationResults();
Assert.assertEquals(1, results.size());
System.out.println(results.iterator().next().toString());
Assert.assertTrue(results.iterator().next().isConform());
// instantiation of goal of need1 fails cause driver is missing
NeedModelWrapper needWrapper1 = new NeedModelWrapper(need1);
Resource goal = needWrapper1.getGoals().iterator().next();
GoalInstantiationResult result = goalInstantiation.findInstantiationForGoal(goal);
System.out.println(result.toString());
Assert.assertFalse(result.isConform());
Assert.assertEquals("hasDriver", result.getShaclReportWrapper().getValidationResults().iterator().next().getResultPath().getLocalName());
// instantiation of goal of need2 fails cause 3 attributes are missing: location, time, client
NeedModelWrapper needWrapper2 = new NeedModelWrapper(need2);
goal = needWrapper2.getGoals().iterator().next();
result = goalInstantiation.findInstantiationForGoal(goal);
System.out.println(result.toString());
Assert.assertFalse(result.isConform());
Assert.assertEquals(3, result.getShaclReportWrapper().getValidationResults().size());
}
@Test
public void example3_multipleGoalsFulfilled() throws IOException {
Dataset need1 = loadDataset(baseFolder + "ex3_need.trig");
Dataset need2 = loadDataset(baseFolder + "ex3_need_debug.trig");
Dataset conversation = loadDataset(baseFolder + "ex3_conversation.trig");
GoalInstantiationProducer goalInstantiation = new GoalInstantiationProducer(need1, need2, conversation, "http:
Collection<GoalInstantiationResult> results = goalInstantiation.createAllGoalCombinationInstantiationResults();
// We have 4 and 2 goals so we expected 8 results
Assert.assertEquals(8, results.size());
// We expected three valid results
Collection<Model> validResults = new LinkedList<>();
for (GoalInstantiationResult result : results) {
if (result.isConform()) {
validResults.add(result.getInstanceModel());
}
}
for (Model valid : validResults) {
valid.write(System.out, "TRIG");
}
Assert.assertEquals(3, validResults.size());
}
@Test
public void example4_geoCoordinatesFulfilled() throws IOException {
Dataset need1 = loadDataset(baseFolder + "ex4_need.trig");
Dataset need2 = loadDataset(baseFolder + "ex4_need_debug.trig");
Dataset conversation = loadDataset(baseFolder + "ex4_conversation.trig");
GoalInstantiationProducer goalInstantiation = new GoalInstantiationProducer(need1, need2, conversation, "http:
Collection<GoalInstantiationResult> results = goalInstantiation.createAllGoalCombinationInstantiationResults();
// We have only one goal on each side so we expect only one result
Assert.assertEquals(1, results.size());
// We expect also one valid result
Collection<Model> validResults = new LinkedList<>();
for (GoalInstantiationResult result : results) {
if (result.isConform()) {
validResults.add(result.getInstanceModel());
}
}
Assert.assertEquals(1, validResults.size());
for (Model valid : validResults) {
valid.write(System.out, "TRIG");
}
}
@Test
public void example5_singleGoalsValidity() throws IOException {
// check that the goals from each need can be validated successfully without each other
Dataset need1 = loadDataset(baseFolder + "ex5_need.trig");
Dataset need2 = loadDataset(baseFolder + "ex5_need_debug.trig");
Dataset conversation = loadDataset(baseFolder + "ex5_conversation.trig");
GoalInstantiationProducer goalInstantiation = new GoalInstantiationProducer(need1, need2, conversation, "http:
Collection<GoalInstantiationResult> results = goalInstantiation.createAllGoalCombinationInstantiationResults();
NeedModelWrapper needWrapper1 = new NeedModelWrapper(need1);
Resource goal = needWrapper1.getGoals().iterator().next();
GoalInstantiationResult result = goalInstantiation.findInstantiationForGoal(goal);
Assert.assertTrue(result.isConform());
NeedModelWrapper needWrapper2 = new NeedModelWrapper(need2);
goal = needWrapper1.getGoals().iterator().next();
result = goalInstantiation.findInstantiationForGoal(goal);
Assert.assertTrue(result.isConform());
}
private static final String latLngPickupQuery = "prefix s: <http://schema.org/>\n" +
"prefix taxi: <http://example.org/taxi/> \n" +
"\n" +
"select ?lat ?lon\n" +
"\n" +
"where {\n" +
"\t?main a s:TravelAction;\n" +
" \t s:fromLocation ?location.\n" +
" \t?location a s:Place;\n" +
" s:geo ?geo.\n" +
" \t?geo a s:GeoCoordinates;\n" +
" s:latitude ?lat;\n" +
" s:longitude ?lon.\n" +
"}";
private static final String latLngDropoffQuery = "prefix s: <http://schema.org/>\n" +
"prefix taxi: <http://example.org/taxi/> \n" +
"\n" +
"select ?lat ?lon\n" +
"\n" +
"where {\n" +
"\t?main a s:TravelAction;\n" +
" \t s:toLocation ?location.\n" +
" \t?location a s:Place;\n" +
" s:geo ?geo.\n" +
" \t?geo a s:GeoCoordinates;\n" +
" s:latitude ?lat;\n" +
" s:longitude ?lon.\n" +
"}";
private static QuerySolution executeQuery(String queryString, Model payload) {
Query query = QueryFactory.create(queryString);
try(QueryExecution qexec = QueryExecutionFactory.create(query, payload)){
ResultSet resultSet = qexec.execSelect();
if (resultSet.hasNext()){
QuerySolution solution = resultSet.nextSolution();
return solution;
}
}
return null;
}
@Test
public void exampleTaxi_validity() throws IOException {
Dataset taxiOffer = loadDataset(baseFolder + "ex6_taxioffer.trig");
Dataset taxiDemand = loadDataset(baseFolder + "ex6_taxi.trig");
Dataset taxiDemandNoLoc = loadDataset(baseFolder + "ex6_taxi_noloc.trig");
Dataset taxiDemandTwoLoc = loadDataset(baseFolder + "ex6_taxi_twoloc.trig");
GoalInstantiationProducer goalInstantiation = new GoalInstantiationProducer(taxiOffer, taxiDemand, null, "http:
Collection<GoalInstantiationResult> results = goalInstantiation.createGoalInstantiationResultsForNeed1();
for(GoalInstantiationResult res : results) {
System.out.println("Result::::::::::::::::::::::::::::::"+res.isConform());
System.out.println(res.toString());
if(res.isConform()) {
Coordinate departureAddress = getAddress(loadSparqlQuery("/won/utils/goals/extraction/address/fromLocationQuery.sq"), res.getInstanceModel());
Coordinate destinationAddress = getAddress(loadSparqlQuery("/won/utils/goals/extraction/address/toLocationQuery.sq"), res.getInstanceModel());
Assert.assertEquals(departureAddress, new Coordinate(10.0f, 11.0f));
Assert.assertEquals(destinationAddress, new Coordinate(12.0f, 13.0f));
}
}
NeedModelWrapper needWrapper1 = new NeedModelWrapper(taxiOffer);
Resource goal = needWrapper1.getGoals().iterator().next();
GoalInstantiationResult result = goalInstantiation.findInstantiationForGoal(goal);
Assert.assertTrue(result.isConform());
goalInstantiation = new GoalInstantiationProducer(taxiOffer, taxiDemandNoLoc, null, "http:
results = goalInstantiation.createGoalInstantiationResultsForNeed1();
for(GoalInstantiationResult res : results) {
Assert.assertFalse(res.isConform());
}
goalInstantiation = new GoalInstantiationProducer(taxiOffer, taxiDemandTwoLoc, null, "http:
results = goalInstantiation.createGoalInstantiationResultsForNeed1();
for(GoalInstantiationResult res : results) {
Assert.assertFalse(res.isConform());
}
}
@Test
public void exampleTaxiFakeLocation_validity() throws IOException {
Dataset taxiOffer = loadDataset(baseFolder + "ex7_taxioffer.trig");
Dataset taxiDemand = loadDataset(baseFolder + "ex7_taxi.trig");
GoalInstantiationProducer goalInstantiation = new GoalInstantiationProducer(taxiOffer, taxiDemand, null, "http:
Collection<GoalInstantiationResult> results = goalInstantiation.createGoalInstantiationResultsForNeed1();
for(GoalInstantiationResult res : results) {
res.getInstanceModel().write(System.out, "TRIG");
Assert.assertTrue(res.isConform());
Coordinate departureAddress = getAddress(loadSparqlQuery("/won/utils/goals/extraction/address/northWestCornerQuery.sq"), res.getInstanceModel());
Coordinate destinationAddress = getAddress(loadSparqlQuery("/won/utils/goals/extraction/address/southEastCornerQuery.sq"), res.getInstanceModel());
Assert.assertEquals(departureAddress, new Coordinate(48.218727f, 16.360141f));
Assert.assertEquals(destinationAddress, new Coordinate(48.218828f, 16.360241f));
}
NeedModelWrapper needWrapper1 = new NeedModelWrapper(taxiOffer);
Resource goal = needWrapper1.getGoals().iterator().next();
GoalInstantiationResult result = goalInstantiation.findInstantiationForGoal(goal);
Assert.assertTrue(result.isConform());
}
private Dataset loadDataset(String path) throws IOException {
InputStream is = null;
Dataset dataset = null;
try {
is = getClass().getResourceAsStream(path);
dataset = DatasetFactory.create();
RDFDataMgr.read(dataset, is, RDFFormat.TRIG.getLang());
} finally {
if (is != null) {
is.close();
}
}
return dataset;
}
private static String loadSparqlQuery(String filePath) {
InputStream is = GoalInstantiationTest.class.getResourceAsStream(filePath);
StringWriter writer = new StringWriter();
try {
IOUtils.copy(is, writer, Charsets.UTF_8);
} catch (IOException e) {
throw new NotFoundException("failed to load resource: " + filePath);
} finally {
try {
is.close();
} catch (Exception e) {
}
}
return writer.toString();
}
private static Coordinate getAddress(String query, Model payload){
QuerySolution solution = executeQuery(query, payload);
if(solution != null){
float lat = solution.getLiteral("lat").getFloat();
float lon = solution.getLiteral("lon").getFloat();
return new Coordinate(lat, lon);
}else{
return null;
}
}
}
|
package org.jscsi.target.conf;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.naming.ConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jscsi.target.connection.Connection;
import org.jscsi.target.connection.Session;
/**
* The OperationalTextConfiguration represents a standard system to work with
* iSCSI text parameter. The global used iSCSI parameters are stored within a
* xml file and will be loaded at startup. Connections and Sessions use these
* parameters to negotiate a working I-T-Nexus.
*
* @author Marcus Specht
*
*/
public class OperationalTextConfiguration {
/** The Log interface. */
private static final Log LOGGER = LogFactory
.getLog(OperationalTextConfiguration.class);
/**
* The relative path (to the project) of the main directory of all
* configuration files.
*/
private static final String CONFIGURATION_DIR = "conf/";
/**
* The file name of the XML Schema configuration file for the global
* settings.
*/
private static final String XSD_VALIDATE_FILE_ADRESS = CONFIGURATION_DIR
+ "iscsi.xsd";
/** The file name, which contains all global settings. */
private static final String XML_CONF_FILE_ADRESS = CONFIGURATION_DIR
+ "iscsi.xml";
private static final String CONFIG_TYPE_GLOBAL = "global";
private static final String CONFIG_TYPE_SESSION = "session";
private static final String CONFIG_TYPE_CONNECTION = "connection";
/** iSCSI's key value delimiter */
public static final String KEY_VALUE_DELIMITER = "=";
/** Delimiter between two key-value-pairs. */
public static final String PAIR_DELIMITER = "\0";
private static GlobalConfigParser globalParser;
private static OperationalTextConfiguration globalConfig;
private OperationalTextConfiguration parentConfiguration;
private final Set<OperationalTextKey> localConfig;
private final String configType;
private OperationalTextConfiguration(String configType,
OperationalTextConfiguration parentConfig) {
if (globalParser == null) {
globalParser = new GlobalConfigParser(XML_CONF_FILE_ADRESS,
XSD_VALIDATE_FILE_ADRESS);
}
if (globalConfig == null) {
globalConfig = parseGlobalConfig();
}
this.configType = configType;
localConfig = new HashSet<OperationalTextKey>();
}
private Set<OperationalTextKey> getConfigSet() {
return localConfig;
}
public void addKey(OperationalTextKey key) throws OperationalTextException {
if (!localConfig.contains(key)) {
localConfig.add(key);
} else {
throw new OperationalTextException(
"Confiduration already contains key: " + key.getKey());
}
}
/**
*
* @param key
* @return
* @throws ConfigurationException
*/
public OperationalTextKey getKey(String key)
throws OperationalTextException {
Iterator<OperationalTextKey> keys = getConfigSet().iterator();
while (keys.hasNext()) {
OperationalTextKey testedKey = keys.next();
if (testedKey.getKey().equals(key)) {
return testedKey;
}
}
throw new OperationalTextException(
"Configuration doesn't contain Key: " + key);
}
public void reset() {
if (!configType.equals(OperationalTextConfiguration.CONFIG_TYPE_GLOBAL)) {
localConfig.clear();
Iterator<OperationalTextKey> globalKeys = globalConfig
.getConfigSet().iterator();
while (globalKeys.hasNext()) {
OperationalTextKey newKey = globalKeys.next();
if (configType
.equals(OperationalTextConfiguration.CONFIG_TYPE_CONNECTION)) {
if (newKey.getScope().equals(
OperationalTextKey.SCOPE_CONNECTION_WIDE)) {
localConfig.add(OperationalTextKey.copy(newKey));
}
}
if (configType
.equals(OperationalTextConfiguration.CONFIG_TYPE_SESSION)) {
if (newKey.getScope().equals(
OperationalTextKey.SCOPE_SESSION_WIDE)) {
localConfig.add(OperationalTextKey.copy(newKey));
}
}
}
}
}
public void reset(String key) {
}
public void delete() {
}
public boolean equals(OperationalTextConfiguration config) {
if (this.getConfigSet().containsAll(config.getConfigSet())) {
return true;
}
return false;
}
public static OperationalTextConfiguration create(Session session) {
OperationalTextConfiguration result = new OperationalTextConfiguration(
OperationalTextConfiguration.CONFIG_TYPE_SESSION, globalConfig);
result.reset();
return result;
}
public static OperationalTextConfiguration create(Connection connection) {
OperationalTextConfiguration result = new OperationalTextConfiguration(
OperationalTextConfiguration.CONFIG_TYPE_CONNECTION, connection
.getReferencedSession().getConfiguration());
result.reset();
return result;
}
public static OperationalTextConfiguration getGlobalConfig() {
if (globalConfig == null) {
globalConfig = parseGlobalConfig();
}
return globalConfig;
}
public static OperationalTextConfiguration parseGlobalConfig() {
return globalParser.parse();
}
public static String toString(String key, String value) {
StringBuffer result = new StringBuffer();
result.append(key.toString());
result.append(KEY_VALUE_DELIMITER);
result.append(value.toString());
return result.toString();
}
public static String toString(OperationalTextConfiguration config) {
StringBuffer result = new StringBuffer();
Iterator<OperationalTextKey> pairs = config.getConfigSet().iterator();
while (pairs.hasNext()) {
result.append(toString(pairs.next().getKey(), pairs.next()
.getValue().getString()));
result.append(PAIR_DELIMITER);
}
result.deleteCharAt(result.length() - 1);
return result.toString();
}
private class GlobalConfigParser {
private final String XML_FILE_ADRESS;
private final String XSD_FILE_ADRESS;
public GlobalConfigParser(String xmlFileAdress, String xsdFileAdress) {
XML_FILE_ADRESS = xmlFileAdress;
XSD_FILE_ADRESS = xsdFileAdress;
}
public synchronized OperationalTextConfiguration parse() {
// don't forget to mark created globalConfig as GlOBAL_WIDE;
return null;
}
}
}
|
package org.jboss.weld.lite.extension.translator;
import jakarta.annotation.Priority;
import jakarta.enterprise.inject.build.compatible.spi.BuildCompatibleExtension;
import jakarta.enterprise.inject.build.compatible.spi.SkipIfPortableExtensionPresent;
import jakarta.interceptor.Interceptor;
import org.jboss.weld.lite.extension.translator.logging.LiteExtensionTranslatorLogger;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.stream.Collectors;
class ExtensionInvoker {
private static final int DEFAULT_PRIORITY = Interceptor.Priority.APPLICATION + 500;
private final Map<String, Class<?>> extensionClasses = new HashMap<>();
private final Map<Class<?>, Object> extensionClassInstances = new HashMap<>();
ExtensionInvoker() {
for (BuildCompatibleExtension extension : ServiceLoader.load(BuildCompatibleExtension.class)) {
Class<? extends BuildCompatibleExtension> extensionClass = extension.getClass();
SkipIfPortableExtensionPresent skip = extensionClass.getAnnotation(SkipIfPortableExtensionPresent.class);
if (skip != null) {
continue;
}
extensionClasses.put(extensionClass.getName(), extensionClass);
extensionClassInstances.put(extensionClass, extension);
}
}
// used from WFLY to initiate with already known collection of extensions
ExtensionInvoker(Collection<Class<? extends BuildCompatibleExtension>> extensions) {
for (Class<? extends BuildCompatibleExtension> extensionClass : extensions) {
SkipIfPortableExtensionPresent skip = extensionClass.getAnnotation(SkipIfPortableExtensionPresent.class);
if (skip != null) {
continue;
}
try {
BuildCompatibleExtension extensionInstance = extensionClass.getDeclaredConstructor().newInstance();
extensionClasses.put(extensionClass.getName(), extensionClass);
extensionClassInstances.put(extensionClass, extensionInstance);
} catch (ReflectiveOperationException e) {
throw LiteExtensionTranslatorLogger.LOG.unableToInstantiateObject(extensionClass, e.toString());
}
}
}
List<java.lang.reflect.Method> findExtensionMethods(Class<? extends Annotation> annotation) {
return extensionClasses.values()
.stream()
.flatMap(it -> Arrays.stream(it.getDeclaredMethods()))
.filter(it -> it.getAnnotation(annotation) != null)
.sorted((m1, m2) -> {
if (m1.equals(m2)) {
return 0;
}
int p1 = getExtensionMethodPriority(m1);
int p2 = getExtensionMethodPriority(m2);
// must _not_ return 0 if priorities are equal, because that isn't consistent
// with the `equals` method
return p1 < p2 ? -1 : 1;
})
.collect(Collectors.toList());
}
private int getExtensionMethodPriority(java.lang.reflect.Method method) {
Priority priority = method.getAnnotation(Priority.class);
if (priority != null) {
return priority.value();
}
return DEFAULT_PRIORITY;
}
void callExtensionMethod(java.lang.reflect.Method method, List<Object> arguments) throws ReflectiveOperationException {
Class<?>[] parameterTypes = new Class[arguments.size()];
for (int i = 0; i < parameterTypes.length; i++) {
Object argument = arguments.get(i);
Class<?> argumentClass = argument.getClass();
// beware of ordering! subtypes must precede supertypes
if (jakarta.enterprise.lang.model.declarations.ClassInfo.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.lang.model.declarations.ClassInfo.class;
} else if (jakarta.enterprise.lang.model.declarations.MethodInfo.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.lang.model.declarations.MethodInfo.class;
} else if (jakarta.enterprise.lang.model.declarations.FieldInfo.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.lang.model.declarations.FieldInfo.class;
} else if (jakarta.enterprise.inject.build.compatible.spi.ScannedClasses.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.inject.build.compatible.spi.ScannedClasses.class;
} else if (jakarta.enterprise.inject.build.compatible.spi.MetaAnnotations.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.inject.build.compatible.spi.MetaAnnotations.class;
} else if (jakarta.enterprise.inject.build.compatible.spi.ClassConfig.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.inject.build.compatible.spi.ClassConfig.class;
} else if (jakarta.enterprise.inject.build.compatible.spi.MethodConfig.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.inject.build.compatible.spi.MethodConfig.class;
} else if (jakarta.enterprise.inject.build.compatible.spi.FieldConfig.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.inject.build.compatible.spi.FieldConfig.class;
} else if (jakarta.enterprise.inject.build.compatible.spi.BeanInfo.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.inject.build.compatible.spi.BeanInfo.class;
} else if (jakarta.enterprise.inject.build.compatible.spi.ObserverInfo.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.inject.build.compatible.spi.ObserverInfo.class;
} else if (jakarta.enterprise.inject.build.compatible.spi.SyntheticComponents.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.inject.build.compatible.spi.SyntheticComponents.class;
} else if (jakarta.enterprise.inject.build.compatible.spi.Messages.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.inject.build.compatible.spi.Messages.class;
} else if (jakarta.enterprise.inject.build.compatible.spi.Types.class.isAssignableFrom(argumentClass)) {
parameterTypes[i] = jakarta.enterprise.inject.build.compatible.spi.Types.class;
} else {
// should never happen, internal error (or missing error handling) if it does
throw LiteExtensionTranslatorLogger.LOG.unexpectedMethodArgument(argument);
}
}
Class<?> extensionClass = extensionClasses.get(method.getDeclaringClass().getName());
Object extensionClassInstance = extensionClassInstances.get(extensionClass);
method.invoke(extensionClassInstance, arguments.toArray());
}
void clear() {
extensionClasses.clear();
extensionClassInstances.clear();
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Path2D;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.util.Objects;
import java.util.stream.IntStream;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.ColorUIResource;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
String[] columnNames = {"Name", "Comment"};
Object[][] data = {
{"test1.jpg", "11111"},
{"test1234.jpg", " "},
{"test15354.gif", "22222"},
{"t.png", "comment"},
{"33333.jpg", "123"},
{"4444444444444444.mpg", "test"},
{"5555555555555", ""},
{"test1.jpg", ""}
};
TableModel model = new DefaultTableModel(data, columnNames) {
@Override public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
@Override public boolean isCellEditable(int row, int column) {
return false;
}
};
JTable table = new FileListTable(model);
add(new JScrollPane(table));
setPreferredSize(new Dimension(320, 240));
}
// private static int getStringWidth(JTable table, int row, int column) {
// FontMetrics fm = table.getFontMetrics(table.getFont());
// Object o = table.getValueAt(row, column);
// return fm.stringWidth(o.toString()) + ICON_SIZE + 2 + 2;
// private static boolean isOnLabel(JTable table, Point pt, int row, int col) {
// Rectangle rect = table.getCellRect(row, col, true);
// rect.setSize(getStringWidth(table, row, col), rect.height);
// return(rect.contains(pt));
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class SelectedImageFilter extends RGBImageFilter {
// public SelectedImageFilter() {
// canFilterIndexColorModel = false;
@Override public int filterRGB(int x, int y, int argb) {
int r = (argb >> 16) & 0xFF;
int g = (argb >> 8) & 0xFF;
return (argb & 0xFF_00_00_FF) | ((r >> 1) << 16) | ((g >> 1) << 8);
// return (argb & 0xFF_FF_FF_00) | ((argb & 0xFF) >> 1);
}
}
class FileNameRenderer implements TableCellRenderer {
protected final Dimension dim = new Dimension();
private final JPanel renderer = new JPanel(new BorderLayout());
private final JLabel textLabel = new JLabel(" ");
private final JLabel iconLabel;
private final Border focusBorder = UIManager.getBorder("Table.focusCellHighlightBorder");
private final Border noFocusBorder;
private final ImageIcon icon;
private final ImageIcon selectedIcon;
protected FileNameRenderer(JTable table) {
Border b = UIManager.getBorder("Table.noFocusBorder");
if (Objects.isNull(b)) { // Nimbus???
Insets i = focusBorder.getBorderInsets(textLabel);
b = BorderFactory.createEmptyBorder(i.top, i.left, i.bottom, i.right);
}
noFocusBorder = b;
JPanel p = new JPanel(new BorderLayout()) {
@Override public Dimension getPreferredSize() {
return dim;
}
};
p.setOpaque(false);
renderer.setOpaque(false);
icon = new ImageIcon(getClass().getResource("wi0063-16.png"));
ImageProducer ip = new FilteredImageSource(icon.getImage().getSource(), new SelectedImageFilter());
selectedIcon = new ImageIcon(p.createImage(ip));
iconLabel = new JLabel(icon);
iconLabel.setBorder(BorderFactory.createEmptyBorder());
p.add(iconLabel, BorderLayout.WEST);
p.add(textLabel);
renderer.add(p, BorderLayout.WEST);
Dimension d = iconLabel.getPreferredSize();
dim.setSize(d);
table.setRowHeight(d.height);
}
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
textLabel.setFont(table.getFont());
textLabel.setText(Objects.toString(value, ""));
textLabel.setBorder(hasFocus ? focusBorder : noFocusBorder);
FontMetrics fm = table.getFontMetrics(table.getFont());
Insets i = textLabel.getInsets();
int width = iconLabel.getPreferredSize().width + fm.stringWidth(textLabel.getText()) + i.left + i.right;
int colWidth = table.getColumnModel().getColumn(column).getWidth();
dim.width = Math.min(width, colWidth);
if (isSelected) {
textLabel.setOpaque(true);
textLabel.setForeground(table.getSelectionForeground());
textLabel.setBackground(table.getSelectionBackground());
iconLabel.setIcon(selectedIcon);
} else {
textLabel.setOpaque(false);
textLabel.setForeground(table.getForeground());
textLabel.setBackground(table.getBackground());
iconLabel.setIcon(icon);
}
return renderer;
}
}
class FileListTable extends JTable {
private static final AlphaComposite ALPHA = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .1f);
private static final Color BAND_COLOR = makeColor(SystemColor.activeCaption);
private static final Path2D RUBBER_BAND = new Path2D.Double();
private transient RubberBandingListener rbl;
protected FileListTable(TableModel model) {
super(model);
}
@Override public void updateUI() {
// [JDK-6788475] Changing to Nimbus LAF and back doesn't reset look and feel of JTable completely - Java Bug System
// XXX: set dummy ColorUIResource
setSelectionForeground(new ColorUIResource(Color.RED));
setSelectionBackground(new ColorUIResource(Color.RED));
removeMouseMotionListener(rbl);
removeMouseListener(rbl);
setDefaultRenderer(Object.class, null);
super.updateUI();
rbl = new RubberBandingListener();
addMouseMotionListener(rbl);
addMouseListener(rbl);
putClientProperty("Table.isFileList", Boolean.TRUE);
setCellSelectionEnabled(true);
setIntercellSpacing(new Dimension());
setShowGrid(false);
setAutoCreateRowSorter(true);
setFillsViewportHeight(true);
TableCellRenderer r = new DefaultTableCellRenderer();
setDefaultRenderer(Object.class, (table, value, isSelected, hasFocus, row, column) ->
r.getTableCellRendererComponent(table, value, false, false, row, column));
TableColumn col = getColumnModel().getColumn(0);
col.setCellRenderer(new FileNameRenderer(this));
col.setPreferredWidth(200);
col = getColumnModel().getColumn(1);
col.setPreferredWidth(300);
}
@Override public String getToolTipText(MouseEvent e) {
Point pt = e.getPoint();
int row = rowAtPoint(pt);
int col = columnAtPoint(pt);
if (convertColumnIndexToModel(col) != 0 || row < 0 || row > getRowCount()) {
return null;
}
Rectangle rect = getCellRect2(this, row, col);
if (rect.contains(pt)) {
return getValueAt(row, col).toString();
}
return null;
}
@Override public void setColumnSelectionInterval(int index0, int index1) {
int idx = convertColumnIndexToView(0);
super.setColumnSelectionInterval(idx, idx);
}
protected Path2D getRubberBand() {
return RUBBER_BAND;
}
private class RubberBandingListener extends MouseAdapter {
private final Point srcPoint = new Point();
@Override public void mouseDragged(MouseEvent e) {
Point destPoint = e.getPoint();
Path2D rb = getRubberBand();
rb.reset();
rb.moveTo(srcPoint.x, srcPoint.y);
rb.lineTo(destPoint.x, srcPoint.y);
rb.lineTo(destPoint.x, destPoint.y);
rb.lineTo(srcPoint.x, destPoint.y);
rb.closePath();
clearSelection();
int col = convertColumnIndexToView(0);
int[] indices = IntStream.range(0, getModel().getRowCount())
.filter(i -> rb.intersects(getCellRect2(FileListTable.this, i, col)))
.toArray();
for (int i: indices) {
addRowSelectionInterval(i, i);
changeSelection(i, col, true, true);
}
repaint();
}
@Override public void mouseReleased(MouseEvent e) {
getRubberBand().reset();
repaint();
}
@Override public void mousePressed(MouseEvent e) {
srcPoint.setLocation(e.getPoint());
if (rowAtPoint(e.getPoint()) < 0) {
clearSelection();
repaint();
} else {
int index = rowAtPoint(e.getPoint());
Rectangle rect = getCellRect2(FileListTable.this, index, convertColumnIndexToView(0));
if (!rect.contains(e.getPoint())) {
clearSelection();
repaint();
}
}
}
}
// SwingUtilities2.pointOutsidePrefSize(...)
protected static Rectangle getCellRect2(JTable table, int row, int col) {
TableCellRenderer tcr = table.getCellRenderer(row, col);
Object value = table.getValueAt(row, col);
Component cell = tcr.getTableCellRendererComponent(table, value, false, false, row, col);
Dimension itemSize = cell.getPreferredSize();
Rectangle cellBounds = table.getCellRect(row, col, false);
cellBounds.width = itemSize.width;
return cellBounds;
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(SystemColor.activeCaption);
g2.draw(RUBBER_BAND);
g2.setComposite(ALPHA);
g2.setPaint(BAND_COLOR);
g2.fill(RUBBER_BAND);
g2.dispose();
}
// private int[] getIntersectedIndices(Path2D path) {
// TableModel model = getModel();
// List<Integer> list = new ArrayList<>(model.getRowCount());
// for (int i = 0; i < getRowCount(); i++) {
// if (path.intersects(getCellRect2(FileListTable.this, i, convertColumnIndexToView(0)))) {
// list.add(i);
// int[] il = new int[list.size()];
// for (int i = 0; i < list.size(); i++) {
// il[i] = list.get(i);
// return il;
public static Color makeColor(Color c) {
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
return r > g ? r > b ? new Color(r, 0, 0) : new Color(0, 0, b)
: g > b ? new Color(0, g, 0) : new Color(0, 0, b);
}
}
|
package am.app.mappingEngine.structuralMatchers.similarityFlooding;
import java.util.HashMap;
import java.util.Iterator;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import am.app.mappingEngine.AbstractMatcher;
import am.app.mappingEngine.AbstractMatcherParametersPanel;
import am.app.mappingEngine.SimilarityMatrix;
import am.app.mappingEngine.structuralMatchers.similarityFlooding.utils.PCGEdge;
import am.app.mappingEngine.structuralMatchers.similarityFlooding.utils.PCGEdgeData;
import am.app.mappingEngine.structuralMatchers.similarityFlooding.utils.PCGVertex;
import am.app.mappingEngine.structuralMatchers.similarityFlooding.utils.PCGVertexData;
import am.app.mappingEngine.structuralMatchers.similarityFlooding.utils.PairwiseConnectivityGraph;
import am.utility.DirectedGraphEdge;
import am.utility.Pair;
/**
* Similarity Flooding algorithm implementation.
* @author Michele Caci
*
*/
public class SimilarityFloodingMatcher extends AbstractMatcher {
private static final long serialVersionUID = -3749229483504509029L;
private static final boolean DEBUG_FLAG = true;
private boolean hasInput;
private PairwiseConnectivityGraph pcg;
public static final double MAX_PC = 1.0;
private enum Direction{ORIG2DEST, DEST2ORIG};
public SimilarityFloodingMatcher() {
super();
needsParam = true; // we need to display the parameters panel.
//setHasInput(false);
}
/**
* @param params_new
*/
public SimilarityFloodingMatcher(SimilarityFloodingMatcherParameters params_new) {
super(params_new);
}
@Override
public AbstractMatcherParametersPanel getParametersPanel() { return new SimilarityFloodingParametersPanel(); };
/**
* Similarity Flooding Algorithm.
* @see am.app.mappingEngine.AbstractMatcher#align(ArrayList<Node> sourceList, ArrayList<Node> targetList, alignType typeOfNodes)
* @author michele
* NOTE: we are using graphs instead of arrayList
*/
protected void align() throws Exception {
progressDisplay.clearReport();
// cannot align just one ontology (this is here to catch improper invocations)
if( sourceOntology == null ) throw new NullPointerException("sourceOntology == null");
if( targetOntology == null ) throw new NullPointerException("targetOntology == null");
progressDisplay.appendToReport("Creating Pairwise Connectivity Graph...");
createPairwiseConnectivityGraph();
if( DEBUG_FLAG ) System.out.println(pcg.toString());
progressDisplay.appendToReport("done.\n");
progressDisplay.appendToReport("Creating Induced Propagation Graph...");
createInducedPropagationGraph();
if( DEBUG_FLAG ) System.out.println(pcg.toString());
progressDisplay.appendToReport("done.\n");
/* TODO: make use of alignClass and alignProp in our code
if(alignClass && !this.isCancelled() ) {
ArrayList<Node> sourceClassList = sourceOntology.getClassesList();
ArrayList<Node> targetClassList = targetOntology.getClassesList();
classesMatrix = alignClasses(sourceClassList,targetClassList );
//classesMatrix.show();
}
if(alignProp && !this.isCancelled() ) {
ArrayList<Node> sourcePropList = sourceOntology.getPropertiesList();
ArrayList<Node> targetPropList = targetOntology.getPropertiesList();
propertiesMatrix = alignProperties(sourcePropList, targetPropList );
}
*/
}
/* PAIRWISE CONNECTIVITY GRAPH OPERATIONS */
/**
* This method creates the Pairwise Connectivity Graph.
*
* Given the graphs for the source and target ontologies, A and B respectively,
* and elements x, y in A and x', y' in B, we construct the PCG in this way:
*
* PCGVertex PCGVertex
* \/ \/
* ( (x, y) , p, (x', y') ) in PCG(A, B) <==> (x, p, x') in A and (y, p, y') in B
* /\
* PCGEdge
*/
protected void createPairwiseConnectivityGraph(){
pcg = new PairwiseConnectivityGraph();
OntModel localSource = sourceOntology.getModel();
OntModel localTarget = targetOntology.getModel();
StmtIterator sStmtIterator = localSource.listStatements();
StmtIterator tStmtIterator = localTarget.listStatements();
Statement sStmt = null;
Statement tStmt = null;
HashMap<RDFNode, HashMap<RDFNode, PCGVertex>> firstHashTable = new HashMap<RDFNode, HashMap<RDFNode, PCGVertex>>();
while(sStmtIterator.hasNext()){
sStmt = sStmtIterator.next();
while(tStmtIterator.hasNext()){
tStmt = tStmtIterator.next();
// condition where we add a new element in the pairwise connectivity graph:
// comparison of predicates
if(sStmt.getPredicate().equals(tStmt.getPredicate())){
if( ((SimilarityFloodingMatcherParameters)param).omitAnonymousNodes &&
( sStmt.getSubject().isAnon() || sStmt.getObject().isAnon() ||
tStmt.getSubject().isAnon() || tStmt.getObject().isAnon() ) ) {
// these nodes are anonymous
// parameter is set to not insert anonymous nodes
// do nothing
} else {
// check to see if we have a node already for the source vertex and for the target vertex.
PCGVertex sourcePCGVertex = getPCGVertex(firstHashTable, sStmt.getSubject(), tStmt.getSubject() );
PCGVertex targetPCGVertex = getPCGVertex(firstHashTable, sStmt.getObject(), tStmt.getObject() );
insertInPCG(sourcePCGVertex, // vertex
sStmt.getPredicate(), // edge
targetPCGVertex, // vertex
sStmt.getSubject(), tStmt.getSubject(), sStmt.getObject(), tStmt.getObject(), firstHashTable );
}
}
}
tStmtIterator = localTarget.listStatements();
}
// System.out.println(pcg.toString());
}
/**
* This method inserts a new "triple" in the PairwiseConnectivityGraph.
* A triple is a ( PCGVertex, PCGEdge, PCGVertex ).
*
* @param sourcePCGVertex (x, y)
* @param predicate p
* @param targetPCGVertex (x', y')
* @param sourceSubject x
* @param targetSubject y
* @param sourceObject x'
* @param targetObject y'
* @param firstHashTable
*/
private void insertInPCG(
PCGVertex sourcePCGVertex, Property predicate, PCGVertex targetPCGVertex,
RDFNode sourceSubject, RDFNode targetSubject, RDFNode sourceObject, RDFNode targetObject,
HashMap<RDFNode, HashMap<RDFNode, PCGVertex>> firstHashTable ) {
boolean sourceVertexCreated;
boolean targetVertexCreated;
if( sourcePCGVertex == null ) {
sourceVertexCreated = true; // we are creating a new sourcePCGVertex, make sure we insert it in the graph.
// the source PCGVertex does not exist, create it.
Pair<RDFNode, RDFNode> sourcePair = new Pair<RDFNode, RDFNode>(sourceSubject, targetSubject);
PCGVertexData vertexData = new PCGVertexData( sourcePair );
sourcePCGVertex = new PCGVertex(vertexData);
// add source vertex to the hash table.
HashMap<RDFNode, PCGVertex> secondHashTable = firstHashTable.get(sourceSubject);
if( secondHashTable == null ) {
// second hash table does not exist. create it.
secondHashTable = new HashMap<RDFNode, PCGVertex>();
// add it to the first hash table.
firstHashTable.put(sourceSubject, secondHashTable);
}
secondHashTable.put(targetSubject, sourcePCGVertex);
} else {
sourceVertexCreated = false; // the sourcePCGVertex exists already. do not insert it again into the graph.
}
if( targetPCGVertex == null ) {
targetVertexCreated = true; // we are creating a new targetPCGVertex, make sure we insert it in the graph.
// the target PCGVertex does not exist, create it.
Pair<RDFNode, RDFNode> targetPair = new Pair<RDFNode, RDFNode>(sourceObject, targetObject);
PCGVertexData vertexData = new PCGVertexData( targetPair );
targetPCGVertex = new PCGVertex(vertexData);
// add the target vertex to the hash table.
HashMap<RDFNode, PCGVertex> secondHashTable = firstHashTable.get(sourceObject);
if( secondHashTable == null ) {
// second hash table does not exist. create it.
secondHashTable = new HashMap<RDFNode, PCGVertex>();
// add it to the first hash table
firstHashTable.put(targetObject, secondHashTable);
}
secondHashTable.put(targetObject, targetPCGVertex);
} else {
targetVertexCreated = false; // the targetPCGVertex exists already. do not insert it again into the graph.
}
// create the edge and insert it into the graph.
PCGEdgeData edgeData = new PCGEdgeData(predicate);
PCGEdge pairEdge = new PCGEdge(sourcePCGVertex, targetPCGVertex, edgeData);
sourcePCGVertex.addOutEdge(pairEdge);
targetPCGVertex.addInEdge(pairEdge);
if( sourceVertexCreated ) pcg.insertVertex(sourcePCGVertex);
if( targetVertexCreated ) pcg.insertVertex(targetPCGVertex);
pcg.insertEdge(pairEdge);
}
/**
* Returns the PCGVertex associated with the sourceSubject and targetSubject.
* @param firstHashTable The first hashtable. (described in createPairwiseConnectivityGraph())
* @param sourceSubject
* @param targetSubject
* @return Returns null if no PCGVertex exists.
*/
private PCGVertex getPCGVertex(
HashMap<RDFNode, HashMap<RDFNode, PCGVertex>> firstHashTable,
RDFNode sourceSubject, RDFNode targetSubject) {
HashMap<RDFNode, PCGVertex> secondHashTable = firstHashTable.get(sourceSubject);
if( secondHashTable == null ) return null;
PCGVertex existingVertex = secondHashTable.get(targetSubject);
return existingVertex; // can be null
}
/**
* This method creates the Induced Propagation Graph.]
* NOTE! This is done in place using the Pairwise Connectivity Graph as the base.
* In other words, a new graph structure is NOT created. Two operations are done:
*
* 1) Existing edges (forward edges) are annotated with a propagation coefficient (edge weight).
* 2) Back edges are created and annotated with a propagation coefficient.
*
*/
protected void createInducedPropagationGraph(){
applyCoefficients();
createBackwardEdges();
}
/* INDUCED PROPAGATION GRAPH OPERATIONS */
public void applyCoefficients(){
Iterator<PCGVertex> iVert = pcg.vertices();
PCGVertex currentVert = null;
while(iVert.hasNext()){
currentVert = iVert.next();
// assigning outgoing propagation coefficients
HashMap<Property, Integer> counter = new HashMap<Property, Integer>();
Iterator<DirectedGraphEdge<PCGEdgeData, PCGVertexData>> iVEdge = currentVert.edgesOutIter();
PCGEdge currentEdge = null;
// counting phase
while(iVEdge.hasNext()){
currentEdge = (PCGEdge) iVEdge.next();
Property currentProp = currentEdge.getObject().getStProperty();
if( counter.containsKey(currentProp) ) {
Integer i = counter.get(currentProp);
i++;
} else {
counter.put(currentProp, new Integer(1) );
}
}
iVEdge = currentVert.edgesOutIter();
// dividing phase
while(iVEdge.hasNext()){
currentEdge = (PCGEdge) iVEdge.next();
Property currentProp = currentEdge.getObject().getStProperty();
currentEdge.getObject().setPropagationCoefficient(MAX_PC / counter.get(currentProp).doubleValue() );
}
}
}
public void createBackwardEdges(){
// System.out.println("anything");
Iterator<PCGVertex> iVert = pcg.vertices();
PCGVertex currentVert = null;
while(iVert.hasNext()){
// System.out.println("anything2");
currentVert = iVert.next();
// creating duplicate outgoing edges for ingoing ones
HashMap<Property, Integer> counter = new HashMap<Property, Integer>();
Iterator<DirectedGraphEdge<PCGEdgeData, PCGVertexData>> iVEdge = currentVert.edgesInIter();
PCGEdge currentEdge = null;
// counting phase
while(iVEdge.hasNext()){
currentEdge = (PCGEdge) iVEdge.next();
Property currentProp = currentEdge.getObject().getStProperty();
if( counter.containsKey(currentProp) ) {
Integer i = counter.get(currentProp);
i++;
} else {
counter.put(currentProp, new Integer(1) );
}
}
iVEdge = currentVert.edgesInIter();
// back-edge creation and weight assignment phase
while(iVEdge.hasNext()){
currentEdge = (PCGEdge) iVEdge.next();
// check if back-edge exists
if(checkEdge( (PCGVertex)currentEdge.getOrigin(), // neighbor (orig)
(PCGVertex)currentEdge.getDestination(), // current vertex (dest)
Direction.DEST2ORIG)
){
continue; // so far ineffective because it goes anyway to the next iteration
}
else{
Property currentProp = currentEdge.getObject().getStProperty();
double tmpPC = MAX_PC / counter.get(currentProp).doubleValue();
//adding new edge
pcg.insertEdge(new PCGEdge( (PCGVertex)currentEdge.getDestination(),
(PCGVertex)currentEdge.getOrigin(),
new PCGEdgeData(null, tmpPC)));
}
}
}
}
private void computeQuantities(){
}
/* SUPPORT FUNCTIONS */
private boolean checkEdge(PCGVertex o, PCGVertex d, Direction dir){
PCGVertex originVertex, destinatonVertex;
if(dir == Direction.ORIG2DEST){
originVertex = o;
destinatonVertex = d;
}
else{ // DEST2ORIG
originVertex = d;
destinatonVertex = o;
}
Iterator<DirectedGraphEdge<PCGEdgeData, PCGVertexData>> iVEdge = originVertex.edgesOutIter();
PCGEdge currentEdge = null;
while(iVEdge.hasNext()){
currentEdge = (PCGEdge) iVEdge.next();
if(currentEdge.getDestination().equals(destinatonVertex)){
System.out.println(currentEdge.getDestination() + " ---- " + destinatonVertex + "\n");
return true;
}
}
return false;
}
/**
* this function has to be called as soon as possible because this matcher needs some sort of input
*/
private void loadSimilarityMatrices(){
if(this.hasInput){
classesMatrix = inputMatchers.get(0).getClassesMatrix();
propertiesMatrix = inputMatchers.get(0).getPropertiesMatrix();
}
else{
// load classesMatrix
if(classesMatrix != null){
classesMatrix.fillMatrix(1.0);
}
else{
classesMatrix = new SimilarityMatrix(getSourceOntology().getClassesList().size(),
getTargetOntology().getClassesList().size(),
alignType.aligningClasses,
1.0);
}
// load propertiesMatrix
if(propertiesMatrix != null){
propertiesMatrix.fillMatrix(1.0);
}
else{
classesMatrix = new SimilarityMatrix(getSourceOntology().getPropertiesList().size(),
getTargetOntology().getPropertiesList().size(),
alignType.aligningClasses,
1.0);
}
}
}
/**
* @return the hasInput
*/
public boolean getHasInput() {
return hasInput;
}
/**
* @param hasInput the hasInput value to set
*/
public void setHasInput(boolean hasInput) {
this.hasInput = hasInput;
}
}
|
package com.intellij.psi.util;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.Nullability;
import com.intellij.codeInsight.NullableNotNullManager;
import com.intellij.codeInsight.daemon.impl.analysis.JavaGenericsUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Key;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.PsiImmediateClassType;
import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.CommonProcessors;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.siyeh.ig.bugs.NullArgumentToVariableArgMethodInspection;
import com.siyeh.ig.psiutils.ExpectedTypeUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class RedundantCastUtil {
private static final Logger LOG = Logger.getInstance(RedundantCastUtil.class);
private static final Key<PsiElement> SELF_REFERENCE = Key.create("SELF_REFERENCE");
private RedundantCastUtil() { }
@NotNull
public static List<PsiTypeCastExpression> getRedundantCastsInside(@NotNull PsiElement where) {
HashSet<PsiTypeCastExpression> casts = new HashSet<>();
JavaElementVisitor visitor = createRedundantCastVisitor(new CommonProcessors.CollectProcessor<>(casts));
where.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitElement(@NotNull PsiElement element) {
super.visitElement(element);
element.accept(visitor);
}
});
return new ArrayList<>(casts);
}
public static boolean isCastRedundant(PsiTypeCastExpression typeCast) {
PsiElement parent = typeCast.getParent();
PsiExpression operand = typeCast.getOperand();
if (operand != null && operand.getType() != null && operand.getType().equals(typeCast.getType())) return true;
while(parent instanceof PsiParenthesizedExpression) parent = parent.getParent();
if (parent instanceof PsiExpressionList) parent = parent.getParent();
if (parent instanceof PsiReferenceExpression) parent = parent.getParent();
if (parent instanceof PsiAnonymousClass) parent = parent.getParent();
HashSet<PsiTypeCastExpression> casts = new HashSet<>();
JavaElementVisitor visitor = createRedundantCastVisitor(new CommonProcessors.CollectProcessor<>(casts));
parent.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitElement(@NotNull PsiElement element) {
super.visitElement(element);
element.accept(visitor);
if (!casts.isEmpty()) {
stopWalking();
}
}
});
return casts.contains(typeCast);
}
public static JavaElementVisitor createRedundantCastVisitor(Processor<? super PsiTypeCastExpression> processor) {
return new MyIsRedundantVisitor() {
@Override
protected void registerCast(@NotNull PsiTypeCastExpression typeCast) {
processor.process(typeCast);
}
};
}
@Nullable
private static PsiExpression deparenthesizeExpression(PsiExpression arg) {
return PsiUtil.skipParenthesizedExprDown(arg);
}
private static abstract class MyIsRedundantVisitor extends JavaElementVisitor {
private void addToResults(@NotNull PsiTypeCastExpression typeCast){
if (!isTypeCastSemantic(typeCast)) {
registerCast(typeCast);
}
}
private void addIfNarrowing(PsiTypeCastExpression castExpression, @NotNull PsiType opType, PsiType expectedTypeByParent) {
PsiTypeElement castElement = castExpression.getCastType();
if (castElement != null && TypeConversionUtil.isAssignable(castElement.getType(), opType, false) &&
(expectedTypeByParent == null || TypeConversionUtil.isAssignable(expectedTypeByParent, opType, false))) {
addToResults(castExpression);
}
}
private void addIfNarrowing(PsiExpression expression, PsiType expectedTypeByParent) {
expression = deparenthesizeExpression(expression);
if (expression instanceof PsiTypeCastExpression) {
PsiExpression operand = getInnerMostOperand(expression);
if (operand != null) {
PsiType opType = operand.getType();
if (opType != null) {
addIfNarrowing((PsiTypeCastExpression)expression, opType, expectedTypeByParent);
}
}
}
}
protected abstract void registerCast(@NotNull PsiTypeCastExpression typeCast);
@Override public void visitAssignmentExpression(PsiAssignmentExpression expression) {
processTypeCastWithExpectedType(expression.getRExpression(), expression.getLExpression().getType());
super.visitAssignmentExpression(expression);
}
@Override
public void visitArrayInitializerExpression(PsiArrayInitializerExpression expression) {
PsiType type = expression.getType();
if (type instanceof PsiArrayType) {
for (PsiExpression initializer : expression.getInitializers()) {
processTypeCastWithExpectedType(initializer, ((PsiArrayType)type).getComponentType());
}
}
super.visitArrayInitializerExpression(expression);
}
@Override public void visitVariable(PsiVariable variable) {
processTypeCastWithExpectedType(variable.getInitializer(), variable.getType());
super.visitVariable(variable);
}
@Override public void visitReturnStatement(PsiReturnStatement statement) {
final PsiMethod method = PsiTreeUtil.getParentOfType(statement, PsiMethod.class, true, PsiLambdaExpression.class);
if (method != null) {
final PsiType returnType = method.getReturnType();
final PsiExpression returnValue = statement.getReturnValue();
if (returnValue != null) {
processTypeCastWithExpectedType(returnValue, returnType);
}
}
super.visitReturnStatement(statement);
}
private void processTypeCastWithExpectedType(PsiExpression rExpr, @Nullable PsiType lType) {
rExpr = deparenthesizeExpression(rExpr);
if (rExpr instanceof PsiTypeCastExpression) {
PsiExpression castOperand = getInnerMostOperand(rExpr);
if (castOperand != null && lType != null) {
PsiType opType = getOpTypeWithExpected(castOperand, lType);
if (opType != null) {
if (castOperand instanceof PsiConditionalExpression) {
if (!isApplicableForConditionalBranch(opType, ((PsiConditionalExpression)castOperand).getThenExpression())) return;
if (!isApplicableForConditionalBranch(opType, ((PsiConditionalExpression)castOperand).getElseExpression())) return;
}
if (TypeConversionUtil.isAssignable(lType, opType, false)) {
if (!isFunctionalExpressionTypePreserved((PsiTypeCastExpression)rExpr, castOperand, lType)) return;
addToResults((PsiTypeCastExpression)rExpr);
}
}
}
}
}
private static boolean isFunctionalExpressionTypePreserved(PsiTypeCastExpression typeCast,
PsiExpression castOperand,
@NotNull PsiType lType) {
if (castOperand instanceof PsiFunctionalExpression) {
final PsiTypeElement typeElement = typeCast.getCastType();
final PsiType castType = typeElement != null ? typeElement.getType() : null;
return lType.equals(castType);
}
return true;
}
@Override
public void visitPolyadicExpression(PsiPolyadicExpression expression) {
class Processor {
private @Nullable PsiType processBinaryExpressionOperand(final PsiExpression operand,
final PsiType otherType,
final IElementType binaryToken) {
if (operand instanceof PsiTypeCastExpression) {
PsiTypeCastExpression typeCast = (PsiTypeCastExpression)operand;
PsiExpression toCast = typeCast.getOperand();
if (toCast != null && otherType != null &&
TypeConversionUtil.isBinaryOperatorApplicable(binaryToken, toCast.getType(), otherType, false)) {
addToResults(typeCast);
return toCast.getType();
}
}
return operand != null ? operand.getType() : null;
}
}
Processor processor = new Processor();
IElementType tokenType = expression.getOperationTokenType();
PsiExpression[] operands = expression.getOperands();
if (operands.length >= 2) {
PsiType lType = processor.processBinaryExpressionOperand(deparenthesizeExpression(operands[0]), operands[1].getType(), tokenType);
for (int i = 1; i < operands.length; i++) {
PsiExpression operand = deparenthesizeExpression(operands[i]);
if (operand == null) continue;
PsiType rType = processor.processBinaryExpressionOperand(operand, lType, tokenType);
lType = TypeConversionUtil.calcTypeForBinaryExpression(lType, rType, tokenType, true);
}
}
super.visitPolyadicExpression(expression);
}
@Override
public void visitCallExpression(PsiCallExpression callExpression) {
processCall(callExpression);
super.visitCallExpression(callExpression);
}
@Override
public void visitEnumConstant(PsiEnumConstant enumConstant) {
processCall(enumConstant);
super.visitEnumConstant(enumConstant);
}
@Override
public void visitReferenceExpression(PsiReferenceExpression expression) {
PsiExpression qualifier = deparenthesizeExpression(expression.getQualifierExpression());
if (qualifier instanceof PsiTypeCastExpression) {
PsiTypeCastExpression typeCast = (PsiTypeCastExpression)qualifier;
PsiExpression operand = getInnerMostOperand(typeCast.getOperand());
if (operand == null) return;
PsiTypeElement typeElement = typeCast.getCastType();
if (typeElement == null) return;
PsiType opType = operand.getType();
if (opType == null) return;
if (!(operand instanceof PsiFunctionalExpression || opType instanceof PsiPrimitiveType) &&
isCastInReferenceQualifierRedundant(expression)) {
addToResults(typeCast);
}
}
super.visitReferenceExpression(expression);
}
private static PsiExpression getInnerMostOperand(@Nullable PsiExpression castOperand) {
castOperand = deparenthesizeExpression(castOperand);
while (castOperand instanceof PsiTypeCastExpression) {
castOperand = deparenthesizeExpression(((PsiTypeCastExpression)castOperand).getOperand());
}
return castOperand;
}
private static boolean isCastInReferenceQualifierRedundant(final PsiReferenceExpression refExpression) {
final JavaResolveResult resolveResult = refExpression.advancedResolve(false);
PsiElement oldMember = resolveResult.getElement();
if (oldMember == null) return false;
try {
PsiElement parent = PsiUtil.skipParenthesizedExprUp(refExpression.getParent());
if (parent instanceof PsiMethodCallExpression) {//check for virtual call
PsiMethod targetMethod = (PsiMethod)oldMember;
if (targetMethod.hasModifierProperty(PsiModifier.STATIC)) {
return false;
}
PsiMethodCallExpression newCall =
(PsiMethodCallExpression)copyCallExpression(((PsiMethodCallExpression)parent), PsiTypesUtil.getExpectedTypeByParent(parent));
if (newCall == null) return false;
PsiExpression newQualifier = deparenthesizeExpression(newCall.getMethodExpression().getQualifierExpression());
LOG.assertTrue(newQualifier != null);
PsiElement oldReference = newQualifier.getCopyableUserData(SELF_REFERENCE);
PsiElement replace = newQualifier.replace(getInnerMostOperand(newQualifier));
replace.putCopyableUserData(SELF_REFERENCE, oldReference);
final JavaResolveResult newResult = newCall.getMethodExpression().advancedResolve(false);
if (!newResult.isValidResult()) return false;
final PsiMethod newTargetMethod = (PsiMethod)newResult.getElement();
LOG.assertTrue(newTargetMethod != null, "isValidResult() check above should find this");
PsiType newReturnType = newCall.getType();
PsiType oldReturnType = ((PsiMethodCallExpression)parent).getType();
if (Comparing.equal(newReturnType == null ? null : new RedundantCastRecaptureMapper().mapType(newReturnType), oldReturnType) &&
(Comparing.equal(newTargetMethod, targetMethod) ||
!(newTargetMethod.isDeprecated() && !targetMethod.isDeprecated()) &&
MethodSignatureUtil.isSuperMethod(newTargetMethod, targetMethod) &&
// see SCR11555, SCR14559
areThrownExceptionsCompatible(targetMethod, newTargetMethod) &&
areNullabilityCompatible(targetMethod, newTargetMethod))) {
return true;
}
return false;
}
else {
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(refExpression.getProject());
final PsiReferenceExpression newExpression = (PsiReferenceExpression)elementFactory.createExpressionFromText(refExpression.getText(), refExpression);
final PsiExpression newQualifier = newExpression.getQualifierExpression();
LOG.assertTrue(newQualifier != null);
newQualifier.replace(getInnerMostOperand(newQualifier));
JavaResolveResult newResult = newExpression.advancedResolve(false);
if (!newResult.isValidResult()) return false;
return oldMember.equals(newResult.getElement());
}
}
catch (IncorrectOperationException ignore) {
return false;
}
}
private void processCall(PsiCall expression){
PsiExpressionList argumentList = expression.getArgumentList();
if (argumentList == null) return;
PsiExpression[] args = argumentList.getExpressions();
if (args.length == 0) return;
final JavaResolveResult oldResult = expression.resolveMethodGenerics();
final PsiElement element = oldResult.getElement();
if (!(element instanceof PsiMethod)) return;
PsiMethod oldMethod = (PsiMethod)element;
PsiParameter[] parameters = oldMethod.getParameterList().getParameters();
PsiCall newCall = null;
for (int i = 0; i < args.length; i++) {
final PsiExpression arg = deparenthesizeExpression(args[i]);
if (!(arg instanceof PsiTypeCastExpression) && !(arg instanceof PsiLambdaExpression) && !(arg instanceof PsiConditionalExpression)) {
continue;
}
ProgressManager.checkCanceled();
if (newCall == null) {
newCall = copyCallExpression(expression, PsiTypesUtil.getExpectedTypeByParent(expression));
}
if (newCall == null) return;
final PsiExpressionList argList = newCall.getArgumentList();
LOG.assertTrue(argList != null);
PsiExpression[] newArgs = argList.getExpressions();
LOG.assertTrue(newArgs.length == args.length, "oldCall: " + expression.getText() + "; old length: " + args.length + "; newCall: " + newCall.getText() + "; new length: " + newArgs.length);
if (arg instanceof PsiTypeCastExpression) {
checkTypeCastInCallArgument(i, (PsiTypeCastExpression)arg, newArgs, expression, newCall);
}
else if (arg instanceof PsiLambdaExpression) {
checkLambdaReturnsInsideCall(i, (PsiLambdaExpression)arg, newArgs, expression, newCall, parameters);
}
else {
PsiType conditionalType = arg.getType();
PsiExpression thenExpression = deparenthesizeExpression(((PsiConditionalExpression)arg).getThenExpression());
PsiExpression elseExpression = deparenthesizeExpression(((PsiConditionalExpression)arg).getElseExpression());
if (thenExpression instanceof PsiTypeCastExpression &&
!castForBoxing(getInnerMostOperand(thenExpression), elseExpression != null ? elseExpression.getType() : null, conditionalType)) {
PsiExpression newThenExpression = deparenthesizeExpression(((PsiConditionalExpression)Objects.requireNonNull(deparenthesizeExpression(newArgs[i]))).getThenExpression());
checkConditionalBranch(expression, newCall, thenExpression, newThenExpression);
}
if (elseExpression instanceof PsiTypeCastExpression &&
!castForBoxing(getInnerMostOperand(elseExpression), thenExpression != null ? thenExpression.getType() : null, conditionalType)) {
PsiExpression newElseExpression = deparenthesizeExpression(((PsiConditionalExpression)Objects.requireNonNull(deparenthesizeExpression(newArgs[i]))).getElseExpression());
checkConditionalBranch(expression, newCall, elseExpression, newElseExpression);
}
}
}
}
private void checkConditionalBranch(PsiCall oldCall,
PsiCall newCall,
PsiExpression oldBranchExpression,
PsiExpression newBranchExpression) {
PsiExpression operand = ((PsiTypeCastExpression)newBranchExpression).getOperand();
if (operand != null) {
newBranchExpression = (PsiExpression)newBranchExpression.replace(operand);
JavaResolveResult oldResult = oldCall.resolveMethodGenerics();
JavaResolveResult newResult = resolveNewResult(oldCall, newCall);
if (isSameResolveResult(oldResult, newResult)) {
addToResults((PsiTypeCastExpression)oldBranchExpression);
}
else {
newBranchExpression.replace(oldBranchExpression);
}
}
}
private static boolean isSameResolveResult(JavaResolveResult oldResult, JavaResolveResult newResult) {
PsiMethod oldMethod = (PsiMethod)oldResult.getElement();
LOG.assertTrue(oldMethod != null);
return oldMethod.equals(newResult.getElement()) &&
newResult.isValidResult() &&
!(newResult instanceof MethodCandidateInfo && ((MethodCandidateInfo)newResult).getInferenceErrorMessage() != null) &&
new RedundantCastRecaptureMapper().recapture(newResult.getSubstitutor()).equals(oldResult.getSubstitutor());
}
private static boolean castForBoxing(PsiExpression operand, PsiType oppositeType, PsiType conditionalType) {
return operand != null &&
TypeConversionUtil.isPrimitiveAndNotNull(operand.getType()) &&
!(oppositeType instanceof PsiPrimitiveType) &&
!(conditionalType instanceof PsiPrimitiveType);
}
private void checkLambdaReturnsInsideCall(int i,
PsiLambdaExpression arg,
PsiExpression[] newArgs,
PsiCall oldCall,
PsiCall newCall,
PsiParameter[] parameters) {
final PsiType interfaceType = arg.getFunctionalInterfaceType();
if (interfaceType != null) {
List<PsiExpression> expressions = LambdaUtil.getReturnExpressions(arg);
PsiLambdaExpression newLambdaExpression = (PsiLambdaExpression)deparenthesizeExpression(newArgs[i]);
LOG.assertTrue(newLambdaExpression != null);
List<PsiExpression> newReturnExpressions = LambdaUtil.getReturnExpressions(newLambdaExpression);
for (int returnExprIdx = 0; returnExprIdx < expressions.size(); returnExprIdx++) {
ProgressManager.checkCanceled();
PsiExpression returnExpression = deparenthesizeExpression(expressions.get(returnExprIdx));
final PsiExpression newReturnExpression = deparenthesizeExpression(newReturnExpressions.get(returnExprIdx));
if (newReturnExpression instanceof PsiTypeCastExpression) {
checkLambdaReturn(i, (PsiTypeCastExpression)returnExpression, (PsiTypeCastExpression)newReturnExpression, interfaceType, newLambdaExpression, oldCall, newCall, parameters);
}
else if (returnExpression instanceof PsiConditionalExpression) {
LOG.assertTrue(newReturnExpression instanceof PsiConditionalExpression);
PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)returnExpression;
PsiConditionalExpression newConditionalExpression = (PsiConditionalExpression)newReturnExpression;
final PsiExpression thenExpression = deparenthesizeExpression(conditionalExpression.getThenExpression());
final PsiExpression newThenExpression = deparenthesizeExpression(newConditionalExpression.getThenExpression());
final PsiExpression elseExpression = deparenthesizeExpression(conditionalExpression.getElseExpression());
final PsiExpression newElseExpression = deparenthesizeExpression(newConditionalExpression.getElseExpression());
if (thenExpression instanceof PsiTypeCastExpression &&
!castForBoxing(getInnerMostOperand(thenExpression), elseExpression != null ? elseExpression.getType() : null, returnExpression.getType())) {
checkLambdaReturn(i, (PsiTypeCastExpression)thenExpression, (PsiTypeCastExpression)newThenExpression, interfaceType, newLambdaExpression, oldCall, newCall, parameters);
}
if (elseExpression instanceof PsiTypeCastExpression &&
!castForBoxing(getInnerMostOperand(elseExpression), thenExpression != null ? thenExpression.getType() : null, returnExpression.getType())) {
checkLambdaReturn(i, (PsiTypeCastExpression)elseExpression, (PsiTypeCastExpression)newElseExpression, interfaceType, newLambdaExpression, oldCall, newCall, parameters);
}
}
}
}
}
private void checkLambdaReturn(int i,
PsiTypeCastExpression returnExpression,
PsiTypeCastExpression newReturnExpression,
PsiType originalFunctionalInterfaceType,
PsiLambdaExpression newLambdaExpression,
PsiCall oldCall,
PsiCall newCall,
PsiParameter[] parameters) {
PsiExpression castOperand = getInnerMostOperand(returnExpression);
if (castOperand == null) return;
final PsiType interfaceReturnType = LambdaUtil.getFunctionalInterfaceReturnType(originalFunctionalInterfaceType);
if (interfaceReturnType == null ||
!isFunctionalExpressionTypePreserved(returnExpression, castOperand, interfaceReturnType)) return;
PsiExpression strippedCast = (PsiExpression)newReturnExpression.replace(castOperand);
PsiType newArgType = calculateNewArgType(i, resolveNewResult(oldCall, newCall), parameters);
final PsiType functionalInterfaceType = newLambdaExpression.getGroundTargetType(newArgType);
if (originalFunctionalInterfaceType.equals(functionalInterfaceType)) {
final PsiType castExprType = LambdaUtil.performWithTargetType(newLambdaExpression, functionalInterfaceType, () -> strippedCast.getType());
if (castExprType != null && interfaceReturnType.isAssignableFrom(castExprType)) {
addToResults(returnExpression);
return;
}
}
strippedCast.replace(returnExpression);
}
private void checkTypeCastInCallArgument(int i,
PsiTypeCastExpression arg,
PsiExpression[] newArgs,
PsiCall oldCall,
PsiCall newCall) {
final PsiTypeElement castTypeElement = arg.getCastType();
final PsiType castType = castTypeElement != null ? castTypeElement.getType() : null;
PsiExpression castOperand = ((PsiTypeCastExpression)Objects.requireNonNull(deparenthesizeExpression(newArgs[i]))).getOperand();
if (castOperand == null) return;
newArgs[i] = (PsiExpression)newArgs[i].replace(castOperand);
JavaResolveResult oldResult = oldCall.resolveMethodGenerics();
final JavaResolveResult newResult = resolveNewResult(oldCall, newCall);
PsiMethod oldMethod = (PsiMethod)oldResult.getElement();
LOG.assertTrue(oldMethod != null);
PsiParameter[] parameters = oldMethod.getParameterList().getParameters();
if (i == newArgs.length - 1 && newArgs.length == parameters.length && parameters[i].isVarArgs() &&
(NullArgumentToVariableArgMethodInspection.isSuspiciousVararg(newCall, newArgs[i].getType(), () -> (PsiMethod)newResult.getElement()) ||
oldResult instanceof MethodCandidateInfo && newResult instanceof MethodCandidateInfo &&
((MethodCandidateInfo)oldResult).getApplicabilityLevel() != ((MethodCandidateInfo)newResult).getApplicabilityLevel())) {
newArgs[i].replace(arg);
return;
}
if (isSameResolveResult(oldResult, newResult)) {
PsiExpression newArg = PsiUtil.deparenthesizeExpression(newArgs[i]);
if (newArg instanceof PsiFunctionalExpression) {
PsiType newArgType = calculateNewArgType(i, newResult, parameters);
if (Comparing.equal(castType, ((PsiFunctionalExpression)newArg).getGroundTargetType(newArgType))) {
addToResults(arg);
return;
}
}
else if (newArg instanceof PsiCallExpression) {
//if top method is not generic, all inference problems may be collected in the argument itself
JavaResolveResult result = ((PsiCallExpression)newArg).resolveMethodGenerics();
if (!(result instanceof MethodCandidateInfo) || ((MethodCandidateInfo)result).getInferenceErrorMessage() == null) {
addToResults(arg);
return;
}
}
else {
addToResults(arg);
return;
}
}
newArgs[i].replace(arg);
}
@Nullable
private static PsiType calculateNewArgType(int i, JavaResolveResult newResult, PsiParameter[] parameters) {
final boolean varargs = newResult instanceof MethodCandidateInfo && ((MethodCandidateInfo)newResult).isVarargs();
final PsiType parameterType = PsiTypesUtil.getParameterType(parameters, i, varargs);
PsiType newArgType = newResult.getSubstitutor().substitute(parameterType);
if (newResult instanceof MethodCandidateInfo && PsiUtil.isRawSubstitutor(((MethodCandidateInfo)newResult).getElement(), newResult.getSubstitutor())) {
newArgType = TypeConversionUtil.erasure(newArgType);
}
return newArgType;
}
@NotNull
private static JavaResolveResult resolveNewResult(PsiCall oldCall, PsiCall newCall) {
final JavaResolveResult newResult;
if (newCall instanceof PsiEnumConstant) {
// do this manually, because PsiEnumConstantImpl.resolveMethodGenerics() will assert (no containing class for the copy)
final PsiEnumConstant enumConstant = (PsiEnumConstant)oldCall;
PsiClass containingClass = enumConstant.getContainingClass();
final JavaPsiFacade facade = JavaPsiFacade.getInstance(enumConstant.getProject());
final PsiClassType type = facade.getElementFactory().createType(Objects.requireNonNull(containingClass));
newResult = facade.getResolveHelper().resolveConstructor(type, Objects.requireNonNull(newCall.getArgumentList()), enumConstant);
}
else {
newResult = newCall.resolveMethodGenerics();
}
return newResult;
}
@Nullable
private static PsiCall copyCallExpression(PsiCall expression, PsiType typeByParent) {
class Encoder {
private void encode(PsiElement expression) {
expression.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitElement(@NotNull PsiElement element) {
if (element instanceof PsiExpression) {
element.putCopyableUserData(SELF_REFERENCE, element);
}
super.visitElement(element);
}
});
}
private void clean(PsiElement expression) {
expression.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitElement(@NotNull PsiElement element) {
if (element instanceof PsiExpression) {
element.putCopyableUserData(SELF_REFERENCE, null);
}
super.visitElement(element);
}
});
}
}
Encoder encoder = new Encoder();
PsiElement encoded = null;
try {
if (typeByParent != null && PsiTypesUtil.isDenotableType(typeByParent, expression)) {
encoder.encode(encoded = expression);
return (PsiCall)LambdaUtil.copyWithExpectedType(expression, typeByParent);
}
else {
final PsiCall call = LambdaUtil.treeWalkUp(expression);
if (call != null) {
encoder.encode(encoded = call);
Object marker = new Object();
PsiTreeUtil.mark(expression, marker);
final PsiCall callCopy = LambdaUtil.copyTopLevelCall(call);
if (callCopy == null) return null;
return (PsiCall)PsiTreeUtil.releaseMark(callCopy, marker);
}
else {
encoder.encode(encoded = expression);
return (PsiCall)expression.copy();
}
}
}
catch (IllegalArgumentException e) {
return null;
}
finally {
if (encoded != null) {
encoder.clean(encoded);
}
}
}
//nested type casts only
@Override public void visitTypeCastExpression(PsiTypeCastExpression typeCast) {
PsiExpression operand = typeCast.getOperand();
if (operand == null) return;
PsiExpression expr = deparenthesizeExpression(operand);
final PsiType topCastType = typeCast.getType();
if (expr instanceof PsiTypeCastExpression) {
PsiTypeCastExpression innerCast = (PsiTypeCastExpression)expr;
PsiTypeElement typeElement = innerCast.getCastType();
if (typeElement == null) return;
PsiType castType = typeElement.getType();
final PsiExpression innerOperand = innerCast.getOperand();
final PsiType operandType = innerOperand != null ? innerOperand.getType() : null;
if (!(castType instanceof PsiPrimitiveType) && !(topCastType instanceof PsiPrimitiveType)) {
if (operandType != null && topCastType != null && TypeConversionUtil.areTypesConvertible(operandType, topCastType)) {
addToResults(innerCast);
}
} else if (Comparing.equal(PsiPrimitiveType.getUnboxedType(operandType), topCastType)) {
addToResults(innerCast);
}
else if (operandType != null && operandType.equals(castType)) {
// like (int)(long)1L
addToResults(innerCast);
}
}
super.visitTypeCastExpression(typeCast);
}
@Override
public void visitForeachStatement(PsiForeachStatement statement) {
PsiExpression iteratedValue = deparenthesizeExpression(statement.getIteratedValue());
if (iteratedValue instanceof PsiTypeCastExpression) {
PsiExpression operand = ((PsiTypeCastExpression)iteratedValue).getOperand();
if (operand != null) {
PsiType collectionItemType = JavaGenericsUtil.getCollectionItemType(operand.getType(), statement.getResolveScope());
if (collectionItemType != null && TypeConversionUtil.isAssignable(statement.getIterationParameter().getType(), collectionItemType)) {
addToResults((PsiTypeCastExpression)iteratedValue);
}
}
}
super.visitForeachStatement(statement);
}
@Override
public void visitInstanceOfExpression(PsiInstanceOfExpression expression) {
final PsiTypeElement checkTypeElement = expression.getCheckType();
if (checkTypeElement == null) return;
PsiExpression typeCast = deparenthesizeExpression(expression.getOperand());
if (typeCast instanceof PsiTypeCastExpression) {
PsiExpression operand = getInnerMostOperand(((PsiTypeCastExpression)typeCast).getOperand());
if (operand != null) {
PsiType opType = operand.getType();
//15.20.2. Type Comparison Operator instanceof:
//If a cast (p15.16) of the RelationalExpression to the ReferenceType would be rejected as a compile-time error,
//then the instanceof relational expression likewise produces a compile-time error.
if (opType != null &&
!(opType instanceof PsiPrimitiveType) &&
TypeConversionUtil.areTypesConvertible(opType, checkTypeElement.getType())) {
addToResults((PsiTypeCastExpression)typeCast);
}
}
}
super.visitInstanceOfExpression(expression);
}
@Override
public void visitThrowStatement(PsiThrowStatement statement) {
PsiExpression typeCast = deparenthesizeExpression(statement.getException());
if (typeCast instanceof PsiTypeCastExpression) {
PsiExpression operand = getInnerMostOperand(((PsiTypeCastExpression)typeCast).getOperand());
if (operand != null) {
PsiType opType = operand.getType();
final PsiClass thrownClass = PsiUtil.resolveClassInType(opType);
if (InheritanceUtil.isInheritor(thrownClass, false, CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION)) {
addToResults((PsiTypeCastExpression)typeCast);
}
if (InheritanceUtil.isInheritor(thrownClass, false, CommonClassNames.JAVA_LANG_THROWABLE)) {
final PsiParameterListOwner listOwner = PsiTreeUtil.getParentOfType(statement, PsiMethod.class, PsiLambdaExpression.class);
if (listOwner instanceof PsiMethod) {
processThrowsList((PsiMethod)listOwner, PsiSubstitutor.EMPTY, (PsiTypeCastExpression)typeCast, opType);
}
else if (listOwner instanceof PsiLambdaExpression) {
PsiType functionalInterfaceType = ((PsiLambdaExpression)listOwner).getFunctionalInterfaceType();
final PsiClassType.ClassResolveResult functionalInterfaceResolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(functionalInterfaceType);
if (interfaceMethod != null) {
processThrowsList(interfaceMethod, LambdaUtil.getSubstitutor(interfaceMethod, functionalInterfaceResolveResult), (PsiTypeCastExpression)typeCast, opType);
}
}
}
}
}
super.visitThrowStatement(statement);
}
private void processThrowsList(PsiMethod interfaceMethod,
PsiSubstitutor psiSubstitutor,
PsiTypeCastExpression typeCast,
PsiType opType) {
for (PsiClassType thrownType : interfaceMethod.getThrowsList().getReferencedTypes()) {
PsiType left = psiSubstitutor.substitute(thrownType);
if (left != null && TypeConversionUtil.isAssignable(left, opType, false)) {
addToResults(typeCast);
}
}
}
@Override
public void visitSynchronizedStatement(PsiSynchronizedStatement statement) {
PsiExpression lockExpression = deparenthesizeExpression(statement.getLockExpression());
if (lockExpression instanceof PsiTypeCastExpression) {
PsiExpression operand = getInnerMostOperand(((PsiTypeCastExpression)lockExpression).getOperand());
if (operand != null) {
PsiType opType = operand.getType();
if (!(operand instanceof PsiFunctionalExpression) && !(opType instanceof PsiPrimitiveType) && opType != null) {
addIfNarrowing((PsiTypeCastExpression)lockExpression, opType, null);
}
}
}
super.visitSynchronizedStatement(statement);
}
@Override
public void visitSwitchStatement(PsiSwitchStatement statement) {
visitSwitchBlockSelector(statement);
super.visitSwitchStatement(statement);
}
@Override
public void visitSwitchExpression(PsiSwitchExpression expression) {
visitSwitchBlockSelector(expression);
PsiType expectedTypeByParent = PsiTypesUtil.getExpectedTypeByParent(expression);
for (PsiExpression resultExpression : PsiUtil.getSwitchResultExpressions(expression)) {
addIfNarrowing(resultExpression, expectedTypeByParent);
}
super.visitSwitchExpression(expression);
}
private void visitSwitchBlockSelector(PsiSwitchBlock expression) {
PsiExpression switchVariable = deparenthesizeExpression(expression.getExpression());
if (switchVariable instanceof PsiTypeCastExpression) {
PsiExpression operand = ((PsiTypeCastExpression)switchVariable).getOperand();
if (operand != null) {
PsiType opType = operand.getType();
if (opType instanceof PsiClassType && PsiPrimitiveType.getUnboxedType(opType) == null && !opType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) {
PsiClass aClass = ((PsiClassType)opType).resolve();
if (aClass != null && !aClass.isEnum()) {
return;
}
}
if (opType != null) {
addIfNarrowing((PsiTypeCastExpression)switchVariable, opType, null);
}
}
}
}
@Override
public void visitAssertStatement(PsiAssertStatement statement) {
addIfNarrowing(statement.getAssertCondition(), PsiType.BOOLEAN);
addIfNarrowing(statement.getAssertDescription(), PsiType.getJavaLangString(statement.getManager(), statement.getResolveScope()));
super.visitAssertStatement(statement);
}
@Override
public void visitDoWhileStatement(PsiDoWhileStatement statement) {
addIfNarrowing(statement.getCondition(), PsiType.BOOLEAN);
super.visitDoWhileStatement(statement);
}
@Override
public void visitIfStatement(PsiIfStatement statement) {
addIfNarrowing(statement.getCondition(), PsiType.BOOLEAN);
super.visitIfStatement(statement);
}
@Override
public void visitWhileStatement(PsiWhileStatement statement) {
addIfNarrowing(statement.getCondition(), PsiType.BOOLEAN);
super.visitWhileStatement(statement);
}
@Override
public void visitResourceExpression(PsiResourceExpression expression) {
addIfNarrowing(expression.getExpression(), null);
super.visitResourceExpression(expression);
}
@Override
public void visitExpressionStatement(PsiExpressionStatement statement) {
if (!(statement.getParent() instanceof PsiSwitchLabeledRuleStatement)) {
addIfNarrowing(statement.getExpression(), null);
}
super.visitExpressionStatement(statement);
}
@Override
public void visitNameValuePair(PsiNameValuePair pair) {
PsiAnnotationMemberValue value = pair.getValue();
if (value instanceof PsiExpression) {
addIfNarrowing((PsiExpression)value, null);
}
super.visitNameValuePair(pair);
}
@Override
public void visitLambdaExpression(PsiLambdaExpression expression) {
if (!(PsiUtil.skipParenthesizedExprUp(expression.getParent()) instanceof PsiExpressionList)) {
PsiMethod method = LambdaUtil.getFunctionalInterfaceMethod(expression);
if (method != null) {
PsiType returnType = method.getReturnType();
if (returnType != null) {
List<PsiExpression> returns = LambdaUtil.getReturnExpressions(expression);
for (PsiExpression aReturn : returns) {
PsiExpression returnInLambda = deparenthesizeExpression(aReturn);
if (returnInLambda instanceof PsiTypeCastExpression) {
PsiExpression operand = getInnerMostOperand(returnInLambda);
if (operand != null && returnType.equals(operand.getType())) {
addToResults((PsiTypeCastExpression)returnInLambda);
}
}
}
}
}
}
super.visitLambdaExpression(expression);
}
@Override
public void visitConditionalExpression(PsiConditionalExpression conditionalExpression) {
PsiElement gParent = PsiUtil.skipParenthesizedExprUp(conditionalExpression.getParent());
if (gParent instanceof PsiLambdaExpression) return;
if (gParent instanceof PsiReturnStatement &&
PsiTreeUtil.getParentOfType(gParent, PsiMethod.class, PsiLambdaExpression.class) instanceof PsiLambdaExpression) return;
if (!(gParent instanceof PsiExpressionList)) {
PsiExpression thenExpression = deparenthesizeExpression(conditionalExpression.getThenExpression());
PsiExpression elseExpression = deparenthesizeExpression(conditionalExpression.getElseExpression());
if (thenExpression instanceof PsiTypeCastExpression) {
visitConditional((PsiTypeCastExpression)thenExpression,
conditionalExpression,
getInnerMostOperand(elseExpression));
}
if (elseExpression instanceof PsiTypeCastExpression) {
visitConditional((PsiTypeCastExpression)elseExpression,
conditionalExpression,
getInnerMostOperand(deparenthesizeExpression(conditionalExpression.getThenExpression())));
}
}
addIfNarrowing(conditionalExpression.getCondition(), PsiType.BOOLEAN);
super.visitConditionalExpression(conditionalExpression);
}
private void visitConditional(PsiTypeCastExpression typeCast, @NotNull PsiConditionalExpression parent, @Nullable PsiExpression oppositeOperand) {
final PsiExpression operand = getInnerMostOperand(typeCast.getOperand());
if (operand == null) return;
PsiType castTo = typeCast.getType();
if (castTo == null) return;
if (operand instanceof PsiFunctionalExpression && !castTo.equals(PsiTypesUtil.getExpectedTypeByParent(parent))) {
return;
}
PsiType opType = operand.getType();
if (opType == null) return;
if (castTo instanceof PsiClassType && TypeConversionUtil.isPrimitiveAndNotNull(opType)) {
if (oppositeOperand != null &&
!(oppositeOperand.getType() instanceof PsiPrimitiveType) &&
!(PsiTypesUtil.getExpectedTypeByParent(parent) instanceof PsiPrimitiveType)) {
return;
}
}
final PsiType conditionalType = parent.getType();
if (!Comparing.equal(opType, conditionalType)) {
if (!PsiUtil.isLanguageLevel5OrHigher(typeCast)) {
return;
}
if (!PsiPolyExpressionUtil.isPolyExpression(parent)) { //branches need to be of the same type
if (oppositeOperand == null || !Comparing.equal(conditionalType, oppositeOperand.getType())) return;
}
}
addIfNarrowing(typeCast, opType, null);
}
private static PsiType getOpTypeWithExpected(PsiExpression operand, PsiType expectedTypeByParent) {
PsiType opType = operand.getType();
if (expectedTypeByParent != null && !(operand instanceof PsiFunctionalExpression)) {
try {
final PsiExpression initializer = (PsiExpression)LambdaUtil.copyWithExpectedType(operand, expectedTypeByParent);
opType = initializer.getType();
if (initializer instanceof PsiMethodCallExpression) {
JavaResolveResult newResult = ((PsiMethodCallExpression)initializer).resolveMethodGenerics();
if (newResult instanceof MethodCandidateInfo && ((MethodCandidateInfo)newResult).getInferenceErrorMessage() != null) {
return null;
}
}
}
catch (IncorrectOperationException ignore) {}
}
return opType;
}
private static boolean isApplicableForConditionalBranch(PsiType opType, PsiExpression thenExpression) {
if (thenExpression != null) {
final PsiType thenType = thenExpression.getType();
if (thenType != null && !TypeConversionUtil.isAssignable(opType, thenType)) {
return false;
}
}
return true;
}
@Override
public void visitArrayAccessExpression(PsiArrayAccessExpression expression) {
PsiExpression arrayExpression = deparenthesizeExpression(expression.getArrayExpression());
if (arrayExpression instanceof PsiTypeCastExpression) {
PsiTypeElement castTypeElement = ((PsiTypeCastExpression)arrayExpression).getCastType();
PsiExpression operand = ((PsiTypeCastExpression)arrayExpression).getOperand();
if (castTypeElement != null && operand != null) {
if (PsiUtil.isAccessedForWriting(expression)) {
PsiType castTo = castTypeElement.getType();
PsiType opType = operand.getType();
if (opType != null && TypeConversionUtil.isAssignable(opType, castTo, false) && opType.getArrayDimensions() == castTo.getArrayDimensions()) {
addToResults((PsiTypeCastExpression)arrayExpression);
}
}
}
}
PsiExpression indexExpression = deparenthesizeExpression(expression.getIndexExpression());
if (indexExpression instanceof PsiTypeCastExpression) {
PsiExpression operand = ((PsiTypeCastExpression)indexExpression).getOperand();
if (operand != null) {
PsiType opType = operand.getType();
if (opType != null) {
addIfNarrowing((PsiTypeCastExpression) indexExpression, opType, null);
}
}
}
super.visitArrayAccessExpression(expression);
}
private static class RedundantCastRecaptureMapper extends PsiTypeMapper {
private final Set<PsiClassType> myVisited = ContainerUtil.newIdentityTroveSet();
@Override
public PsiType visitType(@NotNull PsiType type) {
return type;
}
@Override
public PsiType visitClassType(@NotNull PsiClassType classType) {
if (!myVisited.add(classType)) return classType;
final PsiClassType.ClassResolveResult classResolveResult = classType.resolveGenerics();
final PsiClass psiClass = classResolveResult.getElement();
final PsiSubstitutor substitutor = classResolveResult.getSubstitutor();
if (psiClass == null) return classType;
return new PsiImmediateClassType(psiClass, recapture(substitutor));
}
PsiSubstitutor recapture(PsiSubstitutor substitutor) {
PsiSubstitutor result = PsiSubstitutor.EMPTY;
for (Map.Entry<PsiTypeParameter, PsiType> entry : substitutor.getSubstitutionMap().entrySet()) {
PsiType value = entry.getValue();
result = result.put(entry.getKey(), value == null ? null : mapType(value));
}
return result;
}
@Override
public PsiType visitCapturedWildcardType(@NotNull PsiCapturedWildcardType capturedWildcardType) {
PsiElement context = capturedWildcardType.getContext();
@Nullable PsiElement original = context.getCopyableUserData(SELF_REFERENCE);
if (original != null) {
context = original;
}
PsiCapturedWildcardType mapped =
PsiCapturedWildcardType.create(capturedWildcardType.getWildcard(), context, capturedWildcardType.getTypeParameter());
mapped.setUpperBound(capturedWildcardType.getUpperBound(false).accept(this));
return mapped;
}
}
}
private static boolean isTypeCastSemantic(PsiTypeCastExpression typeCast) {
PsiExpression operand = typeCast.getOperand();
if (operand == null) return false;
if (isInPolymorphicCall(typeCast)) return true;
PsiType opType = operand.getType();
PsiTypeElement typeElement = typeCast.getCastType();
if (typeElement == null) return false;
PsiType castType = typeElement.getType();
if (castType instanceof PsiPrimitiveType) {
if (opType instanceof PsiPrimitiveType) {
PsiElement parent = PsiUtil.skipParenthesizedExprUp(typeCast.getParent());
if ((parent instanceof PsiReturnStatement || parent instanceof PsiExpressionList || parent instanceof PsiVariable ||
parent instanceof PsiAssignmentExpression ||
parent instanceof PsiArrayAccessExpression && PsiTreeUtil.isAncestor(((PsiArrayAccessExpression)parent).getIndexExpression(), typeCast, false)) &&
castType.equals(ExpectedTypeUtils.findExpectedType(typeCast, false))) {
return !TypeConversionUtil.isSafeConversion(castType, opType); // let's suppose that casts losing precision are important
} else {
return !castType.equals(opType); // cast might be necessary (e.g. ((double)1)/5)
}
}
final PsiPrimitiveType unboxedOpType = PsiPrimitiveType.getUnboxedType(opType);
if (unboxedOpType != null && !unboxedOpType.equals(castType) ) {
return true;
}
}
else if (castType instanceof PsiClassType && ((PsiClassType)castType).hasParameters()) {
if (opType instanceof PsiClassType && ((PsiClassType)opType).isRaw()) return true;
}
final PsiExpression stripParenthesisOperand = PsiUtil.skipParenthesizedExprDown(operand);
if (stripParenthesisOperand instanceof PsiFunctionalExpression) {
if (isCastToSerializable(castType)) return true;
}
else if (stripParenthesisOperand instanceof PsiConditionalExpression) {
if (PsiUtil.skipParenthesizedExprDown(((PsiConditionalExpression)stripParenthesisOperand).getThenExpression()) instanceof PsiFunctionalExpression ||
PsiUtil.skipParenthesizedExprDown(((PsiConditionalExpression)stripParenthesisOperand).getElseExpression()) instanceof PsiFunctionalExpression) {
return true;
}
}
PsiElement parent = PsiUtil.skipParenthesizedExprUp(typeCast.getParent());
if (parent instanceof PsiBinaryExpression) {
PsiBinaryExpression expression = (PsiBinaryExpression)parent;
PsiExpression firstOperand = expression.getLOperand();
PsiExpression otherOperand = expression.getROperand();
if (PsiTreeUtil.isAncestor(otherOperand, typeCast, false)) {
PsiExpression temp = otherOperand;
otherOperand = firstOperand;
firstOperand = temp;
}
if (otherOperand != null && wrapperCastChangeSemantics(firstOperand, otherOperand, operand)) {
return true;
}
}
else if (parent instanceof PsiConditionalExpression) {
if (opType instanceof PsiPrimitiveType && !(((PsiConditionalExpression)parent).getType() instanceof PsiPrimitiveType)) {
if (PsiPrimitiveType.getUnboxedType(PsiTypesUtil.getExpectedTypeByParent(parent)) != null) {
return true;
}
}
}
else if (parent instanceof PsiLocalVariable) {
return ((PsiLocalVariable)parent).getTypeElement().isInferredType();
}
return false;
}
private static boolean isCastToSerializable(PsiType castType) {
return InheritanceUtil.isInheritor(castType, CommonClassNames.JAVA_IO_SERIALIZABLE);
}
private static boolean wrapperCastChangeSemantics(PsiExpression operand, PsiExpression otherOperand, PsiExpression toCast) {
final boolean isPrimitiveComparisonWithCast;
final boolean isPrimitiveComparisonWithoutCast;
if (TypeConversionUtil.isPrimitiveAndNotNull(otherOperand.getType())) {
// IDEA-111450: A primitive comparison requires one primitive operand and one primitive or wrapper operand.
isPrimitiveComparisonWithCast = TypeConversionUtil.isPrimitiveAndNotNullOrWrapper(operand.getType());
isPrimitiveComparisonWithoutCast = TypeConversionUtil.isPrimitiveAndNotNullOrWrapper(toCast.getType());
}
else {
// We do not check whether `otherOperand` is a wrapper, because a reference-to-primitive cast has a
// side effect regardless of whether we end up doing a primitive or reference comparison.
isPrimitiveComparisonWithCast = TypeConversionUtil.isPrimitiveAndNotNull(operand.getType());
isPrimitiveComparisonWithoutCast = TypeConversionUtil.isPrimitiveAndNotNull(toCast.getType());
}
// wrapper casted to primitive vs wrapper comparison
return isPrimitiveComparisonWithCast != isPrimitiveComparisonWithoutCast;
}
// see http://download.java.net/jdk7/docs/api/java/lang/invoke/MethodHandle.html#sigpoly
public static boolean isInPolymorphicCall(final PsiTypeCastExpression typeCast) {
if (!PsiUtil.isLanguageLevel7OrHigher(typeCast)) return false;
// return type
final PsiExpression operand = typeCast.getOperand();
if (operand instanceof PsiMethodCallExpression) {
if (isPolymorphicMethod((PsiMethodCallExpression)operand)) return true;
}
// argument type
final PsiElement exprList = PsiUtil.skipParenthesizedExprUp(typeCast.getParent());
if (exprList instanceof PsiExpressionList) {
final PsiElement methodCall = exprList.getParent();
if (methodCall instanceof PsiMethodCallExpression) {
if (isPolymorphicMethod((PsiMethodCallExpression)methodCall)) return true;
}
}
return false;
}
private static boolean isPolymorphicMethod(PsiMethodCallExpression expression) {
final PsiElement method = expression.getMethodExpression().resolve();
return method instanceof PsiMethod &&
AnnotationUtil.isAnnotated((PsiMethod)method, CommonClassNames.JAVA_LANG_INVOKE_MH_POLYMORPHIC, 0);
}
private static boolean areNullabilityCompatible(final PsiMethod oldTargetMethod,
final PsiMethod newTargetMethod) {
// the cast may be for the @NotNull which newTargetMethod has whereas the oldTargetMethod doesn't
Nullability oldNullability = NullableNotNullManager.getNullability(oldTargetMethod);
Nullability newNullability = NullableNotNullManager.getNullability(newTargetMethod);
return oldNullability == newNullability;
}
private static boolean areThrownExceptionsCompatible(final PsiMethod targetMethod, final PsiMethod newTargetMethod) {
final PsiClassType[] oldThrowsTypes = targetMethod.getThrowsList().getReferencedTypes();
final PsiClassType[] newThrowsTypes = newTargetMethod.getThrowsList().getReferencedTypes();
for (final PsiClassType throwsType : newThrowsTypes) {
if (!isExceptionThrown(throwsType, oldThrowsTypes)) return false;
}
return true;
}
private static boolean isExceptionThrown(PsiClassType exceptionType, PsiClassType[] thrownTypes) {
for (final PsiClassType type : thrownTypes) {
if (type.equals(exceptionType)) return true;
}
return false;
}
}
|
package net.bull.javamelody;
import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingException;
import javax.naming.NoInitialContextException;
import javax.servlet.ServletContext;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
/**
* Classe utilitaire pour JdbcWrapper.
* @author Emeric Vernat
*/
final class JdbcWrapperHelper {
private static final String MAX_ACTIVE_PROPERTY_NAME = "maxActive";
private static final Map<String, DataSource> SPRING_DATASOURCES = new LinkedHashMap<String, DataSource>();
private static final Map<String, DataSource> JNDI_DATASOURCES_BACKUP = new LinkedHashMap<String, DataSource>();
private static final BasicDataSourcesProperties TOMCAT_BASIC_DATASOURCES_PROPERTIES = new BasicDataSourcesProperties();
private static final BasicDataSourcesProperties DBCP_BASIC_DATASOURCES_PROPERTIES = new BasicDataSourcesProperties();
private static final BasicDataSourcesProperties TOMCAT_JDBC_DATASOURCES_PROPERTIES = new BasicDataSourcesProperties();
private static class BasicDataSourcesProperties {
private final Map<String, Map<String, Object>> properties = new LinkedHashMap<String, Map<String, Object>>();
BasicDataSourcesProperties() {
super();
}
boolean isEmpty() {
return properties.isEmpty();
}
int getMaxActive() {
int result = 0;
for (final Map<String, Object> dataSourceProperties : properties.values()) {
final Integer maxActive = (Integer) dataSourceProperties
.get(MAX_ACTIVE_PROPERTY_NAME);
if (maxActive == null) {
return -1;
}
result += maxActive;
}
return result;
}
Map<String, Map<String, Object>> getDataSourcesProperties() {
final Map<String, Map<String, Object>> result = new LinkedHashMap<String, Map<String, Object>>();
for (final Map.Entry<String, Map<String, Object>> entry : properties.entrySet()) {
result.put(entry.getKey(), Collections.unmodifiableMap(entry.getValue()));
}
return Collections.unmodifiableMap(result);
}
void put(String dataSourceName, String key, Object value) {
Map<String, Object> dataSourceProperties = properties.get(dataSourceName);
if (dataSourceProperties == null) {
dataSourceProperties = new LinkedHashMap<String, Object>();
properties.put(dataSourceName, dataSourceProperties);
}
dataSourceProperties.put(key, value);
}
}
private JdbcWrapperHelper() {
super();
}
static void registerSpringDataSource(String name, DataSource dataSource) {
SPRING_DATASOURCES.put(name, dataSource);
}
static void rebindDataSource(ServletContext servletContext, String jndiName,
DataSource dataSource, DataSource dataSourceProxy) throws Throwable {
final Object lock = changeContextWritable(servletContext, null);
final InitialContext initialContext = new InitialContext();
initialContext.rebind(jndiName, dataSourceProxy);
JNDI_DATASOURCES_BACKUP.put(jndiName, dataSource);
changeContextWritable(servletContext, lock);
initialContext.close();
}
static void rebindInitialDataSources(ServletContext servletContext) throws Throwable {
try {
final InitialContext initialContext = new InitialContext();
for (final Map.Entry<String, DataSource> entry : JNDI_DATASOURCES_BACKUP.entrySet()) {
final String jndiName = entry.getKey();
final DataSource dataSource = entry.getValue();
final Object lock = changeContextWritable(servletContext, null);
initialContext.rebind(jndiName, dataSource);
changeContextWritable(servletContext, lock);
}
initialContext.close();
} finally {
JNDI_DATASOURCES_BACKUP.clear();
}
}
static Map<String, DataSource> getJndiAndSpringDataSources() throws NamingException {
Map<String, DataSource> dataSources;
try {
dataSources = new LinkedHashMap<String, DataSource>(getJndiDataSources());
} catch (final NoInitialContextException e) {
dataSources = new LinkedHashMap<String, DataSource>();
}
dataSources.putAll(SPRING_DATASOURCES);
return dataSources;
}
static Map<String, DataSource> getJndiDataSources() throws NamingException {
final Map<String, DataSource> dataSources = new LinkedHashMap<String, DataSource>(2);
final String datasourcesParameter = Parameters.getParameter(Parameter.DATASOURCES);
if (datasourcesParameter == null) {
dataSources.putAll(getJndiDataSourcesAt("java:comp/env/jdbc"));
// pour jboss sans jboss-env.xml ou sans resource-ref dans web.xml :
dataSources.putAll(getJndiDataSourcesAt("java:/jdbc"));
// pour JavaEE 6 :
dataSources.putAll(getJndiDataSourcesAt("java:global/jdbc"));
// pour WebLogic 10 et WebSphere 7, cf issue 68
dataSources.putAll(getJndiDataSourcesAt("jdbc"));
} else if (datasourcesParameter.trim().length() != 0) { // NOPMD
final InitialContext initialContext = new InitialContext();
for (final String datasource : datasourcesParameter.split(",")) {
final String jndiName = datasource.trim();
// ici, on n'ajoute pas java:/comp/env
final DataSource dataSource = (DataSource) initialContext.lookup(jndiName);
dataSources.put(jndiName, dataSource);
}
initialContext.close();
}
return Collections.unmodifiableMap(dataSources);
}
private static Map<String, DataSource> getJndiDataSourcesAt(String jndiPrefix)
throws NamingException {
final InitialContext initialContext = new InitialContext();
final Map<String, DataSource> dataSources = new LinkedHashMap<String, DataSource>(2);
try {
for (final NameClassPair nameClassPair : Collections.list(initialContext
.list(jndiPrefix))) {
// note: il ne suffit pas de tester
// (DataSource.class.isAssignableFrom(Class.forName(nameClassPair.getClassName())))
// car nameClassPair.getClassName() vaut "javax.naming.LinkRef" sous jboss 5.1.0.GA
// par exemple, donc on fait le lookup pour voir
final String jndiName;
if (nameClassPair.getName().startsWith("java:")) {
// pour glassfish v3
jndiName = nameClassPair.getName();
} else {
jndiName = jndiPrefix + '/' + nameClassPair.getName();
}
final Object value = initialContext.lookup(jndiName);
if (value instanceof DataSource) {
dataSources.put(jndiName, (DataSource) value);
}
}
} catch (final NamingException e) {
// (dans glassfish 3.0.1, c'est une NamingException et non une NameNotFoundException)
return dataSources;
}
initialContext.close();
return dataSources;
}
static int getMaxConnectionCount() {
if (!TOMCAT_BASIC_DATASOURCES_PROPERTIES.isEmpty()) {
return TOMCAT_BASIC_DATASOURCES_PROPERTIES.getMaxActive();
} else if (!DBCP_BASIC_DATASOURCES_PROPERTIES.isEmpty()) {
return DBCP_BASIC_DATASOURCES_PROPERTIES.getMaxActive();
} else if (!TOMCAT_JDBC_DATASOURCES_PROPERTIES.isEmpty()) {
return TOMCAT_JDBC_DATASOURCES_PROPERTIES.getMaxActive();
}
return -1;
}
static Map<String, Map<String, Object>> getBasicDataSourceProperties() {
if (!TOMCAT_BASIC_DATASOURCES_PROPERTIES.isEmpty()) {
return TOMCAT_BASIC_DATASOURCES_PROPERTIES.getDataSourcesProperties();
} else if (!DBCP_BASIC_DATASOURCES_PROPERTIES.isEmpty()) {
return DBCP_BASIC_DATASOURCES_PROPERTIES.getDataSourcesProperties();
} else if (!TOMCAT_JDBC_DATASOURCES_PROPERTIES.isEmpty()) {
return TOMCAT_JDBC_DATASOURCES_PROPERTIES.getDataSourcesProperties();
}
return Collections.emptyMap();
}
static void pullDataSourceProperties(String name, DataSource dataSource) {
final String dataSourceClassName = dataSource.getClass().getName();
if ("org.apache.tomcat.dbcp.dbcp.BasicDataSource".equals(dataSourceClassName)
&& dataSource instanceof BasicDataSource) {
pullTomcatDbcpDataSourceProperties(name, dataSource);
} else if ("org.apache.commons.dbcp.BasicDataSource"
.equals(dataSource.getClass().getName())
&& dataSource instanceof org.apache.commons.dbcp.BasicDataSource) {
pullCommonsDbcpDataSourceProperties(name, dataSource);
} else if ("org.apache.tomcat.jdbc.pool.DataSource".equals(dataSource.getClass().getName())
&& dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource) {
pullTomcatJdbcDataSourceProperties(name, dataSource);
}
}
private static void pullTomcatDbcpDataSourceProperties(String name, DataSource dataSource) {
final BasicDataSource tcDataSource = (BasicDataSource) dataSource;
final BasicDataSourcesProperties properties = TOMCAT_BASIC_DATASOURCES_PROPERTIES;
properties.put(name, MAX_ACTIVE_PROPERTY_NAME, tcDataSource.getMaxActive());
properties.put(name, "poolPreparedStatements", tcDataSource.isPoolPreparedStatements());
properties.put(name, "defaultCatalog", tcDataSource.getDefaultCatalog());
properties.put(name, "defaultAutoCommit", tcDataSource.getDefaultAutoCommit());
properties.put(name, "defaultReadOnly", tcDataSource.getDefaultReadOnly());
properties.put(name, "defaultTransactionIsolation",
tcDataSource.getDefaultTransactionIsolation());
properties.put(name, "driverClassName", tcDataSource.getDriverClassName());
properties.put(name, "initialSize", tcDataSource.getInitialSize());
properties.put(name, "maxIdle", tcDataSource.getMaxIdle());
properties.put(name, "maxOpenPreparedStatements",
tcDataSource.getMaxOpenPreparedStatements());
properties.put(name, "maxWait", tcDataSource.getMaxWait());
properties.put(name, "minEvictableIdleTimeMillis",
tcDataSource.getMinEvictableIdleTimeMillis());
properties.put(name, "minIdle", tcDataSource.getMinIdle());
properties.put(name, "numTestsPerEvictionRun", tcDataSource.getNumTestsPerEvictionRun());
properties.put(name, "testOnBorrow", tcDataSource.getTestOnBorrow());
properties.put(name, "testOnReturn", tcDataSource.getTestOnReturn());
properties.put(name, "testWhileIdle", tcDataSource.getTestWhileIdle());
properties.put(name, "timeBetweenEvictionRunsMillis",
tcDataSource.getTimeBetweenEvictionRunsMillis());
properties.put(name, "validationQuery", tcDataSource.getValidationQuery());
}
private static void pullCommonsDbcpDataSourceProperties(String name, DataSource dataSource) {
final org.apache.commons.dbcp.BasicDataSource dbcpDataSource = (org.apache.commons.dbcp.BasicDataSource) dataSource;
final BasicDataSourcesProperties properties = DBCP_BASIC_DATASOURCES_PROPERTIES;
properties.put(name, MAX_ACTIVE_PROPERTY_NAME, dbcpDataSource.getMaxActive());
properties.put(name, "poolPreparedStatements", dbcpDataSource.isPoolPreparedStatements());
properties.put(name, "defaultCatalog", dbcpDataSource.getDefaultCatalog());
properties.put(name, "defaultAutoCommit", dbcpDataSource.getDefaultAutoCommit());
properties.put(name, "defaultReadOnly", dbcpDataSource.getDefaultReadOnly());
properties.put(name, "defaultTransactionIsolation",
dbcpDataSource.getDefaultTransactionIsolation());
properties.put(name, "driverClassName", dbcpDataSource.getDriverClassName());
properties.put(name, "initialSize", dbcpDataSource.getInitialSize());
properties.put(name, "maxIdle", dbcpDataSource.getMaxIdle());
properties.put(name, "maxOpenPreparedStatements",
dbcpDataSource.getMaxOpenPreparedStatements());
properties.put(name, "maxWait", dbcpDataSource.getMaxWait());
properties.put(name, "minEvictableIdleTimeMillis",
dbcpDataSource.getMinEvictableIdleTimeMillis());
properties.put(name, "minIdle", dbcpDataSource.getMinIdle());
properties.put(name, "numTestsPerEvictionRun", dbcpDataSource.getNumTestsPerEvictionRun());
properties.put(name, "testOnBorrow", dbcpDataSource.getTestOnBorrow());
properties.put(name, "testOnReturn", dbcpDataSource.getTestOnReturn());
properties.put(name, "testWhileIdle", dbcpDataSource.getTestWhileIdle());
properties.put(name, "timeBetweenEvictionRunsMillis",
dbcpDataSource.getTimeBetweenEvictionRunsMillis());
properties.put(name, "validationQuery", dbcpDataSource.getValidationQuery());
}
private static void pullTomcatJdbcDataSourceProperties(String name, DataSource dataSource) {
final org.apache.tomcat.jdbc.pool.DataSource jdbcDataSource = (org.apache.tomcat.jdbc.pool.DataSource) dataSource;
final BasicDataSourcesProperties properties = TOMCAT_JDBC_DATASOURCES_PROPERTIES;
properties.put(name, MAX_ACTIVE_PROPERTY_NAME, jdbcDataSource.getMaxActive());
properties.put(name, "defaultCatalog", jdbcDataSource.getDefaultCatalog());
properties.put(name, "defaultAutoCommit", jdbcDataSource.getDefaultAutoCommit());
properties.put(name, "defaultReadOnly", jdbcDataSource.getDefaultReadOnly());
properties.put(name, "defaultTransactionIsolation",
jdbcDataSource.getDefaultTransactionIsolation());
properties.put(name, "driverClassName", jdbcDataSource.getDriverClassName());
properties.put(name, "connectionProperties", jdbcDataSource.getConnectionProperties());
properties.put(name, "initSQL", jdbcDataSource.getInitSQL());
properties.put(name, "initialSize", jdbcDataSource.getInitialSize());
properties.put(name, "maxIdle", jdbcDataSource.getMaxIdle());
properties.put(name, "maxWait", jdbcDataSource.getMaxWait());
properties.put(name, "maxAge", jdbcDataSource.getMaxAge());
properties.put(name, "faireQueue", jdbcDataSource.isFairQueue());
properties.put(name, "jmxEnabled", jdbcDataSource.isJmxEnabled());
properties.put(name, "minEvictableIdleTimeMillis",
jdbcDataSource.getMinEvictableIdleTimeMillis());
properties.put(name, "minIdle", jdbcDataSource.getMinIdle());
properties.put(name, "numTestsPerEvictionRun", jdbcDataSource.getNumTestsPerEvictionRun());
properties.put(name, "testOnBorrow", jdbcDataSource.isTestOnBorrow());
properties.put(name, "testOnConnect", jdbcDataSource.isTestOnConnect());
properties.put(name, "testOnReturn", jdbcDataSource.isTestOnReturn());
properties.put(name, "testWhileIdle", jdbcDataSource.isTestWhileIdle());
properties.put(name, "timeBetweenEvictionRunsMillis",
jdbcDataSource.getTimeBetweenEvictionRunsMillis());
properties.put(name, "validationInterval", jdbcDataSource.getValidationInterval());
properties.put(name, "validationQuery", jdbcDataSource.getValidationQuery());
properties.put(name, "validatorClassName", jdbcDataSource.getValidatorClassName());
}
@SuppressWarnings("all")
// CHECKSTYLE:OFF
private static Object changeContextWritable(ServletContext servletContext, Object lock)
throws NoSuchFieldException, ClassNotFoundException, IllegalAccessException,
NamingException {
assert servletContext != null;
final String serverInfo = servletContext.getServerInfo();
if ((serverInfo.contains("Tomcat") || serverInfo.contains("vFabric") || serverInfo
.contains("SpringSource tc Runtime")) && System.getProperty("jonas.name") == null) {
// et si ce n'est pas tomcat dans jonas
final Field field = Class.forName("org.apache.naming.ContextAccessController")
.getDeclaredField("readOnlyContexts");
setFieldAccessible(field);
@SuppressWarnings("unchecked")
final Hashtable<String, Object> readOnlyContexts = (Hashtable<String, Object>) field
.get(null);
// "/Catalina/" + hostName + Parameters.getContextPath(servletContext) ;
// et contextPath vaut "/myapp" par exemple ;
// la valeur est un securityToken
if (lock == null) {
// (cf issue 105)
final Hashtable<String, Object> clone = new Hashtable<String, Object>(
readOnlyContexts);
readOnlyContexts.clear();
return clone;
}
// on remet le contexte not writable comme avant
@SuppressWarnings("unchecked")
final Hashtable<String, Object> myLock = (Hashtable<String, Object>) lock;
readOnlyContexts.putAll(myLock);
return null;
} else if (serverInfo.contains("jetty")) {
final Context jdbcContext = (Context) new InitialContext().lookup("java:comp");
final Field field = getAccessibleField(jdbcContext, "_env");
@SuppressWarnings("unchecked")
final Hashtable<Object, Object> env = (Hashtable<Object, Object>) field
.get(jdbcContext);
if (lock == null) {
// on rend le contexte writable
Object result = env.remove("org.mortbay.jndi.lock");
if (result == null) {
result = env.remove("org.eclipse.jndi.lock");
}
return result;
}
// on remet le contexte not writable comme avant
env.put("org.mortbay.jndi.lock", lock);
env.put("org.eclipse.jndi.lock", lock);
return null;
}
return null;
}
static Object getFieldValue(Object object, String fieldName) throws IllegalAccessException {
return getAccessibleField(object, fieldName).get(object);
}
static void setFieldValue(Object object, String fieldName, Object value)
throws IllegalAccessException {
getAccessibleField(object, fieldName).set(object, value);
}
private static Field getAccessibleField(Object object, String fieldName) {
assert fieldName != null;
Class<?> classe = object.getClass();
Field result = null;
do {
for (final Field field : classe.getDeclaredFields()) {
if (fieldName.equals(field.getName())) {
result = field;
break;
}
}
classe = classe.getSuperclass();
} while (result == null && classe != null);
assert result != null;
setFieldAccessible(result);
return result;
}
private static void setFieldAccessible(final Field field) {
AccessController.doPrivileged(new PrivilegedAction<Object>() { // pour findbugs
/** {@inheritDoc} */
@Override
public Object run() {
field.setAccessible(true);
return null;
}
});
}
// CHECKSTYLE:ON
}
|
package net.dryanhild.collada;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
public class ColladaLoaderTests {
private ColladaLoaderServiceImpl testService;
@Test
public void serviceProviderImplementationFound() {
ColladaLoader loader = new ColladaLoader();
Collection<VersionSupport> versions = loader.getRegisteredVersions();
assertThat(versions).contains(ColladaLoaderServiceImpl.TEST_VERSION);
}
@DataProvider
public Object[][] flagConfigurations() {
return new Object[][]{
{Boolean.FALSE, StandardCharsets.UTF_8},
{Boolean.TRUE, StandardCharsets.UTF_8},
};
}
@Test(dataProvider = "flagConfigurations")
public void loadReader(boolean validate, Charset charset)
throws IOException, NoSuchFieldException, IllegalAccessException {
ColladaLoader loader = createLoader(validate, charset);
InputStream reader =
new ByteArrayInputStream(ColladaLoaderServiceImpl.TEST_BASIC_FILE.getBytes(StandardCharsets.UTF_8));
loader.load(reader);
assertThat(loader.isValidating()).isEqualTo(validate);
assertThat(testService.lastContext.isValidating()).isEqualTo(validate);
assertThat(testService.lastContext.getMainFileInputStream()).isNotNull();
}
@Test(expectedExceptions = IncorrectFormatException.class)
public void loadNonImplementedLoader() throws IOException {
ColladaLoader loader = new ColladaLoader();
InputStream reader = new ByteArrayInputStream("Bad input.".getBytes(StandardCharsets.UTF_8));
loader.load(reader);
}
@Test(expectedExceptions = IOException.class)
public void ioExceptionInHeaderRead() throws IOException {
InputStream reader = new ErrorOnReadReader();
ColladaLoader loader = new ColladaLoader();
loader.load(reader);
}
@Test(expectedExceptions = IOException.class)
public void ioExceptionInClose() throws IOException {
InputStream reader = new ErrorOnCloseReader();
ColladaLoader loader = new ColladaLoader();
loader.load(reader);
}
private static class ErrorOnReadReader extends InputStream {
@Override
public int read() throws IOException {
throw new IOException();
}
}
private static class ErrorOnCloseReader extends InputStream {
private final InputStream reader =
new ByteArrayInputStream(ColladaLoaderServiceImpl.TEST_BASIC_FILE.getBytes(StandardCharsets.UTF_8));
@Override
public void close() throws IOException {
throw new IOException();
}
@Override
public int read() throws IOException {
return reader.read();
}
}
private ColladaLoader createLoader(boolean validate, Charset charset)
throws NoSuchFieldException, IllegalAccessException {
ColladaLoader loader = new ColladaLoader();
loader.setValidating(validate);
loader.setCharset(charset);
Class<?> c = loader.getClass();
Field field = c.getDeclaredField("loaders");
field.setAccessible(true);
Object services = field.get(loader);
if (Iterable.class.isAssignableFrom(services.getClass())) {
for (Object o : (Iterable<?>) services) {
if (o instanceof ColladaLoaderServiceImpl) {
testService = (ColladaLoaderServiceImpl) o;
}
}
}
return loader;
}
}
|
package org.chromium;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class ChromeSocketsUdp extends CordovaPlugin {
private static final String LOG_TAG = "ChromeSocketsUdp";
private Map<Integer, UdpSocket> sockets = new ConcurrentHashMap<Integer, UdpSocket>();
private BlockingQueue<SelectorMessage> selectorMessages =
new LinkedBlockingQueue<SelectorMessage>();
private int nextSocket = 0;
private CallbackContext recvContext;
private Selector selector;
private SelectorThread selectorThread;
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
if ("create".equals(action)) {
create(args, callbackContext);
} else if ("update".equals(action)) {
update(args, callbackContext);
} else if ("setPaused".equals(action)) {
setPaused(args, callbackContext);
} else if ("bind".equals(action)) {
bind(args, callbackContext);
} else if ("send".equals(action)) {
send(args, callbackContext);
} else if ("close".equals(action)) {
close(args, callbackContext);
} else if ("getInfo".equals(action)) {
getInfo(args, callbackContext);
} else if ("getSockets".equals(action)) {
getSockets(args, callbackContext);
} else if ("joinGroup".equals(action)) {
joinGroup(args, callbackContext);
} else if ("leaveGroup".equals(action)) {
leaveGroup(args, callbackContext);
} else if ("setMulticastTimeToLive".equals(action)) {
setMulticastTimeToLive(args, callbackContext);
} else if ("setMulticastLoopbackMode".equals(action)) {
setMulticastLoopbackMode(args, callbackContext);
} else if ("getJoinedGroups".equals(action)) {
getJoinedGroups(args, callbackContext);
} else if ("registerReceiveEvents".equals(action)) {
registerReceiveEvents(args, callbackContext);
} else {
return false;
}
return true;
}
public void onDestory() {
closeAllSockets();
stopSelectorThread();
}
public void onReset() {
closeAllSockets();
stopSelectorThread();
}
private void create(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
JSONObject properties = args.getJSONObject(0);
try {
UdpSocket socket = new UdpSocket(nextSocket++, recvContext, properties);
selectorMessages.put(
new SelectorMessage(socket, SelectorMessageType.SO_CREATE, callbackContext));
selector.wakeup();
} catch (IOException e) {
} catch (InterruptedException e) {
}
}
private void update(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
JSONObject properties = args.getJSONObject(1);
UdpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
try {
socket.setProperties(properties);
} catch (SocketException e) {
}
callbackContext.success();
}
private void setPaused(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
boolean paused = args.getBoolean(1);
UdpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
socket.setPaused(paused);
callbackContext.success();
}
private void bind(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
String address = args.getString(1);
int port = args.getInt(2);
UdpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
callbackContext.error(-1000);
return;
}
try {
socket.bind(address, port);
callbackContext.success();
} catch (SocketException e) {
callbackContext.error(-1000);
}
}
private void send(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
String address = args.getString(1);
int port = args.getInt(2);
byte[] data = args.getArrayBuffer(3);
UdpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
callbackContext.error(-1000);
return;
}
try {
int bytesSent = socket.send(address, port, data);
if (bytesSent > 0) {
callbackContext.success(bytesSent);
} else {
socket.addSendPacket(address, port, data, callbackContext);
}
} catch (IOException e) {
callbackContext.error(-1000);
}
}
private void sendCloseMessage(UdpSocket socket, CallbackContext callbackContext)
throws InterruptedException {
selectorMessages.put(
new SelectorMessage(socket, SelectorMessageType.SO_CLOSE, callbackContext));
}
private void closeAllSockets() {
try {
for (UdpSocket socket: sockets.values()) {
sendCloseMessage(socket, null);
}
selector.wakeup();
} catch (InterruptedException e) {
}
}
private void close(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
UdpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
try {
sendCloseMessage(socket, callbackContext);
selector.wakeup();
} catch (InterruptedException e) {
}
}
private void getInfo(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
UdpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
callbackContext.success(socket.getInfo());
}
private void getSockets(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
JSONArray results = new JSONArray();
for (UdpSocket socket: sockets.values()) {
results.put(socket.getInfo());
}
callbackContext.success(results);
}
private void joinGroup(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
String address = args.getString(1);
UdpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
callbackContext.error(-1000);
return;
}
try {
socket.joinGroup(address);
callbackContext.success();
} catch (UnknownHostException e) {
callbackContext.error(-1000);
} catch (IOException e) {
callbackContext.error(-1000);
}
}
private void leaveGroup(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
String address = args.getString(1);
UdpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
callbackContext.error(-1000);
return;
}
try {
socket.leaveGroup(address);
callbackContext.success();
} catch (UnknownHostException e) {
callbackContext.error(-1000);
} catch (IOException e) {
callbackContext.error(-1000);
}
}
private void setMulticastTimeToLive(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
int ttl = args.getInt(1);
UdpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
callbackContext.error(-1000);
return;
}
try {
socket.setMulticastTimeToLive(ttl);
callbackContext.success();
} catch (IOException e) {
callbackContext.error(-1000);
}
}
private void setMulticastLoopbackMode(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
boolean enabled = args.getBoolean(1);
UdpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
callbackContext.error(-1000);
return;
}
try {
socket.setMulticastLoopbackMode(enabled);
callbackContext.success();
} catch (SocketException e) {
callbackContext.error(-1000);
}
}
private void getJoinedGroups(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
UdpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
callbackContext.success(new JSONArray(socket.getJoinedGroups()));
}
private void registerReceiveEvents(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
recvContext = callbackContext;
startSelectorThread();
}
private void startSelectorThread() {
if (selector != null && selectorThread != null) return;
try {
selector = Selector.open();
selectorThread = new SelectorThread(selector, selectorMessages, sockets);
selectorThread.start();
} catch (IOException e) {
selector = null;
selectorThread = null;
PluginResult err = new PluginResult(Status.ERROR, -1000);
err.setKeepCallback(true);
recvContext.sendPluginResult(err);
}
}
private void stopSelectorThread() {
if (selector == null && selectorThread == null) return;
try {
selectorMessages.put(new SelectorMessage(null, SelectorMessageType.T_STOP, null));
selector.wakeup();
selectorThread.join();
selector = null;
selectorThread = null;
} catch (InterruptedException e) {
}
}
private enum SelectorMessageType {
SO_CREATE,
SO_CLOSE,
T_STOP;
}
private class SelectorMessage {
final UdpSocket socket;
final SelectorMessageType type;
final CallbackContext callbackContext;
SelectorMessage(
UdpSocket socket, SelectorMessageType type, CallbackContext callbackContext) {
this.socket = socket;
this.type = type;
this.callbackContext = callbackContext;
}
}
private class SelectorThread extends Thread {
private final Selector selector;
private BlockingQueue<SelectorMessage> selectorMessages;
private Map<Integer, UdpSocket> sockets;
private boolean running = true;
SelectorThread(
Selector selector, BlockingQueue<SelectorMessage> selectorMessages,
Map<Integer, UdpSocket> sockets) {
this.selector = selector;
this.selectorMessages = selectorMessages;
this.sockets = sockets;
}
private void processPendingMessages() {
while (selectorMessages.peek() != null) {
SelectorMessage msg = null;
try {
msg = selectorMessages.take();
switch (msg.type) {
case SO_CREATE:
msg.socket.register(selector, SelectionKey.OP_READ);
sockets.put(Integer.valueOf(msg.socket.getSocketId()), msg.socket);
msg.callbackContext.success(msg.socket.getSocketId());
break;
case SO_CLOSE:
msg.socket.close();
sockets.remove(Integer.valueOf(msg.socket.getSocketId()));
if (msg.callbackContext != null)
msg.callbackContext.success();
break;
case T_STOP:
running = false;
break;
}
} catch (InterruptedException e) {
} catch (IOException e) {
if (msg.callbackContext != null) {
msg.callbackContext.error(-1000);
}
}
}
}
public void run() {
Iterator<SelectionKey> it;
while (running) {
try {
selector.select();
} catch (IOException e) {
continue;
}
it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (!key.isValid()) {
continue;
}
UdpSocket socket = (UdpSocket)key.attachment();
if (key.isReadable()) {
socket.read();
}
if (key.isWritable()) {
socket.dequeueSend();
}
} // while next
processPendingMessages();
}
}
}
private class UdpSocket {
private final int socketId;
private final DatagramChannel channel;
private final MulticastSocket multicastSocket;
private final CallbackContext recvContext;
private BlockingQueue<UdpSendPacket> sendPackets = new LinkedBlockingQueue<UdpSendPacket>();
private HashSet<String> multicastGroups = new HashSet<String>();
private SelectionKey key;
private boolean paused;
private boolean persistent;
private String name;
private int bufferSize;
private MulticastReadThread multicastReadThread;
UdpSocket(int socketId, CallbackContext recvContext, JSONObject properties)
throws JSONException, IOException {
this.socketId = socketId;
this.recvContext = recvContext;
channel = DatagramChannel.open();
channel.configureBlocking(false);
multicastSocket = new MulticastSocket(null);
// set socket default options
paused = false;
persistent = false;
bufferSize = 4096;
name = "";
multicastReadThread = null;
setProperties(properties);
setBufferSize();
}
void addInterestSet(int interestSet) {
if (key != null) {
key.interestOps(key.interestOps() | interestSet);
key.selector().wakeup();
}
}
void removeInterestSet(int interestSet) {
if (key != null) {
key.interestOps(key.interestOps() & ~interestSet);
key.selector().wakeup();
}
}
int getSocketId() {
return socketId;
}
void register(Selector selector, int interestSets) throws IOException {
key = channel.register(selector, interestSets, this);
}
void setProperties(JSONObject properties) throws JSONException, SocketException {
if (!properties.isNull("persistent"))
persistent = properties.getBoolean("persistent");
if (!properties.isNull("name"))
name = properties.getString("name");
if (!properties.isNull("bufferSize")) {
bufferSize = properties.getInt("bufferSize");
setBufferSize();
}
}
void setBufferSize() throws SocketException {
channel.socket().setSendBufferSize(bufferSize);
channel.socket().setReceiveBufferSize(bufferSize);
}
void setPaused(boolean paused) {
this.paused = paused;
if (paused) {
removeInterestSet(SelectionKey.OP_READ);
} else {
addInterestSet(SelectionKey.OP_READ);
}
}
void addSendPacket(String address, int port, byte[] data, CallbackContext callbackContext) {
UdpSendPacket sendPacket = new UdpSendPacket(address, port, data, callbackContext);
addInterestSet(SelectionKey.OP_WRITE);
try {
sendPackets.put(sendPacket);
} catch (InterruptedException e) {
}
}
void bind(String address, int port) throws SocketException {
channel.socket().setReuseAddress(true);
channel.socket().bind(new InetSocketAddress(port));
}
int send(String address, int port, byte[] data) throws IOException {
return channel.send(ByteBuffer.wrap(data), new InetSocketAddress(address, port));
}
void dequeueSend() {
if (sendPackets.peek() != null) {
UdpSendPacket sendPacket = null;
try {
sendPacket = sendPackets.take();
int bytesSent = channel.send(sendPacket.data, sendPacket.address);
sendPacket.callbackContext.success(bytesSent);
} catch (InterruptedException e) {
} catch (IOException e) {
sendPacket.callbackContext.error(-1000);
}
} else {
removeInterestSet(SelectionKey.OP_WRITE);
}
}
void close() throws IOException {
if (key != null && channel.isRegistered())
key.cancel();
channel.close();
multicastSocket.close();
if (multicastReadThread != null) {
multicastReadThread.cancel();
}
}
JSONObject getInfo() throws JSONException {
JSONObject info = new JSONObject();
info.put("socketId", socketId);
info.put("persistent", persistent);
info.put("bufferSize", bufferSize);
info.put("name", name);
info.put("paused", paused);
if (channel.socket().getLocalAddress() != null) {
info.put("localAddress", channel.socket().getLocalAddress().getHostAddress());
info.put("localPort", channel.socket().getLocalPort());
}
return info;
}
void joinGroup(String address) throws UnknownHostException, IOException {
if (multicastGroups.contains(address)) {
Log.e(LOG_TAG, "Attempted to join an already joined multicast group.");
return;
}
multicastGroups.add(address);
multicastSocket.joinGroup(InetAddress.getByName(address));
if (multicastReadThread == null) {
multicastSocket.setReuseAddress(true);
multicastSocket.bind(new InetSocketAddress(channel.socket().getLocalPort()));
multicastReadThread = new MulticastReadThread(socketId, multicastSocket, recvContext);
multicastReadThread.start();
}
}
void leaveGroup(String address) throws UnknownHostException, IOException {
if (multicastGroups.contains(address)) {
multicastGroups.remove(address);
multicastSocket.leaveGroup(InetAddress.getByName(address));
}
}
void setMulticastTimeToLive(int ttl) throws IOException {
multicastSocket.setTimeToLive(ttl);
}
void setMulticastLoopbackMode(boolean enabled) throws SocketException {
multicastSocket.setLoopbackMode(!enabled);
}
public Collection<String> getJoinedGroups() {
return multicastGroups;
}
void read() {
if (paused) return;
ByteBuffer recvBuffer = ByteBuffer.allocate(bufferSize);
recvBuffer.clear();
try {
SocketAddress address = channel.receive(recvBuffer);
recvBuffer.flip();
byte[] recvBytes = new byte[recvBuffer.limit()];
recvBuffer.get(recvBytes);
PluginResult dataResult = new PluginResult(Status.OK, recvBytes);
dataResult.setKeepCallback(true);
recvContext.sendPluginResult(dataResult);
JSONObject metadata = new JSONObject();
metadata.put("socketId", socketId);
if (address instanceof InetSocketAddress) {
InetSocketAddress remoteInfo = (InetSocketAddress) address;
metadata.put("remoteAddress", remoteInfo.getAddress().getHostAddress());
metadata.put("remotePort", remoteInfo.getPort());
}
PluginResult metadataResult = new PluginResult(Status.OK, metadata);
metadataResult.setKeepCallback(true);
recvContext.sendPluginResult(metadataResult);
} catch (IOException e) {
} catch (JSONException e) {
}
}
private class MulticastReadThread extends Thread {
private final int socketId;
private final MulticastSocket socket;
private final CallbackContext recvContext;
MulticastReadThread(int socketId, MulticastSocket socket, CallbackContext recvContext) {
this.socketId = socketId;
this.socket = socket;
this.recvContext = recvContext;
}
public void run() {
while(!Thread.currentThread().isInterrupted()) {
try {
byte[] out = new byte[socket.getReceiveBufferSize()];
DatagramPacket packet = new DatagramPacket(out, out.length);
socket.receive(packet);
PluginResult dataResult = new PluginResult(Status.OK, out);
dataResult.setKeepCallback(true);
recvContext.sendPluginResult(dataResult);
JSONObject metadata = new JSONObject();
metadata.put("socketId", socketId);
metadata.put("remoteAddress", packet.getAddress().getHostAddress());
metadata.put("remotePort", packet.getPort());
PluginResult metadataResult = new PluginResult(Status.OK, metadata);
metadataResult.setKeepCallback(true);
recvContext.sendPluginResult(metadataResult);
} catch (IOException e) {
} catch (JSONException e) {
}
}
}
public void cancel() {
interrupt();
}
}
private class UdpSendPacket {
final SocketAddress address;
final CallbackContext callbackContext;
final ByteBuffer data;
UdpSendPacket(String address, int port, byte[] data, CallbackContext callbackContext) {
this.address = new InetSocketAddress(address, port);
this.data = ByteBuffer.wrap(data);
this.callbackContext = callbackContext;
}
}
}
}
|
package co.phoenixlab.discord.api.request.channel.message;
import co.phoenixlab.discord.api.util.SnowflakeUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class BulkMessageDeleteRequest {
@Size(min = 2, max = 100)
private String[] messages;
static class Builder {
private ArrayList<String> pending;
public Builder() {
pending = new ArrayList<>();
}
public Builder messages(String[] msgIds) {
pending.addAll(Arrays.asList(msgIds));
return this;
}
public Builder addMessage(String msgId) {
pending.add(msgId);
return this;
}
public Builder messages(long[] msgIds) {
pending.addAll(Arrays.stream(msgIds).
mapToObj(SnowflakeUtils::snowflakeToString).
collect(Collectors.toList()));
return this;
}
public Builder addMessage(long msgId) {
pending.add(SnowflakeUtils.snowflakeToString(msgId));
return this;
}
public BulkMessageDeleteRequest build() {
return new BulkMessageDeleteRequest(pending.toArray(new String[pending.size()]));
}
}
}
|
package org.jetbrains.jps.incremental.java;
import com.intellij.compiler.notNullVerification.NotNullVerifyingInstrumenter;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.uiDesigner.compiler.*;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.lw.CompiledClassPropertiesProvider;
import com.intellij.uiDesigner.lw.LwRootContainer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.ether.dependencyView.Callbacks;
import org.jetbrains.ether.dependencyView.Mappings;
import org.jetbrains.jps.Module;
import org.jetbrains.jps.ModuleChunk;
import org.jetbrains.jps.ProjectPaths;
import org.jetbrains.jps.incremental.Builder;
import org.jetbrains.jps.incremental.CompileContext;
import org.jetbrains.jps.incremental.FileProcessor;
import org.jetbrains.jps.incremental.ProjectBuildException;
import org.jetbrains.jps.incremental.messages.BuildMessage;
import org.jetbrains.jps.incremental.messages.CompilerMessage;
import org.jetbrains.jps.incremental.messages.ProgressMessage;
import org.jetbrains.jps.incremental.storage.TimestampStorage;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.EmptyVisitor;
import javax.tools.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.concurrent.ExecutorService;
public class JavaBuilder extends Builder{
public static final String BUILDER_NAME = "java";
private static final String JAVA_EXTENSION = ".java";
private static final String FORM_EXTENSION = ".form";
private static final FileFilter JAVA_SOURCES_FILTER = new FileFilter() {
public boolean accept(File file) {
return file.getPath().endsWith(JAVA_EXTENSION);
}
};
private static final FileFilter FORM_SOURCES_FILTER = new FileFilter() {
public boolean accept(File file) {
return file.getPath().endsWith(FORM_EXTENSION);
}
};
private static final Key<Callbacks.Backend> DELTA_MAPPINGS_CALLBACK_KEY = Key.create("_dependency_data_");
private final EmbeddedJavac myJavacCompiler;
public JavaBuilder(ExecutorService tasksExecutor) {
myJavacCompiler = new EmbeddedJavac(tasksExecutor);
//add here class processors in the sequence they should be executed
myJavacCompiler.addClassProcessor(new EmbeddedJavac.ClassPostProcessor() {
public void process(CompileContext context, OutputFileObject out) {
final Callbacks.Backend callback = DELTA_MAPPINGS_CALLBACK_KEY.get(context);
if (callback != null) {
final OutputFileObject.Content content = out.getContent();
final File srcFile = out.getSourceFile();
if (srcFile != null && content != null) {
final String outputPath = FileUtil.toSystemIndependentName(out.getFile().getPath());
final String sourcePath = FileUtil.toSystemIndependentName(srcFile.getPath());
try {
context.getBuildDataManager().getOutputToSourceStorage().update(outputPath, sourcePath);
}
catch (Exception e) {
context.processMessage(new CompilerMessage(BUILDER_NAME, e));
}
final ClassReader reader = new ClassReader(content.getBuffer(), content.getOffset(), content.getLength());
// todo: the callback is not thread-safe?
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (context.getMappings()) {
// todo: parse class data out of synchronized block (move it from the 'associate' implementation)
callback.associate(outputPath, Callbacks.getDefaultLookup(sourcePath), reader);
}
}
}
}
});
}
@Override
public String getName() {
return BUILDER_NAME;
}
public String getDescription() {
return "Java Builder";
}
private static final Key<Set<File>> TEMPORARY_SOURCE_ROOTS_KEY = Key.create("_additional_source_roots_");
public static void addTempSourcePathRoot(CompileContext context, File root) {
Set<File> roots = TEMPORARY_SOURCE_ROOTS_KEY.get(context);
if (roots == null) {
roots = new HashSet<File>();
TEMPORARY_SOURCE_ROOTS_KEY.set(context, roots);
}
roots.add(root);
}
public ExitCode build(final CompileContext context, final ModuleChunk chunk) throws ProjectBuildException {
try {
final TimestampStorage tsStorage = context.getBuildDataManager().getTimestampStorage(BUILDER_NAME);
final Set<File> filesToCompile = new LinkedHashSet<File>();
final List<File> formsToCompile = new ArrayList<File>();
final List<File> upToDateForms = new ArrayList<File>();
final Set<String> srcRoots = new HashSet<String>();
final boolean wholeModuleRebuildRequired = context.isDirty(chunk);
context.processFiles(chunk, new FileProcessor() {
public boolean apply(Module module, File file, String sourceRoot) throws Exception {
if (JAVA_SOURCES_FILTER.accept(file)) {
srcRoots.add(sourceRoot);
if (wholeModuleRebuildRequired || isFileDirty(file, context, tsStorage)) {
filesToCompile.add(file);
}
}
else if (FORM_SOURCES_FILTER.accept(file)){
if (wholeModuleRebuildRequired || isFileDirty(file, context, tsStorage)) {
formsToCompile.add(file);
}
else {
upToDateForms.add(file);
}
}
return true;
}
});
// force compilation of bound source file if the form is dirty
for (File form : formsToCompile) {
for (String root : srcRoots) {
final File boundSource = getBoundSource(root, form);
if (boundSource != null) {
// force compilation of classes that modified forms are bound to
filesToCompile.add(boundSource);
break;
}
}
}
// form should be considered dirty if the class it is bound to is also dirty!
for (File form : upToDateForms) {
for (String root : srcRoots) {
final File boundSource = getBoundSource(root, form);
if (boundSource != null && filesToCompile.contains(boundSource)) {
formsToCompile.add(form);
break;
}
}
}
upToDateForms.clear();
context.deleteCorrespondingClasses(filesToCompile);
return compile(context, chunk, filesToCompile, formsToCompile);
}
catch (ProjectBuildException e) {
throw e;
}
catch (Exception e) {
String message = e.getMessage();
if (message == null) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(out));
message = "Internal error: \n" + out.toString();
}
context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, message));
throw new ProjectBuildException(message, e);
}
}
@Nullable
private static File getBoundSource(String srcRoot, File formFile) throws IOException {
final String boundClassName = FormsParsing.readBoundClassName(formFile);
if (boundClassName == null) {
return null;
}
String relPath = boundClassName.replace('.', '/') + JAVA_EXTENSION;
while (true) {
final File candidate = new File(srcRoot, relPath);
if (candidate.exists()) {
return candidate.isFile()? candidate : null;
}
final int index = relPath.lastIndexOf('/');
if (index <= 0) {
return null;
}
relPath = relPath.substring(0, index) + JAVA_EXTENSION;
}
}
private ExitCode compile(final CompileContext context, ModuleChunk chunk, Collection<File> files, Collection<File> forms) throws Exception {
ExitCode exitCode = ExitCode.OK;
final boolean hasSourcesToCompile = !files.isEmpty() || !forms.isEmpty();
if (!hasSourcesToCompile && !context.hasRemovedSources()) {
return exitCode;
}
final ProjectPaths paths = context.getProjectPaths();
final Mappings delta = context.createDelta();
DELTA_MAPPINGS_CALLBACK_KEY.set(context, delta.getCallback());
// todo: consider corresponding setting in CompilerWorkspaceConfiguration
final boolean addNotNullAssertions = true;
final Collection<File> classpath = paths.getCompilationClasspath(chunk, context.isCompilingTests(), !context.isMake());
final Collection<File> platformCp = paths.getPlatformCompilationClasspath(chunk, context.isCompilingTests(), !context.isMake());
final Map<File, Set<File>> outs = buildOutputDirectoriesMap(context, chunk);
final List<String> options = getCompilationOptions(context, chunk);
// begin compilation round
final DiagnosticSink diagnosticSink = new DiagnosticSink(context);
final OutputFilesSink outputSink = new OutputFilesSink(context);
Collection<File> successfulForms = Collections.emptyList();
try {
if (hasSourcesToCompile) {
final Set<File> sourcePath = TEMPORARY_SOURCE_ROOTS_KEY.get(context,Collections.<File>emptySet());
final boolean compiledOk = myJavacCompiler.compile(
options, files, classpath, platformCp, sourcePath, outs, context, diagnosticSink, outputSink
);
final Map<File, String> chunkSourcePath = ProjectPaths.getSourceRootsWithDependents(chunk, context.isCompilingTests());
final ClassLoader compiledClassesLoader = createInstrumentationClassLoader(classpath, platformCp, chunkSourcePath, outputSink);
if (!forms.isEmpty()) {
try {
context.processMessage(new ProgressMessage("Instrumenting forms [" + chunk.getName() + "]"));
successfulForms = instrumentForms(context, chunk, chunkSourcePath, compiledClassesLoader, forms, outputSink);
}
finally {
context.processMessage(new ProgressMessage("Finished instrumenting forms [" + chunk.getName() + "]"));
}
}
if (addNotNullAssertions) {
try {
context.processMessage(new ProgressMessage("Adding NotNull assertions [" + chunk.getName() + "]"));
instrumentNotNull(context, outputSink, compiledClassesLoader);
}
finally {
context.processMessage(new ProgressMessage("Finished adding NotNull assertions [" + chunk.getName() + "]"));
}
}
if (!compiledOk && diagnosticSink.getErrorCount() == 0) {
throw new ProjectBuildException("Compilation failed: internal java compiler error");
}
if (diagnosticSink.getErrorCount() > 0) {
throw new ProjectBuildException("Compilation failed: errors: " + diagnosticSink.getErrorCount() + "; warnings: " + diagnosticSink.getWarningCount());
}
}
}
finally {
context.setDirty(chunk, false); // no matter what result was, we should clear this flag
outputSink.writePendingData();
final Set<File> successfullyCompiled = outputSink.getSuccessfullyCompiled();
DELTA_MAPPINGS_CALLBACK_KEY.set(context, null);
if (updateMappings(context, delta, chunk, files, successfullyCompiled)) {
exitCode = ExitCode.ADDITIONAL_PASS_REQUIRED;
}
final TimestampStorage tsStorage = context.getBuildDataManager().getTimestampStorage(BUILDER_NAME);
for (File file : successfulForms) {
tsStorage.saveStamp(file);
}
}
if (exitCode != ExitCode.ADDITIONAL_PASS_REQUIRED) {
final Set<File> tempRoots = TEMPORARY_SOURCE_ROOTS_KEY.get(context);
TEMPORARY_SOURCE_ROOTS_KEY.set(context, null);
if (tempRoots != null) {
for (File root : tempRoots) {
FileUtil.delete(root);
}
}
}
return exitCode;
}
private static ClassLoader createInstrumentationClassLoader(Collection<File> classpath, Collection<File> platformCp, Map<File, String> chunkSourcePath, OutputFilesSink outputSink)
throws MalformedURLException {
final List<URL> urls = new ArrayList<URL>();
for (Collection<File> cp : Arrays.asList(platformCp, classpath)) {
for (File file : cp) {
urls.add(file.toURI().toURL());
}
}
urls.add(getResourcePath(GridConstraints.class).toURI().toURL()); // forms_rt.jar
//urls.add(getResourcePath(CellConstraints.class).toURI().toURL()); // jgoodies-forms
for (File file : chunkSourcePath.keySet()) {
urls.add(file.toURI().toURL());
}
return new CompiledClassesLoader(outputSink, urls.toArray(new URL[urls.size()]));
}
private static List<String> getCompilationOptions(CompileContext context, ModuleChunk chunk) {
// todo: read full set of options from settings
return Arrays.asList("-g", "-verbose")/*Collections.emptyList()*/;
}
private static Map<File, Set<File>> buildOutputDirectoriesMap(CompileContext context, ModuleChunk chunk) {
final Map<File, Set<File>> map = new HashMap<File, Set<File>>();
final boolean compilingTests = context.isCompilingTests();
for (Module module : chunk.getModules()) {
final String outputPath;
final Collection<String> srcPaths;
if (compilingTests) {
outputPath = module.getTestOutputPath();
srcPaths = (Collection<String>)module.getTestRoots();
}
else {
outputPath = module.getOutputPath();
srcPaths = (Collection<String>)module.getSourceRoots();
}
final Set<File> roots = new HashSet<File>();
for (String path : srcPaths) {
roots.add(new File(path));
}
map.put(new File(outputPath), roots);
}
return map;
}
// todo: probably instrument other NotNull-like annotations defined in project settings?
private static void instrumentNotNull(CompileContext context, OutputFilesSink sink, final ClassLoader loader) {
for (final OutputFileObject fileObject : sink.getFileObjects()) {
final OutputFileObject.Content originalContent = fileObject.getContent();
final ClassReader reader = new ClassReader(originalContent.getBuffer(), originalContent.getOffset(), originalContent.getLength());
final int version = getClassFileVersion(reader);
if (version >= Opcodes.V1_5) {
boolean success = false;
final ClassWriter writer = new InstrumenterClassWriter(getAsmClassWriterFlags(version), loader);
try {
final NotNullVerifyingInstrumenter instrumenter = new NotNullVerifyingInstrumenter(writer);
reader.accept(instrumenter, 0);
if (instrumenter.isModification()) {
fileObject.updateContent(writer.toByteArray());
}
success = true;
}
catch (Throwable e) {
final StringBuilder msg = new StringBuilder();
msg.append("@NotNull instrumentation failed ");
final File sourceFile = fileObject.getSourceFile();
if (sourceFile != null) {
msg.append(" for ").append(sourceFile.getName());
}
msg.append(": ").append(e.getMessage());
context.processMessage(
new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, msg.toString(), sourceFile != null ? sourceFile.getPath() : null));
}
finally {
if (!success) {
sink.markError(fileObject);
}
}
}
}
}
private static Collection<File> instrumentForms(
CompileContext context,
ModuleChunk chunk,
final Map<File, String> chunkSourcePath,
final ClassLoader loader,
Collection<File> formsToInstrument,
OutputFilesSink outputSink) throws ProjectBuildException {
final Map<String, File> class2form = new HashMap<String, File>();
final List<File> successfullForms = new ArrayList<File>();
final Map<String, OutputFileObject> compiledClassNames = new HashMap<String, OutputFileObject>();
for (OutputFileObject fileObject : outputSink.getFileObjects()) {
compiledClassNames.put(fileObject.getClassName(), fileObject);
}
final MyNestedFormLoader nestedFormsLoader = new MyNestedFormLoader(
chunkSourcePath, ProjectPaths.getOutputPathsWithDependents(chunk, context.isCompilingTests())
);
for (File formFile : formsToInstrument) {
final LwRootContainer rootContainer;
try {
rootContainer = Utils.getRootContainer(formFile.toURI().toURL(), new CompiledClassPropertiesProvider(loader));
}
catch (AlienFormFileException e) {
// ignore non-IDEA forms
continue;
}
catch (Exception e) {
throw new ProjectBuildException("Cannot process form file " + formFile.getAbsolutePath(), e);
}
final String classToBind = rootContainer.getClassToBind();
if (classToBind == null) {
continue;
}
final OutputFileObject outputClassFile = findClassFile(compiledClassNames, classToBind);
if (outputClassFile == null) {
context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.WARNING, "Class to bind does not exist: " + classToBind, formFile.getAbsolutePath()));
continue;
}
final File alreadyProcessedForm = class2form.get(classToBind);
if (alreadyProcessedForm != null) {
context.processMessage(new CompilerMessage(
BUILDER_NAME, BuildMessage.Kind.WARNING,
formFile.getAbsolutePath() + ": The form is bound to the class " + classToBind + ".\nAnother form " + alreadyProcessedForm.getAbsolutePath() + " is also bound to this class",
formFile.getAbsolutePath())
);
continue;
}
class2form.put(classToBind, formFile);
boolean success = true;
try {
final OutputFileObject.Content originalContent = outputClassFile.getContent();
final ClassReader classReader = new ClassReader(originalContent.getBuffer(), originalContent.getOffset(), originalContent.getLength());
final int version = getClassFileVersion(classReader);
final InstrumenterClassWriter classWriter = new InstrumenterClassWriter(getAsmClassWriterFlags(version), loader);
final AsmCodeGenerator codeGenerator = new AsmCodeGenerator(rootContainer, loader, nestedFormsLoader, false, classWriter);
final byte[] patchedBytes = codeGenerator.patchClass(classReader);
if (patchedBytes != null) {
outputClassFile.updateContent(patchedBytes);
}
final FormErrorInfo[] warnings = codeGenerator.getWarnings();
for (final FormErrorInfo warning : warnings) {
context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.WARNING, warning.getErrorMessage(), formFile.getAbsolutePath()));
}
final FormErrorInfo[] errors = codeGenerator.getErrors();
if (errors.length > 0) {
success = false;
StringBuilder message = new StringBuilder();
for (final FormErrorInfo error : errors) {
if (message.length() > 0) {
message.append("\n");
}
message.append(formFile.getAbsolutePath()).append(": ").append(error.getErrorMessage());
}
context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, message.toString()));
}
else {
successfullForms.add(formFile);
}
}
catch (Exception e) {
success = false;
context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, "Forms instrumentation failed" + e.getMessage(), formFile.getAbsolutePath()));
}
finally {
if (!success) {
outputSink.markError(outputClassFile);
}
}
}
return successfullForms;
}
private static OutputFileObject findClassFile(Map<String, OutputFileObject> outputs, String classToBind) {
while (true) {
final OutputFileObject fo = outputs.get(classToBind);
if (fo != null) {
return fo;
}
final int dotIndex = classToBind.lastIndexOf('.');
if (dotIndex <= 0) {
return null;
}
classToBind = classToBind.substring(0, dotIndex) + "$" + classToBind.substring(dotIndex + 1);
}
}
private static int getClassFileVersion(ClassReader reader) {
final Ref<Integer> result = new Ref<Integer>(0);
reader.accept(new EmptyVisitor() {
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
result.set(version);
}
}, 0);
return result.get();
}
private static int getAsmClassWriterFlags(int version) {
return version >= Opcodes.V1_6 && version != Opcodes.V1_1 ? ClassWriter.COMPUTE_FRAMES : ClassWriter.COMPUTE_MAXS;
}
private static class DiagnosticSink implements EmbeddedJavac.DiagnosticOutputConsumer {
private final CompileContext myContext;
private volatile int myErrorCount = 0;
private volatile int myWarningCount = 0;
public DiagnosticSink(CompileContext context) {
myContext = context;
}
public void outputLineAvailable(String line) {
if (line != null) {
if (line.startsWith("[") && line.endsWith("]")) {
final String message = line.substring(1, line.length() - 1);
if (message.startsWith("parsing")) {
myContext.processMessage(new ProgressMessage("Parsing sources..."));
}
else {
if (!message.startsWith("total")) {
myContext.processMessage(new ProgressMessage(FileUtil.toSystemDependentName(message)));
}
}
}
else if (line.contains("java.lang.OutOfMemoryError")) {
myContext.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, "OutOfMemoryError: insufficient memory"));
}
}
}
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
final CompilerMessage.Kind kind;
switch (diagnostic.getKind()) {
case ERROR:
kind = BuildMessage.Kind.ERROR;
myErrorCount++;
break;
case MANDATORY_WARNING:
case WARNING:
case NOTE:
kind = BuildMessage.Kind.WARNING;
myWarningCount++;
break;
default:
kind = BuildMessage.Kind.INFO;
}
final String srcPath;
final JavaFileObject source = diagnostic.getSource();
if (source != null) {
srcPath = FileUtil.toSystemIndependentName(source.toUri().getPath());
}
else {
srcPath = null;
}
myContext.processMessage(new CompilerMessage(
BUILDER_NAME, kind, diagnostic.getMessage(Locale.US), srcPath,
diagnostic.getStartPosition(), diagnostic.getEndPosition(), diagnostic.getPosition(),
diagnostic.getLineNumber(), diagnostic.getColumnNumber()
));
}
public int getErrorCount() {
return myErrorCount;
}
public int getWarningCount() {
return myWarningCount;
}
}
private static class OutputFilesSink implements EmbeddedJavac.OutputFileConsumer {
private final CompileContext myContext;
private final Set<File> mySuccessfullyCompiled = new HashSet<File>();
private final Set<File> myProblematic = new HashSet<File>();
private final List<OutputFileObject> myFileObjects = new ArrayList<OutputFileObject>();
private final Map<String, OutputFileObject.Content> myCompiledClasses = new HashMap<String, OutputFileObject.Content>();
public OutputFilesSink(CompileContext context) {
myContext = context;
}
public void save(final @NotNull OutputFileObject fileObject) {
final String className = fileObject.getClassName();
if (className != null) {
final OutputFileObject.Content content = fileObject.getContent();
if (content != null) {
synchronized (myCompiledClasses) {
myCompiledClasses.put(className, content);
}
}
}
synchronized (myFileObjects) {
myFileObjects.add(fileObject);
}
}
@Nullable
public OutputFileObject.Content lookupClassBytes(String className) {
synchronized (myCompiledClasses) {
return myCompiledClasses.get(className);
}
}
public List<OutputFileObject> getFileObjects() {
return Collections.unmodifiableList(myFileObjects);
}
public void writePendingData() {
try {
for (OutputFileObject file : myFileObjects) {
try {
writeToDisk(file);
}
catch (IOException e) {
myContext.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, e.getMessage()));
}
}
}
finally {
myFileObjects.clear();
}
}
public Set<File> getSuccessfullyCompiled() {
return Collections.unmodifiableSet(mySuccessfullyCompiled);
}
private void writeToDisk(@NotNull OutputFileObject fileObject) throws IOException {
final OutputFileObject.Content content = fileObject.getContent();
if (content != null) {
FileUtil.writeToFile(fileObject.getFile(), content.getBuffer(), content.getOffset(), content.getLength());
}
else {
throw new IOException("Missing content for file " + fileObject.getFile());
}
final File source = fileObject.getSourceFile();
if (source != null && !myProblematic.contains(source)) {
mySuccessfullyCompiled.add(source);
final String className = fileObject.getClassName();
if (className != null) {
myContext.processMessage(new ProgressMessage("Compiled " + className));
}
}
}
public void markError(OutputFileObject outputClassFile) {
final File source = outputClassFile.getSourceFile();
if (source != null) {
myProblematic.add(source);
}
}
}
public static class InstrumenterClassWriter extends ClassWriter {
private final ClassLoader myClassLoader;
public InstrumenterClassWriter(int flags, final ClassLoader pseudoLoader) {
super(flags);
myClassLoader = pseudoLoader;
}
protected String getCommonSuperClass(final String type1, final String type2) {
Class c, d;
try {
//c = Class.forName(type1.replace('/', '.'), true, myClassLoader);
//d = Class.forName(type2.replace('/', '.'), true, myClassLoader);
c = myClassLoader.loadClass(type1.replace('/', '.'));
d = myClassLoader.loadClass(type2.replace('/', '.'));
}
catch (Exception e) {
throw new RuntimeException(e.toString(), e);
}
if (c.isAssignableFrom(d)) {
return type1;
}
if (d.isAssignableFrom(c)) {
return type2;
}
if (c.isInterface() || d.isInterface()) {
return "java/lang/Object";
}
else {
do {
c = c.getSuperclass();
}
while (!c.isAssignableFrom(d));
return c.getName().replace('.', '/');
}
}
}
private static class MyNestedFormLoader implements NestedFormLoader {
private final Map<File, String> mySourceRoots;
private final Collection<File> myOutputRoots;
private final HashMap<String, LwRootContainer> myCache = new HashMap<String, LwRootContainer>();
/**
* @param sourceRoots all source roots for current module chunk and all dependent recursively
* @param outputRoots output roots for this module chunk and all dependent recursively
*/
public MyNestedFormLoader(Map<File, String> sourceRoots, Collection<File> outputRoots) {
mySourceRoots = sourceRoots;
myOutputRoots = outputRoots;
}
public LwRootContainer loadForm(String formFileName) throws Exception {
if (myCache.containsKey(formFileName)) {
return myCache.get(formFileName);
}
final String relPath = FileUtil.toSystemIndependentName(formFileName);
for (Map.Entry<File, String> entry : mySourceRoots.entrySet()) {
final File sourceRoot = entry.getKey();
final String prefix = entry.getValue();
String path = relPath;
if (prefix != null && FileUtil.startsWith(path, prefix)) {
path = path.substring(prefix.length());
}
final File formFile = new File(sourceRoot, path);
if (formFile.exists()) {
final BufferedInputStream stream = new BufferedInputStream(new FileInputStream(formFile));
try {
return loadForm(formFileName, stream);
}
finally {
stream.close();
}
}
}
throw new Exception("Cannot find nested form file " + formFileName);
}
private LwRootContainer loadForm(String formFileName, InputStream resourceStream) throws Exception {
final LwRootContainer container = Utils.getRootContainer(resourceStream, null);
myCache.put(formFileName, container);
return container;
}
public String getClassToBindName(LwRootContainer container) {
final String className = container.getClassToBind();
for (File outputRoot : myOutputRoots) {
final String result = getJVMClassName(outputRoot, className.replace('.', '/'));
if (result != null) {
return result.replace('/', '.');
}
}
return className;
}
}
@Nullable
private static String getJVMClassName(File outputRoot, String className) {
while (true) {
final File candidateClass = new File(outputRoot, className + ".class");
if (candidateClass.exists()) {
return className;
}
final int position = className.lastIndexOf('/');
if (position < 0) {
return null;
}
className = className.substring(0, position) + '$' + className.substring(position + 1);
}
}
private static File getResourcePath(Class aClass) {
return new File(PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class"));
}
private static class CompiledClassesLoader extends URLClassLoader {
private final OutputFilesSink mySink;
public CompiledClassesLoader(OutputFilesSink sink, URL[] urls) {
super(urls, null);
mySink = sink;
}
protected Class findClass(String name) throws ClassNotFoundException {
final OutputFileObject.Content content = mySink.lookupClassBytes(name);
if (content != null) {
return defineClass(name, content.getBuffer(), content.getOffset(), content.getLength());
}
return super.findClass(name);
}
public URL findResource(String name) {
return super.findResource(name);
}
}
}
|
package com.jsh.erp.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.Function;
import com.jsh.erp.datasource.entities.User;
import com.jsh.erp.datasource.entities.UserBusiness;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.service.functions.FunctionService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import com.jsh.erp.utils.BaseResponseInfo;
import com.jsh.erp.utils.StringUtil;
import com.jsh.erp.utils.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author ji-sheng-hua jshERP
*/
@RestController
@RequestMapping(value = "/function")
public class FunctionController {
private Logger logger = LoggerFactory.getLogger(FunctionController.class);
@Resource
private FunctionService functionService;
@Resource
private UserBusinessService userBusinessService;
@PostMapping(value = "/findMenuByPNumber")
public JSONArray findMenuByPNumber(@RequestBody JSONObject jsonObject,
HttpServletRequest request)throws Exception {
String pNumber = jsonObject.getString("pNumber");
String userId = jsonObject.getString("userId");
//json
JSONArray dataArray = new JSONArray();
try {
Long roleId = 0L;
String fc = "";
List<UserBusiness> roleList = userBusinessService.getBasicData(userId, "UserRole");
if(roleList!=null && roleList.size()>0){
String value = roleList.get(0).getValue();
if(StringUtil.isNotEmpty(value)){
String roleIdStr = value.replace("[", "").replace("]", "");
roleId = Long.parseLong(roleIdStr);
}
}
//[1][2][5]
List<UserBusiness> funList = userBusinessService.getBasicData(roleId.toString(), "RoleFunctions");
if(funList!=null && funList.size()>0){
fc = funList.get(0).getValue();
}
List<Function> dataList = functionService.getRoleFunction(pNumber);
if (dataList.size() != 0) {
dataArray = getMenuByFunction(dataList, fc);
JSONObject homeItem = new JSONObject();
homeItem.put("id", 0);
homeItem.put("text", "");
homeItem.put("icon", "home");
homeItem.put("url", "/dashboard/analysis");
homeItem.put("component", "/layouts/TabLayout");
dataArray.add(0,homeItem);
}
} catch (DataAccessException e) {
logger.error(">>>>>>>>>>>>>>>>>>>", e);
}
return dataArray;
}
public JSONArray getMenuByFunction(List<Function> dataList, String fc) throws Exception {
JSONArray dataArray = new JSONArray();
for (Function function : dataList) {
JSONObject item = new JSONObject();
List<Function> newList = functionService.getRoleFunction(function.getNumber());
item.put("id", function.getId());
item.put("text", function.getName());
item.put("icon", function.getIcon());
item.put("url", function.getUrl());
item.put("component", function.getComponent());
if (newList.size()>0) {
JSONArray childrenArr = getMenuByFunction(newList, fc);
if(childrenArr.size()>0) {
item.put("children", childrenArr);
dataArray.add(item);
}
} else {
if (fc.indexOf("[" + function.getId().toString() + "]") != -1) {
dataArray.add(item);
}
}
}
return dataArray;
}
/**
*
* @param request
* @return
*/
@GetMapping(value = "/findRoleFunction")
public JSONArray findRoleFunction(@RequestParam("UBType") String type, @RequestParam("UBKeyId") String keyId,
HttpServletRequest request)throws Exception {
JSONArray arr = new JSONArray();
try {
List<Function> dataListFun = functionService.findRoleFunction("0");
//json
JSONObject outer = new JSONObject();
outer.put("id", 0);
outer.put("key", 0);
outer.put("value", 0);
outer.put("title", "");
outer.put("attributes", "");
//json
JSONArray dataArray = new JSONArray();
if (null != dataListFun) {
List<Function> dataList = new ArrayList<>();
for (Function fun : dataListFun) {
String token = request.getHeader("X-Access-Token");
Long tenantId = Tools.getTenantIdByToken(token);
if (tenantId!=0L) {
if(!("").equals(fun.getName())) {
dataList.add(fun);
}
} else {
dataList.add(fun);
}
}
dataArray = getFunctionList(dataList, type, keyId);
outer.put("children", dataArray);
}
arr.add(outer);
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
public JSONArray getFunctionList(List<Function> dataList, String type, String keyId) throws Exception {
JSONArray dataArray = new JSONArray();
String ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, keyId);
if (null != dataList) {
for (Function function : dataList) {
JSONObject item = new JSONObject();
item.put("id", function.getId());
item.put("key", function.getId());
item.put("value", function.getId());
item.put("title", function.getName());
item.put("attributes", function.getName());
Boolean flag = ubValue.contains("[" + function.getId().toString() + "]");
if (flag) {
item.put("checked", true);
}
List<Function> funList = functionService.findRoleFunction(function.getNumber());
if(funList.size()>0) {
JSONArray funArr = getFunctionList(funList, type, keyId);
item.put("children", funArr);
dataArray.add(item);
} else {
dataArray.add(item);
}
}
}
return dataArray;
}
/**
* id
* @param roleId
* @param request
* @return
*/
@GetMapping(value = "/findRoleFunctionsById")
public BaseResponseInfo findByIds(@RequestParam("roleId") Long roleId,
HttpServletRequest request)throws Exception {
BaseResponseInfo res = new BaseResponseInfo();
try {
List<UserBusiness> list = userBusinessService.getBasicData(roleId.toString(), "RoleFunctions");
if(null!=list && list.size()>0) {
Map<Long,String> btnMap = new HashMap<>();
String btnStr = list.get(0).getBtnStr();
if(StringUtil.isNotEmpty(btnStr)) {
JSONArray btnArr = JSONArray.parseArray(btnStr);
for(Object obj: btnArr) {
JSONObject btnObj = JSONObject.parseObject(obj.toString());
if(btnObj.get("funId")!=null && btnObj.get("btnStr")!=null) {
btnMap.put(btnObj.getLong("funId"), btnObj.getString("btnStr"));
}
}
}
String funIds = list.get(0).getValue();
funIds = funIds.substring(1, funIds.length() - 1);
funIds = funIds.replace("][",",");
List<Function> dataList = functionService.findByIds(funIds);
JSONObject outer = new JSONObject();
outer.put("total", dataList.size());
//json
JSONArray dataArray = new JSONArray();
if (null != dataList) {
for (Function function : dataList) {
JSONObject item = new JSONObject();
item.put("id", function.getId());
item.put("name", function.getName());
item.put("pushBtn", function.getPushBtn());
item.put("btnStr", btnMap.get(function.getId()));
dataArray.add(item);
}
}
outer.put("rows", dataArray);
res.code = 200;
res.data = outer;
}
} catch (Exception e) {
e.printStackTrace();
res.code = 500;
res.data = "";
}
return res;
}
}
|
package edu.isi.karma.mapreduce.driver;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.isi.karma.kr2rml.planning.UserSpecifiedRootStrategy;
import edu.isi.karma.kr2rml.writer.KR2RMLRDFWriter;
import edu.isi.karma.rdf.BaseKarma;
import edu.isi.karma.rdf.RDFGeneratorRequest;
public abstract class BaseRDFMapper extends Mapper<Writable, Text, Text, Text> {
private static Logger LOG = LoggerFactory.getLogger(BaseRDFMapper.class);
protected BaseKarma karma;
protected String header = null;
protected String delimiter = null;
protected boolean hasHeader = false;
@Override
public void setup(Context context) {
karma = new BaseKarma();
String inputTypeString = context.getConfiguration().get(
"karma.input.type");
String modelUri = context.getConfiguration().get("model.uri");
String modelFile = context.getConfiguration().get("model.file");
String baseURI = context.getConfiguration().get("base.uri");
String contextURI = context.getConfiguration().get("context.uri");
String rdfGenerationRoot = context.getConfiguration().get("rdf.generation.root");
String rdfSelection = context.getConfiguration().get("rdf.generation.selection");
delimiter = context.getConfiguration().get("karma.input.delimiter");
hasHeader = context.getConfiguration().getBoolean("karma.input.header", false);
karma.setup("./karma.zip/karma", inputTypeString, modelUri, modelFile,
baseURI, contextURI, rdfGenerationRoot, rdfSelection);
}
@Override
public void map(Writable key, Text value, Context context) throws IOException,
InterruptedException {
String filename = key.toString();
String contents = value.toString();
LOG.debug(key.toString() + " started");
if(hasHeader && header ==null)
{
header=contents;
LOG.debug("found header: " + header);
return;
}
else if(hasHeader && header != null)
{
contents = header+"\n" + contents;
}
StringWriter sw = new StringWriter();
KR2RMLRDFWriter outWriter = configureRDFWriter(sw);
try {
RDFGeneratorRequest request = new RDFGeneratorRequest("model", filename);
request.setDataType(karma.getInputType());
request.setInputData(contents);
request.setAddProvenance(false);
request.addWriter(outWriter);
request.setMaxNumLines(0);
request.setEncoding(Charset.defaultCharset().toString());
if(delimiter != null)
{
request.setDelimiter(delimiter);
}
if(karma.getContextId() != null)
{
request.setContextName(karma.getContextId().getName());
}
if(karma.getRdfGenerationRoot() != null)
{
request.setStrategy(new UserSpecifiedRootStrategy(karma.getRdfGenerationRoot()));
}
if (karma.getContextId() != null) {
request.setContextName(karma.getContextId().getName());
}
karma.getGenerator().generateRDF(request);
String results = sw.toString();
if (!results.equals("[\n\n]\n")) {
writeRDFToContext(context, results);
}
else
{
LOG.error("Unable to generate RDF: ");
}
} catch (Exception e) {
e.printStackTrace();
LOG.error("Unable to generate RDF: " + e.getMessage());
}
LOG.debug(key.toString() + " finished");
}
protected abstract KR2RMLRDFWriter configureRDFWriter(StringWriter sw);
protected abstract void writeRDFToContext(Context context, String results)
throws IOException, InterruptedException;
}
|
package com.microsoft.applicationinsights.library;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import com.microsoft.applicationinsights.library.config.ApplicationInsightsConfig;
import com.microsoft.applicationinsights.logging.InternalLogging;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
public enum ApplicationInsights {
INSTANCE;
/**
* The tag for logging.
*/
private static final String TAG = "ApplicationInsights";
/**
* A flag which determines, if developer mode (logging) should be enabled.
*/
private static AtomicBoolean DEVELOPER_MODE = new AtomicBoolean(Util.isEmulator() || Util.isDebuggerAttached());
/**
* The configuration of the SDK.
*/
private ApplicationInsightsConfig config;
/**
* A flag, which determines if auto collection of sessions and page views should be disabled.
* Default is false.
*/
private boolean autoCollectionDisabled;
/**
* A flag, which determines if sending telemetry data should be disabled. Default is false.
*/
private boolean telemetryDisabled;
/**
* A flag, which determines if crash reporting should be disabled. Default is false.
*/
private boolean exceptionTrackingDisabled;
/**
* The instrumentation key associated with the app.
*/
private String instrumentationKey;
/**
* The weakContext which contains additional information for the telemetry data sent out.
*/
private TelemetryContext telemetryContext;
/**
* A custom user ID used for sending telemetry data.
*/
private String userId;
/**
* The weakContext associated with Application Insights.
*/
private WeakReference<Context> weakContext;
/**
* The application needed for auto collecting telemetry data
*/
private WeakReference<Application> weakApplication;
/**
* Properties associated with this telemetryContext.
*/
private Map<String, String> commonProperties;
private static boolean isRunning;
private static boolean isSetup;
/**
* Create ApplicationInsights instance
*/
ApplicationInsights() {
this.telemetryDisabled = false;
this.exceptionTrackingDisabled = false;
this.autoCollectionDisabled = false;
this.config = new ApplicationInsightsConfig();
}
/**
* Configure Application Insights
* Note: This should be called before start
*
* @param context the context associated with Application Insights
* @param context the application context associated with Application Insights
* @warning auto-collection of lifecycle-events is disabled when using this method
* @deprecated This method is deprecated: Use setup(Context context, Application application) instead.
*/
public static void setup(Context context) {
ApplicationInsights.INSTANCE.setupInstance(context, null, null);
}
/**
* Configure Application Insights
* Note: This should be called before start
*
* @param application the application context the application needed for auto collecting telemetry data
*/
public static void setup(Context context, Application application) {
ApplicationInsights.INSTANCE.setupInstance(context, application, null);
}
/**
* Configure Application Insights
* Note: This should be called before start
*
* @param context the application context associated with Application Insights
* @param instrumentationKey the instrumentation key associated with the app
* @warning auto-collection of lifecycle-events is disabled when using this method
* @deprecated This method is deprecated: Use setup(Context context, Application application) instead.
*/
public static void setup(Context context, String instrumentationKey) {
ApplicationInsights.INSTANCE.setupInstance(context, null, instrumentationKey);
}
/**
* Configure Application Insights
* Note: This should be called before start
*
* @param context the application context associated with Application Insights
* @param application the application needed for auto collecting telemetry data
* @param instrumentationKey the instrumentation key associated with the app
*/
public static void setup(Context context, Application application, String instrumentationKey) {
ApplicationInsights.INSTANCE.setupInstance(context, application, instrumentationKey);
}
/**
* Configure Application Insights
* Note: This should be called before start
*
* @param context the application context associated with Application Insights
* @param instrumentationKey the instrumentation key associated with the app
*/
public void setupInstance(Context context, Application application, String instrumentationKey) {
if (!isSetup) {
if (context != null) {
this.weakContext = new WeakReference<Context>(context);
this.instrumentationKey = instrumentationKey;
this.weakApplication = new WeakReference<Application>(application);
isSetup = true;
InternalLogging.info(TAG, "ApplicationInsights has been setup correctly.", null);
} else {
InternalLogging.warn(TAG, "ApplicationInsights could not be setup correctly " +
"because the given weakContext was null");
}
}
}
/**
* Start ApplicationInsights
* Note: This should be called after {@link #isSetup}
*/
public static void start() {
INSTANCE.startInstance();
}
/**
* Start ApplicationInsights
* Note: This should be called after {@link #isSetup}
*/
public void startInstance() {
if (!isSetup) {
InternalLogging.warn(TAG, "Could not start Application Insights since it has not been " +
"setup correctly.");
return;
}
if (!isRunning) {
Context context = INSTANCE.getContext();
if (context == null) {
InternalLogging.warn(TAG, "Could not start Application Insights as context is null");
return;
}
if (this.instrumentationKey == null) {
this.instrumentationKey = readInstrumentationKey(context);
}
this.telemetryContext = new TelemetryContext(context, this.instrumentationKey, userId);
EnvelopeFactory.initialize(telemetryContext, this.commonProperties);
Persistence.initialize(context);
Sender.initialize(this.config);
Channel.initialize(this.config);
// Initialize Telemetry
TelemetryClient.initialize(!telemetryDisabled);
Application application = INSTANCE.getApplication();
if (INSTANCE.getApplication() != null &&
Util.isLifecycleTrackingAvailable() &&
!this.autoCollectionDisabled) {
LifeCycleTracking.initialize(telemetryContext, this.config);
LifeCycleTracking.registerForPersistingWhenInBackground(application);
LifeCycleTracking.registerPageViewCallbacks(application);
LifeCycleTracking.registerSessionManagementCallbacks(application);
} else {
InternalLogging.warn(TAG, "Auto collection of page views could not be " +
"started. Either the given application was null, the device API level " +
"is lower than 14, or the user actively disabled the feature.");
}
// Start crash reporting
if (!this.exceptionTrackingDisabled) {
ExceptionTracking.registerExceptionHandler();
}
isRunning = true;
Sender.getInstance().sendDataOnAppStart();
InternalLogging.info(TAG, "ApplicationInsights has been started.", "");
}
}
/**
* Triggers persisting and if applicable sending of queued data
* note: this will be called
* {@link com.microsoft.applicationinsights.library.config.ApplicationInsightsConfig#maxBatchIntervalMs} after
* tracking any telemetry so it is not necessary to call this in most cases.
*/
public static void sendPendingData() {
if (!isRunning) {
InternalLogging.warn(TAG, "Could not set send pending data, because " +
"ApplicationInsights has not been started, yet.");
return;
}
Channel.getInstance().synchronize();
}
/**
* Enable auto page view tracking as well as auto session tracking. This will only work, if
* {@link ApplicationInsights#telemetryDisabled} is set to false.
*
* @param application the application used to register the life cycle callbacks
* @deprecated This method is deprecated: Use setAutoCollectionDisabled instead.
*/
public static void enableActivityTracking(Application application) {
if (!isRunning) { //TODO fix log warning
InternalLogging.warn(TAG, "Could not set activity tracking, because " +
"ApplicationInsights has not been started, yet.");
return;
}
if (!INSTANCE.telemetryDisabled) {
if(application != null && Util.isLifecycleTrackingAvailable()){
LifeCycleTracking.registerActivityLifecycleCallbacks(application);
}
}
}
/**
* Enable auto page view tracking. This will only work, if ApplicationInsights has been setup
* with an application. This method should only be called after
* {@link com.microsoft.applicationinsights.library.ApplicationInsights#start()}.
*/
public static void enableAutoPageViewTracking() {
if (!isRunning) {
InternalLogging.warn(TAG, "Could not set page view tracking, because " +
"ApplicationInsights has not been started yet.");
return;
} else if (INSTANCE.getApplication() == null) {
InternalLogging.warn(TAG, "Could not set page view tracking, because " +
"ApplicationInsights has not been setup with an application.");
return;
} else if (!Util.isLifecycleTrackingAvailable()) {
InternalLogging.warn(TAG, "Could not set page view tracking, because " +
"it is not supported on this OS version.");
} else {
LifeCycleTracking.registerPageViewCallbacks(INSTANCE.getApplication());
}
}
/**
* Disable auto page view tracking. This will only work, if ApplicationInsights has been setup
* with an application. This method should only be called after
* {@link com.microsoft.applicationinsights.library.ApplicationInsights#start()}.
*/
public static void disableAutoPageViewTracking() {
if (!isRunning) {
InternalLogging.warn(TAG, "Could not unset page view tracking, because " +
"ApplicationInsights has not been started yet.");
return;
} else if (INSTANCE.getApplication() == null) {
InternalLogging.warn(TAG, "Could not unset page view tracking, because " +
"ApplicationInsights has not been setup with an application.");
return;
} else if (!Util.isLifecycleTrackingAvailable()) {
InternalLogging.warn(TAG, "Could not unset page view tracking, because " +
"it is not supported on this OS version.");
} else {
LifeCycleTracking.unregisterPageViewCallbacks(INSTANCE.getApplication());
}
}
/**
* Enable auto session tracking. This will only work, if ApplicationInsights has been setup
* with an application. This method should only be called after
* {@link com.microsoft.applicationinsights.library.ApplicationInsights#start()}.
*/
public static void enableAutoSessionManagement() {
if (!isRunning) {
InternalLogging.warn(TAG, "Could not set session management, because " +
"ApplicationInsights has not been started yet.");
return;
} else if (INSTANCE.getApplication() == null) {
InternalLogging.warn(TAG, "Could not set session management, because " +
"ApplicationInsights has not been setup with an application.");
return;
} else if (!Util.isLifecycleTrackingAvailable()) {
InternalLogging.warn(TAG, "Could not set session management, because " +
"it is not supported on this OS version.");
} else {
LifeCycleTracking.registerSessionManagementCallbacks(INSTANCE.getApplication());
}
}
/**
* Disable auto session tracking. This will only work, if ApplicationInsights has been setup
* with an application. This method should only be called after
* {@link com.microsoft.applicationinsights.library.ApplicationInsights#start()}.
*/
public static void disableAutoSessionManagement() {
if (!isRunning) {
InternalLogging.warn(TAG, "Could not unset session management, because " +
"ApplicationInsights has not been started yet.");
return;
} else if (INSTANCE.getApplication() == null) {
InternalLogging.warn(TAG, "Could not unset session management, because " +
"ApplicationInsights has not been setup with an application.");
return;
} else if (!Util.isLifecycleTrackingAvailable()) {
InternalLogging.warn(TAG, "Could not unset session management, because " +
"it is not supported on this OS version.");
} else {
LifeCycleTracking.unregisterSessionManagementCallbacks(INSTANCE.getApplication());
}
}
/**
* Enable / disable tracking of unhandled exceptions.
*
* @param disabled if set to true, crash reporting will be disabled
*/
public static void setExceptionTrackingDisabled(boolean disabled) {
if (!isSetup) {
InternalLogging.warn(TAG, "Could not enable/disable exception tracking, because " +
"ApplicationInsights has not been setup correctly.");
return;
}
if (isRunning) {
InternalLogging.warn(TAG, "Could not enable/disable exception tracking, because " +
"ApplicationInsights has already been started.");
return;
}
INSTANCE.exceptionTrackingDisabled = disabled;
}
/**
* Enable / disable tracking of telemetry data.
*
* @param disabled if set to true, the telemetry feature will be disabled
*/
public static void setTelemetryDisabled(boolean disabled) {
if (!isSetup) {
InternalLogging.warn(TAG, "Could not enable/disable telemetry, because " +
"ApplicationInsights has not been setup correctly.");
return;
}
if (isRunning) {
InternalLogging.warn(TAG, "Could not enable/disable telemetry, because " +
"ApplicationInsights has already been started.");
return;
}
INSTANCE.telemetryDisabled = disabled;
}
/**
* Enable / disable auto collection of telemetry data.
*
* @param disabled if set to true, the auto collection feature will be disabled
*/
public static void setAutoCollectionDisabled(boolean disabled) {
if (!isSetup) {
InternalLogging.warn(TAG, "Could not enable/disable auto collection, because " +
"ApplicationInsights has not been setup correctly.");
return;
}
if (isRunning) {
InternalLogging.warn(TAG, "Could not enable/disable auto collection, because " +
"ApplicationInsights has already been started.");
return;
}
INSTANCE.autoCollectionDisabled = disabled;
}
/**
* Gets the properties which are common to all telemetry sent from this client.
*
* @return common properties for this telemetry client
*/
public static Map<String, String> getCommonProperties() {
return INSTANCE.commonProperties;
}
/**
* Sets properties which are common to all telemetry sent form this client.
*
* @param commonProperties a dictionary of properties to enqueue with all telemetry.
*/
public static void setCommonProperties(Map<String, String> commonProperties) {
if (!isSetup) {
InternalLogging.warn(TAG, "Could not set common properties, because " +
"ApplicationInsights has not been setup correctly.");
return;
}
if (isRunning) {
InternalLogging.warn(TAG, "Could not set common properties, because " +
"ApplicationInsights has already been started.");
return;
}
INSTANCE.commonProperties = commonProperties;
}
public static void setDeveloperMode(boolean developerMode) {
DEVELOPER_MODE.set(developerMode);
}
public static boolean isDeveloperMode() {
return DEVELOPER_MODE.get();
}
/**
* Reads the instrumentation key from AndroidManifest.xml if it is available
*
* @param context the application weakContext to check the manifest from
* @return the instrumentation key configured for the application
*/
private String readInstrumentationKey(Context context) {
String iKey = "";
if (context != null) {
try {
Bundle bundle = context
.getPackageManager()
.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA)
.metaData;
if (bundle != null) {
iKey = bundle.getString("com.microsoft.applicationinsights.instrumentationKey");
} else {
logInstrumentationInstructions();
}
} catch (PackageManager.NameNotFoundException exception) {
logInstrumentationInstructions();
Log.v(TAG, exception.toString());
}
}
return iKey;
}
/**
* Returns the application reference that Application Insights needs.
*
* @return the Context that's used by the Application Insights SDK
*/
protected Context getContext() {
Context context = null;
if (weakContext != null) {
context = weakContext.get();
}
return context;
}
/**
* Get the reference to the Application (used for life-cycle tracking)
*
* @return the reference to the application that was used during initialization of the SDK
*/
protected Application getApplication() {
Application application = null;
if (weakApplication != null) {
application = weakApplication.get();
}
return application;
}
/* Writes instructions on how to configure the instrumentation key.
*/
private static void logInstrumentationInstructions() {
String instructions = "No instrumentation key found.\n" +
"Set the instrumentation key in AndroidManifest.xml";
String manifestSnippet = "<meta-data\n" +
"android:name=\"com.microsoft.applicationinsights.instrumentationKey\"\n" +
"android:value=\"${AI_INSTRUMENTATION_KEY}\" />";
InternalLogging.error("MissingInstrumentationkey", instructions + "\n" + manifestSnippet);
}
/**
* Gets the configuration for the ApplicationInsights instance
*
* @return the instance ApplicationInsights configuration
*/
public static ApplicationInsightsConfig getConfig() {
return INSTANCE.config;
}
/**
* Sets the session configuration for the instance
*/
public void setConfig(ApplicationInsightsConfig config) {
if (!isSetup) {
InternalLogging.warn(TAG, "Could not set telemetry configuration, because " +
"ApplicationInsights has not been setup correctly.");
return;
}
if (isRunning) {
InternalLogging.warn(TAG, "Could not set telemetry configuration, because " +
"ApplicationInsights has already been started.");
return;
}
INSTANCE.config = config;
}
/**
* Force Application Insights to create a new session with a custom sessionID.
*
* @param sessionId a custom session ID used of the session to create
*/
public static void renewSession(String sessionId) {
if (!INSTANCE.telemetryDisabled && INSTANCE.telemetryContext != null) {
INSTANCE.telemetryContext.renewSessionId(sessionId);
}
}
/**
* Set the user Id associated with the telemetry data. If userId == null, ApplicationInsights
* will generate a random ID.
*
* @param userId a user ID associated with the telemetry data
*/
public static void setUserId(String userId) {
if (isRunning) {
INSTANCE.telemetryContext.configUserContext(userId);
} else {
INSTANCE.userId = userId;
}
}
/**
* Get the instrumentation key associated with this app.
*
* @return the Application Insights instrumentation key set for this app
*/
protected static String getInstrumentationKey() {
return INSTANCE.instrumentationKey;
}
}
|
package org.csstudio.ams.connector.sms;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.csstudio.ams.Activator;
import org.csstudio.ams.AmsConstants;
import org.csstudio.ams.Log;
import org.csstudio.ams.connector.sms.internal.SampleService;
import org.csstudio.ams.connector.sms.service.Environment;
import org.csstudio.ams.connector.sms.service.JmsSender;
import org.csstudio.platform.utility.jms.JmsRedundantReceiver;
import org.eclipse.jface.preference.IPreferenceStore;
import org.smslib.InboundMessage;
import org.smslib.InboundMessage.MessageClasses;
import org.smslib.Message.MessageEncodings;
import org.smslib.Message.MessageTypes;
import org.smslib.InboundBinaryMessage;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.StatusReportMessage;
import org.smslib.modem.SerialModemGateway;
public class SmsConnectorWork extends Thread implements AmsConstants
{
private SmsConnectorStart scs = null;
// private final int CONSUMER_CONNECTIONS = 2;
private Context amsSenderContext = null;
private ConnectionFactory amsSenderFactory = null;
private Connection amsSenderConnection = null;
private Session amsSenderSession = null;
private MessageProducer amsPublisherReply = null;
private JmsRedundantReceiver amsReceiver = null;
private Service modemService = null;
// private CSoftwareService srv = null;
/** Container for SMS */
private SmsContainer smsContainer;
/** Reading period (in ms) for the modem */
private long readWaitingPeriod;
/** This class contains all modem ids (names) */
private ModemInformation modemInfo;
/** Status information of the current modem test */
private ModemTestStatus testStatus;
private short sTest = 0; // 0 - normal behavior, other - for test
private boolean bStop = false;
private boolean bStoppedClean = false;
/** Name of the management topic for sending commands */
public static final String MANAGE_COMMAND_TOPIC = "T_AMS_CON_MANAGE";
public static final String MANAGE_COMMAND_TOPIC_SUB = "T_AMS_TSUB_CON_MANAGE";
/** Name of the management topic for receiving answers */
public static final String MANAGE_REPLY_TOPIC = "T_AMS_CON_MANAGE_REPLY";
public static final String MANAGE_REPLY_TOPIC_SUB = "T_AMS_TSUB_CON_MANAGE_REPLY";
/** Text for the test SMS */
public static final String SMS_TEST_TEXT = "[MODEMTEST{$DATE,$GATEWAYID}]";
public SmsConnectorWork(SmsConnectorStart scs)
{
// Set the "parent" object
this.scs = scs;
smsContainer = new SmsContainer();
readWaitingPeriod = 0;
modemInfo = new ModemInformation();
testStatus = new ModemTestStatus();
}
public void run()
{
boolean bInitedModem = false;
boolean bInitedJms = false;
long lastReadingTime = 0;
int iErr = SmsConnectorStart.STAT_OK;
bStop = false;
bStoppedClean = false;
Log.log(this, Log.INFO, "Start sms connector work");
while(bStop == false)
{
try
{
if (!bInitedModem)
{
bInitedModem = initModem();
if(!bInitedModem)
{
Log.log(this, Log.ERROR, "Cannot init modem.");
iErr = SmsConnectorStart.STAT_ERR_MODEM;
scs.setStatus(iErr); // set it for not overwriting with next error
}
}
if (!bInitedJms)
{
bInitedJms = initJms();
if (!bInitedJms)
{
iErr = SmsConnectorStart.STAT_ERR_JMSCON;
scs.setStatus(iErr); // set it for not overwriting with next error
}
}
sleep(100);
if(bInitedModem && bInitedJms)
{
iErr = SmsConnectorStart.STAT_OK;
if (scs.getStatus() == SmsConnectorStart.STAT_INIT)
scs.setStatus(SmsConnectorStart.STAT_OK);
// Log.log(this, Log.DEBUG, "is running");
// First check the connectors manage topic
// Maybe a user wants to delete some messages
Message message = null;
try
{
message = amsReceiver.receive("amsConnectorManager");
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not receive from internal jms: amsConnectorManager", e);
iErr = SmsConnectorStart.STAT_ERR_JMSCON;
}
// If we got a message from the manager plugin, start the ConnectorMessageManager
if(message != null)
{
Log.log(Log.INFO, "Received a message from ConnectorMessageManager");
ConnectorMessageManager manager = null;
try
{
manager = new ConnectorMessageManager(amsSenderConnection, amsReceiver);
manager.begin(message);
manager.closeJms();
iErr = SmsConnectorStart.STAT_OK;
}
catch(JMSException jmse)
{
manager.closeJms();
Log.log(this, Log.FATAL, "the connector message manager does not work properly", jmse);
iErr = SmsConnectorStart.STAT_ERR_JMSCON;
}
manager = null;
}
if(iErr == SmsConnectorStart.STAT_ERR_JMSCON)
{
Log.log(this, Log.ERROR, "Closing JMS communication.");
closeJms();
bInitedJms = false;
}
if(iErr == SmsConnectorStart.STAT_OK)
{
// TODO: The methods should throw an exception
// Now look for SMS messages
message = null;
try
{
message = amsReceiver.receive("amsSubscriberSms");
iErr = smsContainer.addSms(message);
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "Could not receive from internal jms: amsSubscriberSms", e);
iErr = SmsConnectorStart.STAT_ERR_JMSCON;
}
if (message != null)
{
//FIXME:
//TODO:
// send 1 SMS, other in the next run
// iErr = sendSmsMsg(message);
iErr = sendSmsMsg();
sleep(100);
}
if (iErr == SmsConnectorStart.STAT_OK)
{
if((System.currentTimeMillis() - lastReadingTime) > readWaitingPeriod)
{
// read max. limit SMS, other in the next run
iErr = readSmsMsg();
lastReadingTime = System.currentTimeMillis();
}
}
if (iErr == SmsConnectorStart.STAT_ERR_MODEM_SEND)
{
Log.log(this, Log.ERROR, "Closing Modem.");
closeModem();
bInitedModem = false;
closeJms();
bInitedJms = false;
}
if (iErr == SmsConnectorStart.STAT_ERR_MODEM)
{
Log.log(this, Log.ERROR, "Closing Modem.");
closeModem();
bInitedModem = false;
}
if (iErr == SmsConnectorStart.STAT_ERR_JMSCON)
{
Log.log(this, Log.ERROR, "Closing JMS communication.");
closeJms();
bInitedJms = false;
}
}
}
// set status in every loop
// set error status, can be OK if no error
scs.setStatus(iErr);
}
catch(Exception e)
{
scs.setStatus(SmsConnectorStart.STAT_ERR_UNDEFINED);
Log.log(this, Log.FATAL, e);
closeModem();
bInitedModem = false;
closeJms();
bInitedJms = false;
}
}
// Store the remaining messages
if(smsContainer.hasContent())
{
if(smsContainer.storeContent("./"))
{
Log.log(this, Log.INFO, "SMS objects have been stored.");
smsContainer = null;
}
else
{
Log.log(this, Log.WARN, "SMS objects have NOT been stored.");
}
}
// Close all
closeModem();
closeJms();
bStoppedClean = true;
Log.log(this, Log.INFO, "SMS connector exited");
}
public boolean storeRemainingMessages()
{
boolean success = false;
if(smsContainer != null)
{
success = smsContainer.storeContent("./");
}
return success;
}
/**
* Init Sms-Modem
*
* @return <code>true</code> if all o.k.,
* and <code>false</code> if Modem initialization failed.
*/
private boolean initModem()
{
String[] strComPort = null;
String[] strManufac = null;
String[] strModel = null;
String[] strSimPin = null;
String[] strPhoneNumber = null;
String m = null;
int[] iBaudRate = null;
int modemCount = 1;
boolean result = false;
IPreferenceStore store = SmsConnectorPlugin.getDefault().getPreferenceStore();
try
{
if (sTest != 0)
{
Log.log(this, Log.FATAL, "
return true;
}
// strComPort - COM-Port: "COM1", "COM2", "COM3", ... , "/dev/ttyS1", ...
// iBaudRate - Modem Baud-Rate: 9600, 57600, ...
// strManufac - gsmDeviceManufacturer: "SonyEricsson", "Siemens", "Wavecom", "Nokia", ..., ""
// strModel - gsmDeviceModel: "GS64", "M1306B", "6310i", ..., ""
// strSimPin - SimCard Pin-Number: "1234", ...
try
{
readWaitingPeriod = Long.parseLong(store.getString(SampleService.P_MODEM_READ_WAITING_PERIOD));
Log.log(this, Log.INFO, "Waiting period for reading: " + readWaitingPeriod);
}
catch(NumberFormatException e)
{
readWaitingPeriod = 10000;
Log.log(this, Log.WARN, "Waiting period for reading is not valid. Using default: " + readWaitingPeriod);
}
try
{
modemCount = Integer.parseInt(store.getString(SampleService.P_MODEM_COUNT));
modemCount = (modemCount < 1) ? 1 : modemCount;
modemCount = (modemCount > 3) ? 3 : modemCount;
Log.log(this, Log.INFO, "Number of modems: " + modemCount);
}
catch (NumberFormatException e)
{
modemCount = 1;
Log.log(this, Log.WARN, "Number of modems not defined. Using default: " + modemCount);
}
strComPort = new String[modemCount];
strManufac = new String[modemCount];
strModel = new String[modemCount];
strSimPin = new String[modemCount];
strPhoneNumber = new String[modemCount];
iBaudRate = new int[modemCount];
// TODO: Better error handling and value checks
for(int i = 0;i < modemCount;i++)
{
strComPort[i] = store.getString(SampleService.P_PREFERENCE_STRING + (i + 1) + "ComPort");
strComPort[i] = (strComPort[i] == null) ? "" : strComPort[i];
try
{
iBaudRate[i] = Integer.parseInt(store.getString(SampleService.P_PREFERENCE_STRING + (i + 1) + "ComBaudrate"));
}
catch (NumberFormatException e)
{
iBaudRate[i] = 9600;
Log.log(this, Log.WARN, "Value for Baudrate is not a number, take default: " + iBaudRate[i]);
}
strManufac[i] = store.getString(SampleService.P_PREFERENCE_STRING + (i + 1) + "Manufacture");
strManufac[i] = (strManufac[i] == null) ? "" : strManufac[i];
strModel[i] = store.getString(SampleService.P_PREFERENCE_STRING + (i + 1) + "Model");
strModel[i] = (strModel[i] == null) ? "" : strModel[i];
strSimPin[i] = store.getString(SampleService.P_PREFERENCE_STRING + (i + 1) + "SimPin");
strSimPin[i] = (strSimPin[i] == null) ? "" : strSimPin[i];
strPhoneNumber[i] = store.getString(SampleService.P_PREFERENCE_STRING + (i + 1) + "Number");
strPhoneNumber[i] = (strPhoneNumber[i] == null) ? "" : strPhoneNumber[i];
}
modemService = new Service();
for(int i = 0;i < modemCount;i++)
{
if(strComPort[i].length() > 0)
{
Log.log(this, Log.INFO, "start initModem(" + strComPort[i] + ","
+ iBaudRate[i] + ","
+ strManufac[i] + ","
+ strModel[i] + ")");
// modemService = new CSoftwareService(strComPort, iBaudRate, strManufac, strModel);
m = "modem." + strComPort[i].toLowerCase();
SerialModemGateway modem = new SerialModemGateway(m , strComPort[i], iBaudRate[i], strManufac[i], strModel[i]);
modem.setInbound(true);
modem.setOutbound(true);
modem.setSimPin(strSimPin[i]);
// modem.setOutboundNotification(outboundNotification);
modemService.addGateway(modem);
modemInfo.addModemName(m, strPhoneNumber[i]);
sleep(2000);
}
else
{
Log.log(this, Log.WARN, "No COM port defined for modem " + (i + 1) + ".");
}
}
result = true;
Log.log(this, Log.INFO, "Modem(s) are initialized");
modemService.setGatewayStatusNotification(new GatewayStatusNotification(modemInfo.getModemNames()));
if(result == true)
{
Log.log(this, Log.INFO, "Try to start service");
modemService.startService();
Log.log(this, Log.INFO, "service started");
}
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not init modem", e);
JmsSender sender = new JmsSender("SmsConnectorAlarmSender", store.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_SENDER_PROVIDER_URL), "ALARM");
if(sender.isConnected())
{
if(sender.sendMessage("alarm", "SmsConnectorWork: Cannot init modem [" + e.getMessage() + "]", "MAJOR") == false)
{
Log.log(this, Log.ERROR, "Cannot send alarm message.");
}
else
{
Log.log(this, Log.INFO, "Alarm message sent.");
}
}
else
{
Log.log(this, Log.WARN, "Alarm message sender is NOT connected.");
}
sender.closeAll();
sender = null;
result = false;
}
return result;
}
public void closeModem()
{
if (modemService != null)
{
try
{
modemService.stopService();
Log.log(this, Log.INFO, "Modem communication closed.");
}
catch (Exception e)
{
Log.log(this, Log.WARN, e);
}
}
modemService = null;
}
public synchronized void stopWorking()
{
bStop = true;
}
public boolean stoppedClean()
{
return bStoppedClean;
}
private boolean initJms()
{
IPreferenceStore storeAct = Activator.getDefault().getPreferenceStore();
Hashtable<String, String> properties = null;
boolean result = false;
boolean durable = Boolean.parseBoolean(storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_CREATE_DURABLE));
try
{
properties = new Hashtable<String, String>();
properties.put(Context.INITIAL_CONTEXT_FACTORY,
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_CONNECTION_FACTORY_CLASS));
properties.put(Context.PROVIDER_URL,
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_SENDER_PROVIDER_URL));
amsSenderContext = new InitialContext(properties);
amsSenderFactory = (ConnectionFactory) amsSenderContext.lookup(
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_CONNECTION_FACTORY));
amsSenderConnection = amsSenderFactory.createConnection();
amsSenderConnection.setClientID("SmsConnectorWorkSenderInternal");
amsSenderSession = amsSenderConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
/*
amsPublisherReply = amsSession.createProducer((Topic)amsContext.lookup(
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_TOPIC_REPLY)));
*/
amsPublisherReply = amsSenderSession.createProducer(amsSenderSession.createTopic(
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_TOPIC_REPLY)));
if (amsPublisherReply == null)
{
Log.log(this, Log.FATAL, "could not create amsPublisherReply");
return false;
}
amsSenderConnection.start();
// Create the redundant receiver
amsReceiver = new JmsRedundantReceiver("SmsConnectorWorkReceiverInternal", storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_PROVIDER_URL_1), storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_PROVIDER_URL_2));
// Create first subscriber (default topic for the connector)
result = amsReceiver.createRedundantSubscriber(
"amsSubscriberSms",
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_TOPIC_SMS_CONNECTOR),
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_TSUB_SMS_CONNECTOR),
durable);
if(result == false)
{
Log.log(this, Log.FATAL, "could not create amsSubscriberSms");
return false;
}
// Create second subscriber (topic for message management)
// TODO: Replace constant with preference entry
result = amsReceiver.createRedundantSubscriber(
"amsConnectorManager",
MANAGE_COMMAND_TOPIC,
MANAGE_COMMAND_TOPIC_SUB,
durable);
if(result == false)
{
Log.log(this, Log.FATAL, "could not create amsConnectorManager");
return false;
}
return true;
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not init internal Jms", e);
JmsSender sender = new JmsSender("SmsConnectorAlarmSender", storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_SENDER_PROVIDER_URL), "ALARM");
if(sender.isConnected())
{
if(sender.sendMessage("alarm", "SmsConnectorWork: Cannot init internal Jms [" + e.getMessage() + "]", "MAJOR") == false)
{
Log.log(this, Log.ERROR, "Cannot send alarm message.");
}
else
{
Log.log(this, Log.INFO, "Alarm message sent.");
}
}
else
{
Log.log(this, Log.WARN, "Alarm message sender is NOT connected.");
}
sender.closeAll();
sender = null;
}
return false;
}
public void closeJms()
{
Log.log(this, Log.INFO, "exiting internal jms communication");
if(amsReceiver != null)
{
amsReceiver.closeAll();
}
if (amsPublisherReply != null){try{amsPublisherReply.close();amsPublisherReply=null;}
catch (JMSException e){Log.log(this, Log.WARN, e);}}
if (amsSenderSession != null){try{amsSenderSession.close();amsSenderSession=null;}
catch (JMSException e){Log.log(this, Log.WARN, e);}}
if (amsSenderConnection != null){try{amsSenderConnection.stop();}
catch (JMSException e){Log.log(this, Log.WARN, e);}}
if (amsSenderConnection != null){try{amsSenderConnection.close();amsSenderConnection=null;}
catch (JMSException e){Log.log(this, Log.WARN, e);}}
if (amsSenderContext != null){try{amsSenderContext.close();amsSenderContext=null;}
catch (NamingException e){Log.log(this, Log.WARN, e);}}
Log.log(this, Log.INFO, "jms internal communication closed");
}
private boolean acknowledge(Message msg)
{
try
{
msg.acknowledge();
return true;
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not acknowledge", e);
}
return false;
}
/**
* Sends the SMS stored in the SmsContainer.
*
* @return Error code
*/
private int sendSmsMsg() throws Exception
{
Sms sms = null;
int iErr = SmsConnectorStart.STAT_OK;
if(smsContainer.hasContent())
{
sms = smsContainer.getFirstSms();
if(sms != null)
{
Log.log(this, Log.DEBUG, "SMS: " + sms.toString());
// Check if we have a 'start modem test' message.
if(sms.getMessage().startsWith("MODEM_CHECK"))
{
Pattern pattern = null;
String r = null;
pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}.\\d{3}");
Matcher m = pattern.matcher(sms.getMessage());
if(m.find())
{
r = m.group();
// if(doModemTest(r))
// Log.log(this, Log.INFO, "Modem test DONE.");
// else
// Log.log(this, Log.WARN, "Modem test FAILED.");
sendModemTestSms(r);
smsContainer.removeSms(sms);
}
}
else // A normal SMS to send
{
if((sms.getType() == Sms.Type.OUT) && (sms.getState() != Sms.State.SENT))
{
if(sendSms(sms))
{
smsContainer.removeSms(sms);
}
else
{
iErr = SmsConnectorStart.STAT_ERR_MODEM_SEND;
}
}
}
}
}
return iErr;
}
private void sendModemTestSms(String eventTime)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
OutboundMessage outMsg = null;
String name = null;
String number = null;
String text = null;
String timeStamp = null;
timeStamp = dateFormat.format(Calendar.getInstance().getTime());
testStatus.setTimeStamp(timeStamp);
testStatus.setAnswerEventTime(eventTime);
Log.log(this, Log.INFO, "Number of modems to test: " + modemInfo.getModemCount());
for(int i = 0;i < modemInfo.getModemCount();i++)
{
name = modemInfo.getModemName(i);
if(name != null)
{
number = modemInfo.getPhoneNumber(name);
text = SMS_TEST_TEXT;
text = text.replaceAll("\\$DATE", timeStamp);
text = text.replaceAll("\\$GATEWAYID", name);
outMsg = new OutboundMessage(number, text);
outMsg.setEncoding(MessageEncodings.ENC7BIT);
outMsg.setStatusReport(false);
outMsg.setValidityPeriod(8);
try
{
Log.log(this, Log.INFO, "Sending to modem '" + name + "': " + text);
if(modemService.sendMessage(outMsg, name))
{
testStatus.addGatewayId(name);
}
}
catch(Exception e)
{
Log.log(this, Log.WARN, "Could not send SMS test message to modem '" + name + "'.");
testStatus.addBadModem(name);
}
outMsg = null;
}
}
if(testStatus.getGatewayCount() > 0)
{
testStatus.setActive(true);
testStatus.setTimeOut(System.currentTimeMillis() + 90000); // 1.5 min
}
else
{
sendTestAnswer(testStatus.getAnswerEventTime(), "No modem could send the test SMS.", "MAJOR", "ERROR");
testStatus.reset();
}
}
private void sendTestAnswer(String eventTime, String text, String severity, String value)
{
Topic topic = null;
MessageProducer amsPublisherCheck = null;
MapMessage mapMessage = null;
String topicName = null;
IPreferenceStore storeAct = org.csstudio.ams.Activator.getDefault().getPreferenceStore();
topicName = storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_TOPIC_MONITOR);
try
{
topic = amsSenderSession.createTopic(topicName);
amsPublisherCheck = amsSenderSession.createProducer(topic);
mapMessage = amsSenderSession.createMapMessage();
mapMessage.setString("TYPE", "event");
mapMessage.setString("EVENTTIME", eventTime);
mapMessage.setString("TEXT", text);
mapMessage.setString("SEVERITY", severity);
mapMessage.setString("VALUE", value);
mapMessage.setString("HOST", Environment.getInstance().getHostName());
mapMessage.setString("USER", Environment.getInstance().getUserName());
mapMessage.setString("NAME", "AMS_SYSTEM_CHECK_ANSWER");
mapMessage.setString("APPLICATION-ID", "SmsConnector");
mapMessage.setString("DESTINATION", "AmsSystemMonitor");
amsPublisherCheck.send(mapMessage);
}
catch(JMSException jmse)
{
Log.log(this, Log.ERROR, "Answer message could NOT be sent.");
}
finally
{
if(amsPublisherCheck!=null){try{amsPublisherCheck.close();}catch(JMSException e){}amsPublisherCheck=null;}
topic = null;
}
}
@SuppressWarnings("unused")
@Deprecated
private boolean doModemTest(String eventTime)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
OutboundMessage outMsg = null;
InboundMessage[] inMsg = null;
Topic topic = null;
MessageProducer amsPublisherCheck = null;
MapMessage mapMessage = null;
Vector<String> badModem = null;
Object waitObject = null;
String name = null;
String number = null;
String text = null;
String topicName = null;
String severity = null;
String value = null;
long endTime = 0;
long currentTime = 0;
int checkedModems = 0;
boolean success = false;
Log.log(this, Log.INFO, "Starting modem check.");
badModem = new Vector<String>();
// TODO: Senden und Empfangen der Test-SMS getrennt behandeln.
for(int i = 0;i < modemInfo.getModemCount();i++)
{
name = modemInfo.getModemName(i);
if(name != null)
{
number = modemInfo.getPhoneNumber(name);
text = SMS_TEST_TEXT;
text = text.replaceAll("\\$DATE", dateFormat.format(Calendar.getInstance().getTime()));
text = text.replaceAll("\\$GATEWAYID", name);
outMsg = new OutboundMessage(number, text);
outMsg.setEncoding(MessageEncodings.ENC7BIT);
outMsg.setStatusReport(false);
outMsg.setValidityPeriod(8);
waitObject = new Object();
try
{
Log.log(this, Log.INFO, "Sending to modem '" + name + "': " + text);
if(modemService.sendMessage(outMsg, name))
{
// Try for 1 minute
endTime = System.currentTimeMillis() + 60000;
do
{
synchronized(waitObject)
{
try
{
waitObject.wait(readWaitingPeriod);
}
catch(InterruptedException ie) {}
}
inMsg = modemService.readMessages(MessageClasses.ALL, name);
for(InboundMessage im : inMsg)
{
Log.log(this, Log.INFO, "Received text: " + im.getText());
if(im.getText().compareTo(text) == 0)
{
Log.log(this, Log.INFO, "Modem check was successful for " + name + ".");
modemService.deleteMessage(im);
checkedModems++;
success = true;
break;
}
}
currentTime = System.currentTimeMillis();
}
while(!success && (currentTime <= endTime));
if(!success)
{
badModem.add(name);
}
success = false;
}
else
{
Log.log(this, Log.WARN, "Could not send SMS test message.");
if(badModem.contains(name) == false)
{
badModem.add(name);
}
}
}
catch(Exception e)
{
Log.log(this, Log.ERROR, "Modem check was NOT successful for " + name + ".");
if(badModem.contains(name) == false)
{
badModem.add(name);
}
}
}
} // for
Log.log(this, Log.INFO, "Number of checked modems: " + checkedModems);
Log.log(this, Log.INFO, "Number of modems: " + modemInfo.getModemCount());
success = (checkedModems == modemInfo.getModemCount());
IPreferenceStore storeAct = org.csstudio.ams.Activator.getDefault().getPreferenceStore();
topicName = storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_TOPIC_MONITOR);
if(checkedModems == modemInfo.getModemCount())
{
severity = "NO_ALARM";
value = "OK";
text = "Modems are working fine.";
}
else if((checkedModems > 0) && (checkedModems < modemInfo.getModemCount()))
{
severity = "MINOR";
value = "WARN";
text = (modemInfo.getModemCount() - checkedModems) + " modems are not working properly: ";
for(String s : badModem)
{
text = text + s + " ";
}
}
else if(checkedModems == 0)
{
severity = "MAJOR";
value = "ERROR";
text = "No modem is working.";
}
try
{
topic = amsSenderSession.createTopic(topicName);
amsPublisherCheck = amsSenderSession.createProducer(topic);
mapMessage = amsSenderSession.createMapMessage();
mapMessage.setString("TYPE", "event");
mapMessage.setString("EVENTTIME", eventTime);
mapMessage.setString("TEXT", text);
mapMessage.setString("SEVERITY", severity);
mapMessage.setString("VALUE", value);
mapMessage.setString("NAME", "AMS_SYSTEM_CHECK_ANSWER");
mapMessage.setString("APPLICATION-ID", "SmsConnector");
mapMessage.setString("DESTINATION", "AmsSystemMonitor");
amsPublisherCheck.send(mapMessage);
}
catch(JMSException jmse)
{
Log.log(this, Log.ERROR, "Answer message could NOT be sent.");
}
finally
{
if(amsPublisherCheck!=null){try{amsPublisherCheck.close();}catch(JMSException e){}amsPublisherCheck=null;}
topic = null;
}
badModem.clear();
badModem = null;
return success;
}
@SuppressWarnings("unused")
private int sendSmsMsg(Message message) throws Exception
{
if (!(message instanceof MapMessage))
{
Log.log(this, Log.WARN, "got unknown message " + message);
// Deletes all received messages of the session
if (!acknowledge(message))
return SmsConnectorStart.STAT_ERR_JMSCON;
return SmsConnectorStart.STAT_OK;
}
else
{
MapMessage msg = (MapMessage) message;
String text = msg.getString(MSGPROP_RECEIVERTEXT);
String recNo = msg.getString(MSGPROP_RECEIVERADDR);
String parsedRecNo = null;
int iErr = SmsConnectorStart.STAT_ERR_UNDEFINED;
for (int j = 1 ; j <= 5 ; j++) //only for short net breaks
{
if (parsedRecNo == null)
{
try
{
parsedRecNo = parsePhoneNumber(recNo);
}
catch (Exception e)
{
Log.log(this, Log.FATAL, "Parsing phone number - failed.");
if (acknowledge(message)) // deletes all received messages of the session
return SmsConnectorStart.STAT_OK;
iErr = SmsConnectorStart.STAT_ERR_JMSCON;
}
}
if (parsedRecNo != null)
{
if (sendSms(text, parsedRecNo))
{
if (acknowledge(message)) // deletes all received messages of the session
return SmsConnectorStart.STAT_OK;
iErr = SmsConnectorStart.STAT_ERR_JMSCON;
}
else
{
iErr = SmsConnectorStart.STAT_ERR_MODEM_SEND;
}
}
sleep(2000);
}
return iErr;
}
}
private String parsePhoneNumber(String mobile) throws Exception
{
StringBuffer sbMobile = new StringBuffer(mobile);
StringBuffer sbTest = new StringBuffer("+0123456789");
int i = 0;
if (sbMobile.length() > 0) // first char (can be +0123456789)
{
if (sbTest.indexOf(String.valueOf(sbMobile.charAt(i))) < 0) // first char found in sbTest
sbMobile.deleteCharAt(0); // if not found
else
i++;
sbTest.deleteCharAt(0); // delete '+'
}
while (i < sbMobile.length()) // other chars (can be 0123456789)
{
if (sbTest.indexOf(String.valueOf(sbMobile.charAt(i))) < 0) // char found in sbTest
{
sbMobile.deleteCharAt(i); // if not found
continue; // do not i++
}
i++;
}
return sbMobile.toString();
}
public boolean sendSms(Sms sms) throws Exception
{
boolean success;
success = sendSms(sms.getMessage(), sms.getPhoneNumber());
if(success)
{
sms.setState(Sms.State.SENT);
}
else
{
sms.setState(Sms.State.FAILED);
}
return success;
}
/**
* Send SMS with text to receiver address.
*
* @param text String
* @param recNo String
* @return <code>true</code> if SMS was sent,
* and <code>false</code> if SMS was not sent.
* @throws Exception
*/
private boolean sendSms(String text, String recNo) throws Exception
{
boolean bRet = false;
Log.log(this, Log.INFO, "start sendSms");
scs.setStatus(SmsConnectorStart.STAT_SENDING);
// Lets create a message for dispatch.
// A message needs the recipient's number and the text. Recipient's
// number should always be defined in international format.
OutboundMessage msg = new OutboundMessage(recNo, text);
// Set the message encoding.
// We can use 7bit, 8bit and Unicode. 7bit should be enough for most
// cases. Unicode is necessary for Far-East countries.
msg.setEncoding(MessageEncodings.ENC7BIT);
// Do we require a Delivery Status Report?
// Delivery Status Report
// Changed by Markus Moeller, 2009-01-30
// To avoid restarts of the modems
// msg.setStatusReport(true);
msg.setStatusReport(false);
// We can also define the validity period.
// Validity period is always defined in hours.
// The following statement sets the validity period to 8 hours.
msg.setValidityPeriod(8);
// Do we require a flash SMS? A flash SMS appears immediately on
// recipient's phone.
// Sometimes its called a forced SMS. Its kind of rude, so be
// careful!
// Keep in mind that flash messages are not supported by all
// handsets.
// msg.setFlashSms(true);
// Some special applications are "listening" for messages on
// specific ports.
// The following statements set the Source and Destination port.
// They should always be used in pairs!!!
// Source and Destination ports are defined as 16bit ints in the
// message header.
// msg.setSourcePort(10000);
// msg.setDestinationPort(11000);
// Ok, finished with the message parameters, now send it!
// If we have many messages to send, we could also construct a
// LinkedList with many COutgoingMessage objects and pass it to
// modemService.sendMessage().
if (sTest == 0)
{
Log.log(this, Log.INFO, "call modem.sendMessage");
int totalOutBefore = modemService.getOutboundMessageCount();// total number of outbound messages since restart
// Log.log(this, Log.INFO, "Modem connected: " + modemService.getConnected());
try
{
modemService.sendMessage(msg);
}
catch(Exception e)
{
Log.log(this, Log.ERROR, "could not sendMessage", e);
return false; //only with exceptions at this line => modem error
}
int totalOutAfter = modemService.getOutboundMessageCount();// total number of outbound messages since restart
if (totalOutBefore < totalOutAfter)
{
Log.log(this, Log.INFO, "sms sent to: '" + recNo + "' with text: '" + text + "'");
bRet = true;
}
Log.log(this, Log.INFO, "totalOut sms = " + totalOutAfter);
}
else
{
return true; // in Test Mode - true
}
return bRet;
}
private int readSmsMsg(/*int limit*/) throws Exception
{
int iErr = SmsConnectorStart.STAT_ERR_UNDEFINED;
for (int j = 1 ; j <= 5 ; j++) //TEMPORARAY connections error try some times
{ // (short breaks of ethernet or gsm net)
iErr = readModem(/*limit*/);
if (SmsConnectorStart.STAT_OK == iErr) // only return if read successfully
return SmsConnectorStart.STAT_OK;
sleep(5000);
}
return iErr;
}
private boolean deleteMessage(InboundMessage msg)
{
try
{
if (sTest == 0)
modemService.deleteMessage(msg);
return true;
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not deleteMessage", e);
}
return false;
}
/**
* Reads SMS-Messages from the modem.
*
* @param limit int - Read up to number of messages. If limit is set to 0, read all messages.
* @return int
* @throws Exception
*/
private int readModem(/*int limit*/) throws Exception
{
LinkedList<InboundMessage> msgList = new LinkedList<InboundMessage>();
Log.log(this, Log.DEBUG, "start readModem call modem.readMessages");
scs.setStatus(SmsConnectorStart.STAT_READING);
try
{
if(sTest == 0)
{
// Read up to number of messages, read other SMS at the next run.
// Read out all messages in linked list
try
{
modemService.readMessages(msgList, MessageClasses.ALL /*, limit*/);
}
catch(NumberFormatException nfe)
{
// Sometimes we get this exception, if the PDU contains invalid characters
Log.log(this, Log.FATAL, "[*** NumberFormatException ***]: " + nfe.getMessage());
}
}
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not readMessages", e);
return SmsConnectorStart.STAT_ERR_MODEM;
}
if (!msgList.isEmpty())
Log.log(this, Log.INFO, "readModem done, message count = " + msgList.size());
else
{
Log.log(this, Log.DEBUG, "readModem done, modem is empty");
if (sTest != 0) // TODO FOR TEST ONLY
generateTestMsg();
return SmsConnectorStart.STAT_OK;
}
// Iterate and display.
// The CMessage parent object has a toString() method which displays
// all of its contents. Useful for debugging, but for a real world
// application you should use the necessary getXXX methods.
for (int i = 0; i < msgList.size(); i++)
{
InboundMessage smsMsg = (InboundMessage) msgList.get(i);
String text = null;
// BEWARE: We can get an InboundBinaryMessage and will run into problems
// if we want to get the message text. The getText() method
// of InboundBinaryMessage just throws an exception!!!!!!!
if(smsMsg instanceof InboundBinaryMessage)
{
text = "[InboundBinaryMessage] Cannot read the content.";
}
else
{
text = smsMsg.getText();
}
if(smsMsg.getType() == MessageTypes.STATUSREPORT)
{
StatusReportMessage smsStat = (StatusReportMessage)smsMsg;
Log.log(this, Log.INFO, "receive statusReport message: '" + text
+ "' originator/deliveryStatus/date/dateOrg/dateRec/smscRef = "
+ smsStat.getOriginator() + "/" + smsStat.getStatus().toString() + "/"
+ smsStat.getDate() + "/" + smsStat.getSent() + "/" + smsStat.getReceived() + "/"
+ smsStat.getRefNo());
if (!deleteMessage((InboundMessage)msgList.get(i)))
return SmsConnectorStart.STAT_ERR_MODEM;
continue;
}
if (smsMsg.getType() != MessageTypes.INBOUND)
{
Log.log(this, Log.INFO, "receive message unknown type: '" + text
+ "' originator/type/date/smscRef = "
+ smsMsg.getOriginator() + "/" + smsMsg.getType() + "/" + smsMsg.getDate() + "/" + smsMsg.getMpRefNo());
if (!deleteMessage((InboundMessage)msgList.get(i)))
return SmsConnectorStart.STAT_ERR_MODEM;
continue;
}
else
Log.log(this, Log.INFO, "receive incoming message: '" + text
+ "' originator/date/smscRef = "
+ smsMsg.getOriginator() + "/" + smsMsg.getDate() + "/" + smsMsg.getMpRefNo());
if(testStatus.isTestAnswer(text))
{
Log.log(this, Log.INFO, "Self test SMS");
//TODO:
// Handle incoming test SMS
if(testStatus.isActive())
{
Log.log(this, Log.INFO, "Self test is active");
if(testStatus.isTimeOut() == false)
{
Log.log(this, Log.INFO, "Gateways waiting for answer: " + testStatus.getGatewayCount());
testStatus.checkAndRemove(text);
Log.log(this, Log.INFO, "Gateways waiting for answer after remove: " + testStatus.getGatewayCount());
if((testStatus.getGatewayCount() == 0))
{
if(testStatus.getBadModemCount() == 0)
{
Log.log(this, Log.INFO, "All modems are working fine.");
this.sendTestAnswer(testStatus.getAnswerEventTime(), "All modems are working fine.", "NO_ALARM", "OK");
}
else
{
String list = "";
for(String name : testStatus.getBadModems())
{
list = list + name + " ";
}
Log.log(this, Log.WARN, "Modems not working properly: " + list);
this.sendTestAnswer(testStatus.getAnswerEventTime(), "Modems, not working properly: " + list, "MINOR", "WARN");
}
Log.log(this, Log.INFO, "Reset current test.");
testStatus.reset();
}
}
else
{
Log.log(this, Log.WARN, "Current test timed out.");
Log.log(this, Log.INFO, "Remaining gateways: " + testStatus.getGatewayCount());
Log.log(this, Log.INFO, "Bad gateways before moving: " + testStatus.getBadModemCount());
testStatus.moveGatewayIdToBadModems();
Log.log(this, Log.INFO, "Remaining gateways after moving: " + testStatus.getGatewayCount());
Log.log(this, Log.INFO, "Bad gateways after moving: " + testStatus.getBadModemCount());
if(testStatus.getBadModemCount() == modemInfo.getModemCount())
{
Log.log(this, Log.ERROR, "No modem is working properly.");
this.sendTestAnswer(testStatus.getAnswerEventTime(), "No modem is working properly.", "MAJOR", "ERROR");
}
else
{
String list = "";
for(String name : testStatus.getBadModems())
{
list = list + name + " ";
}
Log.log(this, Log.WARN, "Modems, not working properly: " + list);
this.sendTestAnswer(testStatus.getAnswerEventTime(), "Modems, not working properly: " + list, "MINOR", "WARN");
}
Log.log(this, Log.INFO, "Reset current test.");
testStatus.reset();
}
}
if(!deleteMessage((InboundMessage)msgList.get(i)))
{
return SmsConnectorStart.STAT_ERR_MODEM;
}
continue;
}
// Reply_Message-Format: "<ChainIdAndPos>*<ConfirmCode>"
// Example: "12345001*123"
// Change-Status_Message-Format: "<GroupNum>*<UserNum>*<Status>*<StatusCode>"
// Example: "12*34*1*123"
// Change-Status_Message-Format: "<GroupNum>*<UserNum>*<Status>*<StatusCode>*<Reason>"
// Example: "12*34*0*123*Im ill"
//max 3 Zahlen(Long) + 2 Text
// zahl*zahl reply
// zahl*zahl*zahl*text status change (! letzter ohne stern)
// zahl*zahl*zahl*text*text status change , nur im letzten text sterne zugelassen
String[] arr = new String[5];
int iStarPos = -1;
int iLastStarPos = -1;
int iCnt = 0;
byte bFormat = 0; //no valid format
// ADDED BY Markus Moeller, 2007-12-05
boolean changeGroupState = false;
// ADDED BY Markus Moeller, 2007-12-05
if(text.trim().startsWith("g*") || text.trim().startsWith("G*"))
{
changeGroupState = true;
text = text.trim().substring(2);
}
for (iCnt = 0;iCnt < 3;iCnt++)
{
iStarPos = text.indexOf("*", iLastStarPos + 1);
if (iStarPos < 0)
{
if (text.length() > iLastStarPos)
arr[iCnt] = text.substring(iLastStarPos + 1, text.length());
if (iCnt == 1)
bFormat = 1; //format reply
break;
}
arr[iCnt] = text.substring(iLastStarPos + 1, iStarPos);
iLastStarPos = iStarPos;
}
if (iStarPos > 0 && text.length() > iStarPos) //zahl*zahl*zahl*text
{
bFormat = 2; //format status change
iStarPos = text.indexOf("*", iLastStarPos + 1);
if (iStarPos < 0)
{
arr[iCnt] = text.substring(iLastStarPos + 1, text.length()); //(! letzter ohne stern)
}
else //zahl*zahl*zahl*text*text
{
arr[iCnt] = text.substring(iLastStarPos + 1, iStarPos);
if (iStarPos > 0 && text.length() > iStarPos)
{
arr[iCnt+1] = text.substring(iStarPos + 1, text.length());
}
}
}
//number checking
if (bFormat == 1)
{
try {
if (!arr[0].equals("#")) //accept all
Long.parseLong(arr[0]);
Long.parseLong(handyButton2NumberMode(arr[1]));
}
catch (NumberFormatException e)
{
Log.log(this, Log.WARN, "expected is not a number");
bFormat = 0;
}
}
else if (bFormat == 2)
{
try {
Long.parseLong(arr[0]);
Long.parseLong(arr[1]);
Long.parseLong(arr[2]);
}
catch (NumberFormatException e)
{
Log.log(this, Log.WARN, "expected is not a number");
bFormat = 0;
}
}
if (bFormat <= 0)
{
Log.log(this, Log.WARN, "incoming message from: '" + smsMsg.getOriginator() + "' has unknown Format: '" + text + "'");
}
else
{
MapMessage mapMsg = null;
try
{
mapMsg = amsSenderSession.createMapMessage();
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not createMapMessage", e);
}
if (mapMsg == null)
return SmsConnectorStart.STAT_ERR_JMSCON;
if (bFormat == 1)
{
mapMsg.setString(MSGPROP_MESSAGECHAINID_AND_POS, arr[0]);
mapMsg.setString(MSGPROP_CONFIRMCODE, handyButton2NumberMode(arr[1]));
mapMsg.setString(MSGPROP_REPLY_TYPE, MSG_REPLY_TYPE_SMS);
mapMsg.setString(MSGPROP_REPLY_ADRESS, smsMsg.getOriginator());
Log.log(this, Log.INFO, "message parsed as alarm reply, start internal jms send");
}
else if (bFormat == 2)
{
// ADDED BY Markus Moeller, 2007-12-05
if(changeGroupState == true)
{
mapMsg.setString(MSGPROP_CHANGESTAT_ACTION, "group");
}
else
{
mapMsg.setString(MSGPROP_CHANGESTAT_ACTION, "user");
}
mapMsg.setString(MSGPROP_CHANGESTAT_GROUPNUM, arr[0]);
mapMsg.setString(MSGPROP_CHANGESTAT_USERNUM, arr[1]);
mapMsg.setString(MSGPROP_CHANGESTAT_STATUS, arr[2]);
mapMsg.setString(MSGPROP_CHANGESTAT_STATUSCODE, arr[3]);
if (arr[4] == null)
mapMsg.setString(MSGPROP_CHANGESTAT_REASON, "");
else
mapMsg.setString(MSGPROP_CHANGESTAT_REASON, arr[4]);
mapMsg.setString(MSGPROP_REPLY_TYPE, MSG_REPLY_TYPE_SMS);
mapMsg.setString(MSGPROP_REPLY_ADRESS, smsMsg.getOriginator());
Log.log(this, Log.INFO, "message parsed as change status, start internal jms send");
}
try
{
amsPublisherReply.send(mapMsg);
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not send to internal jms", e);
return SmsConnectorStart.STAT_ERR_JMSCON;
}
Log.log(this, Log.INFO, "send internal jms message done");
}
Log.log(this, Log.DEBUG, "start delete");
if (!deleteMessage((InboundMessage)msgList.get(i)))
return SmsConnectorStart.STAT_ERR_MODEM;
Log.log(this, Log.DEBUG, "delete done");
}
Log.log(this, Log.DEBUG, "readReply . . . exit");
return SmsConnectorStart.STAT_OK;
}
private String handyButton2NumberMode(String str)
{
String ret = "";
byte[] b = str.toLowerCase().getBytes();
for (int i = 0; i < b.length; i++)
switch (b[i])
{
default:
ret += (b[i] - 48); // CHANGED BY Markus Moeller, 2007-11-20
break;
case '.':
case ' ':
ret += "1";
break;
case 'a':
case 'b':
case 'c':
ret += "2";
break;
case 'd':
case 'e':
case 'f':
ret += "3";
break;
case 'g':
case 'h':
case 'i':
ret += "4";
break;
case 'j':
case 'k':
case 'l':
ret += "5";
break;
case 'm':
case 'n':
case 'o':
ret += "6";
break;
case 'p':
case 'q':
case 'r':
case 's':
ret += "7";
break;
case 't':
case 'u':
case 'v':
ret += "8";
break;
case 'w':
case 'x':
case 'y':
case 'z':
ret += "9";
break;
}
return ret;
}
private void generateTestMsg()
{
try
{
Log.log(this, Log.FATAL, "
String smsTxt = "";
String strOriginator = "";
if (sTest == 1)
{
// Reply_Message-Format: "<ChainIdAndPos>*<ConfirmCode>"
// Example: "12345001*123"
smsTxt = "1001*5678";
strOriginator = "01736079941";
}
else if (sTest == 2)
{
// Change-Status_Message-Format: "<GroupNum>*<UserNum>*<Status>*<StatusCode>*<Reason>"
// Example: "12*34*0*123*Im ill." (Logout with reason)
// or "12*34*1*123*" (Login without reason)
// or "12*34*1*123" (Login without reason)
smsTxt = "1*1*0*1234*Ich bin krank.";
strOriginator = "01736079941";
}
int[] arr = new int[5]; // should be 1 more than in "switch (iStarPos)" statement
int iStarPos = -1;
for (int x = 0 ; x < 5 ; x++)
{
iStarPos = smsTxt.indexOf("*", iStarPos+1);
if (iStarPos < 0)
{
iStarPos = x;// count of "*"
break;
}
arr[x] = iStarPos;
}
switch (iStarPos)
{
case 4:
// Change-Status_Message-Format: "<GroupNum>*<UserNum>*<Status>*<StatusCode>*<Reason>"
// Example: "12*34*0*123*Im ill"
if ( (arr[0] > 0)
&& (arr[1] > arr[0]+1)
&& (arr[2] > arr[1]+1)
&& (arr[3] > arr[2]+1) // at least one char for each
&& (arr[3]+1 <= smsTxt.length()) ) // (reason can be "")
{
MapMessage mapMsg = amsSenderSession.createMapMessage();
mapMsg.setString(MSGPROP_CHANGESTAT_GROUPNUM, smsTxt.substring(0, arr[0]));
mapMsg.setString(MSGPROP_CHANGESTAT_USERNUM, smsTxt.substring(arr[0]+1, arr[1]));
mapMsg.setString(MSGPROP_CHANGESTAT_STATUS, smsTxt.substring(arr[1]+1, arr[2]));
mapMsg.setString(MSGPROP_CHANGESTAT_STATUSCODE, smsTxt.substring(arr[2]+1, arr[3]));
mapMsg.setString(MSGPROP_CHANGESTAT_REASON, smsTxt.substring(arr[3]+1, smsTxt.length()));// with reason
mapMsg.setString(MSGPROP_REPLY_TYPE, MSG_REPLY_TYPE_SMS);
mapMsg.setString(MSGPROP_REPLY_ADRESS, strOriginator);
Log.log(this, Log.INFO, "start Change-Status");
amsPublisherReply.send(mapMsg);
Log.log(this, Log.INFO, "Change-Status done");
break;
}
Log.log(this, Log.WARN, "SMS-Reply from: '" + strOriginator + "' has unknown Format: '" + smsTxt + "'");
break;
case 3:
// Change-Status_Message-Format: "<GroupNum>*<UserNum>*<Status>*<StatusCode>"
// Example: "12*34*1*123"
if ( (arr[0] > 0)
&& (arr[1] > arr[0]+1)
&& (arr[2] > arr[1]+1)
&& (arr[2]+1 < smsTxt.length()) ) // at least one char for each
{
MapMessage mapMsg = amsSenderSession.createMapMessage();
mapMsg.setString(MSGPROP_CHANGESTAT_GROUPNUM, smsTxt.substring(0, arr[0]));
mapMsg.setString(MSGPROP_CHANGESTAT_USERNUM, smsTxt.substring(arr[0]+1, arr[1]));
mapMsg.setString(MSGPROP_CHANGESTAT_STATUS, smsTxt.substring(arr[1]+1, arr[2]));
mapMsg.setString(MSGPROP_CHANGESTAT_STATUSCODE, smsTxt.substring(arr[2]+1, smsTxt.length()));
mapMsg.setString(MSGPROP_CHANGESTAT_REASON, ""); // without a reason
mapMsg.setString(MSGPROP_REPLY_TYPE, MSG_REPLY_TYPE_SMS);
mapMsg.setString(MSGPROP_REPLY_ADRESS, strOriginator);
Log.log(this, Log.INFO, "start Change-Status");
amsPublisherReply.send(mapMsg);
Log.log(this, Log.INFO, "Change-Status done");
break;
}
Log.log(this, Log.WARN, "SMS-Reply from: '" + strOriginator + "' has unknown Format: '" + smsTxt + "'");
break;
case 1:
// Reply_Message-Format: "<ChainIdAndPos>*<ConfirmCode>"
// Example: "12345001*123"
if ((arr[0] > MSG_POS_LENGTH_FOR_MSGPROP) // at least (MSG_POS_LENGTH_FOR_MSGPROP + 1) char for ChainIdAndPos
&& (arr[0]+1 < smsTxt.length())) // at least one char for ConfirmCode
{
MapMessage mapMsg = amsSenderSession.createMapMessage();
mapMsg.setString(MSGPROP_MESSAGECHAINID_AND_POS, smsTxt.substring(0, arr[0]));
mapMsg.setString(MSGPROP_CONFIRMCODE, smsTxt.substring(arr[0]+1, smsTxt.length()));
mapMsg.setString(MSGPROP_REPLY_TYPE, MSG_REPLY_TYPE_SMS);
mapMsg.setString(MSGPROP_REPLY_ADRESS, strOriginator);
Log.log(this, Log.INFO, "start reply");
amsPublisherReply.send(mapMsg);
Log.log(this, Log.INFO, "reply done");
break;
}
Log.log(this, Log.WARN, "SMS-Reply from: '" + strOriginator + "' has unknown Format: '" + smsTxt + "'");
break;
default:// -1, 0, 2, 5
Log.log(this, Log.WARN, "SMS-Reply from: '" + strOriginator + "' has unknown Format: '" + smsTxt + "'");
}// switch (iStarPos)
}// (sTest != 0)
catch(Exception e)
{
Log.log(this, Log.FATAL, e);
}
}
}
|
package org.csstudio.ams.connector.sms;
import java.util.Hashtable;
import java.util.LinkedList;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
// import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
// import javax.jms.Topic;
// import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.csstudio.ams.Activator;
import org.csstudio.ams.AmsConstants;
import org.csstudio.ams.Log;
import org.csstudio.ams.connector.sms.internal.SampleService;
import org.csstudio.platform.utility.jms.JmsRedundantReceiver;
import org.eclipse.jface.preference.IPreferenceStore;
import org.smslib.InboundMessage;
import org.smslib.InboundMessage.MessageClasses;
import org.smslib.Message.MessageEncodings;
import org.smslib.Message.MessageTypes;
import org.smslib.InboundBinaryMessage;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.StatusReportMessage;
import org.smslib.modem.SerialModemGateway;
public class SmsConnectorWork extends Thread implements AmsConstants
{
private SmsConnectorStart scs = null;
// private final int CONSUMER_CONNECTIONS = 2;
private Context amsSenderContext = null;
private ConnectionFactory amsSenderFactory = null;
private Connection amsSenderConnection = null;
private Session amsSenderSession = null;
private MessageProducer amsPublisherReply = null;
private JmsRedundantReceiver amsReceiver = null;
private Service modemService = null;
// private CSoftwareService srv = null;
/** Container for SMS */
private SmsContainer smsContainer;
private short sTest = 0; // 0 - normal behavior, other - for test
private boolean bStop = false;
private boolean bStoppedClean = false;
/** Name of the management topic for sending commands */
public static final String MANAGE_COMMAND_TOPIC = "T_AMS_CON_MANAGE";
public static final String MANAGE_COMMAND_TOPIC_SUB = "T_AMS_TSUB_CON_MANAGE";
/** Name of the management topic for receiving answers */
public static final String MANAGE_REPLY_TOPIC = "T_AMS_CON_MANAGE_REPLY";
public static final String MANAGE_REPLY_TOPIC_SUB = "T_AMS_TSUB_CON_MANAGE_REPLY";
public SmsConnectorWork(SmsConnectorStart scs)
{
// Set the "parent" object
this.scs = scs;
smsContainer = new SmsContainer();
}
public void run()
{
boolean bInitedModem = false;
boolean bInitedJms = false;
bStop = false;
bStoppedClean = false;
int iErr = SmsConnectorStart.STAT_OK;
Log.log(this, Log.INFO, "start sms connector work");
while(bStop == false)
{
try
{
if (!bInitedModem)
{
bInitedModem = initModem();
if(!bInitedModem)
{
Log.log(this, Log.ERROR, "Cannot init modem.");
iErr = SmsConnectorStart.STAT_ERR_MODEM;
scs.setStatus(iErr); // set it for not overwriting with next error
}
}
if (!bInitedJms)
{
bInitedJms = initJms();
if (!bInitedJms)
{
iErr = SmsConnectorStart.STAT_ERR_JMSCON;
scs.setStatus(iErr); // set it for not overwriting with next error
}
}
sleep(100);
if(bInitedModem && bInitedJms)
{
iErr = SmsConnectorStart.STAT_OK;
if (scs.getStatus() == SmsConnectorStart.STAT_INIT)
scs.setStatus(SmsConnectorStart.STAT_OK);
// Log.log(this, Log.DEBUG, "is running");
// First check the connectors manage topic
// Maybe a user wants to delete some messages
Message message = null;
try
{
message = amsReceiver.receive("amsConnectorManager");
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not receive from internal jms: amsConnectorManager", e);
iErr = SmsConnectorStart.STAT_ERR_JMSCON;
}
// If we got a message from the manager plugin, start the ConnectorMessageManager
if(message != null)
{
Log.log(Log.INFO, "Received a message from ConnectorMessageManager");
ConnectorMessageManager manager = null;
try
{
manager = new ConnectorMessageManager(amsSenderConnection, amsReceiver);
manager.begin(message);
manager.closeJms();
iErr = SmsConnectorStart.STAT_OK;
}
catch(JMSException jmse)
{
manager.closeJms();
Log.log(this, Log.FATAL, "the connector message manager does not work properly", jmse);
iErr = SmsConnectorStart.STAT_ERR_JMSCON;
}
manager = null;
}
if(iErr == SmsConnectorStart.STAT_ERR_JMSCON)
{
Log.log(this, Log.ERROR, "Closing JMS communication.");
closeJms();
bInitedJms = false;
}
if(iErr == SmsConnectorStart.STAT_OK)
{
// TODO: The methods should throw an exception
// Now look for SMS messages
message = null;
try
{
message = amsReceiver.receive("amsSubscriberSms");
iErr = smsContainer.addSms(message);
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "Could not receive from internal jms: amsSubscriberSms", e);
iErr = SmsConnectorStart.STAT_ERR_JMSCON;
}
if (message != null)
{
//FIXME:
//TODO:
// send 1 SMS, other in the next run
// iErr = sendSmsMsg(message);
iErr = sendSmsMsg();
sleep(100);
}
if (iErr == SmsConnectorStart.STAT_OK)
{
// read max. limit SMS, other in the next run
iErr = readSmsMsg();
sleep(50);
}
if (iErr == SmsConnectorStart.STAT_ERR_MODEM_SEND)
{
Log.log(this, Log.ERROR, "Closing Modem.");
closeModem();
bInitedModem = false;
closeJms();
bInitedJms = false;
}
if (iErr == SmsConnectorStart.STAT_ERR_MODEM)
{
Log.log(this, Log.ERROR, "Closing Modem.");
closeModem();
bInitedModem = false;
}
if (iErr == SmsConnectorStart.STAT_ERR_JMSCON)
{
Log.log(this, Log.ERROR, "Closing JMS communication.");
closeJms();
bInitedJms = false;
}
}
}
// set status in every loop
// set error status, can be OK if no error
scs.setStatus(iErr);
}
catch(Exception e)
{
scs.setStatus(SmsConnectorStart.STAT_ERR_UNDEFINED);
Log.log(this, Log.FATAL, e);
closeModem();
bInitedModem = false;
closeJms();
bInitedJms = false;
}
}
// Store the remaining messages
if(smsContainer.hasContent())
{
if(smsContainer.storeContent("./"))
{
Log.log(this, Log.INFO, "SMS objects have been stored.");
smsContainer = null;
}
else
{
Log.log(this, Log.WARN, "SMS objects have NOT been stored.");
}
}
// Close all
closeModem();
closeJms();
bStoppedClean = true;
Log.log(this, Log.INFO, "SMS connector exited");
}
public boolean storeRemainingMessages()
{
boolean success = false;
if(smsContainer != null)
{
success = smsContainer.storeContent("./");
}
return success;
}
/**
* Init Sms-Modem
*
* @return <code>true</code> if all o.k.,
* and <code>false</code> if Modem initialization failed.
*/
private boolean initModem()
{
String[] strComPort = null;
String[] strManufac = null;
String[] strModel = null;
String[] strSimPin = null;
int[] iBaudRate = null;
int modemCount = 1;
boolean result = false;
try
{
if (sTest != 0)
{
Log.log(this, Log.FATAL, "
return true;
}
// strComPort - COM-Port: "COM1", "COM2", "COM3", ... , "/dev/ttyS1", ...
// iBaudRate - Modem Baud-Rate: 9600, 57600, ...
// strManufac - gsmDeviceManufacturer: "SonyEricsson", "Siemens", "Wavecom", "Nokia", ..., ""
// strModel - gsmDeviceModel: "GS64", "M1306B", "6310i", ..., ""
// strSimPin - SimCard Pin-Number: "1234", ...
IPreferenceStore store = SmsConnectorPlugin.getDefault().getPreferenceStore();
try
{
modemCount = Integer.parseInt(store.getString(SampleService.P_MODEM_COUNT));
modemCount = (modemCount < 1) ? 1 : modemCount;
modemCount = (modemCount > 3) ? 3 : modemCount;
Log.log(this, Log.INFO, "Number of modems: " + modemCount);
}
catch (NumberFormatException e)
{
modemCount = 1;
Log.log(this, Log.WARN, "Number of modems not defined. Using default: " + modemCount);
}
strComPort = new String[modemCount];
strManufac = new String[modemCount];
strModel = new String[modemCount];
strSimPin = new String[modemCount];
iBaudRate = new int[modemCount];
// TODO: Better error handling and value checks
for(int i = 0;i < modemCount;i++)
{
strComPort[i] = store.getString(SampleService.P_PREFERENCE_STRING + (i + 1) + "ComPort");
strComPort[i] = (strComPort[i] == null) ? "" : strComPort[i];
try
{
iBaudRate[i] = Integer.parseInt(store.getString(SampleService.P_PREFERENCE_STRING + (i + 1) + "ComBaudrate"));
}
catch (NumberFormatException e)
{
iBaudRate[i] = 9600;
Log.log(this, Log.WARN, "Value for Baudrate is not a number, take default: " + iBaudRate[i]);
}
strManufac[i] = store.getString(SampleService.P_PREFERENCE_STRING + (i + 1) + "Manufacture");
strManufac[i] = (strManufac[i] == null) ? "" : strManufac[i];
strModel[i] = store.getString(SampleService.P_PREFERENCE_STRING + (i + 1) + "Model");
strModel[i] = (strModel[i] == null) ? "" : strModel[i];
strSimPin[i] = store.getString(SampleService.P_PREFERENCE_STRING + (i + 1) + "SimPin");
strSimPin[i] = (strSimPin[i] == null) ? "" : strSimPin[i];
}
modemService = new Service();
for(int i = 0;i < modemCount;i++)
{
if(strComPort[i].length() > 0)
{
Log.log(this, Log.INFO, "start initModem(" + strComPort[i] + ","
+ iBaudRate[i] + ","
+ strManufac[i] + ","
+ strModel[i] + ")");
// modemService = new CSoftwareService(strComPort, iBaudRate, strManufac, strModel);
SerialModemGateway modem = new SerialModemGateway("modem." + strComPort[i].toLowerCase(), strComPort[i], iBaudRate[i], strManufac[i], strModel[i]);
modem.setInbound(true);
modem.setOutbound(true);
modem.setSimPin(strSimPin[i]);
// modem.setOutboundNotification(outboundNotification);
modemService.addGateway(modem);
sleep(2000);
}
else
{
Log.log(this, Log.WARN, "No COM port defined for modem " + (i + 1) + ".");
}
}
result = true;
Log.log(this, Log.INFO, "Modem(s) are initialized");
if(result == true)
{
Log.log(this, Log.INFO, "Try to start service");
modemService.startService();
Log.log(this, Log.INFO, "service started");
}
}
catch (Exception e)
{
Log.log(this, Log.FATAL, "could not init modem", e);
result = false;
}
return result;
}
public void closeModem()
{
if (modemService != null)
{
try
{
modemService.stopService();
Log.log(this, Log.INFO, "Modem communication closed.");
}
catch (Exception e)
{
Log.log(this, Log.WARN, e);
}
}
modemService = null;
}
public synchronized void stopWorking()
{
bStop = true;
}
public boolean stoppedClean()
{
return bStoppedClean;
}
private boolean initJms()
{
IPreferenceStore storeAct = Activator.getDefault().getPreferenceStore();
Hashtable<String, String> properties = null;
boolean result = false;
boolean durable = Boolean.parseBoolean(storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_CREATE_DURABLE));
try
{
properties = new Hashtable<String, String>();
properties.put(Context.INITIAL_CONTEXT_FACTORY,
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_CONNECTION_FACTORY_CLASS));
properties.put(Context.PROVIDER_URL,
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_SENDER_PROVIDER_URL));
amsSenderContext = new InitialContext(properties);
amsSenderFactory = (ConnectionFactory) amsSenderContext.lookup(
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_CONNECTION_FACTORY));
amsSenderConnection = amsSenderFactory.createConnection();
amsSenderConnection.setClientID("SmsConnectorWorkSenderInternal");
amsSenderSession = amsSenderConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
/*
amsPublisherReply = amsSession.createProducer((Topic)amsContext.lookup(
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_TOPIC_REPLY)));
*/
amsPublisherReply = amsSenderSession.createProducer(amsSenderSession.createTopic(
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_TOPIC_REPLY)));
if (amsPublisherReply == null)
{
Log.log(this, Log.FATAL, "could not create amsPublisherReply");
return false;
}
amsSenderConnection.start();
// Create the redundant receiver
amsReceiver = new JmsRedundantReceiver("SmsConnectorWorkReceiverInternal", storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_PROVIDER_URL_1), storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_PROVIDER_URL_2));
// Create first subscriber (default topic for the connector)
result = amsReceiver.createRedundantSubscriber(
"amsSubscriberSms",
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_TOPIC_SMS_CONNECTOR),
storeAct.getString(org.csstudio.ams.internal.SampleService.P_JMS_AMS_TSUB_SMS_CONNECTOR),
durable);
if(result == false)
{
Log.log(this, Log.FATAL, "could not create amsSubscriberSms");
return false;
}
// Create second subscriber (topic for message management)
// TODO: Replace constant with preference entry
result = amsReceiver.createRedundantSubscriber(
"amsConnectorManager",
MANAGE_COMMAND_TOPIC,
MANAGE_COMMAND_TOPIC_SUB,
durable);
if(result == false)
{
Log.log(this, Log.FATAL, "could not create amsConnectorManager");
return false;
}
return true;
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not init internal Jms", e);
}
return false;
}
public void closeJms()
{
Log.log(this, Log.INFO, "exiting internal jms communication");
if(amsReceiver != null)
{
amsReceiver.closeAll();
}
if (amsPublisherReply != null){try{amsPublisherReply.close();amsPublisherReply=null;}
catch (JMSException e){Log.log(this, Log.WARN, e);}}
if (amsSenderSession != null){try{amsSenderSession.close();amsSenderSession=null;}
catch (JMSException e){Log.log(this, Log.WARN, e);}}
if (amsSenderConnection != null){try{amsSenderConnection.stop();}
catch (JMSException e){Log.log(this, Log.WARN, e);}}
if (amsSenderConnection != null){try{amsSenderConnection.close();amsSenderConnection=null;}
catch (JMSException e){Log.log(this, Log.WARN, e);}}
if (amsSenderContext != null){try{amsSenderContext.close();amsSenderContext=null;}
catch (NamingException e){Log.log(this, Log.WARN, e);}}
Log.log(this, Log.INFO, "jms internal communication closed");
}
private boolean acknowledge(Message msg)
{
try
{
msg.acknowledge();
return true;
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not acknowledge", e);
}
return false;
}
/**
* Sends the SMS stored in the SmsContainer.
*
* @return Error code
*/
private int sendSmsMsg() throws Exception
{
Sms sms = null;
int iErr = SmsConnectorStart.STAT_OK;
if(smsContainer.hasContent())
{
sms = smsContainer.getFirstSms();
if(sms != null)
{
Log.log(this, Log.DEBUG, "SMS: " + sms.toString());
if((sms.getType() == Sms.Type.OUT) && (sms.getState() != Sms.State.SENT))
{
if(sendSms(sms))
{
smsContainer.removeSms(sms);
}
else
{
iErr = SmsConnectorStart.STAT_ERR_MODEM_SEND;
}
}
}
}
return iErr;
}
private int sendSmsMsg(Message message) throws Exception
{
if (!(message instanceof MapMessage))
{
Log.log(this, Log.WARN, "got unknown message " + message);
// Deletes all received messages of the session
if (!acknowledge(message))
return SmsConnectorStart.STAT_ERR_JMSCON;
return SmsConnectorStart.STAT_OK;
}
else
{
MapMessage msg = (MapMessage) message;
String text = msg.getString(MSGPROP_RECEIVERTEXT);
String recNo = msg.getString(MSGPROP_RECEIVERADDR);
String parsedRecNo = null;
int iErr = SmsConnectorStart.STAT_ERR_UNDEFINED;
for (int j = 1 ; j <= 5 ; j++) //only for short net breaks
{
if (parsedRecNo == null)
{
try
{
parsedRecNo = parsePhoneNumber(recNo);
}
catch (Exception e)
{
Log.log(this, Log.FATAL, "Parsing phone number - failed.");
if (acknowledge(message)) // deletes all received messages of the session
return SmsConnectorStart.STAT_OK;
iErr = SmsConnectorStart.STAT_ERR_JMSCON;
}
}
if (parsedRecNo != null)
{
if (sendSms(text, parsedRecNo))
{
if (acknowledge(message)) // deletes all received messages of the session
return SmsConnectorStart.STAT_OK;
iErr = SmsConnectorStart.STAT_ERR_JMSCON;
}
else
{
iErr = SmsConnectorStart.STAT_ERR_MODEM_SEND;
}
}
sleep(2000);
}
return iErr;
}
}
private String parsePhoneNumber(String mobile) throws Exception
{
StringBuffer sbMobile = new StringBuffer(mobile);
StringBuffer sbTest = new StringBuffer("+0123456789");
int i = 0;
if (sbMobile.length() > 0) // first char (can be +0123456789)
{
if (sbTest.indexOf(String.valueOf(sbMobile.charAt(i))) < 0) // first char found in sbTest
sbMobile.deleteCharAt(0); // if not found
else
i++;
sbTest.deleteCharAt(0); // delete '+'
}
while (i < sbMobile.length()) // other chars (can be 0123456789)
{
if (sbTest.indexOf(String.valueOf(sbMobile.charAt(i))) < 0) // char found in sbTest
{
sbMobile.deleteCharAt(i); // if not found
continue; // do not i++
}
i++;
}
return sbMobile.toString();
}
public boolean sendSms(Sms sms) throws Exception
{
boolean success;
success = sendSms(sms.getMessage(), sms.getPhoneNumber());
if(success)
{
sms.setState(Sms.State.SENT);
}
else
{
sms.setState(Sms.State.NOT_SENT);
}
return success;
}
/**
* Send SMS with text to receiver address.
*
* @param text String
* @param recNo String
* @return <code>true</code> if SMS was sent,
* and <code>false</code> if SMS was not sent.
* @throws Exception
*/
private boolean sendSms(String text, String recNo) throws Exception
{
boolean bRet = false;
Log.log(this, Log.INFO, "start sendSms");
scs.setStatus(SmsConnectorStart.STAT_SENDING);
// Lets create a message for dispatch.
// A message needs the recipient's number and the text. Recipient's
// number should always be defined in international format.
OutboundMessage msg = new OutboundMessage(recNo, text);
// Set the message encoding.
// We can use 7bit, 8bit and Unicode. 7bit should be enough for most
// cases. Unicode is necessary for Far-East countries.
msg.setEncoding(MessageEncodings.ENC7BIT);
// Do we require a Delivery Status Report?
// Delivery Status Report
// Changed by Markus Moeller, 2009-01-30
// To avoid restarts of the modems
// msg.setStatusReport(true);
msg.setStatusReport(false);
// We can also define the validity period.
// Validity period is always defined in hours.
// The following statement sets the validity period to 8 hours.
msg.setValidityPeriod(8);
// Do we require a flash SMS? A flash SMS appears immediately on
// recipient's phone.
// Sometimes its called a forced SMS. Its kind of rude, so be
// careful!
// Keep in mind that flash messages are not supported by all
// handsets.
// msg.setFlashSms(true);
// Some special applications are "listening" for messages on
// specific ports.
// The following statements set the Source and Destination port.
// They should always be used in pairs!!!
// Source and Destination ports are defined as 16bit ints in the
// message header.
// msg.setSourcePort(10000);
// msg.setDestinationPort(11000);
// Ok, finished with the message parameters, now send it!
// If we have many messages to send, we could also construct a
// LinkedList with many COutgoingMessage objects and pass it to
// modemService.sendMessage().
if (sTest == 0)
{
Log.log(this, Log.INFO, "call modem.sendMessage");
int totalOutBefore = modemService.getOutboundMessageCount();// total number of outbound messages since restart
// Log.log(this, Log.INFO, "Modem connected: " + modemService.getConnected());
try
{
modemService.sendMessage(msg);
}
catch(Exception e)
{
Log.log(this, Log.ERROR, "could not sendMessage", e);
return false; //only with exceptions at this line => modem error
}
int totalOutAfter = modemService.getOutboundMessageCount();// total number of outbound messages since restart
if (totalOutBefore < totalOutAfter)
{
Log.log(this, Log.INFO, "sms sent to: '" + recNo + "' with text: '" + text + "'");
bRet = true;
}
Log.log(this, Log.INFO, "totalOut sms = " + totalOutAfter);
}
else
{
return true; // in Test Mode - true
}
return bRet;
}
private int readSmsMsg(/*int limit*/) throws Exception
{
int iErr = SmsConnectorStart.STAT_ERR_UNDEFINED;
for (int j = 1 ; j <= 5 ; j++) //TEMPORARAY connections error try some times
{ // (short breaks of ethernet or gsm net)
iErr = readModem(/*limit*/);
if (SmsConnectorStart.STAT_OK == iErr) // only return if read successfully
return SmsConnectorStart.STAT_OK;
sleep(2000);
}
return iErr;
}
private boolean deleteMessage(InboundMessage msg)
{
try
{
if (sTest == 0)
modemService.deleteMessage(msg);
return true;
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not deleteMessage", e);
}
return false;
}
/**
* Reads SMS-Messages from the modem.
*
* @param limit int - Read up to number of messages. If limit is set to 0, read all messages.
* @return int
* @throws Exception
*/
private int readModem(/*int limit*/) throws Exception
{
LinkedList<InboundMessage> msgList = new LinkedList<InboundMessage>();
Log.log(this, Log.DEBUG, "start readModem call modem.readMessages");
scs.setStatus(SmsConnectorStart.STAT_READING);
try
{
if(sTest == 0)
{
// Read up to number of messages, read other SMS at the next run.
// Read out all messages in linked list
modemService.readMessages(msgList, MessageClasses.ALL /*, limit*/);
}
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not readMessages", e);
return SmsConnectorStart.STAT_ERR_MODEM;
}
if (!msgList.isEmpty())
Log.log(this, Log.INFO, "readModem done, message count = " + msgList.size());
else
{
Log.log(this, Log.DEBUG, "readModem done, modem is empty");
if (sTest != 0) // TODO FOR TEST ONLY
generateTestMsg();
return SmsConnectorStart.STAT_OK;
}
// Iterate and display.
// The CMessage parent object has a toString() method which displays
// all of its contents. Useful for debugging, but for a real world
// application you should use the necessary getXXX methods.
for (int i = 0; i < msgList.size(); i++)
{
InboundMessage smsMsg = (InboundMessage) msgList.get(i);
String text = null;
// BEWARE: We can get an InboundBinaryMessage and will run into problems
// if we want to get the message text. The getText() method
// of InboundBinaryMessage just throws an exception!!!!!!!
if(smsMsg instanceof InboundBinaryMessage)
{
text = "[InboundBinaryMessage] Cannot read the content.";
}
else
{
text = smsMsg.getText();
}
if(smsMsg.getType() == MessageTypes.STATUSREPORT)
{
StatusReportMessage smsStat = (StatusReportMessage)smsMsg;
Log.log(this, Log.INFO, "receive statusReport message: '" + text
+ "' originator/deliveryStatus/date/dateOrg/dateRec/smscRef = "
+ smsStat.getOriginator() + "/" + smsStat.getStatus().toString() + "/"
+ smsStat.getDate() + "/" + smsStat.getSent() + "/" + smsStat.getReceived() + "/"
+ smsStat.getRefNo());
if (!deleteMessage((InboundMessage)msgList.get(i)))
return SmsConnectorStart.STAT_ERR_MODEM;
continue;
}
if (smsMsg.getType() != MessageTypes.INBOUND)
{
Log.log(this, Log.INFO, "receive message unknown type: '" + text
+ "' originator/type/date/smscRef = "
+ smsMsg.getOriginator() + "/" + smsMsg.getType() + "/" + smsMsg.getDate() + "/" + smsMsg.getMpRefNo());
if (!deleteMessage((InboundMessage)msgList.get(i)))
return SmsConnectorStart.STAT_ERR_MODEM;
continue;
}
else
Log.log(this, Log.INFO, "receive incoming message: '" + text
+ "' originator/date/smscRef = "
+ smsMsg.getOriginator() + "/" + smsMsg.getDate() + "/" + smsMsg.getMpRefNo());
// Reply_Message-Format: "<ChainIdAndPos>*<ConfirmCode>"
// Example: "12345001*123"
// Change-Status_Message-Format: "<GroupNum>*<UserNum>*<Status>*<StatusCode>"
// Example: "12*34*1*123"
// Change-Status_Message-Format: "<GroupNum>*<UserNum>*<Status>*<StatusCode>*<Reason>"
// Example: "12*34*0*123*Im ill"
//max 3 Zahlen(Long) + 2 Text
// zahl*zahl reply
// zahl*zahl*zahl*text status change (! letzter ohne stern)
// zahl*zahl*zahl*text*text status change , nur im letzten text sterne zugelassen
String[] arr = new String[5];
int iStarPos = -1;
int iLastStarPos = -1;
int iCnt = 0;
byte bFormat = 0; //no valid format
// ADDED BY Markus Moeller, 2007-12-05
boolean changeGroupState = false;
// ADDED BY Markus Moeller, 2007-12-05
if(text.trim().startsWith("g*") || text.trim().startsWith("G*"))
{
changeGroupState = true;
text = text.trim().substring(2);
}
for (iCnt = 0;iCnt < 3;iCnt++)
{
iStarPos = text.indexOf("*", iLastStarPos + 1);
if (iStarPos < 0)
{
if (text.length() > iLastStarPos)
arr[iCnt] = text.substring(iLastStarPos + 1, text.length());
if (iCnt == 1)
bFormat = 1; //format reply
break;
}
arr[iCnt] = text.substring(iLastStarPos + 1, iStarPos);
iLastStarPos = iStarPos;
}
if (iStarPos > 0 && text.length() > iStarPos) //zahl*zahl*zahl*text
{
bFormat = 2; //format status change
iStarPos = text.indexOf("*", iLastStarPos + 1);
if (iStarPos < 0)
{
arr[iCnt] = text.substring(iLastStarPos + 1, text.length()); //(! letzter ohne stern)
}
else //zahl*zahl*zahl*text*text
{
arr[iCnt] = text.substring(iLastStarPos + 1, iStarPos);
if (iStarPos > 0 && text.length() > iStarPos)
{
arr[iCnt+1] = text.substring(iStarPos + 1, text.length());
}
}
}
//number checking
if (bFormat == 1)
{
try {
if (!arr[0].equals("#")) //accept all
Long.parseLong(arr[0]);
Long.parseLong(handyButton2NumberMode(arr[1]));
}
catch (NumberFormatException e)
{
Log.log(this, Log.WARN, "expected is not a number");
bFormat = 0;
}
}
else if (bFormat == 2)
{
try {
Long.parseLong(arr[0]);
Long.parseLong(arr[1]);
Long.parseLong(arr[2]);
}
catch (NumberFormatException e)
{
Log.log(this, Log.WARN, "expected is not a number");
bFormat = 0;
}
}
if (bFormat <= 0)
{
Log.log(this, Log.WARN, "incoming message from: '" + smsMsg.getOriginator() + "' has unknown Format: '" + text + "'");
}
else
{
MapMessage mapMsg = null;
try
{
mapMsg = amsSenderSession.createMapMessage();
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not createMapMessage", e);
}
if (mapMsg == null)
return SmsConnectorStart.STAT_ERR_JMSCON;
if (bFormat == 1)
{
mapMsg.setString(MSGPROP_MESSAGECHAINID_AND_POS, arr[0]);
mapMsg.setString(MSGPROP_CONFIRMCODE, handyButton2NumberMode(arr[1]));
mapMsg.setString(MSGPROP_REPLY_TYPE, MSG_REPLY_TYPE_SMS);
mapMsg.setString(MSGPROP_REPLY_ADRESS, smsMsg.getOriginator());
Log.log(this, Log.INFO, "message parsed as alarm reply, start internal jms send");
}
else if (bFormat == 2)
{
// ADDED BY Markus Moeller, 2007-12-05
if(changeGroupState == true)
{
mapMsg.setString(MSGPROP_CHANGESTAT_ACTION, "group");
}
else
{
mapMsg.setString(MSGPROP_CHANGESTAT_ACTION, "user");
}
mapMsg.setString(MSGPROP_CHANGESTAT_GROUPNUM, arr[0]);
mapMsg.setString(MSGPROP_CHANGESTAT_USERNUM, arr[1]);
mapMsg.setString(MSGPROP_CHANGESTAT_STATUS, arr[2]);
mapMsg.setString(MSGPROP_CHANGESTAT_STATUSCODE, arr[3]);
if (arr[4] == null)
mapMsg.setString(MSGPROP_CHANGESTAT_REASON, "");
else
mapMsg.setString(MSGPROP_CHANGESTAT_REASON, arr[4]);
mapMsg.setString(MSGPROP_REPLY_TYPE, MSG_REPLY_TYPE_SMS);
mapMsg.setString(MSGPROP_REPLY_ADRESS, smsMsg.getOriginator());
Log.log(this, Log.INFO, "message parsed as change status, start internal jms send");
}
try
{
amsPublisherReply.send(mapMsg);
}
catch(Exception e)
{
Log.log(this, Log.FATAL, "could not send to internal jms", e);
return SmsConnectorStart.STAT_ERR_JMSCON;
}
Log.log(this, Log.INFO, "send internal jms message done");
}
Log.log(this, Log.DEBUG, "start delete");
if (!deleteMessage((InboundMessage)msgList.get(i)))
return SmsConnectorStart.STAT_ERR_MODEM;
Log.log(this, Log.DEBUG, "delete done");
}
Log.log(this, Log.DEBUG, "readReply . . . exit");
return SmsConnectorStart.STAT_OK;
}
private String handyButton2NumberMode(String str)
{
String ret = "";
byte[] b = str.toLowerCase().getBytes();
for (int i = 0; i < b.length; i++)
switch (b[i])
{
default:
ret += (b[i] - 48); // CHANGED BY Markus Moeller, 2007-11-20
break;
case '.':
case ' ':
ret += "1";
break;
case 'a':
case 'b':
case 'c':
ret += "2";
break;
case 'd':
case 'e':
case 'f':
ret += "3";
break;
case 'g':
case 'h':
case 'i':
ret += "4";
break;
case 'j':
case 'k':
case 'l':
ret += "5";
break;
case 'm':
case 'n':
case 'o':
ret += "6";
break;
case 'p':
case 'q':
case 'r':
case 's':
ret += "7";
break;
case 't':
case 'u':
case 'v':
ret += "8";
break;
case 'w':
case 'x':
case 'y':
case 'z':
ret += "9";
break;
}
return ret;
}
private void generateTestMsg()
{
try
{
Log.log(this, Log.FATAL, "
String smsTxt = "";
String strOriginator = "";
if (sTest == 1)
{
// Reply_Message-Format: "<ChainIdAndPos>*<ConfirmCode>"
// Example: "12345001*123"
smsTxt = "1001*5678";
strOriginator = "01736079941";
}
else if (sTest == 2)
{
// Change-Status_Message-Format: "<GroupNum>*<UserNum>*<Status>*<StatusCode>*<Reason>"
// Example: "12*34*0*123*Im ill." (Logout with reason)
// or "12*34*1*123*" (Login without reason)
// or "12*34*1*123" (Login without reason)
smsTxt = "1*1*0*1234*Ich bin krank.";
strOriginator = "01736079941";
}
int[] arr = new int[5]; // should be 1 more than in "switch (iStarPos)" statement
int iStarPos = -1;
for (int x = 0 ; x < 5 ; x++)
{
iStarPos = smsTxt.indexOf("*", iStarPos+1);
if (iStarPos < 0)
{
iStarPos = x;// count of "*"
break;
}
arr[x] = iStarPos;
}
switch (iStarPos)
{
case 4:
// Change-Status_Message-Format: "<GroupNum>*<UserNum>*<Status>*<StatusCode>*<Reason>"
// Example: "12*34*0*123*Im ill"
if ( (arr[0] > 0)
&& (arr[1] > arr[0]+1)
&& (arr[2] > arr[1]+1)
&& (arr[3] > arr[2]+1) // at least one char for each
&& (arr[3]+1 <= smsTxt.length()) ) // (reason can be "")
{
MapMessage mapMsg = amsSenderSession.createMapMessage();
mapMsg.setString(MSGPROP_CHANGESTAT_GROUPNUM, smsTxt.substring(0, arr[0]));
mapMsg.setString(MSGPROP_CHANGESTAT_USERNUM, smsTxt.substring(arr[0]+1, arr[1]));
mapMsg.setString(MSGPROP_CHANGESTAT_STATUS, smsTxt.substring(arr[1]+1, arr[2]));
mapMsg.setString(MSGPROP_CHANGESTAT_STATUSCODE, smsTxt.substring(arr[2]+1, arr[3]));
mapMsg.setString(MSGPROP_CHANGESTAT_REASON, smsTxt.substring(arr[3]+1, smsTxt.length()));// with reason
mapMsg.setString(MSGPROP_REPLY_TYPE, MSG_REPLY_TYPE_SMS);
mapMsg.setString(MSGPROP_REPLY_ADRESS, strOriginator);
Log.log(this, Log.INFO, "start Change-Status");
amsPublisherReply.send(mapMsg);
Log.log(this, Log.INFO, "Change-Status done");
break;
}
Log.log(this, Log.WARN, "SMS-Reply from: '" + strOriginator + "' has unknown Format: '" + smsTxt + "'");
break;
case 3:
// Change-Status_Message-Format: "<GroupNum>*<UserNum>*<Status>*<StatusCode>"
// Example: "12*34*1*123"
if ( (arr[0] > 0)
&& (arr[1] > arr[0]+1)
&& (arr[2] > arr[1]+1)
&& (arr[2]+1 < smsTxt.length()) ) // at least one char for each
{
MapMessage mapMsg = amsSenderSession.createMapMessage();
mapMsg.setString(MSGPROP_CHANGESTAT_GROUPNUM, smsTxt.substring(0, arr[0]));
mapMsg.setString(MSGPROP_CHANGESTAT_USERNUM, smsTxt.substring(arr[0]+1, arr[1]));
mapMsg.setString(MSGPROP_CHANGESTAT_STATUS, smsTxt.substring(arr[1]+1, arr[2]));
mapMsg.setString(MSGPROP_CHANGESTAT_STATUSCODE, smsTxt.substring(arr[2]+1, smsTxt.length()));
mapMsg.setString(MSGPROP_CHANGESTAT_REASON, ""); // without a reason
mapMsg.setString(MSGPROP_REPLY_TYPE, MSG_REPLY_TYPE_SMS);
mapMsg.setString(MSGPROP_REPLY_ADRESS, strOriginator);
Log.log(this, Log.INFO, "start Change-Status");
amsPublisherReply.send(mapMsg);
Log.log(this, Log.INFO, "Change-Status done");
break;
}
Log.log(this, Log.WARN, "SMS-Reply from: '" + strOriginator + "' has unknown Format: '" + smsTxt + "'");
break;
case 1:
// Reply_Message-Format: "<ChainIdAndPos>*<ConfirmCode>"
// Example: "12345001*123"
if ((arr[0] > MSG_POS_LENGTH_FOR_MSGPROP) // at least (MSG_POS_LENGTH_FOR_MSGPROP + 1) char for ChainIdAndPos
&& (arr[0]+1 < smsTxt.length())) // at least one char for ConfirmCode
{
MapMessage mapMsg = amsSenderSession.createMapMessage();
mapMsg.setString(MSGPROP_MESSAGECHAINID_AND_POS, smsTxt.substring(0, arr[0]));
mapMsg.setString(MSGPROP_CONFIRMCODE, smsTxt.substring(arr[0]+1, smsTxt.length()));
mapMsg.setString(MSGPROP_REPLY_TYPE, MSG_REPLY_TYPE_SMS);
mapMsg.setString(MSGPROP_REPLY_ADRESS, strOriginator);
Log.log(this, Log.INFO, "start reply");
amsPublisherReply.send(mapMsg);
Log.log(this, Log.INFO, "reply done");
break;
}
Log.log(this, Log.WARN, "SMS-Reply from: '" + strOriginator + "' has unknown Format: '" + smsTxt + "'");
break;
default:// -1, 0, 2, 5
Log.log(this, Log.WARN, "SMS-Reply from: '" + strOriginator + "' has unknown Format: '" + smsTxt + "'");
}// switch (iStarPos)
}// (sTest != 0)
catch(Exception e)
{
Log.log(this, Log.FATAL, e);
}
}
public void abortModem()
{
// String result = null;
Log.log(Log.INFO, "Try to abort modem connection.");
/*
try
{
result = modemService.sendCustomCmd("+++");
Log.log(Log.INFO, "+++ " + result.trim());
result = modemService.sendCustomCmd("AT*E2RESET=?\r");
Log.log(Log.INFO, "AT*E2RESET=? " + result.trim());
result = modemService.sendCustomCmd("AT*E2RESET\r");
Log.log(Log.INFO, "AT*E2RESET" + result.trim());
}
catch(Exception e)
{
Log.log(Log.ERROR, e);
}
*/
modemService = null;
Log.log(Log.INFO, "Leaving abortModem()");
}
}
|
package org.ovirt.engine.core.common.businessentities;
import java.util.HashSet;
import java.util.Set;
import org.ovirt.engine.core.common.VdcObjectType;
/**
* The provider type determines what external provider is used.
*/
public enum ProviderType implements Identifiable {
OPENSTACK_NETWORK(0, VdcObjectType.Network),
FOREMAN(1, VdcObjectType.VDS),
OPENSTACK_IMAGE(2, VdcObjectType.Storage),
OPENSTACK_VOLUME(3, VdcObjectType.Storage);
private int value;
private Set<VdcObjectType> providedTypes;
private ProviderType(int value, VdcObjectType... providedTypes) {
this.value = value;
this.providedTypes = new HashSet<VdcObjectType>();
for (VdcObjectType providedType : providedTypes) {
this.providedTypes.add(providedType);
}
}
@Override
public int getValue() {
return value;
}
public Set<VdcObjectType> getProvidedTypes() {
return providedTypes;
}
}
|
package org.intermine.bio.dataconversion;
import java.io.Reader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.util.FormattedTextParser;
import org.intermine.xml.full.Item;
/**
* DataConverter to load WormBase gene identifiers from genes2molecular_names.txt.
*
* @author Richard Smith
*/
public class WormBaseIdentifiersConverter extends BioFileConverter
{
protected Item worm;
private Set<String> identifiers = new HashSet<String>();
/**
* Constructor
* @param writer the ItemWriter used to handle the resultant items
* @param model the Model
*/
public WormBaseIdentifiersConverter(ItemWriter writer, Model model) {
super(writer, model, "WormBase", "WormBase genes");
}
/**
* Read each line from flat file, create genes and synonyms.
*
* {@inheritDoc}
*/
public void process(Reader reader) throws Exception {
Iterator<?> lineIter = FormattedTextParser.parseCsvDelimitedReader(reader);
// data is in format:
// primaryIdentifier | identifier | symbol
while (lineIter.hasNext()) {
String[] line = (String[]) lineIter.next();
if (line.length < 3 || line[0].startsWith("
continue;
}
// if (line.length < 3) {
// throw new RuntimeException("Line does not have enough elements: "
// + Arrays.asList(line));
String primaryidentifier = line[0];
String identifier = line[2];
String symbol = line[1];
Item gene = createItem("Gene");
if (!StringUtils.isEmpty(primaryidentifier)
&& !identifiers.contains(primaryidentifier)) {
gene.setAttribute("primaryIdentifier", primaryidentifier);
identifiers.add(primaryidentifier);
}
if (!StringUtils.isEmpty(identifier) && !identifiers.contains(identifier)) {
gene.setAttribute("secondaryIdentifier", identifier);
identifiers.add(identifier);
}
if (!StringUtils.isEmpty(symbol) && !identifiers.contains(symbol)) {
gene.setAttribute("symbol", symbol);
// per Rachel. We can't seem to get the gene names out of wormmart.
gene.setAttribute("name", symbol);
identifiers.add(symbol);
}
gene.setReference("organism", getOrganism("6239"));
store(gene);
}
}
}
|
package gov.nih.nci.cabig.caaers.service.synchronizer;
import gov.nih.nci.cabig.caaers.domain.AbstractIdentifiableDomainObject;
import gov.nih.nci.cabig.caaers.domain.Identifier;
import gov.nih.nci.cabig.caaers.domain.OrganizationAssignedIdentifier;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;
import gov.nih.nci.cabig.caaers.service.migrator.Migrator;
import java.util.ArrayList;
import java.util.List;
/**
* This class synchronizes the identifiers
* @author Monish Dombla
*
* @param <E>
*/
public class IdentifierSynchronizer<E extends AbstractIdentifiableDomainObject> implements Migrator<E> {
public void migrate(E dbObj, E xmlObj,
DomainObjectImportOutcome<E> outcome) {
List<Identifier> newIdentifiersList = new ArrayList<Identifier>();
//Identify newly added Identifiers.
for(Identifier xmlIdentifer : xmlObj.getIdentifiers()){
if(xmlIdentifer instanceof OrganizationAssignedIdentifier){
for(Identifier dbIdentifer : dbObj.getIdentifiers()){
if(dbIdentifer instanceof OrganizationAssignedIdentifier){
xmlIdentifer.setId(dbIdentifer.getId());
if(xmlIdentifer.equals(dbIdentifer)){
break;
}else{
xmlIdentifer.setId(null);
}
}
}
if(xmlIdentifer.getId() == null){
newIdentifiersList.add(xmlIdentifer);
}
}
}
//Adding the new identifiers to the existing Study.
for(Identifier newIdentifier : newIdentifiersList){
String type = newIdentifier.getType();
if ("Protocol Authority Identifier".equals(type) || "Coordinating Center Identifier".equals(type)){
//FundingSponsor identifier which is of type "Protocol Authority Identifier" cannot be modified.
//CoordinatingCenter identifier which is of type "Coordinating Center Identifier" cannot be modified.
}else{
dbObj.getIdentifiers().add(newIdentifier);
}
}
} //end method
}
|
package com.dataart.spreadsheetanalytics.engine;
import static com.dataart.spreadsheetanalytics.api.model.IExecutionGraphVertex.Type.CELL_WITH_FORMULA;
import static org.apache.poi.common.execgraph.IExecutionGraphVertexProperty.PropertyName.FORMULA_PTG_STRING;
import static org.apache.poi.common.execgraph.IExecutionGraphVertexProperty.PropertyName.FORMULA_STRING;
import static org.apache.poi.common.execgraph.IExecutionGraphVertexProperty.PropertyName.FORMULA_VALUES;
import static org.apache.poi.common.execgraph.IExecutionGraphVertexProperty.PropertyName.SOURCE_OBJECT_ID;
import static org.apache.poi.common.execgraph.IExecutionGraphVertexProperty.PropertyName.PTG_STRING;
import static org.apache.poi.common.execgraph.IExecutionGraphVertexProperty.PropertyName.TYPE;
import static org.apache.poi.common.execgraph.IExecutionGraphVertexProperty.PropertyName.VALUE;
import org.apache.poi.common.execgraph.IncorrectExternalReferenceException;
import java.util.HashSet;
import java.util.Set;
import org.apache.poi.common.execgraph.IExecutionGraphVertex;
import org.apache.poi.ss.formula.FormulaParseException;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.jgrapht.DirectedGraph;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import com.dataart.spreadsheetanalytics.api.engine.IAuditor;
import com.dataart.spreadsheetanalytics.api.engine.IEvaluator;
import com.dataart.spreadsheetanalytics.api.model.ICellAddress;
import com.dataart.spreadsheetanalytics.api.model.ICellValue;
import com.dataart.spreadsheetanalytics.api.model.IExecutionGraph;
import com.dataart.spreadsheetanalytics.api.model.IExecutionGraphVertex.Type;
import com.dataart.spreadsheetanalytics.engine.execgraph.ExecutionGraph;
import com.dataart.spreadsheetanalytics.engine.execgraph.ExecutionGraphVertex;
import com.dataart.spreadsheetanalytics.engine.execgraph.PoiExecutionGraphBuilder;
/**
* TODO
*/
public class SpreadsheetAuditor implements IAuditor {
private static final String WORKBOOK_NAME = "workbook name";
private static final String FORMULA_STRING_PREFIX = "Cell with formula:";
protected final SpreadsheetEvaluator evaluator;
protected final PoiExecutionGraphBuilder graphBuilder;
public SpreadsheetAuditor(SpreadsheetEvaluator evaluator) {
this.evaluator = evaluator;
this.graphBuilder = new PoiExecutionGraphBuilder();
this.evaluator.setExecutionGraphBuilder(this.graphBuilder);
}
@Override
public IExecutionGraph buildStaticExecutionGraph(ICellAddress cell) {
//TODO: implement
return null;
}
@Override
public IExecutionGraph buildStaticExecutionGraph() {
//TODO: implement
return null;
}
@Override
public IExecutionGraph buildDynamicExecutionGraph(ICellAddress cell) {
ICellValue cv = null;
try {
cv = evaluator.evaluate(cell);
} catch (FormulaParseException e) {
return getSingleNodeGraphForParseException(cell, ErrorEval.NAME_INVALID, null);
} catch (IllegalStateException e) {
if (e.getMessage().contains(ErrorEval.VALUE_INVALID.getErrorString())) {
return getSingleNodeGraphForParseException(cell, ErrorEval.VALUE_INVALID, null);
} else {
throw e;
}
} catch (IncorrectExternalReferenceException e) {
return handleIncorrectExternalReference(e, cell);
}
IExecutionGraph nonFormulaResult = buildGraphForEdgeCases(cv, cell);
if (nonFormulaResult != null) { return nonFormulaResult; }
graphBuilder.runPostProcessing();
return graphBuilder.get();
}
private ExecutionGraph handleIncorrectExternalReference(IncorrectExternalReferenceException e, ICellAddress cell) {
String formulaString = e.getFormulaString();
ExecutionGraph result = getSingleNodeGraphForParseException(cell, ErrorEval.REF_INVALID, formulaString);
return result;
}
protected ExecutionGraph getSingleNodeGraphForParseException(ICellAddress address, ErrorEval error, String formulaString) {
DirectedGraph<IExecutionGraphVertex, DefaultEdge> emptyGraph = new DefaultDirectedGraph<>(DefaultEdge.class);
ExecutionGraphVertex vertex = new ExecutionGraphVertex(address.a1Address().address());
vertex.property(TYPE).set(CELL_WITH_FORMULA);
vertex.property(VALUE).set(error);
if (formulaString != null) {
vertex.property(FORMULA_STRING).set(formulaString);
} else {
vertex.property(FORMULA_STRING).set(error.getErrorString());
}
vertex.property(FORMULA_VALUES).set(error.getErrorString());
vertex.property(FORMULA_PTG_STRING).set(error.getErrorString());
vertex.property(PTG_STRING).set(error.getErrorString());
vertex.property(SOURCE_OBJECT_ID).set("");
Set<com.dataart.spreadsheetanalytics.api.model.IExecutionGraphVertex> vertices = new HashSet<>();
emptyGraph.addVertex(vertex);
vertices.add(vertex);
ExecutionGraph graph = ExecutionGraph.wrap(emptyGraph);
graph.setVertices(vertices);
return graph;
}
@Override
public IExecutionGraph buildDynamicExecutionGraph() {
/*
//Model Iterator
for (XSSFSheet xssfSheet : model) {
for (Row row : xssfSheet) {
for (Cell cell : row) {
ICellAddress addr = new CellAddress()
.a1Address(new A1Address(new CellReference(cell).formatAsString()))
.row(cell.getRowIndex())
.column(cell.getColumnIndex());
evaluator.evaluate(addr);
}
}
}
graphBuilder.runPostProcessing();
return graphBuilder.get();
*/
return null;
}
protected IExecutionGraph buildGraphForEdgeCases(ICellValue evalCell, ICellAddress cell) {
if (evalCell == null) { return graphBuilder.getSingleNodeGraph(cell); }
if (!evaluator.isFormulaCell(cell)) { return buildGraphForNonFormulaCell(graphBuilder, evalCell); }
return null;
}
private IExecutionGraph buildGraphForNonFormulaCell(PoiExecutionGraphBuilder gBuilder, ICellValue cell) {
DirectedGraph<IExecutionGraphVertex, DefaultEdge> dgraph = ExecutionGraph.unwrap(gBuilder.get());
ExecutionGraphVertex vertex = new ExecutionGraphVertex("VALUE");
vertex.property(VALUE).set(cell.get());
vertex.property(TYPE).set(Type.CELL_WITH_VALUE);
dgraph.addVertex(vertex);
return ExecutionGraph.wrap(dgraph);
}
@Override
public IEvaluator getEvaluator() { return evaluator; }
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.