answer
stringlengths 17
10.2M
|
|---|
package com.metamx.druid.master;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.Closeables;
import com.metamx.common.IAE;
import com.metamx.common.Pair;
import com.metamx.common.concurrent.ScheduledExecutorFactory;
import com.metamx.common.concurrent.ScheduledExecutors;
import com.metamx.common.guava.Comparators;
import com.metamx.common.guava.FunctionalIterable;
import com.metamx.common.lifecycle.LifecycleStart;
import com.metamx.common.lifecycle.LifecycleStop;
import com.metamx.druid.client.DataSegment;
import com.metamx.druid.client.DruidDataSource;
import com.metamx.druid.client.DruidServer;
import com.metamx.druid.client.ServerInventoryView;
import com.metamx.druid.client.indexing.IndexingServiceClient;
import com.metamx.druid.concurrent.Execs;
import com.metamx.druid.config.JacksonConfigManager;
import com.metamx.druid.db.DatabaseRuleManager;
import com.metamx.druid.db.DatabaseSegmentManager;
import com.metamx.druid.index.v1.IndexIO;
import com.metamx.druid.initialization.ZkPathsConfig;
import com.metamx.emitter.EmittingLogger;
import com.metamx.emitter.service.ServiceEmitter;
import com.metamx.emitter.service.ServiceMetricEvent;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.utils.ZKPaths;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicReference;
public class DruidMaster
{
public static final String MASTER_OWNER_NODE = "_MASTER";
private static final EmittingLogger log = new EmittingLogger(DruidMaster.class);
private final Object lock = new Object();
private volatile boolean started = false;
private volatile boolean master = false;
private final DruidMasterConfig config;
private final ZkPathsConfig zkPaths;
private final JacksonConfigManager configManager;
private final DatabaseSegmentManager databaseSegmentManager;
private final ServerInventoryView<Object> serverInventoryView;
private final DatabaseRuleManager databaseRuleManager;
private final CuratorFramework curator;
private final ServiceEmitter emitter;
private final IndexingServiceClient indexingServiceClient;
private final ScheduledExecutorService exec;
private final LoadQueueTaskMaster taskMaster;
private final Map<String, LoadQueuePeon> loadManagementPeons;
private final AtomicReference<LeaderLatch> leaderLatch;
private volatile AtomicReference<MasterSegmentSettings> segmentSettingsAtomicReference;
public DruidMaster(
DruidMasterConfig config,
ZkPathsConfig zkPaths,
JacksonConfigManager configManager,
DatabaseSegmentManager databaseSegmentManager,
ServerInventoryView serverInventoryView,
DatabaseRuleManager databaseRuleManager,
CuratorFramework curator,
ServiceEmitter emitter,
ScheduledExecutorFactory scheduledExecutorFactory,
IndexingServiceClient indexingServiceClient,
LoadQueueTaskMaster taskMaster
)
{
this(
config,
zkPaths,
configManager,
databaseSegmentManager,
serverInventoryView,
databaseRuleManager,
curator,
emitter,
scheduledExecutorFactory,
indexingServiceClient,
taskMaster,
Maps.<String, LoadQueuePeon>newConcurrentMap()
);
}
DruidMaster(
DruidMasterConfig config,
ZkPathsConfig zkPaths,
JacksonConfigManager configManager,
DatabaseSegmentManager databaseSegmentManager,
ServerInventoryView serverInventoryView,
DatabaseRuleManager databaseRuleManager,
CuratorFramework curator,
ServiceEmitter emitter,
ScheduledExecutorFactory scheduledExecutorFactory,
IndexingServiceClient indexingServiceClient,
LoadQueueTaskMaster taskMaster,
ConcurrentMap<String, LoadQueuePeon> loadQueuePeonMap
)
{
this.config = config;
this.zkPaths = zkPaths;
this.configManager = configManager;
this.databaseSegmentManager = databaseSegmentManager;
this.serverInventoryView = serverInventoryView;
this.databaseRuleManager = databaseRuleManager;
this.curator = curator;
this.emitter = emitter;
this.indexingServiceClient = indexingServiceClient;
this.taskMaster = taskMaster;
this.exec = scheduledExecutorFactory.create(1, "Master-Exec
this.leaderLatch = new AtomicReference<LeaderLatch>(null);
this.segmentSettingsAtomicReference= new AtomicReference<MasterSegmentSettings>(null);
this.loadManagementPeons = loadQueuePeonMap;
}
public boolean isClusterMaster()
{
return master;
}
public Map<String, Double> getLoadStatus()
{
// find available segments
Map<String, Set<DataSegment>> availableSegments = Maps.newHashMap();
for (DataSegment dataSegment : getAvailableDataSegments()) {
Set<DataSegment> segments = availableSegments.get(dataSegment.getDataSource());
if (segments == null) {
segments = Sets.newHashSet();
availableSegments.put(dataSegment.getDataSource(), segments);
}
segments.add(dataSegment);
}
// find segments currently loaded
Map<String, Set<DataSegment>> segmentsInCluster = Maps.newHashMap();
for (DruidServer druidServer : serverInventoryView.getInventory()) {
for (DruidDataSource druidDataSource : druidServer.getDataSources()) {
Set<DataSegment> segments = segmentsInCluster.get(druidDataSource.getName());
if (segments == null) {
segments = Sets.newHashSet();
segmentsInCluster.put(druidDataSource.getName(), segments);
}
segments.addAll(druidDataSource.getSegments());
}
}
// compare available segments with currently loaded
Map<String, Double> loadStatus = Maps.newHashMap();
for (Map.Entry<String, Set<DataSegment>> entry : availableSegments.entrySet()) {
String dataSource = entry.getKey();
Set<DataSegment> segmentsAvailable = entry.getValue();
Set<DataSegment> loadedSegments = segmentsInCluster.get(dataSource);
if (loadedSegments == null) {
loadedSegments = Sets.newHashSet();
}
Set<DataSegment> unloadedSegments = Sets.difference(segmentsAvailable, loadedSegments);
loadStatus.put(
dataSource,
100 * ((double) (segmentsAvailable.size() - unloadedSegments.size()) / (double) segmentsAvailable.size())
);
}
return loadStatus;
}
public int lookupSegmentLifetime(DataSegment segment)
{
return serverInventoryView.lookupSegmentLifetime(segment);
}
public void decrementRemovedSegmentsLifetime()
{
serverInventoryView.decrementRemovedSegmentsLifetime();
}
public void removeSegment(DataSegment segment)
{
log.info("Removing Segment[%s]", segment);
databaseSegmentManager.removeSegment(segment.getDataSource(), segment.getIdentifier());
}
public void removeDatasource(String ds)
{
databaseSegmentManager.removeDatasource(ds);
}
public void enableDatasource(String ds)
{
databaseSegmentManager.enableDatasource(ds);
}
public String getCurrentMaster()
{
try {
final LeaderLatch latch = leaderLatch.get();
return latch == null ? null : latch.getLeader().getId();
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
public void moveSegment(String from, String to, String segmentName, final LoadPeonCallback callback)
{
try {
final DruidServer fromServer = serverInventoryView.getInventoryValue(from);
if (fromServer == null) {
throw new IAE("Unable to find server [%s]", from);
}
final DruidServer toServer = serverInventoryView.getInventoryValue(to);
if (toServer == null) {
throw new IAE("Unable to find server [%s]", to);
}
if (to.equalsIgnoreCase(from)) {
throw new IAE("Redundant command to move segment [%s] from [%s] to [%s]", segmentName, from, to);
}
final DataSegment segment = fromServer.getSegment(segmentName);
if (segment == null) {
throw new IAE("Unable to find segment [%s] on server [%s]", segmentName, from);
}
final LoadQueuePeon loadPeon = loadManagementPeons.get(to);
if (loadPeon == null) {
throw new IAE("LoadQueuePeon hasn't been created yet for path [%s]", to);
}
final LoadQueuePeon dropPeon = loadManagementPeons.get(from);
if (dropPeon == null) {
throw new IAE("LoadQueuePeon hasn't been created yet for path [%s]", from);
}
final ServerHolder toHolder = new ServerHolder(toServer, loadPeon);
if (toHolder.getAvailableSize() < segment.getSize()) {
throw new IAE(
"Not enough capacity on server [%s] for segment [%s]. Required: %,d, available: %,d.",
to,
segment,
segment.getSize(),
toHolder.getAvailableSize()
);
}
final String toLoadQueueSegPath = ZKPaths.makePath(ZKPaths.makePath(zkPaths.getLoadQueuePath(), to), segmentName);
final String toServedSegPath = ZKPaths.makePath(
ZKPaths.makePath(serverInventoryView.getInventoryManagerConfig().getInventoryPath(), to), segmentName
);
loadPeon.loadSegment(
segment,
new LoadPeonCallback()
{
@Override
protected void execute()
{
try {
if (curator.checkExists().forPath(toServedSegPath) != null &&
curator.checkExists().forPath(toLoadQueueSegPath) == null &&
!dropPeon.getSegmentsToDrop().contains(segment)) {
dropPeon.dropSegment(segment, callback);
} else if (callback != null) {
callback.execute();
}
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
);
}
catch (Exception e) {
log.makeAlert(e, "Exception moving segment %s", segmentName).emit();
callback.execute();
}
}
public void dropSegment(String from, String segmentName, final LoadPeonCallback callback)
{
try {
final DruidServer fromServer = serverInventoryView.getInventoryValue(from);
if (fromServer == null) {
throw new IAE("Unable to find server [%s]", from);
}
final DataSegment segment = fromServer.getSegment(segmentName);
if (segment == null) {
throw new IAE("Unable to find segment [%s] on server [%s]", segmentName, from);
}
final LoadQueuePeon dropPeon = loadManagementPeons.get(from);
if (dropPeon == null) {
throw new IAE("LoadQueuePeon hasn't been created yet for path [%s]", from);
}
if (!dropPeon.getSegmentsToDrop().contains(segment)) {
dropPeon.dropSegment(segment, callback);
}
}
catch (Exception e) {
log.makeAlert(e, "Exception dropping segment %s", segmentName).emit();
callback.execute();
}
}
public Set<DataSegment> getAvailableDataSegments()
{
Set<DataSegment> availableSegments = Sets.newTreeSet(Comparators.inverse(DataSegment.bucketMonthComparator()));
Iterable<DataSegment> dataSegments = Iterables.concat(
Iterables.transform(
databaseSegmentManager.getInventory(),
new Function<DruidDataSource, Iterable<DataSegment>>()
{
@Override
public Iterable<DataSegment> apply(DruidDataSource input)
{
return input.getSegments();
}
}
)
);
for (DataSegment dataSegment : dataSegments) {
if (dataSegment.getSize() < 0) {
log.makeAlert("No size on Segment, wtf?")
.addData("segment", dataSegment)
.emit();
}
availableSegments.add(dataSegment);
}
return availableSegments;
}
@LifecycleStart
public void start()
{
synchronized (lock) {
if (started) {
return;
}
started = true;
createNewLeaderLatch();
try {
leaderLatch.get().start();
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
private LeaderLatch createNewLeaderLatch()
{
final LeaderLatch newLeaderLatch = new LeaderLatch(
curator, ZKPaths.makePath(zkPaths.getMasterPath(), MASTER_OWNER_NODE), config.getHost()
);
newLeaderLatch.addListener(
new LeaderLatchListener()
{
@Override
public void isLeader()
{
DruidMaster.this.becomeMaster();
}
@Override
public void notLeader()
{
DruidMaster.this.stopBeingMaster();
}
},
Execs.singleThreaded("MasterLeader-%s")
);
return leaderLatch.getAndSet(newLeaderLatch);
}
@LifecycleStop
public void stop()
{
synchronized (lock) {
if (!started) {
return;
}
stopBeingMaster();
try {
leaderLatch.get().close();
}
catch (IOException e) {
log.warn(e, "Unable to close leaderLatch, ignoring");
}
started = false;
exec.shutdownNow();
}
}
private void becomeMaster()
{
synchronized (lock) {
if (!started) {
return;
}
log.info("I am the master, all must bow!");
try {
master = true;
databaseSegmentManager.start();
databaseRuleManager.start();
serverInventoryView.start();
final List<Pair<? extends MasterRunnable, Duration>> masterRunnables = Lists.newArrayList();
segmentSettingsAtomicReference = configManager.watch(MasterSegmentSettings.CONFIG_KEY, MasterSegmentSettings.class,new MasterSegmentSettings.Builder().build());
masterRunnables.add(Pair.of(new MasterComputeManagerRunnable(), config.getMasterPeriod()));
if (indexingServiceClient != null) {
masterRunnables.add(
Pair.of(
new MasterIndexingServiceRunnable(
makeIndexingServiceHelpers(configManager.watch(MergerWhitelist.CONFIG_KEY, MergerWhitelist.class))
),
config.getMasterSegmentMergerPeriod()
)
);
}
for (final Pair<? extends MasterRunnable, Duration> masterRunnable : masterRunnables) {
ScheduledExecutors.scheduleWithFixedDelay(
exec,
config.getMasterStartDelay(),
masterRunnable.rhs,
new Callable<ScheduledExecutors.Signal>()
{
private final MasterRunnable theRunnable = masterRunnable.lhs;
@Override
public ScheduledExecutors.Signal call()
{
if (master) {
theRunnable.run();
}
if (master) { // (We might no longer be master)
return ScheduledExecutors.Signal.REPEAT;
} else {
return ScheduledExecutors.Signal.STOP;
}
}
}
);
}
}
catch (Exception e) {
log.makeAlert(e, "Unable to become master")
.emit();
final LeaderLatch oldLatch = createNewLeaderLatch();
Closeables.closeQuietly(oldLatch);
try {
leaderLatch.get().start();
}
catch (Exception e1) {
// If an exception gets thrown out here, then the master will zombie out 'cause it won't be looking for
// the latch anymore. I don't believe it's actually possible for an Exception to throw out here, but
// Curator likes to have "throws Exception" on methods so it might happen...
log.makeAlert(e1, "I am a zombie")
.emit();
}
}
}
}
private void stopBeingMaster()
{
synchronized (lock) {
try {
log.info("I am no longer the master...");
for (String server : loadManagementPeons.keySet()) {
LoadQueuePeon peon = loadManagementPeons.remove(server);
peon.stop();
}
loadManagementPeons.clear();
databaseSegmentManager.stop();
serverInventoryView.stop();
master = false;
}
catch (Exception e) {
log.makeAlert(e, "Unable to stopBeingMaster").emit();
}
}
}
private List<DruidMasterHelper> makeIndexingServiceHelpers(final AtomicReference<MergerWhitelist> whitelistRef)
{
List<DruidMasterHelper> helpers = Lists.newArrayList();
helpers.add(new DruidMasterSegmentInfoLoader(DruidMaster.this));
if (config.isConvertSegments()) {
helpers.add(new DruidMasterVersionConverter(indexingServiceClient, whitelistRef));
}
if (config.isMergeSegments()) {
helpers.add(new DruidMasterSegmentMerger(indexingServiceClient, whitelistRef));
helpers.add(
new DruidMasterHelper()
{
@Override
public DruidMasterRuntimeParams run(DruidMasterRuntimeParams params)
{
MasterStats stats = params.getMasterStats();
log.info("Issued merge requests for %s segments", stats.getGlobalStats().get("mergedCount").get());
params.getEmitter().emit(
new ServiceMetricEvent.Builder().build(
"master/merge/count", stats.getGlobalStats().get("mergedCount")
)
);
return params;
}
}
);
}
return ImmutableList.copyOf(helpers);
}
public static class DruidMasterVersionConverter implements DruidMasterHelper
{
private final IndexingServiceClient indexingServiceClient;
private final AtomicReference<MergerWhitelist> whitelistRef;
public DruidMasterVersionConverter(
IndexingServiceClient indexingServiceClient,
AtomicReference<MergerWhitelist> whitelistRef
)
{
this.indexingServiceClient = indexingServiceClient;
this.whitelistRef = whitelistRef;
}
@Override
public DruidMasterRuntimeParams run(DruidMasterRuntimeParams params)
{
MergerWhitelist whitelist = whitelistRef.get();
for (DataSegment dataSegment : params.getAvailableSegments()) {
if (whitelist == null || whitelist.contains(dataSegment.getDataSource())) {
final Integer binaryVersion = dataSegment.getBinaryVersion();
if (binaryVersion == null || binaryVersion < IndexIO.CURRENT_VERSION_ID) {
log.info("Upgrading version on segment[%s]", dataSegment.getIdentifier());
indexingServiceClient.upgradeSegment(dataSegment);
}
}
}
return params;
}
}
public abstract class MasterRunnable implements Runnable
{
private final long startTime = System.currentTimeMillis();
private final List<DruidMasterHelper> helpers;
protected MasterRunnable(List<DruidMasterHelper> helpers)
{
this.helpers = helpers;
}
@Override
public void run()
{
try {
synchronized (lock) {
final LeaderLatch latch = leaderLatch.get();
if (latch == null || !latch.hasLeadership()) {
log.info("LEGGO MY EGGO. [%s] is master.", latch == null ? null : latch.getLeader().getId());
stopBeingMaster();
return;
}
}
List<Boolean> allStarted = Arrays.asList(
databaseSegmentManager.isStarted(),
serverInventoryView.isStarted()
);
for (Boolean aBoolean : allStarted) {
if (!aBoolean) {
log.error("InventoryManagers not started[%s]", allStarted);
stopBeingMaster();
return;
}
}
// Do master stuff.
DruidMasterRuntimeParams params =
DruidMasterRuntimeParams.newBuilder()
.withStartTime(startTime)
.withDatasources(databaseSegmentManager.getInventory())
.withMasterSegmentSettings(segmentSettingsAtomicReference.get())
.withEmitter(emitter)
.build();
for (DruidMasterHelper helper : helpers) {
params = helper.run(params);
}
}
catch (Exception e) {
log.makeAlert(e, "Caught exception, ignoring so that schedule keeps going.").emit();
}
}
}
private class MasterComputeManagerRunnable extends MasterRunnable
{
private MasterComputeManagerRunnable()
{
super(
ImmutableList.of(
new DruidMasterSegmentInfoLoader(DruidMaster.this),
new DruidMasterHelper()
{
@Override
public DruidMasterRuntimeParams run(DruidMasterRuntimeParams params)
{
// Display info about all historical servers
Iterable<DruidServer> servers = FunctionalIterable
.create(serverInventoryView.getInventory())
.filter(
new Predicate<DruidServer>()
{
@Override
public boolean apply(
@Nullable DruidServer input
)
{
return input.getType().equalsIgnoreCase("historical");
}
}
);
if (log.isDebugEnabled()) {
log.debug("Servers");
for (DruidServer druidServer : servers) {
log.debug(" %s", druidServer);
log.debug(" -- DataSources");
for (DruidDataSource druidDataSource : druidServer.getDataSources()) {
log.debug(" %s", druidDataSource);
}
}
}
// Find all historical servers, group them by subType and sort by ascending usage
final DruidCluster cluster = new DruidCluster();
for (DruidServer server : servers) {
if (!loadManagementPeons.containsKey(server.getName())) {
String basePath = ZKPaths.makePath(zkPaths.getLoadQueuePath(), server.getName());
LoadQueuePeon loadQueuePeon = taskMaster.giveMePeon(basePath);
log.info("Creating LoadQueuePeon for server[%s] at path[%s]", server.getName(), basePath);
loadManagementPeons.put(server.getName(), loadQueuePeon);
}
cluster.add(new ServerHolder(server, loadManagementPeons.get(server.getName())));
}
SegmentReplicantLookup segmentReplicantLookup = SegmentReplicantLookup.make(cluster);
// Stop peons for servers that aren't there anymore.
for (String name : Sets.difference(
Sets.newHashSet(
Iterables.transform(
servers,
new Function<DruidServer, String>()
{
@Override
public String apply(@Nullable DruidServer input)
{
return input.getName();
}
}
)
), loadManagementPeons.keySet()
)) {
log.info("Removing listener for server[%s] which is no longer there.", name);
LoadQueuePeon peon = loadManagementPeons.remove(name);
peon.stop();
}
decrementRemovedSegmentsLifetime();
return params.buildFromExisting()
.withDruidCluster(cluster)
.withDatabaseRuleManager(databaseRuleManager)
.withLoadManagementPeons(loadManagementPeons)
.withSegmentReplicantLookup(segmentReplicantLookup)
.withBalancerReferenceTimestamp(DateTime.now())
.withMasterSegmentSettings(
segmentSettingsAtomicReference.get()
)
.build();
}
},
new DruidMasterRuleRunner(
DruidMaster.this,
config.getReplicantLifetime(),
config.getReplicantThrottleLimit()
),
new DruidMasterCleanup(DruidMaster.this),
new DruidMasterBalancer(DruidMaster.this),
new DruidMasterLogger()
)
);
}
}
private class MasterIndexingServiceRunnable extends MasterRunnable
{
private MasterIndexingServiceRunnable(List<DruidMasterHelper> helpers)
{
super(helpers);
}
}
}
|
package io.spine.server.aggregate;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.protobuf.Any;
import com.google.protobuf.Empty;
import com.google.protobuf.Message;
import io.grpc.Internal;
import io.spine.core.CommandContext;
import io.spine.core.CommandEnvelope;
import io.spine.core.Event;
import io.spine.core.EventClass;
import io.spine.core.EventContext;
import io.spine.core.EventEnvelope;
import io.spine.core.MessageEnvelope;
import io.spine.core.RejectionEnvelope;
import io.spine.core.Version;
import io.spine.core.Versions;
import io.spine.protobuf.AnyPacker;
import io.spine.server.command.CommandHandlerMethod;
import io.spine.server.command.CommandHandlingEntity;
import io.spine.server.event.EventFactory;
import io.spine.server.event.EventReactorMethod;
import io.spine.server.model.Model;
import io.spine.server.rejection.RejectionReactorMethod;
import io.spine.validate.ValidatingBuilder;
import javax.annotation.CheckReturnValue;
import java.util.Collection;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static io.spine.core.Events.getMessage;
import static io.spine.time.Time.getCurrentTime;
import static io.spine.validate.Validate.isNotDefault;
/**
* Abstract base for aggregates.
*
* <p>An aggregate is the main building block of a business model.
* Aggregates guarantee consistency of data modifications in response to
* commands they receive.
*
* <p>An aggregate modifies its state in response to a command and produces
* one or more events. These events are used later to restore the state of the
* aggregate.
*
* <h2>Creating an aggregate class</h2>
*
* <p>In order to create a new aggregate class you need to:
* <ol>
* <li>Select a type for identifiers of the aggregate.
* If you select to use a typed identifier (which is recommended),
* you need to define a protobuf message for the ID type.
* <li>Define the structure of the aggregate state as a Protobuf message.
* <li>Generate Java code for ID and state types.
* <li>Create new Java class derived from {@code Aggregate} passing ID and
* state types as generic parameters.
* </ol>
*
* <h2>Adding command handler methods</h2>
*
* <p>Command handling methods of an {@code Aggregate} are defined in
* the same way as described in {@link CommandHandlingEntity}.
*
* <p>Event(s) returned by command handling methods are posted to
* the {@link io.spine.server.event.EventBus EventBus} automatically
* by {@link AggregateRepository}.
*
* <h2>Adding event applier methods</h2>
*
* <p>Aggregate data is stored as a sequence of events it produces.
* The state of the aggregate is restored by re-playing the history of
* events and invoking corresponding <em>event applier methods</em>.
*
* <p>An event applier is a method that changes the state of the aggregate
* in response to an event. An event applier takes a single parameter of the
* event message it handles and returns {@code void}.
*
* <p>The modification of the state is done via a builder instance obtained
* from {@link #getBuilder()}.
*
* <p>An {@code Aggregate} class must have applier methods for
* <em>all</em> types of the events that it produces.
*
* <h2>Performance considerations for aggregate state</h2>
*
* <p>In order to improve performance of loading aggregates an
* {@link AggregateRepository} periodically stores aggregate snapshots.
* See {@link AggregateRepository#setSnapshotTrigger(int)} for details.
*
* @param <I> the type for IDs of this class of aggregates
* @param <S> the type of the state held by the aggregate
* @param <B> the type of the aggregate state builder
*
* @author Alexander Yevsyukov
* @author Alexander Litus
* @author Mikhail Melnik
*/
@SuppressWarnings("OverlyCoupledClass") // OK for this central class.
public abstract class Aggregate<I,
S extends Message,
B extends ValidatingBuilder<S, ? extends Message.Builder>>
extends CommandHandlingEntity<I, S, B> {
/**
* Events generated in the process of handling commands that were not yet committed.
*
* @see #commitEvents()
*/
private final List<Event> uncommittedEvents = Lists.newLinkedList();
/**
* Creates a new instance.
*
* <p>Constructors of derived classes should have package access level
* because of the following reasons:
* <ol>
* <li>These constructors are not public API of an application.
* Commands and aggregate IDs are.
* <li>These constructors need to be accessible from tests in the same package.
* </ol>
*
* <p>Because of the last reason consider annotating constructors with
* {@code @VisibleForTesting}. The package access is needed only for tests.
* Otherwise aggregate constructors (that are invoked by {@link AggregateRepository}
* via Reflection) may be left {@code private}.
*
* @param id the ID for the new aggregate
*/
protected Aggregate(I id) {
super(id);
}
/**
* Obtains model class for this aggregate.
*/
@Override
protected AggregateClass<?> thisClass() {
return (AggregateClass<?>)super.thisClass();
}
/**
* Obtains the model class as {@link Model#asAggregateClass(Class) AggregateClass}.
*/
@Override
protected AggregateClass<?> getModelClass() {
return Model.getInstance()
.asAggregateClass(getClass());
}
@Override
@VisibleForTesting
protected B getBuilder() {
return super.getBuilder();
}
/**
* Obtains a method for the passed command and invokes it.
*
* <p>All the {@link Empty} messages are filtered out from the result.
*
* @param command the envelope with the command to dispatch
* @return a list with event messages that the aggregate produces in reaction to the event or
* an empty list if the aggregate state does not change in reaction to the event
*/
@Override
protected List<? extends Message> dispatchCommand(CommandEnvelope command) {
final CommandHandlerMethod method = thisClass().getHandler(command.getMessageClass());
final List<? extends Message> messages =
method.invoke(this, command.getMessage(), command.getCommandContext());
return EmptyFilter.INSTANCE.apply(messages);
}
/**
* Dispatches the event on which the aggregate reacts.
*
* <p>All the {@link Empty} messages are filtered out from the result.
*
* @param event the envelope with the event to dispatch
* @return a list with event messages that the aggregate produces in reaction to the event or
* an empty list if the aggregate state does not change in reaction to the event
*/
List<? extends Message> reactOn(EventEnvelope event) {
final EventReactorMethod method = thisClass().getReactor(event.getMessageClass());
final List<? extends Message> messages =
method.invoke(this, event.getMessage(), event.getEventContext());
return EmptyFilter.INSTANCE.apply(messages);
}
/**
* Dispatches the rejection to which the aggregate reacts.
*
* <p>All the {@link Empty} messages are filtered out from the result.
*
* @param rejection the envelope with the rejection
* @return a list with event messages that the aggregate produces in reaction to
* the rejection, or an empty list if the aggregate state does not change in
* response to this rejection
*/
List<? extends Message> reactOn(RejectionEnvelope rejection) {
final RejectionReactorMethod method = thisClass().getReactor(rejection.getMessageClass());
final List<? extends Message> messages =
method.invoke(this, rejection.getMessage(), rejection.getRejectionContext());
return EmptyFilter.INSTANCE.apply(messages);
}
/**
* Invokes applier method for the passed event message.
*
* @param eventMessage the event message to apply
*/
void invokeApplier(Message eventMessage) {
final EventApplierMethod method = thisClass().getApplier(EventClass.of(eventMessage));
method.invoke(this, eventMessage);
}
void play(AggregateStateRecord aggregateStateRecord) {
final Snapshot snapshot = aggregateStateRecord.getSnapshot();
if (isNotDefault(snapshot)) {
restore(snapshot);
}
final List<Event> events = aggregateStateRecord.getEventList();
play(events);
}
/**
* Applies event messages.
*
* @param eventMessages the event messages or events to apply
* @param origin the envelope of a message which caused the events
* @see #ensureEventMessage(Message)
*/
void apply(Iterable<? extends Message> eventMessages, MessageEnvelope origin) {
final List<? extends Message> messages = newArrayList(eventMessages);
final EventFactory eventFactory =
EventFactory.on(origin, getProducerId());
final List<Event> events = newArrayListWithCapacity(messages.size());
Version projectedEventVersion = getVersion();
for (Message eventOrMessage : messages) {
/* Applying each message would increment the entity version.
Therefore, we should simulate this behaviour. */
projectedEventVersion = Versions.increment(projectedEventVersion);
final Message eventMessage = ensureEventMessage(eventOrMessage);
final Event event;
if (eventOrMessage instanceof Event) {
/* If we get instances of Event, it means we are dealing with an import command,
which contains these events in the body. So we deal with a command envelope.
*/
final CommandEnvelope ce = (CommandEnvelope)origin;
event = importEvent((Event) eventOrMessage,
ce.getCommandContext(),
projectedEventVersion);
} else {
event = eventFactory.createEvent(eventMessage, projectedEventVersion);
}
events.add(event);
}
play(events);
uncommittedEvents.addAll(events);
}
/**
* Creates an event based on the event received in an import command.
*
* @param event the event to import
* @param commandContext the context of the import command
* @param version the version of the aggregate to use for the event
* @return an event with updated command context and entity version
*/
private static Event importEvent(Event event, CommandContext commandContext, Version version) {
final EventContext eventContext = event.getContext()
.toBuilder()
.setCommandContext(commandContext)
.setTimestamp(getCurrentTime())
.setVersion(version)
.build();
final Event result = event.toBuilder()
.setContext(eventContext)
.build();
return result;
}
/**
* Ensures that an event applier gets an instance of an event message,
* not {@link Event}.
*
* <p>Instances of {@code Event} may be passed to an applier during
* importing events or processing integration events. This may happen because
* corresponding command handling method returned either {@code List<Event>}
* or {@code Event}.
*
* @param eventOrMsg an event message or {@code Event}
* @return the passed instance or an event message extracted from the passed
* {@code Event} instance
*/
private static Message ensureEventMessage(Message eventOrMsg) {
final Message eventMsg;
if (eventOrMsg instanceof Event) {
final Event event = (Event) eventOrMsg;
eventMsg = getMessage(event);
} else {
eventMsg = eventOrMsg;
}
return eventMsg;
}
/**
* Restores the state and version from the passed snapshot.
*
* <p>If this method is called during a {@linkplain #play(AggregateStateRecord) replay}
* (because the snapshot was encountered) the method uses the state
* {@linkplain #getBuilder() builder}, which is used during the replay.
*
* <p>If not in replay, the method sets the state and version directly to the aggregate.
*
* @param snapshot the snapshot with the state to restore
*/
void restore(Snapshot snapshot) {
final S stateToRestore = AnyPacker.unpack(snapshot.getState());
final Version versionFromSnapshot = snapshot.getVersion();
setInitialState(stateToRestore, versionFromSnapshot);
}
/**
* Returns all uncommitted events.
*
* @return immutable view of all uncommitted events
*/
@CheckReturnValue
List<Event> getUncommittedEvents() {
return ImmutableList.copyOf(uncommittedEvents);
}
/**
* Obtains the number of uncommitted events.
*/
@Internal
@VisibleForTesting
protected int uncommittedEventsCount() {
return uncommittedEvents.size();
}
/**
* Returns and clears all the events that were uncommitted before the call of this method.
*
* @return the list of events
*/
List<Event> commitEvents() {
final List<Event> result = ImmutableList.copyOf(uncommittedEvents);
uncommittedEvents.clear();
return result;
}
/**
* Instructs to modify the state of an aggregate only within an event applier method.
*/
@Override
protected String getMissingTxMessage() {
return "Modification of aggregate state or its lifecycle flags is not available this way." +
" Make sure to modify those only from an event applier method.";
}
/**
* Transforms the current state of the aggregate into the {@link Snapshot} instance.
*
* @return new snapshot
*/
@CheckReturnValue
Snapshot toSnapshot() {
final Any state = AnyPacker.pack(getState());
final Snapshot.Builder builder = Snapshot.newBuilder()
.setState(state)
.setVersion(getVersion())
.setTimestamp(getCurrentTime());
return builder.build();
}
/**
* {@inheritDoc}
*
* <p>Overrides to expose the method to the package.
*/
@Override
@VisibleForTesting
protected int versionNumber() {
return super.versionNumber();
}
private enum EmptyFilter implements Function<Collection<? extends Message>, List<? extends Message>> {
INSTANCE;
private static final Empty EMPTY = Empty.getDefaultInstance();
/**
* Creates a new collection without {@link Empty} messages.
*
* @param messages a list of messages to be filtered
* @return a new list with all the items of the passed {@code messages}
* except for {@link Empty}
*/
@Override
public List<? extends Message> apply(Collection<? extends Message> messages) {
final ImmutableList.Builder<Message> list = ImmutableList.builder();
for (Message message : messages) {
if (!message.equals(EMPTY)) {
list.add(message);
}
}
return list.build();
}
}
}
|
package io.spine.server.event.enrich;
import com.google.common.collect.ImmutableCollection;
import com.google.protobuf.Any;
import com.google.protobuf.Message;
import io.spine.base.EventMessage;
import io.spine.core.EventContext;
import io.spine.core.EventEnvelope;
import io.spine.protobuf.AnyPacker;
import io.spine.type.TypeName;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Maps.newHashMap;
/**
* Performs enrichment operation for an event.
*/
final class Action {
/**
* The envelope with the event to enrich.
*/
private final EventEnvelope envelope;
/**
* Active functions applicable to the enriched event.
*/
private final ImmutableCollection<EnrichmentFunction<?, ?, ?>> functions;
/**
* A map from the type name of an enrichment to its packed instance, in the form
* it is used in the enriched event context.
*/
private final Map<String, Any> enrichments = newHashMap();
Action(Enricher parent, EventEnvelope envelope) {
this.envelope = envelope;
Class<? extends Message> sourceClass = envelope.getMessageClass()
.value();
this.functions = parent.schema()
.get(sourceClass);
}
/**
* Creates new envelope with the enriched version of the event.
*/
EventEnvelope perform() {
createEnrichments();
EventEnvelope enriched = envelope.toEnriched(enrichments);
return enriched;
}
private void createEnrichments() {
EventMessage event = envelope.getMessage();
for (EnrichmentFunction function : functions) {
Message enrichment = apply(function, event, envelope.getEventContext());
checkResult(enrichment, function);
put(enrichment);
}
}
private void put(Message enrichment) {
String typeName = TypeName.of(enrichment)
.value();
enrichments.put(typeName, AnyPacker.pack(enrichment));
}
/**
* Applies the passed function to the message.
*
* <p>We suppress the {@code "unchecked"} because we ensure types when we...
* <ol>
* <li>create enrichments,
* <li>put them into {@link Enricher} by their message class.
* </ol>
*/
@SuppressWarnings("unchecked")
private static Message apply(EnrichmentFunction fn, EventMessage event, EventContext context) {
Message result = (Message) fn.apply(event, context);
return result;
}
private void checkResult(@Nullable Message enriched, EnrichmentFunction function) {
checkNotNull(
enriched,
"EnrichmentFunction %s produced `null` for the source message %s",
function, envelope.getMessage()
);
}
}
|
package massim.scenario.city;
import massim.config.TeamConfig;
import massim.protocol.DynamicWorldData;
import massim.protocol.StaticWorldData;
import massim.protocol.messagecontent.Action;
import massim.protocol.messagecontent.RequestAction;
import massim.protocol.messagecontent.SimEnd;
import massim.protocol.messagecontent.SimStart;
import massim.protocol.scenario.city.data.*;
import massim.protocol.scenario.city.percept.CityInitialPercept;
import massim.protocol.scenario.city.percept.CityStepPercept;
import massim.scenario.AbstractSimulation;
import massim.scenario.city.data.*;
import massim.scenario.city.data.facilities.Facility;
import massim.scenario.city.data.facilities.Shop;
import massim.scenario.city.data.facilities.Storage;
import massim.scenario.city.util.Generator;
import massim.util.Log;
import massim.util.RNG;
import org.json.JSONObject;
import java.util.*;
import java.util.stream.Collectors;
/**
* Main class of the City scenario (2017).
* @author ta10
*/
public class CitySimulation extends AbstractSimulation {
private int currentStep = -1;
private WorldState world;
private ActionExecutor actionExecutor;
private Generator generator;
private StaticCityData staticData;
@Override
public Map<String, SimStart> init(int steps, JSONObject config, Set<TeamConfig> matchTeams) {
// build the random generator
JSONObject randomConf = config.optJSONObject("generate");
if(randomConf == null){
Log.log(Log.Level.ERROR, "No random generation parameters!");
randomConf = new JSONObject();
}
generator = new Generator(randomConf);
// create the most important things
world = new WorldState(steps, config, matchTeams, generator);
actionExecutor = new ActionExecutor(world);
// create data objects for all items
List<Item> allItems = world.getItems();
allItems.addAll(world.getTools());
List<ItemData> itemData = allItems.stream()
.map(item -> new ItemData(
item.getName(),
item.getVolume(),
item.getRequiredItems().entrySet().stream()
.map(e -> new ItemAmountData(e.getKey().getName(), e.getValue()))
.collect(Collectors.toList()),
item.getRequiredTools().stream()
.map(tool -> new ToolData(tool.getName()))
.collect(Collectors.toList())))
.collect(Collectors.toList());
// create the static data object
staticData = new StaticCityData(world.getSimID(), world.getSteps(), world.getMapName(), world.getSeedCapital(),
world.getTeams().stream()
.map(TeamState::getName)
.collect(Collectors.toList()),
world.getRoles().stream()
.map(Role::getRoleData)
.collect(Collectors.toList()),
itemData);
// determine initial percepts
Map<String, SimStart> initialPercepts = new HashMap<>();
world.getAgents().forEach(agName -> initialPercepts.put(agName,
new CityInitialPercept(
world.getSimID(),
steps,
world.getTeamForAgent(agName),
world.getMapName(),
world.getSeedCapital(),
world.getEntity(agName).getRole().getRoleData(),
itemData
)));
return initialPercepts;
}
@Override
public Map<String, RequestAction> preStep(int stepNo) {
currentStep = stepNo;
// step job generator
generator.generateJobs(stepNo, world).forEach(job -> world.addJob(job));
// activate jobs for this step
world.getJobs().stream()
.filter(job -> job.getBeginStep() == stepNo)
.forEach(Job::activate);
/* create percept data */
// create team data
Map<String, TeamData> teamData = new HashMap<>();
world.getTeams().forEach(team -> teamData.put(team.getName(), new TeamData(null, team.getMoney())));
// create entity data as visible to other entities (containing name, team, role and location)
List<EntityData> entities = new Vector<>();
world.getAgents().forEach(agent -> {
Entity entity = world.getEntity(agent);
entities.add(new EntityData(null, null, null, null, null, null,
agent, world.getTeamForAgent(agent),
entity.getRole().getName(),
entity.getLocation().getLat(),
entity.getLocation().getLon()));
});
// create complete snapshots of entities
Map<String, EntityData> completeEntities = buildEntityData();
/* create facility data */
List<ShopData> shops = buildShopData();
List<WorkshopData> workshops = buildWorkshopData();
List<ChargingStationData> stations = buildChargingStationData();
List<DumpData> dumps = buildDumpData();
List<ResourceNodeData> resourceNodes = buildResourceNodeData();
// storage
Map<String, List<StorageData>> storageMap = new HashMap<>();
for (TeamState team : world.getTeams()) {
List<StorageData> storageData = new Vector<>();
for (Storage storage: world.getStorages()){
List<StoredData> items = new Vector<>();
for(Item item: world.getItems()){
// add an entry if item is either stored or delivered for the team
int stored = storage.getStored(item, team.getName());
int delivered = storage.getDelivered(item, team.getName());
if(stored > 0 || delivered > 0) items.add(new StoredData(item.getName(), stored, delivered));
}
StorageData sd = new StorageData(storage.getName(),
storage.getLocation().getLat(),
storage.getLocation().getLon(),
storage.getCapacity(),
storage.getFreeSpace(),
items,
null);
storageData.add(sd);
}
storageMap.put(team.getName(), storageData);
}
/* create job data */
Map<String, List<JobData>> jobsPerTeam = new HashMap<>();
Map<String, List<JobData>> postedJobsPerTeam = new HashMap<>();
Map<String, List<AuctionJobData>> auctionsPerTeam = new HashMap<>();
Map<String, List<MissionData>> missionsPerTeam = new HashMap<>();
world.getTeams().forEach(team -> postedJobsPerTeam.put(team.getName(), new ArrayList<>()));
world.getTeams().forEach(team -> jobsPerTeam.put(team.getName(), new ArrayList<>()));
// add all regular jobs (either as posted or not)
for (Job job : world.getJobs()) {
if(!(job instanceof AuctionJob) && job.isActive()){
JobData jobData = job.toJobData(false, false);
for(TeamState team: world.getTeams()){
if(job.getPoster().equals(team.getName())){
// add to team's posted jobs
postedJobsPerTeam.get(team.getName()).add(jobData);
}
else{
// add as regular job
jobsPerTeam.get(team.getName()).add(jobData);
}
}
}
}
// list of auction jobs in auctioning state (visible to all)
List<AuctionJobData> auctioningJobs = world.getJobs().stream()
.filter(job -> (job instanceof AuctionJob && job.getStatus() == Job.JobStatus.AUCTION ))
.map(job -> job.toJobData(false, false))
.map(jobData -> (AuctionJobData)jobData)
.collect(Collectors.toList());
// add per team: auctions assigned to that team + missions
world.getTeams().forEach(team -> {
List<AuctionJobData> teamJobs = new Vector<>(auctioningJobs);
List<MissionData> teamMissions = new Vector<>();
for (Job job : world.getJobs()) {
if(job instanceof AuctionJob
&& ((AuctionJob)job).getAuctionWinner().equals(team.getName())
&& job.isActive()){
if(job instanceof Mission) teamMissions.add((MissionData) job.toJobData(false, false));
else teamJobs.add((AuctionJobData) job.toJobData(false, false));
}
}
auctionsPerTeam.put(team.getName(), teamJobs);
missionsPerTeam.put(team.getName(), teamMissions);
});
// create and deliver percepts
Map<String, RequestAction> percepts = new HashMap<>();
world.getAgents().forEach(agent -> {
String team = world.getTeamForAgent(agent);
percepts.put(agent,
new CityStepPercept(
completeEntities.get(agent),
team, stepNo, teamData.get(team), entities, shops, workshops, stations, dumps,
storageMap.get(team),
resourceNodes,
jobsPerTeam,
auctionsPerTeam,
missionsPerTeam,
postedJobsPerTeam,
world.getVisibilityRange()
));
});
return percepts;
}
/**
* Builds dump data objects for all dumps.
* @return a list of those objects
*/
private List<DumpData> buildDumpData() {
return world.getDumps().stream()
.map(dump -> new DumpData(dump.getName(), dump.getLocation().getLat(), dump.getLocation().getLon()))
.collect(Collectors.toList());
}
/**
* Builds charging station data objects for all charging stations.
* @return a list of those objects
*/
private List<ChargingStationData> buildChargingStationData() {
return world.getChargingStations().stream()
.map(cs -> new ChargingStationData(cs.getName(), cs.getLocation().getLat(),
cs.getLocation().getLon(), cs.getRate()))
.collect(Collectors.toList());
}
/**
* Builds workshop data objects for all workshops.
* @return a list of those objects
*/
private List<WorkshopData> buildWorkshopData() {
return world.getWorkshops().stream()
.map(ws -> new WorkshopData(ws.getName(), ws.getLocation().getLat(), ws.getLocation().getLon()))
.collect(Collectors.toList());
}
/**
* Builds shop data objects for all shops.
* @return a list of those objects
*/
private List<ShopData> buildShopData() {
return world.getShops().stream()
.map(shop ->
new ShopData(
shop.getName(), shop.getLocation().getLat(), shop.getLocation().getLon(),
shop.getRestock(),
shop.getOfferedItems().stream()
.map(item -> new StockData(item.getName(), shop.getPrice(item), shop.getItemCount(item)))
.collect(Collectors.toList())))
.collect(Collectors.toList());
}
/**
* Builds resource node data objects for all shops.
* @return a list of those objects
*/
private List<ResourceNodeData> buildResourceNodeData() {
return world.getResourceNodes().stream()
.map(node -> new ResourceNodeData(node.getName(), node.getLocation().getLat(), node.getLocation().getLon(), node.getResource().getName()))
.collect(Collectors.toList());
}
/**
* Builds an {@link EntityData} object for each entity in the simulation.
* @return mapping from agent/entity names to the data objects
*/
private Map<String,EntityData> buildEntityData() {
Map<String, EntityData> result = new HashMap<>();
world.getAgents().forEach(agent -> {
Entity entity = world.getEntity(agent);
// check if entity is in some facility
String facilityName = null;
Facility facility = world.getFacilityByLocation(entity.getLocation());
if(facility != null) facilityName = facility.getName();
// check if entity has a route
List<WayPointData> waypoints = new Vector<>();
if(entity.getRoute() != null){
int i = 0;
for (Location loc: entity.getRoute().getWaypoints()) {
waypoints.add(new WayPointData(i++, loc.getLat(), loc.getLon()));
}
}
// create entity snapshot
result.put(agent,
new EntityData(
entity.getCurrentBattery(),
entity.getCurrentLoad(),
new ActionData(entity.getLastAction().getActionType(),
entity.getLastAction().getParameters(),
entity.getLastActionResult()),
facilityName,
waypoints,
entity.getInventory().toItemAmountData(),
agent,
world.getTeamForAgent(agent),
entity.getRole().getName(),
entity.getLocation().getLat(),
entity.getLocation().getLon()
));
});
return result;
}
@Override
public void step(int stepNo, Map<String, Action> actions) {
// execute all actions in random order
List<String> agents = world.getAgents();
RNG.shuffle(agents);
actionExecutor.preProcess();
for(String agent: agents)
actionExecutor.execute(agent, actions, stepNo);
actionExecutor.postProcess();
world.getShops().forEach(Shop::step);
// process new jobs (created in this step)
world.processNewJobs();
// tell all jobs which have to end that they have to end
world.getJobs().stream().filter(job -> job.getEndStep() == stepNo).forEach(Job::terminate);
// assign auction jobs which have finished auctioning
world.getJobs().stream()
.filter(job -> job instanceof AuctionJob
&& job.getBeginStep() + ((AuctionJob)job).getAuctionTime() - 1 == stepNo
&& !((AuctionJob)job).isAssigned())
.forEach(job -> ((AuctionJob)job).assign());
}
@Override
public Map<String, SimEnd> finish() {
Map<TeamState, Integer> rankings = getRankings();
Map<String, SimEnd> results = new HashMap<>();
world.getAgents().forEach(agent -> {
TeamState team = world.getTeam(world.getTeamForAgent(agent));
results.put(agent, new SimEnd(rankings.get(team), team.getMoney()));
});
return results;
}
@Override
public JSONObject getResult() {
JSONObject result = new JSONObject();
Map<TeamState, Integer> rankings = getRankings();
world.getTeams().forEach(team -> {
JSONObject teamResult = new JSONObject();
teamResult.put("score", team.getMoney());
teamResult.put("ranking", rankings.get(team));
result.put(team.getName(), teamResult);
});
return result;
}
/**
* Calculates the current rankings based on the teams' current money values.
* @return a map of the current rankings
*/
private Map<TeamState, Integer> getRankings(){
Map<TeamState, Integer> rankings = new HashMap<>();
Map<Long, Set<TeamState>> scoreToTeam = new HashMap<>();
world.getTeams().forEach(team -> {
scoreToTeam.putIfAbsent(team.getMoney(), new HashSet<>());
scoreToTeam.get(team.getMoney()).add(team);
});
List<Long> scoreRanking = new ArrayList<>(scoreToTeam.keySet());
Collections.sort(scoreRanking); // sort ascending
Collections.reverse(scoreRanking); // now descending
final int[] ranking = {1};
scoreRanking.forEach(score -> {
Set<TeamState> teams = scoreToTeam.get(score);
teams.forEach(team -> rankings.put(team, ranking[0]));
ranking[0] += teams.size();
});
return rankings;
}
@Override
public String getName() {
return world.getSimID();
}
@Override
public DynamicWorldData getSnapshot() {
return new DynamicCityData(
currentStep,
new ArrayList<>(buildEntityData().values()),
buildShopData(),
buildWorkshopData(),
buildChargingStationData(),
buildDumpData(),
buildResourceNodeData(),
world.getJobs().stream()
.map(job -> job.toJobData(true, true))
.collect(Collectors.toList()),
world.getStorages().stream()
.map(s -> s.toStorageData(world.getTeams().stream()
.map(TeamState::getName)
.collect(Collectors.toList())))
.collect(Collectors.toList()),
world.getTeams().stream()
.map(team -> new TeamData(team.getName(), team.getMoney()))
.collect(Collectors.toList()));
}
@Override
public StaticWorldData getStaticData() {
return staticData;
}
/**
* Retrieves the simulation state. This is not a replica. Handle with care!!
* @return the simulation's world state
*/
public WorldState getWorldState(){
return world;
}
@Override
public void handleCommand(String[] command) {
switch (command[0]){
case "give": // "give item0 agentA1 1"
if(command.length == 4){
Item item = world.getItemOrTool(command[1]);
Entity agent = world.getEntity(command[2]);
int amount = -1;
try{amount = Integer.parseInt(command[3]);} catch (NumberFormatException ignored){}
if(item != null && agent != null && amount > 0 ){
if(agent.addItem(item, amount)){
Log.log(Log.Level.NORMAL,
"Added " + amount + " of item " + command[1] + " to agent " + command[2]);
}
break;
}
}
Log.log(Log.Level.ERROR, "Invalid give command parameters.");
break;
case "store": // "store storage0 item0 A 1"
if(command.length == 5){
Facility facility = world.getFacility(command[1]);
Item item = world.getItemOrTool(command[2]);
int amount = -1;
try{amount = Integer.parseInt(command[4]);} catch (NumberFormatException ignored){}
if(facility instanceof Storage && item != null && amount > 0){
if(((Storage) facility).store(item, amount, command[3])){
Log.log(Log.Level.NORMAL, "Stored items in " + facility.getName());
}
break;
}
}
Log.log(Log.Level.ERROR, "Invalid store command parameters.");
break;
case "addJob": // "addJob 1 2 100 storage0 item0 1 item1 1 ..."
if(command.length >= 7 && command.length % 2 == 1){
int start = -1;
try{start = Integer.parseInt(command[1]);} catch (NumberFormatException ignored){}
int end = -1;
try{end = Integer.parseInt(command[2]);} catch (NumberFormatException ignored){}
int reward = -1;
try{reward = Integer.parseInt(command[3]);} catch (NumberFormatException ignored){}
Facility facility = world.getFacility(command[4]);
Map<Item, Integer> requirements = new HashMap<>();
for(int i = 5; i < command.length; i += 2){
Item item = world.getItemOrTool(command[i]);
int amount = -1;
try{amount = Integer.parseInt(command[i+1]);} catch (NumberFormatException ignored){}
if(item != null && amount > 0) requirements.put(item, amount);
}
if(start > 0 && end >= start && reward > 0 && requirements.size() > 0 && facility instanceof Storage) {
Job job = new Job(reward, (Storage) facility, start, end, JobData.POSTER_SYSTEM);
requirements.forEach(job::addRequiredItem);
world.addJob(job);
break;
}
}
Log.log(Log.Level.ERROR, "Invalid addJob command parameters.");
break;
case "addAuction": // "addAuction 1 2 100 5 1000 storage0 item0 1 item1 1 ..."
if(command.length >= 9 && command.length % 2 == 1){
int start = -1;
try{start = Integer.parseInt(command[1]);} catch (NumberFormatException ignored){}
int end = -1;
try{end = Integer.parseInt(command[2]);} catch (NumberFormatException ignored){}
int reward = -1;
try{reward = Integer.parseInt(command[3]);} catch (NumberFormatException ignored){}
int auctionTime = -1;
try{auctionTime = Integer.parseInt(command[4]);} catch (NumberFormatException ignored){}
int fine = -1;
try{fine = Integer.parseInt(command[5]);} catch (NumberFormatException ignored){}
Facility facility = world.getFacility(command[6]);
Map<Item, Integer> requirements = new HashMap<>();
for(int i = 7; i < command.length; i += 2){
Item item = world.getItemOrTool(command[i]);
int amount = -1;
try{amount = Integer.parseInt(command[i+1]);} catch (NumberFormatException ignored){}
if(item != null && amount > 0) requirements.put(item, amount);
}
if(start > 0 && end >= start && reward > 0 && requirements.size() > 0 && facility instanceof Storage) {
AuctionJob auction = new AuctionJob(reward, (Storage) facility, start, end, auctionTime, fine);
requirements.forEach(auction::addRequiredItem);
world.addJob(auction);
break;
}
}
Log.log(Log.Level.ERROR, "Invalid addAuction command parameters.");
break;
case "print":
if(command.length > 1) {
switch (command[1]) {
case "facilities":
case "facs":
world.getFacilities().forEach(f -> Log.log(Log.Level.NORMAL, f.toString()));
break;
case "items":
world.getItems().forEach(i -> Log.log(Log.Level.NORMAL, i.toString()));
break;
default:
Log.log(Log.Level.ERROR, "Invalid print command argument.");
}
}
else{
Log.log(Log.Level.ERROR, "Invalid print command.");
}
break;
}
}
}
|
package io.scalecube.services;
import static io.scalecube.services.CommunicationMode.FIRE_AND_FORGET;
import static io.scalecube.services.CommunicationMode.REQUEST_CHANNEL;
import static io.scalecube.services.CommunicationMode.REQUEST_RESPONSE;
import static io.scalecube.services.CommunicationMode.REQUEST_STREAM;
import io.scalecube.services.api.NullData;
import io.scalecube.services.api.ServiceMessage;
import io.scalecube.services.api.ServiceMessageHandler;
import io.scalecube.services.codec.ServiceMessageDataCodec;
import io.scalecube.services.exceptions.ExceptionProcessor;
import io.scalecube.services.exceptions.ServiceUnavailableException;
import io.scalecube.services.metrics.Metrics;
import io.scalecube.services.registry.api.ServiceRegistry;
import io.scalecube.services.routing.Router;
import io.scalecube.services.routing.Routers;
import io.scalecube.services.transport.HeadAndTail;
import io.scalecube.services.transport.LocalServiceHandlers;
import io.scalecube.services.transport.client.api.ClientTransport;
import io.scalecube.transport.Address;
import com.google.common.reflect.Reflection;
import org.reactivestreams.Processor;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.UnicastProcessor;
public class ServiceCall {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceCall.class);
private final ClientTransport transport;
private final LocalServiceHandlers serviceHandlers;
private final ServiceRegistry serviceRegistry;
private final Router router;
private final Metrics metrics;
private final ServiceMessageDataCodec dataCodec = new ServiceMessageDataCodec();
ServiceCall(Call call) {
this.transport = call.transport;
this.serviceHandlers = call.serviceHandlers;
this.serviceRegistry = call.serviceRegistry;
this.router = call.router;
this.metrics = call.metrics;
}
public static class Call {
private Router router;
private Metrics metrics;
private final ClientTransport transport;
private final LocalServiceHandlers serviceHandlers;
private final ServiceRegistry serviceRegistry;
public Call(ClientTransport transport, LocalServiceHandlers serviceHandlers, ServiceRegistry serviceRegistry) {
this.transport = transport;
this.serviceRegistry = serviceRegistry;
this.serviceHandlers = serviceHandlers;
}
public Call router(Class<? extends Router> routerType) {
this.router = Routers.getRouter(routerType);
return this;
}
public Call router(Router router) {
this.router = router;
return this;
}
public Call metrics(Metrics metrics) {
this.metrics = metrics;
return this;
}
public ServiceCall create() {
return new ServiceCall(this);
}
}
/**
* Issues fire-and-rorget request.
*
* @param request request message to send.
* @return mono publisher completing normally or with error.
*/
public Mono<Void> oneWay(ServiceMessage request) {
return requestOne(request, Void.class).then();
}
/**
* Issues request-and-reply request.
*
* @param request request message to send.
* @return mono publisher completing with single response message or with error.
*/
public Mono<ServiceMessage> requestOne(ServiceMessage request) {
return requestBidirectional(Mono.just(request)).as(Mono::from);
}
/**
* Issues request-and-reply request.
*
* @param request request message to send.
* @param responseType type of response.
* @return mono publisher completing with single response message or with error.
*/
public Mono<ServiceMessage> requestOne(ServiceMessage request, Class<?> responseType) {
return requestBidirectional(Mono.just(request), responseType).as(Mono::from);
}
/**
* Issues request to service which returns stream of service messages back.
*
* @param request request message to send.
* @return stream of service responses.
*/
public Flux<ServiceMessage> requestMany(ServiceMessage request) {
return requestBidirectional(Mono.just(request));
}
/**
* Issues request to service which returns stream of service messages back.
*
* @param request request with given headers.
* @param responseType type of responses.
* @return stream of service responses.
*/
public Flux<ServiceMessage> requestMany(ServiceMessage request, Class<?> responseType) {
return requestBidirectional(Mono.just(request), responseType);
}
/**
* Issues stream of service requests to service which returns stream of service messages back.
*
* @param stream of service requests.
* @return stream of service responses.
*/
public Flux<ServiceMessage> requestBidirectional(Publisher<ServiceMessage> publisher) {
return requestBidirectional(publisher, null);
}
/**
* Issues stream of service requests to service which returns stream of service messages back.
*
* @param stream of service requests.
* @param responseType type of responses.
* @return stream of service responses.
*/
public Flux<ServiceMessage> requestBidirectional(Publisher<ServiceMessage> publisher, Class<?> responseType) {
return Flux.from(HeadAndTail.createFrom(publisher)).flatMap(pair -> {
ServiceMessage request = pair.head();
Flux<ServiceMessage> requestPublisher = Flux.from(pair.tail()).startWith(request);
Messages.validate().serviceRequest(request);
String qualifier = request.qualifier();
if (serviceHandlers.contains(qualifier)) {
ServiceMessageHandler serviceHandler = serviceHandlers.get(qualifier);
return serviceHandler.invoke(requestPublisher).onErrorMap(ExceptionProcessor::mapException);
} else {
ServiceReference serviceReference =
router.route(serviceRegistry, request)
.orElseThrow(() -> noReachableMemberException(request));
Address address =
Address.create(serviceReference.host(), serviceReference.port());
Flux<ServiceMessage> responsePublisher =
transport.create(address).requestBidirectional(requestPublisher);
return responsePublisher.map(message -> dataCodec.decode(message, responseType));
}
});
}
/**
* Issues service request for each service message of the given stream for each message find a service endpoint and
* invoke the request according the target endpoint mode.
*
* @param publisher of service requests.
* @return flux publisher of service responses no encoding is applied.
*/
public Flux<ServiceMessage> invoke(Publisher<ServiceMessage> publisher) {
return this.invoke(publisher, null);
}
/**
* Issues service request for each service message of the given stream for each message find a service endpoint and
* invoke the request according the target end-point type/mode. in case local handlers contains given end-point they
* will be preferred over remote end-point.
*
* @param publisher of service requests.
* @param responseType type of responses.
* @return flux publisher of service responses decoded by a given responseType.
*/
public Flux<ServiceMessage> invoke(Publisher<ServiceMessage> publisher, Class<?> responseType) {
final Processor<ServiceMessage, ServiceMessage> upstream =
UnicastProcessor.<ServiceMessage>create();
Flux.from(publisher).subscribe(request -> {
Messages.validate().serviceRequest(request);
String qualifier = request.qualifier();
if (serviceHandlers.contains(qualifier)) {
ServiceMessageHandler serviceHandler = serviceHandlers.get(qualifier);
Flux.from(serviceHandler
.invoke(Flux.just(request))
.onErrorMap(ExceptionProcessor::mapException))
.subscribe(upstream::onNext);
} else {
ServiceReference serviceReference =
router.route(serviceRegistry, request)
.orElseThrow(() -> noReachableMemberException(request));
invoke(request, serviceReference.mode(),
Address.create(serviceReference.host(), serviceReference.port()))
.map(message -> dataCodec.decode(message, responseType))
.subscribe(upstream::onNext);
}
});
return Flux.from(upstream);
}
/**
* Invoke remote service end-point with a given Address and mode of invocation.
*
* @param request to invoke remote.
* @param mode and style of desired invocation.
* @param address of the target end-point.
* @return flux publisher of service responses no encoding is applied.
*/
public Flux<ServiceMessage> invoke(ServiceMessage request, CommunicationMode mode, Address address) {
final Processor<ServiceMessage, ServiceMessage> upstream =
UnicastProcessor.<ServiceMessage>create();
if (mode.equals(REQUEST_RESPONSE)) {
Flux.from(transport.create(address)
.requestBidirectional(Flux.just(request)).as(Mono::from))
.map(message -> dataCodec.encode(message))
.subscribe(next -> upstream.onNext(next));
} else if (mode.equals(REQUEST_STREAM)) {
Flux.from(transport.create(address)
.requestBidirectional(Flux.just(request)))
.map(message -> dataCodec.encode(message))
.subscribe(next -> upstream.onNext(next));
} else if (mode.equals(FIRE_AND_FORGET)) {
Flux.from(transport.create(address)
.requestBidirectional(Flux.just(request)).as(Mono::from))
.then();
} else if (mode.equals(REQUEST_CHANNEL)) {
throw new IllegalArgumentException("Communication mode is not supported: " + request.qualifier());
}
return Flux.from(upstream);
}
/**
* Create proxy creates a java generic proxy instance by a given service interface.
*
* @param serviceInterface Service Interface type.
* @return newly created service proxy object.
*/
public <T> T api(Class<T> serviceInterface) {
final ServiceCall serviceCall = this;
return Reflection.newProxy(serviceInterface, (proxy, method, args) -> {
Object check = objectToStringEqualsHashCode(method.getName(), serviceInterface, args);
if (check != null) {
return check; // toString, hashCode was invoked.
}
Metrics.mark(serviceInterface, metrics, method, "request");
Class<?> parameterizedReturnType = Reflect.parameterizedReturnType(method);
CommunicationMode mode = Reflect.communicationMode(method);
ServiceMessage request = ServiceMessage.builder()
.qualifier(Reflect.serviceName(serviceInterface), method.getName())
.data(method.getParameterCount() != 0 ? args[0] : NullData.NULL_DATA)
.build();
switch (mode) {
case FIRE_AND_FORGET:
return serviceCall.oneWay(request);
case REQUEST_RESPONSE:
return serviceCall.requestOne(request, parameterizedReturnType)
.transform(mono -> parameterizedReturnType.equals(ServiceMessage.class) ? mono
: mono.map(ServiceMessage::data));
case REQUEST_STREAM:
return serviceCall.requestMany(request, parameterizedReturnType)
.transform(flux -> parameterizedReturnType.equals(ServiceMessage.class) ? flux
: flux.map(ServiceMessage::data));
case REQUEST_CHANNEL:
// falls to default
default:
throw new IllegalArgumentException("Communication mode is not supported: " + method);
}
});
}
private static ServiceUnavailableException noReachableMemberException(ServiceMessage request) {
LOGGER.error("Failed to invoke service, No reachable member with such service definition [{}], args [{}]",
request.qualifier(), request);
return new ServiceUnavailableException("No reachable member with such service: " + request.qualifier());
}
private static Object objectToStringEqualsHashCode(String method, Class<?> serviceInterface, Object... args) {
if ("hashCode".equals(method)) {
return serviceInterface.hashCode();
} else if ("equals".equals(method)) {
return serviceInterface.equals(args[0]);
} else if ("toString".equals(method)) {
return serviceInterface.toString();
} else {
return null;
}
}
}
|
package bio.terra.cli.apps.utils;
import bio.terra.cli.command.exception.SystemException;
import bio.terra.cli.command.exception.UserActionableException;
import bio.terra.cli.context.utils.Printer;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.WaitContainerResultCallback;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Volume;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** This class provides utility methods for running Docker containers. */
public class DockerClientWrapper {
private static final Logger logger = LoggerFactory.getLogger(DockerClientWrapper.class);
private final DockerClient dockerClient;
private String containerId;
public DockerClientWrapper() {
this.dockerClient = DockerClientWrapper.buildDockerClient();
}
/** Build the Docker client object with standard options. */
private static DockerClient buildDockerClient() {
DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().build();
DockerHttpClient httpClient =
new ApacheDockerHttpClient.Builder()
.dockerHost(config.getDockerHost())
.sslConfig(config.getSSLConfig())
.build();
return DockerClientImpl.getInstance(config, httpClient);
}
/**
* Check if the Docker image id exists on the local machine.
*
* @param imageId the id of the docker image to look for
* @return true if the given image id exists
*/
public boolean checkImageExists(String imageId) {
try {
dockerClient.inspectImageCmd(imageId).exec();
return true;
} catch (NotFoundException nfEx) {
return false;
} catch (RuntimeException rtEx) {
throw wrapExceptionIfDockerConnectionFailed(rtEx);
}
}
/**
* Start a Docker container and run the given command.
*
* <p>Note this method cannot be called concurrently, because it updates the internal state of
* this instance with the container id.
*
* @param imageId the id of the docker image to use for the container
* @param command the full string command to execute in a bash shell (bash -c ..cmd..)
* @param workingDir the directory where the commmand will be executed
* @param envVars a mapping of environment variable names to values
* @param bindMounts a mapping of container mount point to the local directory being mounted
* @throws SystemException if the local directory does not exist or is not a directory
*/
public void startContainer(
String imageId,
String command,
String workingDir,
Map<String, String> envVars,
Map<Path, Path> bindMounts) {
// flatten the environment variables from a map, into a list of key=val strings
List<String> envVarsStr = new ArrayList<>();
for (Map.Entry<String, String> envVar : envVars.entrySet()) {
envVarsStr.add(envVar.getKey() + "=" + envVar.getValue());
}
// create Bind objects for each specified mount
List<Bind> bindMountsObj = new ArrayList<>();
for (Map.Entry<Path, Path> bindMount : bindMounts.entrySet()) {
File localDirectory = bindMount.getValue().toFile();
if (!localDirectory.exists() || !localDirectory.isDirectory()) {
throw new SystemException(
"Bind mount does not specify a local directory: " + localDirectory.getAbsolutePath());
}
bindMountsObj.add(
new Bind(localDirectory.getAbsolutePath(), new Volume(bindMount.getKey().toString())));
}
// create the container and start it
CreateContainerCmd createContainerCmd =
dockerClient
.createContainerCmd(imageId)
.withCmd("bash", "-c", command)
.withEnv(envVarsStr)
.withHostConfig(HostConfig.newHostConfig().withBinds(bindMountsObj))
.withAttachStdout(true)
.withAttachStderr(true);
if (workingDir != null) {
createContainerCmd.withWorkingDir(workingDir);
}
try {
containerId = createContainerCmd.exec().getId();
dockerClient.startContainerCmd(containerId).exec();
logger.debug("container id: {}", containerId);
} catch (RuntimeException rtEx) {
throw wrapExceptionIfDockerConnectionFailed(rtEx);
}
}
/** Block until the Docker container exits, then return its status code. */
public Integer waitForContainerToExit() {
WaitContainerResultCallback waitContainerResultCallback = new WaitContainerResultCallback();
try {
WaitContainerResultCallback exec =
dockerClient.waitContainerCmd(containerId).exec(waitContainerResultCallback);
return exec.awaitStatusCode();
} catch (RuntimeException rtEx) {
throw wrapExceptionIfDockerConnectionFailed(rtEx);
}
}
/** Delete the Docker container. */
public void deleteContainer() {
try {
dockerClient.removeContainerCmd(containerId).exec();
} catch (RuntimeException rtEx) {
throw wrapExceptionIfDockerConnectionFailed(rtEx);
}
}
/** Read the Docker container logs and write them to standard out. */
public void streamLogsForContainer() {
try {
dockerClient
.logContainerCmd(containerId)
.withStdOut(true)
.withStdErr(true)
.withFollowStream(true)
.withTailAll()
.exec(new LogContainerCommandCallback());
} catch (RuntimeException rtEx) {
throw wrapExceptionIfDockerConnectionFailed(rtEx);
}
}
/** Helper class for reading Docker container logs into a string. */
private static class LogContainerCommandCallback extends ResultCallback.Adapter<Frame> {
protected final StringBuffer log = new StringBuffer();
List<Frame> framesList = new ArrayList<>();
// these two boolean flags are useful for debugging
// buildSingleStringOutput = concatenate the output into a single String (be careful of very
// long outputs)
boolean buildSingleStringOutput;
// buildFramesList = keep a list of all the output lines (frames) as they come back
boolean buildFramesList;
public LogContainerCommandCallback() {
this(false, false);
}
public LogContainerCommandCallback(boolean buildSingleStringOutput, boolean buildFramesList) {
this.buildSingleStringOutput = buildSingleStringOutput;
this.buildFramesList = buildFramesList;
}
@Override
public void onNext(Frame frame) {
String logStr = new String(frame.getPayload(), StandardCharsets.UTF_8);
PrintStream err = Printer.getErr();
err.print(logStr);
err.flush();
if (buildSingleStringOutput) {
log.append(logStr);
}
if (buildFramesList) {
framesList.add(frame);
}
}
@Override
public String toString() {
return log.toString();
}
public List<Frame> getFramesList() {
return framesList;
}
}
/**
* Check if the given exception indicates that connecting to the Docker daemon failed. This
* usually means that Docker is either not installed or not running.
*
* <p>- If this exception was caused by a Docker connection failure, then this method wraps the
* given exception in a new RuntimeException with a more readable error message. Previously, it
* was an obscure connection refused error.
*
* <p>- If this exception was NOT caused by a Docker connection failure, then this method returns
* the given exception, unchanged.
*
* @param ex exception to check
* @return a RuntimeException for the caller to re-throw
*/
private RuntimeException wrapExceptionIfDockerConnectionFailed(RuntimeException ex) {
boolean isDockerConnectionFailed =
ex.getCause() != null
&& ex.getCause() instanceof IOException
&& ex.getCause().getMessage() != null
&& (ex.getCause().getMessage().contains("Connection refused")
|| ex.getCause().getMessage().contains("native connect() failed"));
if (isDockerConnectionFailed) {
return new UserActionableException(
"Connecting to Docker daemon failed. Check that Docker is installed and running.", ex);
} else {
return ex;
}
}
}
|
package br.com.caelum.brutal.sanitizer;
import org.owasp.html.HtmlPolicyBuilder;
import org.owasp.html.PolicyFactory;
public class HtmlSanitizer {
private static final PolicyFactory
POLICY = new HtmlPolicyBuilder()
.allowElements("a", "p", "pre", "code", "img", "kbd", "ol", "ul",
"li", "strong", "h2", "blockquote", "hr")
.allowUrlProtocols("https", "http")
.allowAttributes("href").onElements("a")
.allowAttributes("class").onElements("pre")
.allowAttributes("src", "alt", "width", "height").onElements("img")
.requireRelNofollowOnLinks()
.toFactory();
public static String sanitize(String html){
return POLICY.sanitize(html);
}
}
|
package br.com.livreprogramacao.entity.ticket;
import br.com.livreprogramacao.entity.base.EntityBase;
import br.com.livreprogramacao.entity.marca.Marca;
import br.com.livreprogramacao.entity.modelo.Modelo;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
/**
*
* @author user
*/
@Entity
public class Ticket extends EntityBase {
private String numero;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Marca marca;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Modelo modelo;
private String placa;
public Ticket() {
}
public Ticket(Long id, Marca marca, Modelo modelo, String placa) {
this.id = id;
this.marca = marca;
this.modelo = modelo;
this.placa = placa;
}
@Override
public String toString() {
return "Ticket{" + "numero=" + numero + ", marca=" + marca + ", modelo=" + modelo + ", placa=" + placa + '}';
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public Marca getMarca() {
return marca;
}
public void setMarca(Marca marca) {
this.marca = marca;
}
public Modelo getModelo() {
return modelo;
}
public void setModelo(Modelo modelo) {
this.modelo = modelo;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
}
|
package ch.bind.philib.net.tcp;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicLong;
import ch.bind.philib.io.Ring;
import ch.bind.philib.io.RingImpl;
import ch.bind.philib.lang.ExceptionUtil;
import ch.bind.philib.net.context.NetContext;
import ch.bind.philib.net.events.EventHandlerBase;
import ch.bind.philib.net.events.EventUtil;
import ch.bind.philib.validation.Validation;
class TcpStreamEventHandler extends EventHandlerBase {
private static final boolean doWriteTimings = false;
private static final boolean doReadTimings = false;
private static final int IO_READ_LIMIT_PER_ROUND = 16 * 1024;
private static final int IO_WRITE_LIMIT_PER_ROUND = 16 * 1024;
private final AtomicLong rx = new AtomicLong(0);
private final AtomicLong tx = new AtomicLong(0);
private final SocketChannel channel;
private final NetContext context;
private final TcpConnection connection;
private final Ring<Buf> writeBacklog = new RingImpl<Buf>();
private boolean registeredForWriteEvt = false;
private TcpStreamEventHandler(NetContext context, TcpConnection connection, SocketChannel channel) {
super();
Validation.notNull(context);
Validation.notNull(connection);
Validation.notNull(channel);
this.context = context;
this.connection = connection;
this.channel = channel;
}
@Override
public SelectableChannel getChannel() {
return channel;
}
@Override
public void handleRead() throws IOException {
doRead();
}
@Override
public void handleWrite() throws IOException {
long s = System.nanoTime();
sendNonBlocking(null);
long t = System.nanoTime() - s;
if (t > 1000000L) { // 1ms
System.out.printf("handleWrite took %.6fms%n", (t / 1000000f));
}
}
@Override
public void close() {
context.getEventDispatcher().unregister(this);
try {
if (channel.isOpen()) {
channel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
writeBacklog.clear();
connection.notifyClosed();
}
void sendNonBlocking(final ByteBuffer data) throws IOException {
synchronized (writeBacklog) {
// write as much as possible until the os-buffers are full or the
// write-per-round limit is reached
boolean finished = s_sendPendingNonBlock();
if (!finished) {
s_copyIntoBacklog(data);
registerForWriteEvents();
return;
}
// all data in the backlog has been written
// this means that the write backlog is empty
Validation.isTrue(writeBacklog.isEmpty());
if (data != null) {
_channelWrite(data);
if (data.hasRemaining()) {
s_copyIntoBacklog(data);
registerForWriteEvents();
return;
}
}
// backlog and input buffer written
unregisterFromWriteEvents();
// notify blocking writes
writeBacklog.notifyAll();
}
}
void sendBlocking(final ByteBuffer data) throws IOException, InterruptedException {
if (connection.getContext().getEventDispatcher().isEventDispatcherThread(Thread.currentThread())) {
throw new IllegalStateException("cant write in blocking mode from the dispatcher thread");
}
// first the remaining data in the backlog has to be written (if
// any), then our buffer
// if in the meantime more data arrives we do not want to block
// longer
final Buf externBuf = new ExternBuf(data);
synchronized (writeBacklog) {
writeBacklog.addBack(externBuf);
do {
boolean finished = s_sendPendingNonBlock();
if (finished) {
Validation.isFalse(externBuf.isPending());
// all data writes from the backlog have been written
// unregisterFromWriteEvents();
// notify other blocking writes
writeBacklog.notifyAll();
return;
} else {
if (externBuf.isPending()) {
writeBacklog.wait();
} else {
writeBacklog.notifyAll();
return;
}
}
} while (true);
}
}
private void s_copyIntoBacklog(final ByteBuffer src) {
if (src == null) {
return;
}
int srcRem = src.remaining();
while (srcRem > 0) {
ByteBuffer dst = acquireBuffer();
Buf buf = new InternBuf(dst);
int dstCap = dst.capacity();
if (dstCap >= srcRem) {
dst.put(src);
dst.flip();
assert (dst.remaining() == srcRem);
writeBacklog.addBack(buf);
return;
} else {
final int limit = src.limit();
int pos = src.position();
src.limit(pos + dstCap);
// remaining = limit - position
// remaining = (position + dstCap) - position;
// remaining = dstCap
Validation.isTrue(src.remaining() == dstCap);
dst.put(src);
dst.flip();
assert (dst.remaining() == dstCap);
writeBacklog.addBack(buf);
src.limit(limit);
srcRem -= dstCap;
}
}
}
// rv: true = all writes finished, false=blocked
private boolean s_sendPendingNonBlock() throws IOException {
int totalWrite = 0;
do {
final Buf pending = writeBacklog.poll();
if (pending == null) {
// finished
unregisterFromWriteEvents();
return true;
}
final ByteBuffer bb = pending.bb;
final int rem = bb.remaining();
if (rem == 0) {
releaseBuffer(pending);
} else {
final int num = _channelWrite(bb);
totalWrite += num;
if (num == rem) {
releaseBuffer(pending);
} else {
// write channel is blocked
writeBacklog.addFront(pending);
break;
}
}
} while (totalWrite < IO_WRITE_LIMIT_PER_ROUND);
registerForWriteEvents();
return false;
}
private int _channelWrite(final ByteBuffer data) throws IOException {
int num;
if (doWriteTimings) {
long tStart = System.nanoTime();
num = channel.write(data);
long t = System.nanoTime() - tStart;
if (t > 2000000L) {
System.out.printf("write took %.6fms%n", (t / 1000000f));
}
} else {
num = channel.write(data);
}
tx.addAndGet(num);
return num;
}
private int _channelRead(final ByteBuffer rbuf) throws IOException {
int num;
if (doReadTimings) {
long tStart = System.nanoTime();
num = channel.read(rbuf);
long t = System.nanoTime() - tStart;
if (t > 2000000) {
System.out.printf("read took: %.6fms%n", (t / 1000000f));
}
} else {
num = channel.read(rbuf);
}
if (num > 0) {
rx.addAndGet(num);
}
return num;
}
private void doRead() throws IOException {
final ByteBuffer rbuf = acquireBuffer();
try {
int totalRead = 0;
while (totalRead < IO_READ_LIMIT_PER_ROUND) {
int num = _channelRead(rbuf);
if (num == -1) {
// connection closed
close();
return;
} else if (num == 0) {
// no more data to read
return;
} else {
rbuf.flip();
assert (num == rbuf.limit());
assert (num == rbuf.remaining());
totalRead += num;
try {
connection.receive(rbuf);
} catch (Exception e) {
System.err.println("TODO: " + ExceptionUtil.buildMessageChain(e));
e.printStackTrace(System.err);
close();
}
}
}
} finally {
releaseBuffer(rbuf);
}
}
private ByteBuffer acquireBuffer() {
return context.getBufferCache().acquire();
}
private void releaseBuffer(final ByteBuffer buf) {
context.getBufferCache().release(buf);
}
private void releaseBuffer(final Buf buf) {
buf.finished();
if (buf.isIntern()) {
context.getBufferCache().release(buf.bb);
}
}
private void registerForWriteEvents() {
if (!registeredForWriteEvt) {
context.getEventDispatcher().reRegister(this, EventUtil.READ_WRITE, true);
registeredForWriteEvt = true;
}
}
private void unregisterFromWriteEvents() {
if (registeredForWriteEvt) {
context.getEventDispatcher().reRegister(this, EventUtil.READ, false);
registeredForWriteEvt = false;
}
}
public static TcpStreamEventHandler create(NetContext context, TcpConnection connection, SocketChannel channel) {
TcpStreamEventHandler rv = new TcpStreamEventHandler(context, connection, channel);
context.getEventDispatcher().register(rv, EventUtil.READ);
return rv;
}
long getRx() {
return rx.get();
}
long getTx() {
return tx.get();
}
private static abstract class Buf {
private final ByteBuffer bb;
private boolean pending = true;
abstract boolean isIntern();
Buf(ByteBuffer bb) {
this.bb = bb;
}
final void finished() {
pending = false;
}
final boolean isPending() {
return pending;
}
}
private static final class InternBuf extends Buf {
InternBuf(ByteBuffer bb) {
super(bb);
}
@Override
boolean isIntern() {
return true;
}
}
private static final class ExternBuf extends Buf {
ExternBuf(ByteBuffer bb) {
super(bb);
}
@Override
boolean isIntern() {
return false;
}
}
}
|
package com.advancedpwr.record.inspect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.advancedpwr.record.AccessPath;
import com.advancedpwr.record.InstanceTree;
import com.advancedpwr.record.RecorderException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BeanInspector extends Inspector
{
private Logger log = LoggerFactory.getLogger(BeanInspector.class);
protected List<Method> sortedMethods()
{
Method[] methods = objectClass().getMethods();
List list = Arrays.asList( methods );
Collections.sort( list, new MethodNameComparator() );
Collections.sort( list, new CollectionMethodComparator() );
Collections.sort( list, new MapMethodComparator() );
Collections.sort( list, new ArrayMethodComparator() );
return list;
}
public void inspect( InstanceTree inTree )
{
setInstanceTree( inTree );
List<Method> methods = sortedMethods();
for ( Method method : methods )
{
setCurrentMethod( method );
addMethodAccessPath();
}
}
protected void addMethodAccessPath()
{
if ( isSetter() && hasGetterMethod() )
{
Method getter = getterMethod();
Object result = invoke( getter );
//handle the case where we have multiple getters with different parameter types but one setter
if ( result != null && (getCurrentMethod().getParameterTypes()[0].isPrimitive() || getCurrentMethod().getParameterTypes()[0].isAssignableFrom(result.getClass())))
{
addAccessPathForResult( result );
}
}
}
protected void addAccessPathForResult( Object result )
{
AccessPath path = createAccessorMethodPath( result );
addAccessPath( path );
}
protected AccessPath createAccessorMethodPath( Object result )
{
AccessorMethodPath accessor = new AccessorMethodPath();
accessor.setSetter( getCurrentMethod() );
InstanceTree tree = createInstanceTree( result );
accessor.setTree( tree );
debug( "created accessor " + accessor + " for result " + result );
return accessor;
}
protected boolean isSetter()
{
Method method = getCurrentMethod();
return Modifier.isPublic( method.getModifiers() ) && method.getName().startsWith( "set" ) && method.getParameterTypes().length == 1;
}
protected String getterName()
{
if( boolean.class.equals( getCurrentMethod().getParameterTypes()[0] ) )
{
return getCurrentMethod().getName().replaceFirst( "set", "is" );
}
return getCurrentMethod().getName().replaceFirst( "set", "get" );
}
protected Method getterMethod()
{
Method[] methods = objectClass().getMethods();
for ( int i = 0; i < methods.length; i++ )
{
Method method = methods[i];
if ( isGetter( method ) )
{
return method;
}
}
return null;
}
protected boolean isGetter( Method method )
{
String name = method.getName();
//trim out 'set'
String setterName = getCurrentMethod().getName().substring(3);
if(name.startsWith("is")) {
name = name.substring(2);
} else if(name.startsWith("get")) {
name = name.substring(3);
}
return name.equals(setterName) && method.getParameterTypes().length == 0 && !Modifier.isStatic( method.getModifiers() );
}
protected boolean hasGetterMethod()
{
return getterMethod() != null;
}
protected Method getCurrentMethod()
{
return getInstanceTree().getCurrentMethod();
}
protected void setCurrentMethod( Method currentMethod )
{
getInstanceTree().setCurrentMethod( currentMethod );
}
protected Object invoke( Method getter )
{
try
{
return getter.invoke( getObject() );
}
catch (InvocationTargetException e )
{
log.warn("Error invoking getter " + getter + ". Method will return null", e.getCause());
return null;
}
catch(Exception ex) {
throw new RecorderException(ex);
}
}
}
|
package com.akiban.server.entity.changes;
import com.akiban.ais.model.AISBuilder;
import com.akiban.ais.model.AkibanInformationSchema;
import com.akiban.ais.model.Column;
import com.akiban.ais.model.Index;
import com.akiban.ais.model.Join;
import com.akiban.ais.model.TableName;
import com.akiban.ais.model.Type;
import com.akiban.ais.model.Types;
import com.akiban.ais.model.UserTable;
import com.akiban.server.entity.model.AbstractEntityVisitor;
import com.akiban.server.entity.model.Attribute;
import com.akiban.server.entity.model.Entity;
import com.akiban.server.entity.model.EntityColumn;
import com.akiban.server.entity.model.EntityIndex;
import com.akiban.server.entity.model.Validation;
import com.google.common.collect.BiMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class EntityToAIS extends AbstractEntityVisitor {
private static final Logger LOG = LoggerFactory.getLogger(EntityToAIS.class);
private static final boolean ATTR_REQUIRED_DEFAULT = true;
private static final Index.JoinType GI_JOIN_TYPE_DEFAULT = Index.JoinType.LEFT;
private final String schemaName;
private final AISBuilder builder = new AISBuilder();
private final List<TableInfo> tableInfoStack = new ArrayList<>();
private TableName groupName = null;
private TableInfo curTable = null;
private Set<String> uniqueValidations = new HashSet<>();
public EntityToAIS(String schemaName) {
this.schemaName = schemaName;
}
// EntityVisitor
@Override
public void visitEntity(String name, Entity entity) {
builder.createGroup(name, schemaName);
groupName = new TableName(schemaName, name);
beginTable(name, entity.uuid());
builder.addTableToGroup(groupName, schemaName, name);
}
@Override
public void leaveEntity() {
curTable = null;
groupName = null;
uniqueValidations.clear();
}
@Override
public void visitScalar(String name, Attribute scalar) {
String typeName = scalar.getType();
Type type = builder.akibanInformationSchema().getType(typeName);
Long params[] = getTypeParams(type, scalar.getProperties());
String charAndCol[] = getCharAndCol(type, scalar.getProperties());
boolean isNullable = !ATTR_REQUIRED_DEFAULT;
boolean isAutoInc = false;
if(scalar.isSpinal()) {
isNullable = false;
addSpinalColumn(name, scalar.getSpinePos());
}
Column column = builder.column(schemaName, curTable.name,
name, curTable.nextColPos++,
typeName, params[0], params[1],
isNullable, isAutoInc,
charAndCol[0], charAndCol[1]);
column.setUuid(scalar.getUUID());
visitScalarValidations(column, scalar.getValidation());
}
@Override
public void visitCollection(String name, Attribute collection) {
TableInfo parent = curTable;
beginTable(name, collection.getUUID());
parent.childTables.add(curTable);
}
@Override
public void leaveCollection() {
endTable();
}
@Override
public void leaveEntityAttributes() {
endTable();
builder.basicSchemaIsComplete();
builder.groupingIsComplete();
}
@Override
public void visitEntityValidations(Set<Validation> validations) {
for(Validation v : validations) {
if("unique".equals(v.getName())) {
String indexName = (String)v.getValue();
uniqueValidations.add(indexName);
} else {
LOG.warn("Ignored entity validation on {}: {}", groupName, v);
}
}
}
@Override
public void visitIndexes(BiMap<String, EntityIndex> indexes) {
for(Map.Entry<String,EntityIndex> entry : indexes.entrySet()) {
String indexName = entry.getKey();
List<EntityColumn> columns = entry.getValue().getColumns();
boolean isGI = isMultiTable(columns);
boolean isUnique = uniqueValidations.contains(indexName);
if(isGI) {
if(isUnique) {
throw new IllegalArgumentException("Unique group index not allowed");
}
builder.groupIndex(groupName, indexName, false, GI_JOIN_TYPE_DEFAULT);
int pos = 0;
for(EntityColumn col : columns) {
builder.groupIndexColumn(groupName, indexName, schemaName, col.getTable(), col.getColumn(), pos++);
}
} else {
builder.index(schemaName, columns.get(0).getTable(), indexName, isUnique, Index.KEY_CONSTRAINT);
int pos = 0;
for(EntityColumn col : columns) {
builder.indexColumn(schemaName, col.getTable(), indexName, col.getColumn(), pos++, true, null);
}
}
}
}
// EntityToAIS
public AkibanInformationSchema getAIS() {
return builder.akibanInformationSchema();
}
// Helpers
private void addSpinalColumn(String name, int spinePos) {
while(curTable.spinalCols.size() <= spinePos) {
curTable.spinalCols.add(null);
}
curTable.spinalCols.set(spinePos, name);
}
private void beginTable(String name, UUID uuid) {
UserTable table = builder.userTable(schemaName, name);
table.setUuid(uuid);
curTable = new TableInfo(name, table);
tableInfoStack.add(curTable);
}
private void endTable() {
// Create joins to children.
// Parent spinal columns are automatically propagated to each child.
if(curTable.spinalCols.isEmpty() && !curTable.childTables.isEmpty()) {
throw new IllegalArgumentException("Has collections but no spine: " + curTable.name);
}
for(TableInfo child : curTable.childTables) {
String joinName = child.name + "_" + curTable.name;
builder.joinTables(joinName, schemaName, curTable.name, schemaName, child.name);
for(String parentColName : curTable.spinalCols) {
Column parentCol = curTable.table.getColumn(parentColName);
String childColName = createColumnName(child.table.getColumns(), parentColName + "_ref");
Column newCol = Column.create(child.table, parentCol, childColName, child.nextColPos++);
// Should be exactly the same *except* UUID
newCol.setUuid(null);
builder.joinColumns(joinName,
schemaName, curTable.name, parentColName,
schemaName, child.name, childColName);
}
}
if(tableInfoStack.size() == 1) {
// Create PKs at the end (root to leaf) so IDs are ordered as such. Shouldn't matter but is safe.
createPrimaryKeys(builder, schemaName, curTable);
addJoinsToGroup(builder, groupName, curTable);
}
tableInfoStack.remove(tableInfoStack.size() - 1);
curTable = tableInfoStack.isEmpty() ? null : tableInfoStack.get(tableInfoStack.size() - 1);
}
private void visitScalarValidations(Column column, Collection<Validation> validations) {
for(Validation v : validations) {
if("required".equals(v.getName())) {
boolean isRequired = (Boolean)v.getValue();
column.setNullable(!isRequired);
} else {
LOG.warn("Ignored scalar validation on table {}: {}", curTable, v);
}
}
}
private static void addJoinsToGroup(AISBuilder builder, TableName groupName, TableInfo curTable) {
for(TableInfo child : curTable.childTables) {
List<Join> joins = child.table.getCandidateParentJoins();
assert joins.size() == 1 : joins;
builder.addJoinToGroup(groupName, joins.get(0).getName(), 0);
addJoinsToGroup(builder, groupName, child);
}
}
private static String createColumnName(List<Column> curColumns, String proposed) {
int offset = 1;
String newName = proposed;
for(int i = 0; i < curColumns.size(); ++i) {
if(curColumns.get(i).getName().equals(newName)) {
newName = proposed + "$" + offset++;
i = -1;
}
}
return newName;
}
private static void createPrimaryKeys(AISBuilder builder, String schemaName, TableInfo table) {
if(!table.spinalCols.isEmpty()) {
builder.index(schemaName, table.name, Index.PRIMARY_KEY_CONSTRAINT, true, Index.PRIMARY_KEY_CONSTRAINT);
int pos = 0;
for(String column : table.spinalCols) {
builder.indexColumn(schemaName, table.name, Index.PRIMARY_KEY_CONSTRAINT, column, pos++, true, null);
}
}
for(TableInfo child : table.childTables) {
createPrimaryKeys(builder, schemaName, child);
}
}
private static Long[] getTypeParams(Type type, Map<String,Object> props) {
Long params[] = { null, null };
if(type == Types.DECIMAL || type == Types.U_DECIMAL) {
params[0] = maybeLong(props.get("precision"));
params[1] = maybeLong(props.get("scale"));
} else if(type == Types.CHAR || type == Types.VARCHAR || type == Types.BINARY || type == Types.VARBINARY) {
params[0] = maybeLong(props.get("max_length"));
}
return params;
}
private static String[] getCharAndCol(Type type, Map<String,Object> props) {
String charAndCol[] = { null, null };
if(Types.isTextType(type)) {
charAndCol[0] = maybeString(props.get("charset"));
charAndCol[1] = maybeString(props.get("collation"));
}
return charAndCol;
}
private static boolean isMultiTable(List<EntityColumn> columns) {
for(int i = 1; i < columns.size(); ++i) {
if(!columns.get(0).getTable().equals(columns.get(i).getTable())) {
return true;
}
}
return false;
}
private static Long maybeLong(Object o) {
return (o != null) ? ((Number)o).longValue() : null;
}
private static String maybeString(Object o) {
return (o != null) ? o.toString() : null;
}
private static class TableInfo {
public final String name;
public final UserTable table;
public final List<String> spinalCols;
public final List<TableInfo> childTables;
public int nextColPos;
public TableInfo(String name, UserTable table) {
this.name = name;
this.table = table;
this.spinalCols = new ArrayList<>();
this.childTables = new ArrayList<>();
}
@Override
public String toString() {
return name;
}
}
}
|
package com.akiban.server.types3.common.funcs;
import com.akiban.server.types3.LazyList;
import com.akiban.server.types3.TClass;
import com.akiban.server.types3.TExecutionContext;
import com.akiban.server.types3.TOverloadResult;
import com.akiban.server.types3.TScalar;
import com.akiban.server.types3.pvalue.PValueSource;
import com.akiban.server.types3.pvalue.PValueTarget;
import com.akiban.server.types3.texpressions.TInputSetBuilder;
import com.akiban.server.types3.texpressions.TScalarBase;
public class IsNull extends TScalarBase
{
public static TScalar create(TClass boolType)
{
return new IsNull(boolType);
}
private final TClass boolType;
private IsNull(TClass boolType)
{
this.boolType = boolType;
}
@Override
protected void buildInputSets(TInputSetBuilder builder)
{
builder.covers(null, 0);
}
@Override
protected boolean nullContaminates(int inputIndex) {
return false;
}
@Override
public void evaluate(TExecutionContext context, LazyList<? extends PValueSource> inputs, PValueTarget output)
{
output.putBool(inputs.get(0).isNull());
}
@Override
protected void doEvaluate(TExecutionContext context, LazyList<? extends PValueSource> inputs, PValueTarget output)
{
assert false : "should have called evaluate";
}
@Override
public String displayName()
{
return "IsNull";
}
@Override
public TOverloadResult resultType()
{
return TOverloadResult.fixed(boolType.instance());
}
}
|
package com.amee.service.profile;
import com.amee.domain.cache.CacheHelper;
import com.amee.domain.cache.CacheableFactory;
import com.amee.domain.data.DataCategory;
import com.amee.domain.profile.Profile;
import com.amee.domain.sheet.Sheet;
import com.amee.base.utils.ThreadBeanHolder;
import org.springframework.stereotype.Service;
import java.io.Serializable;
@Service
public class ProfileSheetService implements Serializable {
private CacheHelper cacheHelper = CacheHelper.getInstance();
ProfileSheetService() {
super();
}
public Sheet getSheet(CacheableFactory builder) {
return (Sheet) cacheHelper.getCacheable(builder);
}
public void removeSheets(Profile profile) {
cacheHelper.clearCache("ProfileSheets", "ProfileSheet_" + profile.getUid());
}
}
|
package com.areen.jlib.gui.fcb;
import com.areen.jlib.tuple.Pair;
import com.areen.jlib.util.Sise;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.AbstractListModel;
import javax.swing.MutableComboBoxModel;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
/**
* The only reason for this class is that we have to maintain two lists. One list is the list of ALL
* data records (fcbObjects), and the list of records that match the filter (super.objects).
*
* Note: this is almost a full-copy of the DefaultComboBoxModel. I could not subclass it because its
* "objects" ArrayList is not accessible...
*
* Also note that once we start using JDK 7 we will have to add type parameter E here.
*
* @author dejan
*/
public class FilteredComboBoxModel
extends AbstractListModel
implements MutableComboBoxModel, Serializable {
//ArrayList<E> objects; JDK 7
ArrayList objects;
Object selectedObject;
//private ArrayList<E> fcbObjects; JDK 7
private final ArrayList fcbObjects;
private String lastPattern = "";
private int keyFieldIndex = 0; /// The index of the (unique) key part of each item.
private boolean tableModelInUse = false;
AbstractTableModel tableModel;
private Object exactObject = null; /// If there is an exact match, here we hold a reference to the Object.
private int exactIndex = -1; /// If there is an exact match, here we hold the index of the Object.
private int[] columns;
/**
* Indicator whether cell editors should stop editing. This value is most useful in case when we want to
* pick the item with the mouse.
*/
private boolean readyToFinish = false;
private int keyIndex = 0; /// Index of a key in the SISE record.
/**
* Constructs an empty ArrayListModel object.
*/
public FilteredComboBoxModel() {
objects = new ArrayList();
fcbObjects = new ArrayList();
} // FilteredComboBoxModel constructor (default)
/**
* Constructs a ArrayListModel object initialized with
* an array of objects.
*
* @param items an array of Object objects
*/
public FilteredComboBoxModel(final Object[] items) {
//objects = new ArrayList<E>(); JDK 7
objects = new ArrayList();
objects.ensureCapacity(items.length);
int i, c;
for (i = 0, c = items.length; i < c; i++) {
//objects.addElement(items[i]);
objects.add(items[i]);
} // for
if (getSize() > 0) {
setSelectedItem(getElementAt(0));
}
// fcbObjects = new ArrayList<E>(); JDK 7
fcbObjects = new ArrayList();
fcbObjects.addAll(Arrays.asList(items));
} // FilteredComboBoxModel constructor
/**
* Be sure the type E is equal to Object[] when using this constructor!
*
* @param argAbstractTableModel
* @param columns An int[] array holding information what columns from the model we want to show in the
* combo-box. The first element in the columns array contains the index of the key field.
* @param argKeyFieldNumber
*/
public FilteredComboBoxModel(
AbstractTableModel argAbstractTableModel
, int[] argColumns) {
tableModelInUse = true;
tableModel = argAbstractTableModel;
columns = argColumns;
objects = new ArrayList();
objects.ensureCapacity(argAbstractTableModel.getRowCount());
fcbObjects = new ArrayList();
fcbObjects.ensureCapacity(argAbstractTableModel.getRowCount());
for (int i = 0; i < tableModel.getRowCount(); i++) {
//objects.addElement(items[i]);
Object[] row = new Object[tableModel.getColumnCount()];
for (int j = 0; j < tableModel.getColumnCount(); j++) {
row[j] = tableModel.getValueAt(i, j);
} // for
objects.add(row); // have to cast because Java will shout otherwise...
fcbObjects.add(row);
} // for
keyIndex = columns[0]; // by convention the first element in the columns array is the index of the key
if (getSize() > 0) {
setSelectedItem(getElementAt(0));
}
tableModel.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
int first;
int last;
switch (e.getType()) {
case TableModelEvent.INSERT:
System.out.println("FCBM: TableModel insert");
first = e.getFirstRow();
last = e.getLastRow();
//fcbObjects.add(first, getRow(first));
FilteredComboBoxModel.this.addElement(getRow(first));
break;
case TableModelEvent.DELETE:
System.out.println("FCBM: TableModel delete");
first = e.getFirstRow();
last = e.getLastRow();
break;
case TableModelEvent.UPDATE:
System.out.println("FCBM: TableModel update");
first = e.getFirstRow();
last = e.getLastRow();
objects.set(first, getRow(first));
fcbObjects.set(first, getRow(first));
break;
default:
// nothing
} // switch
} // tableChanged() method
}); // TableModelListener implementation (anonymous)
} // FilteredComboBoxModel constructor
/**
* Constructs a ArrayListModel object initialized with
* a ArrayList.
*
* @param v a ArrayList object ...
*/
public FilteredComboBoxModel(ArrayList v) {
objects = v;
if (getSize() > 0) {
selectedObject = getElementAt(0);
}
fcbObjects = new ArrayList();
fcbObjects.ensureCapacity(v.size());
for (Object obj : v) {
fcbObjects.add(obj);
} // foreach
} // // FilteredComboBoxModel constructor
// implements javax.swing.ComboBoxModel
/**
* Set the value of the selected item. The selected item may be null.
* <p>
* @param anObject The combo box value or null for no selection.
*/
@Override
public void setSelectedItem(Object anObject) {
if ((selectedObject != null && !selectedObject.equals(anObject))
|| selectedObject == null
&& anObject != null) {
selectedObject = anObject;
fireContentsChanged(this, -1, -1);
}
} // setSelectedItem() method
// implements javax.swing.ComboBoxModel
@Override
public Object getSelectedItem() {
return selectedObject;
}
// implements javax.swing.ListModel
@Override
public int getSize() {
return objects.size();
}
// implements javax.swing.ListModel
@Override
public Object getElementAt(int index) {
if (index >= 0 && index < objects.size()) {
//return objects.elementAt(index);
return objects.get(index);
} else {
return null;
}
}
/**
* Returns the index-position of the specified object in the list.
*
* @param anObject
* @return an int representing the index position, where 0 is
* the first position
*/
public int getIndexOf(Object anObject) {
return objects.indexOf(anObject);
}
// implements javax.swing.MutableComboBoxModel
@Override
public void addElement(Object anObject) {
//TODO: when an element is added to the combo box, we should check if it matches the filter or not!
//objects.addElement(anObject);
objects.add(anObject);
fcbObjects.add(anObject);
fireIntervalAdded(this, objects.size() - 1, objects.size() - 1);
if (objects.size() == 1 && selectedObject == null && anObject != null) {
setSelectedItem(anObject);
}
} // addElement() method
// implements javax.swing.MutableComboBoxModel
@Override
public void insertElementAt(Object anObject, int index) {
//objects.insertElementAt(anObject, index);
objects.add(index, anObject);
fireIntervalAdded(this, index, index);
}
// implements javax.swing.MutableComboBoxModel
@Override
public void removeElementAt(int index) {
if (getElementAt(index) == selectedObject) {
if (index == 0) {
setSelectedItem(getSize() == 1 ? null : getElementAt(index + 1));
} else {
setSelectedItem(getElementAt(index - 1));
}
}
//objects.removeElementAt(index);
objects.remove(index);
fireIntervalRemoved(this, index, index);
}
// implements javax.swing.MutableComboBoxModel
@Override
public void removeElement(Object anObject) {
int index = objects.indexOf(anObject);
if (index != -1) {
removeElementAt(index);
}
}
/**
* Empties the list.
*/
public void removeAllElements() {
if (objects.size() > 0) {
int firstIndex = 0;
int lastIndex = objects.size() - 1;
//objects.removeAllElements();
objects.clear();
selectedObject = null;
fireIntervalRemoved(this, firstIndex, lastIndex);
} else {
selectedObject = null;
}
}
/* backup copy
public void setPattern(String argPattern) {
Object exactObject = null;
int exactIndex = -1;
String copy = argPattern.trim();
if (lastPattern.equals(copy)) {
// we have the same pattern, probably with an additional space, no need for filtering.
System.out.println("DEBUG: (equal) setPattern(" + argPattern + ");");
return;
}
System.out.println("DEBUG: setPattern(" + argPattern + ");");
// record the size before we start modifying the filtered list of objects
int size1 = getSize();
if (!objects.isEmpty()) {
objects.clear();
}
if (argPattern.isEmpty()) {
// pattern contains no characters - might be erased, so we have to populate objects list.
objects.addAll(fcbObjects);
} else {
// Before we split, lets remove some special characters.
copy.replaceAll(" - ", " ");
// pattern contains at least one character
String[] strings = copy.split(" ");
boolean found;
Object obj = null;
for (int i = 0; i < fcbObjects.size(); i++) {
obj = fcbObjects.get(i);
int tst = check("in", obj);
System.out.println(tst);
found = true;
for (String str : strings) {
String itemAsString = null;
if (tableModelInUse) {
// if we use the table model, we have to convert an array of Objects to a String
// before we try to find the match.
itemAsString = Sise.record((Object[]) obj);
//itemAsString = ((Object[]) obj)[0].toString();
} else {
itemAsString = obj.toString();
} // else
// we are going to to AND found with true or false because we want objects that
// match all elements in the "strings" array of String objects.
if (itemAsString.toLowerCase().contains(str.toLowerCase())) {
found &= true;
} else {
found &= false;
}
} // foreach
if (found) {
// obj contains one of the strings in the pattern. Let's see if we have that object in
// filtered list. If not, we must add it.
objects.add(obj);
} // if
} // for
} // else
// get the size after filtering
int size2 = getSize();
System.out.println(size1 + ", " + size2);
if (size1 < size2) {
fireIntervalAdded(this, size1, size2 - 1);
fireContentsChanged(this, 0, size1 - 1);
} else if (size1 > size2) {
fireIntervalRemoved(this, size2, size1 - 1);
fireContentsChanged(this, 0, size2 - 1);
} else {
fireContentsChanged(this, 0, size2 - 1);
}
if (this.getSize() > 0) {
setSelectedItem(objects.get(0));
}
lastPattern = copy;
} // setPattern() method implementation
*/
public void setPattern(String argPattern) {
exactObject = null;
exactIndex = -1;
String copy = argPattern.trim();
if (lastPattern.equals(copy)) {
// we have the same pattern, probably with an additional space, no need for filtering.
//System.out.println("DEBUG: (equal) setPattern(" + argPattern + ");");
return;
}
//System.out.println("DEBUG: setPattern(" + argPattern + ");");
// record the size before we start modifying the filtered list of objects
int size1 = getSize();
if (!objects.isEmpty()) {
objects.clear();
}
boolean exactMatchFound = false;
if (argPattern.isEmpty()) {
// pattern contains no characters - might be erased, so we have to populate objects list.
objects.addAll(fcbObjects);
} else {
// Before we split, lets remove some special characters.
copy.replaceAll(" - ", " ");
// pattern contains at least one character
String[] strings = copy.split(" ");
boolean found;
Object obj = null;
int val = -1;
for (int i = 0; i < fcbObjects.size(); i++) {
obj = fcbObjects.get(i);
if (check(copy, obj) == 2) {
// we have an exact match!
exactObject = obj;
exactIndex = i;
exactMatchFound = true;
}
found = true;
for (String str : strings) {
val = check(str, obj);
found &= ((val == 1) || (val == 2));
} // foreach
if (found) {
//System.out.println("M(" + exactIndex + ")" + obj.toString());
objects.add(obj);
}
} // for
} // else
// get the size after filtering
int size2 = getSize();
System.out.println(size1 + ", " + size2);
if (size1 < size2) {
fireIntervalAdded(this, size1, size2 - 1);
fireContentsChanged(this, 0, size1 - 1);
} else if (size1 > size2) {
fireIntervalRemoved(this, size2, size1 - 1);
fireContentsChanged(this, 0, size2 - 1);
} else {
fireContentsChanged(this, 0, size2 - 1);
}
// Let's select appropriate item.
if (this.getSize() > 0) {
if (exactMatchFound) {
// if we had an exact match, select that item.
System.out.println("### Exact match found!");
System.out.println("(" + exactIndex + ")" + exactObject.toString());
setSelectedItem(exactObject);
} else {
// if we did not have an exact match, select the first item in the newly created list.
setSelectedIndex(0);
} // else
}
lastPattern = copy;
} // setPattern() method implementation
public Object lookupItem(String argPattern) {
if (argPattern.isEmpty()) {
return null;
}
Object selectedItem = getSelectedItem();
// only search for a different item if the currently selected does not match
if (selectedItem != null && startsWithIgnoreCase(selectedItem.toString(), argPattern)) {
return selectedItem;
} else {
// iterate over all items
for (int i = 0, n = getSize(); i < n; i++) {
Object currentItem = getElementAt(i);
// current item starts with the pattern?
if (startsWithIgnoreCase(currentItem.toString(), argPattern)) {
return currentItem;
}
} // for
} // else
// no item starts with the pattern => return null
return null;
}
// checks if str1 starts with str2 - ignores case
private boolean startsWithIgnoreCase(String str1, String str2) {
return str1.toUpperCase().startsWith(str2.toUpperCase());
}
public boolean isTableModelInUse() {
return tableModelInUse;
}
public void setTableModelInUse(boolean argTableModelInUse) {
tableModelInUse = argTableModelInUse;
}
public void setSelectedIndex(int argIndex) {
if (argIndex > -1 && argIndex < getSize()) {
setSelectedItem(objects.get(argIndex));
}
}
/**
* Use this method to objtain a reference to an object containing the key part of the Item. In the case
* our combo-box contains a list of Pairs, we will get the first element. In the case it is a list of
* Object[] arrays, then we use the columns array to get the index of the key.
* @return
*/
public Object getKeyOfTheSelectedItem() {
//System.out.println("getKeyOfTheSelectedItem()");
Object selected = getSelectedItem();
if (selected instanceof Pair) {
return ((Pair) selected).getFirst();
}
if (selected instanceof Object[]) {
// we assume whenever we deal with Object[] array, it came from a table model.
int idx = columns[0];
return ((Object[]) selected)[idx];
}
// in any other case we will convert object to String and check if it is a Sise record or not.
String str = selected.toString();
if (str.contains(Sise.UNIT_SEPARATOR_STRING)) {
// we deal with a Sise record
String[] units = Sise.units(str);
return units[0];
} else {
// If it is any other String, just simply return it.
return str;
} // else
} // getKeyOfTheSelectedItem() method
// Accessors
public boolean isReadyToFinish() {
return readyToFinish;
}
public void setReadyToFinish(boolean argReadyToFinish) {
readyToFinish = argReadyToFinish;
}
/**
* Use this method to obtain the index of the key in a SISE record.
*
* @return
*/
public int getKeyIndex() {
return keyIndex;
} // getKeyIndex() method
// Private methods
/**
* Use this method when you need to get all fields of a row in an AbstractTableModel as an array of
* Objects.
*
* @param argRowIndex
* @return
*/
private Object[] getRow(int argRowIndex) {
Object[] row = new Object[tableModel.getColumnCount()];
for (int j = 0; j < row.length; j++) {
row[j] = tableModel.getValueAt(argRowIndex, j);
}
return row;
}
/**
* This method acts as a "dispatcher" to appropriate check() function.
* @param argWhat
* @param argObject
* @return 0 - if not found, 1 - if found , 2 - if the exact match was found
*/
private int check(String argWhat, Object argObject) {
if (argObject instanceof Pair) {
return check(argWhat, (Pair) argObject);
}
if (argObject instanceof Object[]) {
return check(argWhat, (Object[]) argObject);
}
// fall back to using String
return check(argWhat, argObject.toString());
} // check() method
/**
* Checks for partial or exact match of argWhat within the argPair object.
* @param argWhat
* @param argString
* @return 0 - if there is no match, 1 - if argString contains argWhat or 2 if argString is equal
* to argWhat (case insensitive equality).
*/
private int check(String argWhat, Pair argPair) {
//System.out.println("PAIR: " + argWhat + " ? " + argPair.toString());
String left = argPair.getFirst() != null ? argPair.getFirst().toString() : null;
String right = argPair.getSecond() != null ? argPair.getSecond().toString() : "";
if (left == null && right == null) {
return 0;
}
if ((left != null && left.toLowerCase().equals(argWhat.toLowerCase()))
|| (right != null && right.toLowerCase().equals(argWhat.toLowerCase()))) {
// we have an exact match
return 2;
}
if ((left != null && left.toLowerCase().contains(argWhat.toLowerCase()))
|| (right != null && right.toLowerCase().contains(argWhat.toLowerCase()))) {
// we found a partial match
return 1;
}
return 0;
} // check() method
/**
* Checks for partial or exact match of argWhat within an array of Objects.
*
* @param argWhat
* @param argObjects
* @return 0 - if there is no match, 1 - if argString contains argWhat or 2 if argString is equal
* to argWhat (case insensitive equality).
*/
private int check(String argWhat, Object[] argObjects) {
//System.out.println("OBJECT[]: " + argWhat + " ? " + Sise.record(argObjects));
String str = null;
for (Object obj : argObjects) {
str = obj.toString();
if (str.equalsIgnoreCase(argWhat)) {
// we found an exact match
return 2;
}
if (str.toLowerCase().contains(argWhat.toLowerCase())) {
// we found a partial match
return 1;
}
} // foreach
return 0;
} // check() method
/**
* Checks for partial or exact match of argWhat within argString
* @param argWhat
* @param argString
* @return 0 - if there is no match, 1 - if argString contains argWhat or 2 if argString is equal
* to argWhat (case insensitive equality).
*/
private int check(String argWhat, String argString) {
//System.out.println("String: " + argWhat + " ? " + Sise.record(argObjects));
if (argString.equalsIgnoreCase(argWhat)) {
// we have an exact match
return 2;
}
if (argString.toLowerCase().contains(argWhat.toLowerCase())) {
// we found a partial match
return 1;
}
return 0;
} // check() method
} // FilteredComboBoxModel class
|
package com.booking.replication.applier;
import static com.codahale.metrics.MetricRegistry.name;
import static org.apache.kafka.common.protocol.Protocol.BROKER;
import com.booking.replication.Configuration;
import com.booking.replication.Metrics;
import com.booking.replication.augmenter.AugmentedRow;
import com.booking.replication.augmenter.AugmentedRowsEvent;
import com.booking.replication.augmenter.AugmentedSchemaChangeEvent;
import com.booking.replication.pipeline.PipelineOrchestrator;
import com.google.code.or.binlog.impl.event.FormatDescriptionEvent;
import com.google.code.or.binlog.impl.event.QueryEvent;
import com.google.code.or.binlog.impl.event.RotateEvent;
import com.google.code.or.binlog.impl.event.XidEvent;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Meter;
import org.apache.commons.lang.mutable.MutableLong;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
public class KafkaApplier implements Applier {
private final com.booking.replication.Configuration replicatorConfiguration;
private static long totalEventsCounter = 0;
private static long totalRowsCounter = 0;
private Properties props;
private KafkaProducer<String, String> producer;
private ProducerRecord<String, String> message;
private static List<String> topicList;
private static final Meter kafka_messages = Metrics.registry.meter(name("Kafka", "producerToBroker"));
private static final HashMap<String, MutableLong> stats = new HashMap<>();
private static final Logger LOGGER = LoggerFactory.getLogger(KafkaApplier.class);
public KafkaApplier(String broker, List<String> topics, Configuration configuration) {
replicatorConfiguration = configuration;
/**
* kafka.producer.Producer provides the ability to batch multiple produce requests (producer.type=async),
* before serializing and dispatching them to the appropriate kafka broker partition. The size of the batch
* can be controlled by a few config parameters. As events enter a queue, they are buffered in a queue, until
* either queue.time or batch.size is reached. A background thread (kafka.producer.async.ProducerSendThread)
* dequeues the batch of data and lets the kafka.producer.DefaultEventHandler serialize and send the data to
* the appropriate kafka broker partition.
*/
// Below is the new version of Configuration
props = new Properties();
props.put("bootstrap.servers", broker);
props.put("acks", "all"); // Default 1
props.put("retries", 1); // Default value: 0
props.put("batch.size", 16384); // Default value: 16384
props.put("linger.ms", 1); // Default 0, Artificial delay
props.put("buffer.memory", 33554432); // Default value: 33554432
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
producer = new KafkaProducer<>(props);
topicList = topics;
}
@Override
public void applyAugmentedRowsEvent(AugmentedRowsEvent augmentedSingleRowEvent, PipelineOrchestrator caller) {
for (AugmentedRow row : augmentedSingleRowEvent.getSingleRowEvents()) {
if (row.getTableName() == null) {
LOGGER.error("tableName not exists");
throw new RuntimeException("tableName does not exist");
}
String topic = row.getTableName();
if (topicList.contains(topic)) {
message = new ProducerRecord<>(topic, row.toJson());
totalRowsCounter ++;
producer.send(message);
if (totalRowsCounter % 500 == 0) {
LOGGER.info("500 lines have been sent to Kafka broker...");
}
kafka_messages.mark();
} else {
// LOGGER.warn("No supported topic: " + topic);
}
}
}
@Override
public void applyCommitQueryEvent(QueryEvent event) {
}
@Override
public void applyXidEvent(XidEvent event) {
}
@Override
public void applyRotateEvent(RotateEvent event) {
}
@Override
public void applyAugmentedSchemaChangeEvent(AugmentedSchemaChangeEvent augmentedSchemaChangeEvent, PipelineOrchestrator caller) {
}
@Override
public void forceFlush() {
}
@Override
public void resubmitIfThereAreFailedTasks() {
}
@Override
public void applyFormatDescriptionEvent(FormatDescriptionEvent event) {
}
@Override
public void waitUntilAllRowsAreCommitted() {
boolean wait = true;
while (wait) {
if (true) {
LOGGER.debug("All tasks have completed!");
wait = false;
} else {
resubmitIfThereAreFailedTasks();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
|
package com.btk5h.skriptmirror.skript;
import com.btk5h.skriptmirror.JavaType;
import org.bukkit.event.Event;
import java.util.Arrays;
import ch.njol.skript.expressions.base.PropertyExpression;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.UnparsedLiteral;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
public class ExprJavaTypeOf extends SimpleExpression<JavaType> {
static {
PropertyExpression.register(ExprJavaTypeOf.class, JavaType.class, "([java] class|java[ ]type)",
"objects");
}
private Expression<Object> target;
@Override
protected JavaType[] get(Event e) {
return Arrays.stream(target.getArray(e))
.map(Object::getClass)
.map(JavaType::new)
.toArray(JavaType[]::new);
}
@Override
public boolean isSingle() {
return target.isSingle();
}
@Override
public Class<? extends JavaType> getReturnType() {
return JavaType.class;
}
@Override
public String toString(Event e, boolean debug) {
return "class of " + target.toString(e, debug);
}
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed,
SkriptParser.ParseResult parseResult) {
target = (Expression<Object>) exprs[0];
return !(target instanceof UnparsedLiteral);
}
}
|
package com.cflint.listeners;
import javax.swing.ProgressMonitor;
public class ProgressMonitorListener implements ScanProgressListener {
int fileCounter = 0;
int totalFileCount = 1;
final ProgressMonitor progressMonitor;
boolean indeterminate = true;
public ProgressMonitorListener(final String progressLabel) {
super();
progressMonitor = new ProgressMonitor(null, progressLabel, "processing", 0, 1);
}
@Override
public void startedProcessing(final String srcidentifier) {
if (progressMonitor.isCanceled()) {
throw new RuntimeException("Cancelled by user");
}
if (indeterminate && fileCounter + 1 >= totalFileCount) {
totalFileCount += 10;
progressMonitor.setMaximum(totalFileCount);
}
progressMonitor.setProgress(fileCounter++);
progressMonitor.setNote("[" + fileCounter + "/" + totalFileCount + "] processing " + shorten(srcidentifier));
}
private String shorten(final String srcidentifier) {
if (srcidentifier == null) {
return "";
}
if (srcidentifier.length() < 80) {
return srcidentifier;
}
return srcidentifier.substring(0, 78) + "..";
}
@Override
public void finishedProcessing(final String srcidentifier) {
//Empty implementation
}
public void setTotalToProcess(final int total) {
indeterminate = false;
totalFileCount = total;
progressMonitor.setMaximum(total);
}
@Override
public void close() {
progressMonitor.close();
}
}
|
package com.codeborne.selenide.ex;
import static com.codeborne.selenide.ex.ErrorMessages.screenshot;
public class DialogTextMismatch extends AssertionError {
public DialogTextMismatch(String actualText, String expectedText) {
super("\nActual: " + actualText +
"\nExpected: " + expectedText +
screenshot());
}
@Override
public String toString() {
return getClass().getSimpleName() + ' ' + getMessage();
}
}
|
package com.conveyal.r5.analyst.scenario;
import com.conveyal.r5.transit.TransportNetwork;
import com.conveyal.r5.transit.TripPattern;
import com.conveyal.r5.transit.TripSchedule;
import com.google.common.primitives.Booleans;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Scale the speed of travel by a constant factor. That is, uniformly speed trips up or slow them down.
* This modification can also be applied to only part of a route by specifying a series of "hops", i.e.
* pairs of stops adjacent to one another in the pattern.
* We do not have an absolute speed parameter, only a scale parameter, because the server does not necessarily know
* the route alignment and the inter-stop distances to calculate travel times from speeds.
* You can specify either routes or trips to modify, but not both at once. Changing the speed of only some trips
* on a pattern does not cause problems like adding or removing stops does.
*/
public class AdjustSpeed extends Modification {
public static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(AdjustSpeed.class);
/** The routes which should be sped up or slowed down. */
public Set<String> routes;
/** Trips which should be sped up or slowed down. */
public Set<String> trips;
/** The multiplicative scale factor for speeds. */
public double scale = -1;
/**
* Which stops in the route serve as the fixed points around which trips are contracted or expanded.
* TODO Implement.
*/
public List<String> referenceStops;
/**
* Hops which should have their speed set or scaled. If not supplied, all hops should be modified.
* Each hop is a pair of adjacent stop IDs (from/to) and the hop specification is directional.
*/
public List<String[]> hops;
/**
* If true, the scale factor applies to both dwells and inter-stop rides. If false, dwells remain the
* same length and the scale factor only applies to rides.
*/
public boolean scaleDwells = false;
/** These are two parallel arrays of the same length, where (hopFromStops[i], hopToStops[i]) represents one hop. */
private transient TIntList hopFromStops;
private transient TIntList hopToStops;
@Override
public String getType() {
return "adjust-speed";
}
@Override
public boolean resolve(TransportNetwork network) {
if (scale <= 0) {
warnings.add("Scaling factor must be a positive number.");
}
hopFromStops = new TIntArrayList(hops.size());
hopToStops = new TIntArrayList(hops.size());
for (String[] pair: hops) {
if (pair.length != 2) {
warnings.add("Hops must all have exactly two stops.");
continue;
}
int intFromId = network.transitLayer.indexForStopId.get(pair[0]);
int intToId = network.transitLayer.indexForStopId.get(pair[1]);
if (intFromId == 0) { // FIXME should be -1 not 0
warnings.add("Could not find hop origin stop " + pair[0]);
continue;
}
if (intToId == 0) { // FIXME should be -1 not 0
warnings.add("Could not find hop destination stop " + pair[1]);
continue;
}
hopFromStops.add(intFromId);
hopToStops.add(intToId);
}
// Not bitwise operator: non-short-circuit logical XOR.
boolean onlyOneDefined = (routes != null) ^ (trips != null);
if (!onlyOneDefined) {
warnings.add("Routes or trips must be specified, but not both.");
}
return warnings.size() > 0;
}
@Override
public boolean apply(TransportNetwork network) {
network.transitLayer.tripPatterns = network.transitLayer.tripPatterns.stream()
.map(this::processTripPattern)
.collect(Collectors.toList());
return warnings.size() > 0;
}
private TripPattern processTripPattern (TripPattern originalPattern) {
if (routes != null && !routes.contains(originalPattern.routeId)) {
// This TripPattern is not on a route that has been chosen for adjustment.
return originalPattern;
}
// Avoid unnecessary new lists and cloning when no trips in this pattern are affected.
if (trips != null && originalPattern.tripSchedules.stream().noneMatch(s -> trips.contains(s.tripId))) {
return originalPattern;
}
// First, decide which hops in this pattern should be scaled.
boolean[] shouldScaleHop = new boolean[originalPattern.stops.length - 1];
if (hops == null) {
Arrays.fill(shouldScaleHop, true);
} else {
for (int i = 0; i < originalPattern.stops.length; i++) {
for (int j = 0; j < hopFromStops.size(); j++) {
if (originalPattern.stops[i] == hopFromStops.get(j)
&& originalPattern.stops[i + 1] == hopToStops.get(j)) {
shouldScaleHop[i] = true;
break;
}
}
}
}
if (!Booleans.contains(shouldScaleHop, true)) {
// No hops would be modified. Keep the original pattern unchanged.
return originalPattern;
}
// There are hops that will have their speed changed. Make a shallow protective copy of this TripPattern.
TripPattern pattern = originalPattern.clone();
double timeScaleFactor = 1/scale; // Invert speed coefficient to get time coefficient
int nStops = pattern.stops.length;
pattern.tripSchedules = new ArrayList<>();
for (TripSchedule originalSchedule : originalPattern.tripSchedules) {
if (trips != null && !trips.contains(originalSchedule.tripId)) {
// This trip has not been chosen for adjustment.
pattern.tripSchedules.add(originalSchedule);
continue;
}
TripSchedule newSchedule = originalSchedule.clone();
pattern.tripSchedules.add(newSchedule);
newSchedule.arrivals = new int[nStops];
newSchedule.departures = new int[nStops];
// Use a floating-point number to avoid accumulating integer truncation error.
double seconds = originalSchedule.arrivals[0];
for (int s = 0; s < nStops; s++) {
int dwellTime = originalSchedule.departures[s] - originalSchedule.arrivals[s];
newSchedule.arrivals[s] = (int) Math.round(seconds);
if (scaleDwells) {
seconds += dwellTime * timeScaleFactor;
} else {
seconds += dwellTime;
}
newSchedule.departures[s] = (int) Math.round(seconds);
if (s < nStops - 1) {
// We are not at the last stop in the pattern, so compute and optionally scale the following hop.
int rideTime = originalSchedule.arrivals[s + 1] - originalSchedule.departures[s];
if (shouldScaleHop[s]) {
seconds += rideTime * timeScaleFactor;
} else {
seconds += rideTime;
}
}
}
int originalTravelTime = originalSchedule.departures[nStops - 1] - originalSchedule.arrivals[0];
int updatedTravelTime = newSchedule.departures[nStops - 1] - newSchedule.arrivals[0];
LOG.debug("Total travel time on trip {} changed from {} to {} seconds.",
newSchedule.tripId, originalTravelTime, updatedTravelTime);
postSanityCheck(newSchedule);
}
LOG.debug("Scaled speeds (factor {}) for all trips on {}.", scale, originalPattern);
return pattern;
}
private static void postSanityCheck (TripSchedule schedule) {
// TODO check that modified trips still make sense after applying the modification
// This should be called in any Modification that changes a schedule.
}
}
|
package com.egf.db.services.impl;
import org.apache.log4j.Logger;
import com.egf.db.core.CreateTableCallback;
import com.egf.db.core.db.DbFactory;
import com.egf.db.core.db.DbInterface;
import com.egf.db.core.define.ColumnType;
import com.egf.db.core.define.column.ColumnDefine;
import com.egf.db.core.define.column.Comment;
import com.egf.db.core.define.column.Default;
import com.egf.db.core.define.column.NotNull;
import com.egf.db.core.define.column.PrimaryKey;
import com.egf.db.core.define.column.Unique;
import com.egf.db.core.define.name.ColumnName;
import com.egf.db.core.define.name.ForeignKeyName;
import com.egf.db.core.define.name.IndexName;
import com.egf.db.core.define.name.PrimaryKeyName;
import com.egf.db.core.define.name.TableName;
import com.egf.db.core.define.name.UniqueName;
import com.egf.db.core.jdbc.JdbcService;
import com.egf.db.core.jdbc.JdbcServiceImpl;
import com.egf.db.core.sql.template.Generate;
import com.egf.db.core.sql.template.GenerateFactory;
import com.egf.db.exception.MigrationException;
import com.egf.db.services.DatabaseService;
import com.egf.db.utils.StringUtils;
/**
* @author fangj
* @version $Revision: 2.0 $
* @since 1.0
*/
class DatabaseServiceImpl implements DatabaseService{
Logger logger=Logger.getLogger(DatabaseServiceImpl.class);
private final String PRIMARY_KEY="primary key";
private final String FOREIGN_KEY="foreign key";
private final String UNIQUE_KEY="unique";
private final String NOT_NULL="not null";
private final static String HANDLE_COLUMN_TYPE_ADD="add";
private final static String HANDLE_COLUMN_TYPE_CHANGE="change";
private JdbcService jdbcService=new JdbcServiceImpl();
private Generate generate=GenerateFactory.getGenerate();
void setJdbcService(JdbcService jdbcService){
this.jdbcService = jdbcService;
}
public void createTable(TableName tableName, Comment comment,CreateTableCallback createTableCallback)throws MigrationException {
TableImpl tmi=new TableImpl();
String tableComment="";
createTableCallback.doCreateAction(tmi);
StringBuffer columns=tmi.columns;
columns=columns.delete(columns.length()-2, columns.length());
String tn=tableName.getName();
if(tn.indexOf(".")!=-1){
DbInterface di=DbFactory.getDb();
String schema=tn.split("\\.")[0];
di.createSchema(schema);
}
String sql=String.format("create table %s (\n%s\n);",tableName.getName(),columns.toString());
if(comment!=null){
tableComment=GenerateFactory.getGenerate().changeTableComment(tableName.getName(),comment.getComment());
}
String commentsSql=tmi.comments.toString();
commentsSql=commentsSql.replaceAll("TN", tableName.getName());
logger.info("\n"+sql+"\n"+tableComment+"\n"+commentsSql.toString());
jdbcService.execute(sql+"\n"+tableComment+"\n"+commentsSql.toString());
}
public void createTable(TableName tableName, CreateTableCallback createTableCallback) throws MigrationException{
createTable(tableName, null, createTableCallback);
}
public void addColumn(TableName tableName, ColumnName columnName,ColumnType columnType, ColumnDefine... define) throws MigrationException{
String sql=this.handleColumn(HANDLE_COLUMN_TYPE_ADD, tableName, columnName, columnType, define);
logger.info("\n"+sql);
jdbcService.execute(sql);
}
public void changeColumn(TableName tableName, ColumnName columnName,ColumnDefine... define) throws MigrationException {
changeColumn(tableName, columnName,null, define);
}
public void changeColumn(TableName tableName, ColumnName columnName,ColumnType columnType, ColumnDefine... define)throws MigrationException {
String sql=this.handleColumn(HANDLE_COLUMN_TYPE_CHANGE, tableName, columnName, columnType, define);
logger.info("\n"+sql);
jdbcService.execute(sql);
}
public void addIndex(TableName tableName, ColumnName... columnName)throws MigrationException {
addIndex(tableName, null, columnName);
}
public void addIndex(TableName tableName, IndexName indexName,ColumnName... columnName) throws MigrationException{
String[] columnNames=new String[columnName.length];
String tn=tableName.getName();
String in=null;
String sql=null;
for (int i=0;i<columnName.length;i++) {
ColumnNameImpl columnImpl=(ColumnNameImpl)columnName[i];
columnNames[i]=columnImpl.getName();
}
if(indexName==null){
in=StringUtils.getUnionStringArray(columnNames, "_")+"_index";
if(in.length()>30){
for (String s : columnNames) {
in=in+s.charAt(0)+"_";
}
in=in+"index";
}
}else{
in=indexName.getName();
}
sql=generate.addIndex(tn, in, columnNames);
logger.info("\n"+sql);
jdbcService.execute(sql);
}
public void addPrimaryKey(PrimaryKeyName primaryKeyName, TableName tableName,ColumnName... columnName) throws MigrationException{
StringBuffer sb=new StringBuffer();
for (ColumnName cn : columnName) {
String sql=this.handleColumn(HANDLE_COLUMN_TYPE_CHANGE, tableName, cn, null,new NotNullImpl());
sb.append(sql+"\n");
}
String sql=addKey(primaryKeyName.getName(),tableName,null,PRIMARY_KEY,columnName);
sb.append(sql+"\n");
logger.info("\n"+sb.toString());
jdbcService.execute(sb.toString());
}
public void addForeignKey(ForeignKeyName foreignKeyName, TableName tableName,TableName refTableName,ColumnName... columnName) throws MigrationException{
String sql=addKey(foreignKeyName.getName(), tableName,refTableName,FOREIGN_KEY, columnName);
logger.info("\n"+sql);
jdbcService.execute(sql);
}
public void addUnique(UniqueName uniqueName, TableName tableName, ColumnName... columnName) throws MigrationException{
String sql=addKey(uniqueName.getName(), tableName,null,UNIQUE_KEY, columnName);
logger.info("\n"+sql);
jdbcService.execute(sql);
}
public void dropTable(TableName tableName) throws MigrationException{
String sql=generate.dropTalbe(tableName.getName());
logger.info("\n"+sql);
jdbcService.execute(sql);
}
public void dropColumn(TableName tableName,ColumnName columnName) throws MigrationException{
String tn=tableName.getName();
String cn=columnName.getName();
String sql=generate.dropColumn(tn, cn);
logger.info("\n"+sql);
jdbcService.execute(sql);
}
public void dropIndex(IndexName indexName) throws MigrationException{
String sql= generate.dropIndex(indexName.getName());
logger.info("\n"+sql);
jdbcService.execute(sql);
}
public void dropForeignKey(TableName tableName,ForeignKeyName foreignKeyName) throws MigrationException{
String sql=dropKey(tableName, foreignKeyName.getName());
logger.info("\n"+sql);
jdbcService.execute(sql);
}
public void dropPrimaryKey(TableName tableName) throws MigrationException{
DbInterface di=DbFactory.getDb();
String pkName=di.getPrimaryKeyName(tableName.getName());
String sql=dropKey(tableName, pkName);
logger.info("\n"+sql);
jdbcService.execute(sql);
}
public void dropUnique(TableName tableName,UniqueName uniqueName) throws MigrationException{
String sql=dropKey(tableName, uniqueName.getName());
logger.info("\n"+sql);
jdbcService.execute(sql);
}
public void renameColumn(TableName tableName, ColumnName oldColumnName,ColumnName newColumnName) {
DbInterface di=DbFactory.getDb();
String type=di.getColumnType(tableName.getName(), oldColumnName.getName());
String sql=generate.renameColumnName(tableName.getName(), oldColumnName.getName(), newColumnName.getName(),type);
logger.info("\n"+sql);
jdbcService.execute(sql);
}
/**
* ()
* @param handleType (add,change)
* @param tableName
* @param columnName
* @param columnType
* @param define
*/
private String handleColumn(String handleType,TableName tableName, ColumnName columnName,ColumnType columnType, ColumnDefine... define){
Default deft=null;
NotNull notNull=null;
Comment comment=null;
Unique unique=null;
String sql=null;
PrimaryKey primaryKey=null;
for (ColumnDefine columnDefine : define) {
if(columnDefine!=null){
if(columnDefine instanceof Default){
deft=(Default)columnDefine;
}else if(columnDefine instanceof NotNull){
notNull=(NotNull)columnDefine;
}else if (columnDefine instanceof Comment){
comment=(Comment)columnDefine;
}else if(columnDefine instanceof Unique){
unique=(Unique)columnDefine;
}else if(columnDefine instanceof PrimaryKey){
primaryKey=(PrimaryKey)columnDefine;
}
}
}
if(HANDLE_COLUMN_TYPE_ADD.equals(handleType)){
sql=generate.addColumn(tableName.getName(), columnName.getName(), columnType.getColumnType(),notNull==null?null:NOT_NULL, deft==null?null:deft.getValue(), comment==null?null:comment.getComment(), unique==null?null:UNIQUE_KEY, primaryKey==null?null:PRIMARY_KEY);
}else if(HANDLE_COLUMN_TYPE_CHANGE.equals(handleType)){
String type=DbFactory.getDb().getColumnType(tableName.getName(), columnName.getName());
sql= generate.changeColumn(tableName.getName(), columnName.getName(),type,notNull==null?null:NOT_NULL, deft==null?null:deft.getValue(), comment==null?null:comment.getComment());
}
return sql;
}
/**
*
* @param name
* @param tableName
* @param refTableName
* @param keyType
* @param columnName
* @return
*/
private String addKey(String name, TableName tableName,TableName refTableName, String keyType,ColumnName... columnName){
String[] columnNames=new String[columnName.length];
String sql=null;
String tn=tableName.getName();
for (int i=0;i<columnName.length;i++) {
ColumnNameImpl columnImpl=(ColumnNameImpl)columnName[i];
columnNames[i]=columnImpl.getName();
}
if(refTableName!=null){
DbInterface di=DbFactory.getDb();
String[] referencesColumns=di.getPrimaryKeyColumn(refTableName.getName());
String referencesColumn=StringUtils.getUnionStringArray(referencesColumns, ",");
sql=generate.addForeignKey(tn, name, refTableName.getName(), referencesColumn, columnNames);
}else{
sql=generate.addConstraint(tn, name, keyType, columnNames);
}
return sql;
}
/**
*
* @param tableName
* @param name
* @return
*/
private String dropKey(TableName tableName,String name){
String tn=tableName.getName();
String sql=generate.dropConstraint(tn, name);
return sql;
}
}
|
package com.flowpowered.networking.protocol;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import io.netty.buffer.ByteBuf;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.flowpowered.commons.Named;
import com.flowpowered.commons.StringToUniqueIntegerMap;
import com.flowpowered.commons.store.MemoryStore;
import com.flowpowered.networking.Codec;
import com.flowpowered.networking.Message;
import com.flowpowered.networking.MessageHandler;
import com.flowpowered.networking.exception.UnknownPacketException;
/**
* A {@code Protocol} stores {@link Message}s and their respective {@link Codec}s and {@link MessageHandler}s.
* It also stores to what port the protocol should be bound to.
*/
public abstract class Protocol implements Named {
private final CodecLookupService codecLookup;
private final HandlerLookupService handlerLookup;
private final String name;
private final int defaultPort;
private final Logger logger;
public Protocol(String name, int defaultPort, int maxPackets) {
this(name, defaultPort, maxPackets, LogManager.getLogger("Protocol." + name));
}
public Protocol(String name, int defaultPort, int maxPackets, Logger logger) {
this.name = name;
StringToUniqueIntegerMap dynamicPacketLookup = new StringToUniqueIntegerMap(null, new MemoryStore<Integer>(), maxPackets, maxPackets, this.name + "ProtocolDynamicPackets");
codecLookup = new CodecLookupService(dynamicPacketLookup, maxPackets);
handlerLookup = new HandlerLookupService();
this.defaultPort = defaultPort;
this.logger = logger;
}
/**
* Gets the handler lookup service associated with this Protocol
*
* @return the handler lookup service
*/
public HandlerLookupService getHandlerLookupService() {
return handlerLookup;
}
/**
* Gets the codec lookup service associated with this Protocol
*
* @return the codec lookup service
*/
public CodecLookupService getCodecLookupService() {
return codecLookup;
}
public <M extends Message, C extends Codec<M>, H extends MessageHandler<M>> C registerMessage(Class<C> codec, Class<H> handler) {
try {
C bind = codecLookup.bind(codec);
if (bind != null && handler != null) {
handlerLookup.bind(bind.getMessage(), handler);
}
return bind;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
logger.log(Level.ERROR, "Error registering codec " + codec + ": ", e);
return null;
}
}
/**
* Gets the name of the Protocol
*
* @return the name
*/
@Override
public String getName() {
return name;
}
/**
* The default port is the port used when autogenerating default bindings for this protocol and in the client when no port is given.
*
* @return The default port
*/
public int getDefaultPort() {
return defaultPort;
}
/**
* Returns the logger for this protocol.
*
* @return the logger
*/
public Logger getLogger() {
return logger;
}
/**
* Allows applying a wrapper to messages with dynamically allocated id's, in case this protocol needs to provide special treatment for them.
*
* @param dynamicMessage The message with a dynamically-allocated codec
* @return The new message
*/
public <T extends Message> Message getWrappedMessage(T dynamicMessage) throws IOException {
return dynamicMessage;
}
/**
* Read a packet header from the buffer. If a codec is not known, throw a {@link UnknownPacketException}
*
* @param buf The buffer to read from
* @return The correct codec
* @throws UnknownPacketException when the opcode does not have an associated codec
*/
public abstract Codec<?> readHeader(ByteBuf buf) throws UnknownPacketException;
/**
* Writes a packet header to a new buffer.
*
* @param codec The codec the message was written with
* @param data The data from the encoded message
* @param header the buffer which to write the header to
* @return The buffer with the packet header
*/
public abstract ByteBuf writeHeader(Codec<?> codec, ByteBuf data, ByteBuf header);
}
|
package com.github._1element.sc.domain; //NOSONAR
import com.github._1element.sc.events.RemoteCopyEvent;
import com.github._1element.sc.exception.FtpRemoteCopyException;
import com.github._1element.sc.properties.FtpRemoteCopyProperties;
import com.github._1element.sc.service.FileService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Map;
import java.util.TreeMap;
/**
* Copy surveillance image to ftp remote server (backup).
*/
@ConditionalOnProperty(name="sc.remotecopy.ftp.enabled", havingValue="true")
@Component
@Scope("prototype")
public class FtpRemoteCopy implements RemoteCopy {
private FileService fileService;
private FtpRemoteCopyProperties ftpRemoteCopyProperties;
private FTPClient ftp;
private long sizeRemoved = 0;
private long filesRemoved = 0;
private long totalSize = 0;
private static final String CRON_EVERY_DAY_AT_5_AM = "0 0 5 * * *";
private static final Logger LOG = LoggerFactory.getLogger(FtpRemoteCopy.class);
@Autowired
public FtpRemoteCopy(FtpRemoteCopyProperties ftpRemoteCopyProperties, FTPClient ftp, FileService fileService) {
this.ftpRemoteCopyProperties = ftpRemoteCopyProperties;
this.ftp = ftp;
this.fileService = fileService;
}
@Override
public void handle(RemoteCopyEvent remoteCopyEvent) {
LOG.debug("Ftp remote copy handler for '{}' invoked.", remoteCopyEvent.getFileName());
try {
connect();
transferFile(remoteCopyEvent.getFileName());
} catch (Exception e) {
LOG.warn("Error during remote ftp copy: {}", e.getMessage());
} finally {
disconnect();
}
}
@Override
@Scheduled(cron=CRON_EVERY_DAY_AT_5_AM)
public void cleanup() {
if (!ftpRemoteCopyProperties.isCleanupEnabled()) {
LOG.info("Ftp remote copy cleanup task is disabled in configuration.");
return;
}
try {
connect();
removeOldFiles();
} catch (Exception e) {
LOG.warn("Error during cleanup remote ftp images: {}", e.getMessage());
} finally {
disconnect();
}
}
/**
* Connect to ftp server.
*
* @throws FtpRemoteCopyException
* @throws IOException
*/
private void connect() throws FtpRemoteCopyException, IOException {
ftp.connect(ftpRemoteCopyProperties.getHost());
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
throw new FtpRemoteCopyException("Could not connect to remote ftp server '" + ftpRemoteCopyProperties.getHost() + "'. Response was: " + ftp.getReplyString());
}
if (!ftp.login(ftpRemoteCopyProperties.getUsername(), ftpRemoteCopyProperties.getPassword())) {
throw new FtpRemoteCopyException("Could not login to remote ftp server. Invalid username or password.");
}
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
}
/**
* Delete old files from ftp server.
* Files are deleted either if timestamp is too old or if quota is reached.
*
* @throws FtpRemoteCopyException
* @throws IOException
*/
private void removeOldFiles() throws FtpRemoteCopyException, IOException {
if (!ftp.changeWorkingDirectory(ftpRemoteCopyProperties.getDir())) {
throw new FtpRemoteCopyException("Could not change to directory '" + ftpRemoteCopyProperties.getDir() + "' on remote ftp server. Response was: " + ftp.getReplyString());
}
sizeRemoved = 0;
filesRemoved = 0;
totalSize = 0;
Map<Calendar, FTPFile> ftpFileMap = removeFilesByDate();
removeFilesByQuota(ftpFileMap);
LOG.info("Cleanup job deleted " + filesRemoved + " files with " + FileUtils.byteCountToDisplaySize(sizeRemoved) + " disk space.");
}
/**
* Remove files from ftp server that are older than the configured number of days.
* Returns map of still existing files on ftp after deletion.
*
* @return map of all ftp files left
* @throws IOException
*/
private Map<Calendar, FTPFile> removeFilesByDate() throws IOException {
Map<Calendar, FTPFile> ftpFileMap = new TreeMap<>();
FTPFile[] ftpFiles = ftp.listFiles();
for (FTPFile ftpFile : ftpFiles) {
if (ftpFile.isFile() && fileService.hasValidExtension(ftpFile.getName())) {
LocalDateTime removeBefore = LocalDateTime.now().minusDays(ftpRemoteCopyProperties.getCleanupKeep());
LocalDateTime ftpFileTimestamp = LocalDateTime.ofInstant(Instant.ofEpochMilli(ftpFile.getTimestamp().getTimeInMillis()), ZoneId.systemDefault());
if (ftpFileTimestamp.isBefore(removeBefore) && ftp.deleteFile(ftpFile.getName())) {
// delete straight if file is too old
LOG.debug("Successfully removed file '{}' on remote ftp server, was older than {} days.", ftpFile.getName(), ftpRemoteCopyProperties.getCleanupKeep());
sizeRemoved += ftpFile.getSize();
filesRemoved++;
} else {
// put to return map for deletion by quota
ftpFileMap.put(ftpFile.getTimestamp(), ftpFile);
totalSize += ftpFile.getSize();
}
}
}
return ftpFileMap;
}
/**
* Removes files from ftp server if configured quota has been reached.
*
* @param ftpFileMap map of ftp files to consider for deletion
* @throws IOException
*/
private void removeFilesByQuota(Map<Calendar, FTPFile> ftpFileMap) throws IOException {
if (totalSize < ftpRemoteCopyProperties.getCleanupMaxDiskSpace()) {
// do nothing if max disk space/quota has not been reached
return;
}
long sizeToBeRemoved = totalSize - ftpRemoteCopyProperties.getCleanupMaxDiskSpace();
for (Map.Entry<Calendar, FTPFile> entry: ftpFileMap.entrySet()) {
FTPFile ftpFile = entry.getValue();
if (ftp.deleteFile(ftpFile.getName())) {
LOG.debug("Successfully removed file '{}' on remote ftp server, quota was reached.", ftpFile.getName());
sizeRemoved += ftpFile.getSize();
filesRemoved++;
}
if (sizeRemoved >= sizeToBeRemoved) {
break;
}
}
}
/**
* Transfer file to ftp server.
*
* @param localFullFilepath full path to local file
* @throws FtpRemoteCopyException
* @throws IOException
*/
private void transferFile(String localFullFilepath) throws FtpRemoteCopyException, IOException {
File file = new File(localFullFilepath);
InputStream inputStream = new FileInputStream(file);
if (!ftp.storeFile(ftpRemoteCopyProperties.getDir() + file.getName(), inputStream)) {
throw new FtpRemoteCopyException("Could not upload file to remote ftp server. Response was: " + ftp.getReplyString());
}
LOG.info("File '{}' was successfully uploaded to remote ftp server.", file.getName());
}
/**
* Disconnect from ftp server.
*/
private void disconnect() {
if (ftp != null && ftp.isConnected()) {
try {
ftp.logout();
ftp.disconnect();
} catch (IOException e) {
// silently ignore disconnect exceptions
}
}
}
}
|
package com.github.jillesvangurp.osm2geojson;
import static com.github.jsonj.tools.JsonBuilder.array;
import static com.github.jsonj.tools.JsonBuilder.object;
import static com.github.jsonj.tools.JsonBuilder.primitive;
import static com.jillesvangurp.iterables.Iterables.consume;
import static com.jillesvangurp.iterables.Iterables.map;
import static com.jillesvangurp.iterables.Iterables.processConcurrently;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.xpath.XPathExpressionException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import com.github.jillesvangurp.common.ResourceUtil;
import com.github.jillesvangurp.mergesort.SortingWriter;
import com.github.jillesvangurp.metrics.StopWatch;
import com.github.jillesvangurp.osm2geojson.EntryJoiningIterable.JoinedEntries;
import com.github.jsonj.JsonArray;
import com.github.jsonj.JsonObject;
import com.github.jsonj.tools.JsonParser;
import com.jillesvangurp.iterables.ConcurrentProcessingIterable;
import com.jillesvangurp.iterables.LineIterable;
import com.jillesvangurp.iterables.PeekableIterator;
import com.jillesvangurp.iterables.Processor;
public class OsmJoin {
private static final Logger LOG = LoggerFactory.getLogger(OsmJoin.class);
private static final String NODE_ID_NODEJSON_MAP = "nodeid2rawnodejson.gz";
private static final String REL_ID_RELJSON_MAP = "relid2rawreljson.gz";
private static final String WAY_ID_WAYJSON_MAP = "wayid2rawwayjson.gz";
private static final String NODE_ID_WAY_ID_MAP = "nodeid2wayid.gz";
private static final String NODE_ID_REL_ID_MAP = "nodeid2relid.gz";
private static final String WAY_ID_REL_ID_MAP = "wayid2relid.gz";
private static final String WAY_ID_NODE_JSON_MAP = "wayid2nodejson.gz";
private static final String WAY_ID_COMPLETE_JSON = "wqyid2completejson.gz";
private static final String REL_ID_NODE_JSON_MAP = "relid2nodejson.gz";
private static final String REL_ID_JSON_WITH_NODES = "relid2jsonwithnodes.gz";
private static final String REL_ID_WAY_JSON_MAP = "relid2wayjson.gz";
private static final String REL_ID_COMPLETE_JSON = "relid2completejson.gz";
// choose a bucket size that will fit in memory. Larger means less bucket files and more ram are used.
private static final int BUCKET_SIZE = 100000;
final Pattern idPattern = Pattern.compile("id=\"([0-9]+)");
final Pattern latPattern = Pattern.compile("lat=\"([0-9]+(\\.[0-9]+)?)");
final Pattern lonPattern = Pattern.compile("lon=\"([0-9]+(\\.[0-9]+)?)");
final Pattern kvPattern = Pattern.compile("k=\"(.*?)\"\\s+v=\"(.*?)\"");
final Pattern ndPattern = Pattern.compile("nd ref=\"([0-9]+)");
final Pattern memberPattern = Pattern.compile("member type=\"(.*?)\" ref=\"([0-9]+)\" role=\"(.*?)\"");
private static final String OSM_XML = "/Users/jilles/data/brandenburg.osm.bz2";
private final String workDirectory;
private final JsonParser parser;
public OsmJoin(String workDirectory, JsonParser parser) {
this.workDirectory = workDirectory;
this.parser = parser;
try {
FileUtils.forceMkdir(new File(workDirectory));
} catch (IOException e) {
throw new IllegalStateException("cannot create dir " + workDirectory);
}
}
private String bucketDir(String file) {
return workDirectory + File.separatorChar + file + ".buckets";
}
private SortingWriter sortingWriter(String file) {
try {
return new SortingWriter(bucketDir(file), file, BUCKET_SIZE);
} catch (IOException e) {
throw new IllegalStateException("cannot create sorting writer " + file);
}
}
public void splitAndEmit(String osmFile) {
// create various sorted maps that need to be joined in the next steps
try (SortingWriter nodesWriter = sortingWriter(NODE_ID_NODEJSON_MAP)) {
try (SortingWriter nodeid2WayidWriter = sortingWriter(NODE_ID_WAY_ID_MAP)) {
try (SortingWriter waysWriter = sortingWriter(WAY_ID_WAYJSON_MAP)) {
try (SortingWriter relationsWriter = sortingWriter(REL_ID_RELJSON_MAP)) {
try (SortingWriter nodeId2RelIdWriter = sortingWriter(NODE_ID_REL_ID_MAP)) {
try (SortingWriter wayId2RelIdWriter = sortingWriter(WAY_ID_REL_ID_MAP)) {
try (LineIterable lineIterable = new LineIterable(ResourceUtil.bzip2Reader(OSM_XML));) {
OpenStreetMapBlobIterable osmIterable = new OpenStreetMapBlobIterable(lineIterable);
Processor<String, Boolean> processor = new Processor<String, Boolean>() {
@Override
public Boolean process(String blob) {
try {
if (blob.trim().startsWith("<node")) {
parseNode(nodesWriter, blob);
} else if (blob.trim().startsWith("<way")) {
parseWay(waysWriter, nodeid2WayidWriter, blob);
} else {
parseRelation(relationsWriter, nodeId2RelIdWriter, wayId2RelIdWriter, blob);
}
return true;
} catch (XPathExpressionException e) {
throw new IllegalStateException("invalid xpath!",e);
} catch (SAXException e) {
LOG.warn("parse error for " + blob);
return false;
}
}
};
try(ConcurrentProcessingIterable<String, Boolean> it = processConcurrently(osmIterable, processor, 1000, 9, 10000)) {
consume(it);
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void parseNode(SortingWriter nodeWriter, String input) throws XPathExpressionException, SAXException {
Matcher idm = idPattern.matcher(input);
Matcher latm = latPattern.matcher(input);
Matcher lonm = lonPattern.matcher(input);
Matcher kvm = kvPattern.matcher(input);
if (idm.find()) {
long id = Long.valueOf(idm.group(1));
if (latm.find() && lonm.find()) {
double latitude = Double.valueOf(latm.group(1));
double longitude = Double.valueOf(lonm.group(1));
// using a more compact notation for points here than the geojson point type. OSM has a billion+ nodes.
JsonObject node = object().put("id", id).put("l", array(longitude, latitude)).get();
JsonObject tags=new JsonObject();
while (kvm.find()) {
String name = kvm.group(1);
tags.put(name, kvm.group(2));
}
node.put("tags", tags);
nodeWriter.put("" + id, node.toString());
} else {
LOG.warn("no lat/lon for " + id);
}
} else {
LOG.warn("no id");
}
}
private void parseWay(SortingWriter waysWriter, SortingWriter nodeid2WayidWriter, String input) throws XPathExpressionException, SAXException {
Matcher idm = idPattern.matcher(input);
Matcher kvm = kvPattern.matcher(input);
Matcher ndm = ndPattern.matcher(input);
if (idm.find()) {
long wayId = Long.valueOf(idm.group(1));
JsonObject way = object().put("id", wayId).get();
JsonObject tags=new JsonObject();
while (kvm.find()) {
String name = kvm.group(1);
tags.put(name, kvm.group(2));
}
way.put("tags", tags);
JsonArray nodeRefs=array();
while (ndm.find()) {
Long nodeId = Long.valueOf(ndm.group(1));
nodeid2WayidWriter.put("" + nodeId, "" + wayId);
nodeRefs.add(primitive(nodeId));
}
way.put("ns", nodeRefs);
waysWriter.put("" + wayId, way.toString());
}
}
private void parseRelation(SortingWriter relationsWriter, SortingWriter nodeId2RelIdWriter, SortingWriter wayId2RelIdWriter, String input) throws XPathExpressionException, SAXException {
Matcher idm = idPattern.matcher(input);
Matcher kvm = kvPattern.matcher(input);
Matcher mm = memberPattern.matcher(input);
if (idm.find()) {
long relationId = Long.valueOf(idm.group(1));
JsonObject relation = object().put("id", relationId).get();
JsonObject tags=new JsonObject();
while (kvm.find()) {
String name = kvm.group(1);
tags.put(name, kvm.group(2));
}
relation.put("tags", tags);
JsonArray members = array();
while (mm.find()) {
String type = mm.group(1);
Long ref = Long.valueOf(mm.group(2));
String role = mm.group(3);
if ("way".equalsIgnoreCase(type)) {
members.add(object().put("id",ref).put("type", type).put("role", role).get());
wayId2RelIdWriter.put(""+ref, ""+relationId);
} else if ("node".equalsIgnoreCase(type)) {
members.add(object().put("id",ref).put("type", type).put("role", role).get());
nodeId2RelIdWriter.put(""+ref, ""+relationId);
}
}
relation.put("members", members);
relationsWriter.put(""+relationId, relation.toString());
}
}
public static <In, Out> void processIt(Iterable<In> iterable, Processor<In, Out> processor, int blockSize, int threads, int queueSize) {
try (ConcurrentProcessingIterable<In, Out> concIt = processConcurrently(iterable, processor, blockSize, threads, queueSize)) {
consume(concIt);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
static PeekableIterator<Entry<String,String>> peekableEntryIterable(Iterable<String> it) {
return new PeekableIterator<Entry<String,String>>(map(it, new EntryParsingProcessor()));
}
void createWayId2NodeJsonMap(String nodeId2wayIdFile, String nodeId2nodeJsonFile, String outputFile) {
try (SortingWriter out = sortingWriter(outputFile)) {
EntryJoiningIterable.join(nodeId2nodeJsonFile,nodeId2wayIdFile, new Processor<JoinedEntries, Boolean>() {
@Override
public Boolean process(JoinedEntries joined) {
String nodeJson = joined.left.get(0).getValue();
for(Entry<String, String> e: joined.right) {
String wayId = e.getValue();
out.put(wayId, nodeJson);
}
return true;
}
});
} catch (IOException e) {
throw new IllegalStateException("exception while closing sorted writer " + outputFile,e);
}
}
private void createWayId2CompleteJsonMap(String wayIdWayjsonMap, String wayIdNodeJsonMap, String outputFile) {
try (SortingWriter out = sortingWriter(outputFile)) {
EntryJoiningIterable.join(wayIdWayjsonMap,wayIdNodeJsonMap, new Processor<JoinedEntries, Boolean>() {
@Override
public Boolean process(JoinedEntries joined) {
HashMap<String, JsonObject> nodes = new HashMap<String, JsonObject>();
for(Entry<String, String> e: joined.right) {
JsonObject node = parser.parse(e.getValue()).asObject();
nodes.put(node.getString("id"), node);
}
Entry<String, String> wayEntry = joined.left.get(0);
JsonObject way=parser.parse(wayEntry.getValue()).asObject();
JsonArray nodeObjects = array();
for(long nodeId: way.getArray("ns").longs()) {
JsonObject node=nodes.get(""+nodeId);
if(node != null) {
nodeObjects.add(node);
} else {
way.getOrCreateArray("missingNodeRefs").add(primitive(nodeId));
}
}
way.put("nodes", nodeObjects);
way.remove("ns");
out.put(wayEntry.getKey(), way.toString());
return true;
}
});
} catch (IOException e) {
throw new IllegalStateException("exception while closing sorted writer " + outputFile ,e);
}
}
private void createRelid2NodeJsonMap(String nodeIdRelIdMap, String nodeIdNodejsonMap, String outputFile) {
try (SortingWriter out = sortingWriter(outputFile)) {
EntryJoiningIterable.join(nodeIdRelIdMap,nodeIdNodejsonMap, new Processor<JoinedEntries, Boolean>() {
@Override
public Boolean process(JoinedEntries joined) {
String nodeJson = joined.right.get(0).getValue();
for(Entry<String, String> e: joined.left) {
String relId = e.getValue();
out.put(relId, nodeJson);
}
return true;
}
});
} catch (IOException e) {
throw new IllegalStateException("exception while closing sorted writer " + outputFile ,e);
}
}
private void createRelid2JsonWithNodes(String relIdReljsonMap, String relIdNodeJsonMap, String outputFile) {
try (SortingWriter out = sortingWriter(outputFile)) {
EntryJoiningIterable.join(relIdReljsonMap,relIdNodeJsonMap, new Processor<JoinedEntries, Boolean>() {
@Override
public Boolean process(JoinedEntries joined) {
JsonArray nodes = array();
for(Entry<String, String> e: joined.right) {
JsonObject nodeJson = parser.parse(e.getValue()).asObject();
nodes.add(nodeJson);
}
for(Entry<String, String> e: joined.left) {
JsonObject relJson = parser.parse(e.getValue()).asObject();
relJson.put("nodes", nodes);
out.put(e.getKey(), relJson.toString());
}
return true;
}
});
} catch (IOException e) {
throw new IllegalStateException("exception while closing sorted writer " + outputFile ,e);
}
}
private void createRelId2WayJsonMap(String wayIdRelIdMap, String wayIdWayjsonMap, String outputFile) {
try (SortingWriter out = sortingWriter(outputFile)) {
EntryJoiningIterable.join(wayIdRelIdMap,wayIdWayjsonMap, new Processor<JoinedEntries, Boolean>() {
@Override
public Boolean process(JoinedEntries joined) {
String wayJson = joined.right.get(0).getValue();
for(Entry<String, String> e: joined.left) {
String relId = e.getValue();
out.put(relId, wayJson);
}
return true;
}
});
} catch (IOException e) {
throw new IllegalStateException("exception while closing sorted writer " + outputFile ,e);
}
}
private void createRelId2CompleteJson(String relIdJsonWithNodes, String relIdWayJsonMap, String outputFile) {
try (SortingWriter out = sortingWriter(outputFile)) {
EntryJoiningIterable.join(relIdJsonWithNodes,relIdWayJsonMap, new Processor<JoinedEntries, Boolean>() {
@Override
public Boolean process(JoinedEntries joined) {
JsonArray ways = array();
for(Entry<String, String> e: joined.right) {
JsonObject wayJson = parser.parse(e.getValue()).asObject();
ways.add(wayJson);
}
for(Entry<String, String> e: joined.left) {
JsonObject relJson = parser.parse(e.getValue()).asObject();
relJson.put("ways", ways);
out.put(e.getKey(), relJson.toString());
}
return true;
}
});
} catch (IOException e) {
throw new IllegalStateException("exception while closing sorted writer " + outputFile ,e);
}
}
public void processAll() {
// the join process works by parsing the osm xml blob for blob and creating several sorted multi maps as files using SortingWriter
// these map files are then joined to more complex files in several steps using the EntryJoiningIterable
// the main idea behind this approach is to not try to fit everything in ram at once and process efficiently by working with sorted files
// the output should be a big gzip file with all the nodes, ways, and relations as json blobs on each line. Each blob should have all the stuff it refers embedded.
StopWatch processTimer = StopWatch.time(LOG, "process " + OSM_XML);
StopWatch timer;
timer = StopWatch.time(LOG, "splitting " +OSM_XML);
splitAndEmit(OSM_XML);
timer.stop();
timer=StopWatch.time(LOG, "create "+WAY_ID_NODE_JSON_MAP);
createWayId2NodeJsonMap(NODE_ID_WAY_ID_MAP, NODE_ID_NODEJSON_MAP, WAY_ID_NODE_JSON_MAP);
timer.stop();
timer=StopWatch.time(LOG, "create "+WAY_ID_NODE_JSON_MAP);
createWayId2CompleteJsonMap(WAY_ID_WAYJSON_MAP, WAY_ID_NODE_JSON_MAP, WAY_ID_COMPLETE_JSON);
timer.stop();
timer = StopWatch.time(LOG, "create " + REL_ID_NODE_JSON_MAP);
createRelid2NodeJsonMap(NODE_ID_REL_ID_MAP, NODE_ID_NODEJSON_MAP, REL_ID_NODE_JSON_MAP);
timer.stop();
timer = StopWatch.time(LOG, "create " + REL_ID_JSON_WITH_NODES);
createRelid2JsonWithNodes(REL_ID_RELJSON_MAP, REL_ID_NODE_JSON_MAP, REL_ID_JSON_WITH_NODES);
timer.stop();
timer = StopWatch.time(LOG, "create " + REL_ID_WAY_JSON_MAP);
createRelId2WayJsonMap(WAY_ID_REL_ID_MAP, WAY_ID_COMPLETE_JSON, REL_ID_WAY_JSON_MAP);
timer.stop();
timer = StopWatch.time(LOG, "create " + REL_ID_COMPLETE_JSON);
createRelId2CompleteJson(REL_ID_JSON_WITH_NODES, REL_ID_WAY_JSON_MAP, REL_ID_COMPLETE_JSON);
timer.stop();
processTimer.stop();
}
public static void main(String[] args) {
OsmJoin osmJoin = new OsmJoin("./temp", new JsonParser());
osmJoin.processAll();
}
}
|
package com.google.sps.data;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections4.keyvalue.MultiKey;
/*
* Class representing one row/entry in the aggregation response. A NULL field value
* means the field was not being aggregated by, and will be omitted from the JSON response
*/
public final class AggregationResponseEntry {
private String annotatedAssetId;
private String annotatedLocation;
private String annotatedUser;
private final int count;
public AggregationResponseEntry(MultiKey key, int count, Set<AnnotatedField> fields) {
String keys[] = (String[]) key.getKeys();
int currKey = 0;
Iterator<AnnotatedField> it = fields.iterator();
while (it.hasNext()) {
switch(it.next()) {
case ASSET_ID:
this.annotatedAssetId = keys[currKey++];
break;
case LOCATION:
this.annotatedLocation = keys[currKey++];
break;
case USER:
this.annotatedUser = keys[currKey++];
break;
}
}
this.count = count;
}
}
|
package com.ibm.giraph.graph.example.sssp;
import java.io.IOException;
import java.util.Iterator;
import org.apache.giraph.graph.GiraphJob;
import org.apache.giraph.graph.LongDoubleDoubleDoubleVertex;
import org.apache.giraph.graph.LongDoubleDoubleNeighborhood;
import org.apache.giraph.graph.partition.HashMasterPartitioner;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
import com.ibm.giraph.graph.example.ioformats.KVBinaryInputFormat;
import com.ibm.giraph.graph.example.ioformats.KVBinaryOutputFormat;
import com.ibm.giraph.graph.example.ioformats.SimpleLongDoubleDoubleVertexBinaryInputFormat;
import com.ibm.giraph.graph.example.ioformats.SimpleLongXXXBinaryVertexOutputFormat;
import com.ibm.giraph.graph.example.partitioners.MyLongRangePartitionerFactory;
import com.ibm.giraph.utils.MapRedudeUtils;
public class SSSPVertex extends LongDoubleDoubleDoubleVertex
implements Tool {
Configuration conf = null;
/** Logger */
private static final Logger LOG =
Logger.getLogger(SSSPVertex.class);
public static void main(String[] args) throws Exception {
System.exit(ToolRunner.run(new SSSPVertex(), args));
}
@Override
public Configuration getConf() {
return conf;
}
@Override
public void setConf(Configuration conf) {
this.conf = conf;
}
private boolean isSource() {
return this.getVertexId().get() == 0;
}
@Override
public void compute(Iterator<DoubleWritable> msgs) throws IOException {
if (getSuperstep() == 0) {
setVertexValue(new DoubleWritable(Double.MAX_VALUE));
}
System.out.println("step: " + this.getSuperstep() + " vid: " + this.getVertexId() + " value: " + this.getVertexValue());
double minDist = isSource() ? 0d : Double.MAX_VALUE;
while(msgs.hasNext()) {
double v = msgs.next().get();
minDist = Math.min(minDist, v);
}
if (minDist < getVertexValue().get()) {
setVertexValue(new DoubleWritable(minDist));
for (int i = 0 ;i < this.getNumOutEdges() ; i ++) {
double distance = minDist + getSimpleEdgeValue(i);
sendMsg(this.getEdgeID(i), new DoubleWritable(distance));
}
}
voteToHalt();
}
public static class SimpleLongDoubleDoubleVertexBinaryOutputFormat
extends SimpleLongXXXBinaryVertexOutputFormat<DoubleWritable, DoubleWritable, LongDoubleDoubleNeighborhood<DoubleWritable,DoubleWritable> >
{
}
@Override
public int run(String[] args) throws Exception {
if (args.length != 6) {
System.err.println(
"run: Must have 6 arguments <input path> <output path> <# of workers> <hash partition: true, range partition: false>"
+ "<if hash partition, #partitions, otherwise range partiton file> <hybrid model: true, otherwise: false>");
System.exit(-1);
}
GiraphJob job = new GiraphJob(getConf(), "SSSPVertex");
job.getConfiguration().setInt(GiraphJob.CHECKPOINT_FREQUENCY, 0);
job.setVertexClass(SSSPVertex.class);
job.setVertexInputFormatClass(SimpleLongDoubleDoubleVertexBinaryInputFormat.class);
job.setVertexOutputFormatClass(SimpleLongDoubleDoubleVertexBinaryOutputFormat.class);
FileInputFormat.addInputPath(job.getInternalJob(), new Path(args[0]));
Path outpath=new Path(args[1]);
FileOutputFormat.setOutputPath(job.getInternalJob(), outpath);
MapRedudeUtils.deleteFileIfExistOnHDFS(outpath, job.getConfiguration());
KVBinaryInputFormat.setInputNeighborhoodClass(job.getConfiguration(), SimpleLongDoubleDoubleVertexBinaryInputFormat.NEIGHBORHOOD_CLASS);
KVBinaryOutputFormat.setOutputNeighborhoodClass(job.getConfiguration(), LongDoubleDoubleNeighborhood.class);
job.setVertexCombinerClass(MinCombiner.class);
if(Boolean.parseBoolean(args[3]))
job.getConfiguration().setInt(HashMasterPartitioner.USER_PARTITION_COUNT, Integer.parseInt(args[4]));
else
MyLongRangePartitionerFactory.setRangePartitioner(job, args[4]);
job.setWorkerConfiguration(Integer.parseInt(args[2]),
Integer.parseInt(args[2]), 100.0f);
if(Boolean.parseBoolean(args[5]))
job.getConfiguration().setInt(GiraphJob.NUM_SUB_STEPS_PER_ITERATION, 1);
else
job.getConfiguration().setInt(GiraphJob.NUM_SUB_STEPS_PER_ITERATION, 0);
if (job.run(true) == true) {
return 0;
} else {
return -1;
}
}
}
|
package com.jdkcn.jabber.web.listener;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import com.jdkcn.jabber.robot.Robot;
import com.jdkcn.jabber.robot.RobotMessageListener;
import com.jdkcn.jabber.util.JsonUtil;
import com.jdkcn.jabber.web.filter.UserSigninFilter;
import com.jdkcn.jabber.web.servlet.AddRosterEntryServlet;
import com.jdkcn.jabber.web.servlet.DisconnectServlet;
import com.jdkcn.jabber.web.servlet.IndexServlet;
import com.jdkcn.jabber.web.servlet.ReconnectServlet;
import com.jdkcn.jabber.web.servlet.RemoveRosterEntryServlet;
import com.jdkcn.jabber.web.servlet.RenameServlet;
import com.jdkcn.jabber.web.servlet.SigninServlet;
import com.jdkcn.jabber.web.servlet.SignoutServlet;
import org.codehaus.jackson.JsonNode;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.Roster.SubscriptionMode;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import static com.jdkcn.jabber.util.Constants.JABBERERJSONCONFIG;
import static com.jdkcn.jabber.util.Constants.ROBOTS;
/**
* The webapp listener for robot startup.
*
* @author Rory
* @version $Id$
* Time Feb 7, 2012
*/
@WebListener
public class WebAppListener extends GuiceServletContextListener {
/**
* The slf4j logger.
*/
private static Logger logger = LoggerFactory.getLogger(WebAppListener.class);
/**
* All the robots.
*/
private List<Robot> robots = new ArrayList<Robot>();
/**
* connec the robot.
*
* @param robotNode the robot's json config.
* @return the robot.
*/
public static Robot connect(JsonNode robotNode) {
String username = robotNode.get("username").asText();
Robot robot = new Robot();
robot.setUsername(username);
robot.setName(robotNode.get("name").asText());
Boolean sendOfflineMessage = robotNode.get("send.offline.message").getBooleanValue();
robot.setSendOfflineMessage(sendOfflineMessage);
findAdministrators(robot, robotNode);
try {
String password = robotNode.get("password").asText();
String robotStatusMessage = robotNode.get("robot.status.message").asText();
String host = robotNode.get("host").asText();
String serviceName = host;
if (robotNode.has("service.name")) {
serviceName = robotNode.get("service.name").asText();
}
robot.setPassword(password);
ConnectionConfiguration connConfig = new ConnectionConfiguration(host, robotNode.get("port").asInt(), serviceName);
connConfig.setCompressionEnabled(true);
connConfig.setSASLAuthenticationEnabled(true);
XMPPConnection connection = new XMPPConnection(connConfig);
connection.connect();
connection.login(username, password);
Presence presence = new Presence(Presence.Type.available, robotStatusMessage, 0, Presence.Mode.available);
connection.sendPacket(presence);
Roster roster = connection.getRoster();
roster.setSubscriptionMode(SubscriptionMode.manual);
PacketListener subscriptionListener = new SubscriptionListener(roster, connection);
connection.addPacketListener(subscriptionListener, new PacketTypeFilter(Presence.class));
final Collection<RosterEntry> entries = roster.getEntries();
logger.info(" robot {} online now.", username);
robot.setStartTime(new Date());
robot.getRosters().addAll(entries);
robot.setStatus(Robot.Status.Online);
ChatManager chatManager = connection.getChatManager();
final MessageListener messageListener = new RobotMessageListener(robot, sendOfflineMessage);
chatManager.addChatListener(new ChatManagerListener() {
@Override
public void chatCreated(Chat chat, boolean createdLocally) {
chat.addMessageListener(messageListener);
}
});
robot.setConnection(connection);
} catch (Exception e) {
logger.error(String.format(" robot[%s] connect error.", username), e);
e.printStackTrace();
robot.setStatus(Robot.Status.LoginFailed);
}
return robot;
}
/**
* find the administrators and set to robot.
*
* @param robot the robot.
* @param robotNode the robot's json config.
*/
private static void findAdministrators(Robot robot, JsonNode robotNode) {
List<String> administrators = new ArrayList<String>();
robot.getAdministrators().clear();
for (JsonNode node : robotNode.get("administrators")) {
administrators.add(node.asText());
}
for (RosterEntry entry : robot.getRosters()) {
if (administrators.contains(entry.getUser())) {
robot.getAdministrators().add(entry);
}
}
robot.setAdministratorIds(administrators);
}
/**
* {@inheritDoc}
*/
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
super.contextInitialized(servletContextEvent);
try {
JsonNode jsonConfig = JsonUtil.fromJson(WebAppListener.class.getResourceAsStream("/config.json"), JsonNode.class);
servletContextEvent.getServletContext().setAttribute(JABBERERJSONCONFIG, jsonConfig);
for (JsonNode robotNode : jsonConfig.get("robots")) {
Robot robot = connect(robotNode);
robots.add(robot);
}
servletContextEvent.getServletContext().setAttribute(ROBOTS, robots);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* {@inheritDoc}
*/
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
super.contextDestroyed(servletContextEvent);
for (Robot robot : robots) {
if (robot.getConnection() != null) {
logger.info("bot {} disconnect now.", robot.getName());
robot.getConnection().disconnect();
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected Injector getInjector() {
return Guice.createInjector(new ServletModule() {
/**
* {@inheritDoc}
*/
@Override
protected void configureServlets() {
/**
* Deal the subscription manual.
*/
private static class SubscriptionListener implements PacketListener {
/**
* The roster.
*/
private Roster roster;
/**
* The xmpp connection.
*/
private Connection connection;
/**
* Constructor with roster and connection.
*
* @param roster the roster.
* @param connection the xmpp connection.
*/
public SubscriptionListener(Roster roster, Connection connection) {
this.roster = roster;
this.connection = connection;
}
@Override
public void processPacket(Packet packet) {
if (packet instanceof Presence) {
Presence presence = (Presence) packet;
String from = presence.getFrom();
if (presence.getType() == Presence.Type.subscribe) {
logger.info("receive a subscribe presence.");
if (roster.contains(from)) {
// Accept the subscription request.
Presence response = new Presence(Presence.Type.subscribed);
response.setTo(from);
connection.sendPacket(response);
logger.info("Accept the subscription request from:" + from);
} else {
// Reject the subscription request.
Presence response = new Presence(Presence.Type.unsubscribed);
response.setTo(from);
connection.sendPacket(response);
logger.info("Reject the subscription request from:" + from);
}
} else if (presence.getType() == Presence.Type.unsubscribe) {
logger.info("Unsubscribe from:" + from);
Presence response = new Presence(Presence.Type.unsubscribed);
response.setTo(from);
connection.sendPacket(response);
}
}
}
}
}
|
package segment_tree;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Main {
public static int T;
public static int N = 100000; // 1 <= N <= 100,000
public static int Q; // 1 <= Q <= 300,000
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("input.txt");
System.setIn(fis);
float start = System.currentTimeMillis();
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter bw = new BufferedWriter(osw);
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
StringTokenizer st = new StringTokenizer(br.readLine());
T = Integer.parseInt(st.nextToken());
for (int i = 1; i <= T; i++) {
bw.write("
RMQ rmq = new RMQ(N);
st = new StringTokenizer(br.readLine());
int Q = Integer.parseInt(st.nextToken());
for (int q = 0; q < Q; q++) {
st = new StringTokenizer(br.readLine());
int type = Integer.parseInt(st.nextToken());
int num = Integer.parseInt(st.nextToken());
if (type == 1) {
// add
rmq.update(num, 1, 1, 0, N - 1);
} else {
// query and remove
int result = rmq.query(num, 1, 0, N - 1);
bw.write(" " + result);
rmq.update(num, -1, 1, 0, N - 1);
}
}
bw.write("\n");
}
float end = System.currentTimeMillis();
bw.write("time: " + ((end - start) / 1000.0) + " sec.");
br.close();
bw.close();
}
static class RMQ {
int n;
int range[];
public RMQ(int n) {
this.n = n;
range = new int[getSize(n)];
}
public int getSize(int n) {
Double H = Math.ceil(Math.log(n) / Math.log(2.0));
return 1 << (H.intValue() + 1);
}
public void update(int index, int diff, int node, int nodeLeft, int nodeRight) {
if (index < nodeLeft || nodeRight < index) {
return;
}
range[node] += diff;
if (nodeLeft != nodeRight) {
int mid = (nodeLeft + nodeRight) / 2;
update(index, diff, node * 2, nodeLeft, mid);
update(index, diff, node * 2 + 1, mid + 1, nodeRight);
range[node] = range[node * 2] + range[node * 2 + 1];
}
}
public int query(int k, int node, int nodeLeft, int nodeRight) {
if (nodeLeft == nodeRight) {
return nodeLeft;
}
int mid = (nodeLeft + nodeRight) / 2;
int leftK = range[node * 2];
if (leftK < k) {
// right
return query(k - leftK, node * 2 + 1, mid + 1, nodeRight);
} else {
// left
return query(k, node * 2, nodeLeft, mid);
}
}
}
}
|
package com.kodedu.tryjshell.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kodedu.tryjshell.helper.IOHelper;
import com.kodedu.tryjshell.helper.ThreadHelper;
import com.kodedu.tryjshell.nano.NanoApp;
import com.kodedu.tryjshell.process.ProcessWrapper;
import com.kodedu.tryjshell.websocket.TerminalSocket;
import com.pty4j.PtyProcess;
import com.pty4j.WinSize;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.LinkedBlockingQueue;
//@Component
//@Scope("prototype")
public class TerminalService {
private static String shellStarter;
private static LinkedBlockingQueue<ProcessWrapper> processQueue = new LinkedBlockingQueue<>();
private final NanoApp nanoApp;
private final TerminalSocket terminalSocket;
private ProcessWrapper processWrapper;
private BufferedWriter outputWriter;
private boolean firstSent = false;
private String cols = "80";
private String rows = "20";
public TerminalService(NanoApp nanoApp, TerminalSocket terminalSocket) {
this.nanoApp = nanoApp;
this.terminalSocket = terminalSocket;
init();
}
public synchronized void addSingleProcess() {
String tmpDir = System.getProperty("java.io.tmpdir");
Path dataDir = Paths.get(tmpDir).resolve(".terminalfx");
IOHelper.copyLibPty(dataDir);
// Path systemRoot = Files.createTempDirectory(Paths.get(tmpDir), "systemRoot");
// Files.createDirectories(systemRoot);
// Path prefsFile = Files.createTempFile(systemRoot, ".userPrefs", null);
// System.setProperty("java.util.prefs.systemRoot", systemRoot.normalize().toString());
// System.setProperty("java.util.prefs.userRoot", prefsFile.normalize().toString());
String[] termCommand = shellStarter.split("\\s+");
Map<String, String> envs = new HashMap<>(System.getenv());
envs.put("TERM", "xterm");
System.setProperty("PTY_LIB_FOLDER", dataDir.resolve("libpty").toString());
try {
PtyProcess process = PtyProcess.exec(termCommand, envs, System.getProperty("user.home"));
process.setWinSize(new WinSize(50, 20));
BufferedWriter outputWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
BufferedReader inputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
ProcessWrapper processWrapper = new ProcessWrapper(process);
processWrapper.setOutputWriter(outputWriter);
processWrapper.setInputReader(inputReader);
processWrapper.setErrorReader(errorReader);
processQueue.offer(processWrapper);
} catch (Exception e) {
e.printStackTrace();
}
}
public void init() {
shellStarter = System.getenv("shell");
if (Objects.isNull(shellStarter)) {
shellStarter = "jshell.exe";
}
}
public void onTerminalInit() {
}
public void onTerminalReady() {
ThreadHelper.start(() -> {
try {
initializeProcess();
} catch (Exception e) {
e.printStackTrace();
}
});
}
private void initializeProcess() throws Exception {
if (processQueue.size() < 5) {
addSingleProcess();
addSingleProcess();
}
this.processWrapper = processQueue.poll();
onTerminalResize(this.cols, this.rows);
this.outputWriter = processWrapper.getOutputWriter();
BufferedReader inputReader = processWrapper.getInputReader();
BufferedReader errorReader = processWrapper.getErrorReader();
ThreadHelper.start(() -> {
printReader(inputReader);
});
ThreadHelper.start(() -> {
printReader(errorReader);
});
processWrapper.getProcess().waitFor();
destroyProcess();
// addSingleProcess();
}
public void destroyProcess() {
if (Objects.isNull(processWrapper)) {
return;
}
PtyProcess process = processWrapper.getProcess();
try {
process.destroyForcibly();
} catch (Exception e) {
e.printStackTrace();
}
processQueue.remove(process);
IOHelper.close(process.getInputStream(), process.getErrorStream(), process.getOutputStream());
// addSingleProcess();
}
public void print(String text) throws IOException {
Map<String, String> map = new HashMap<>();
map.put("type", "TERMINAL_PRINT");
map.put("text", text);
String message = new ObjectMapper().writeValueAsString(map);
if (terminalSocket.isOpen()) {
terminalSocket.send(message);
if (!firstSent) {
firstSent = true;
this.onCommand(outputWriter, "/set editor /usr/bin/vim\n");
}
}
}
private void printReader(BufferedReader bufferedReader) {
try {
int nRead;
char[] data = new char[1 * 1024];
while ((nRead = bufferedReader.read(data, 0, data.length)) != -1) {
StringBuilder builder = new StringBuilder(nRead);
builder.append(data, 0, nRead);
print(builder.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void onCommand(BufferedWriter outputWriter, String command) {
if (Objects.isNull(command)) {
return;
}
try {
outputWriter.write(command);
outputWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onCommand(String command) {
onCommand(this.outputWriter, command);
}
public void onTerminalResize(String cols, String rows) {
if (Objects.nonNull(cols) && Objects.nonNull(rows)) {
this.cols = cols;
this.rows = rows;
if (Objects.nonNull(processWrapper)) {
processWrapper.getProcess().setWinSize(new WinSize(Integer.parseInt(cols), Integer.parseInt(rows)));
}
}
}
}
|
package com.losd.reqbot.repository;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.losd.reqbot.config.RedisSettings;
import com.losd.reqbot.model.Response;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
public class ResponseRedisRepo implements ResponseRepo {
public static final String RESPONSE_KEY_PREFIX = "response:";
@Autowired
Jedis jedis = null;
@Autowired
RedisSettings settings;
Gson gson = new GsonBuilder().serializeNulls().create();
@Override
public Response get(String uuid) {
String response = jedis.get(RESPONSE_KEY_PREFIX + uuid);
return gson.fromJson(response, Response.class);
}
@Override
public void save(Response response) {
String key = RESPONSE_KEY_PREFIX + response.getUuid().toString();
jedis.set(key, gson.toJson(response, Response.class));
jedis.expire(key, settings.getResponseTtl());
}
}
|
package com.mixpanel.android.viewcrawler;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import com.mixpanel.android.mpmetrics.MPConfig;
import com.mixpanel.android.mpmetrics.MixpanelAPI;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.ref.WeakReference;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
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.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
/**
* This class is for internal use by the Mixpanel API, and should
* not be called directly by your code.
*/
@TargetApi(14)
public class ViewCrawler implements ViewVisitor.OnVisitedListener, UpdatesFromMixpanel {
public ViewCrawler(Context context, String token, MixpanelAPI mixpanel) {
mPersistentChanges = new HashMap<String, List<JSONObject>>();
mEditorChanges = new HashMap<String, List<JSONObject>>();
mPersistentEventBindings = new HashMap<String, List<JSONObject>>();
mEditorEventBindings = new HashMap<String, List<JSONObject>>();
mProtocol = new EditProtocol(context);
final Application app = (Application) context.getApplicationContext();
app.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
final HandlerThread thread = new HandlerThread(ViewCrawler.class.getCanonicalName());
thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mMessageThreadHandler = new ViewCrawlerHandler(context, token, thread.getLooper());
mMessageThreadHandler.sendMessage(mMessageThreadHandler.obtainMessage(MESSAGE_INITIALIZE_CHANGES));
// We build our own, private SSL context here to prevent things from going
// crazy if client libs are using older versions of OkHTTP, or otherwise doing crazy junk
SSLSocketFactory foundSSLFactory;
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, null, null);
foundSSLFactory = sslContext.getSocketFactory();
} catch (GeneralSecurityException e) {
Log.e(LOGTAG, "System has no SSL support. Built-in events editor will not be available", e);
foundSSLFactory = null;
}
mSSLSocketFactory = foundSSLFactory;
mUiThreadHandler = new Handler(Looper.getMainLooper());
mMixpanel = mixpanel;
}
@Override
public Tweaks getTweaks() {
return mTweaks;
}
@Override
public void setEventBindings(JSONArray bindings) {
Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_EVENT_BINDINGS_RECEIVED);
msg.obj = bindings;
mMessageThreadHandler.sendMessage(msg);
}
@Override
public void OnVisited(String eventName) {
mMixpanel.track(eventName, null);
}
private void applyAllChangesOnUiThread() {
mUiThreadHandler.post(new Runnable() {
@Override
public void run() {
applyAllChanges();
}
});
}
// Must be called on UI Thread
private void applyAllChanges() {
synchronized (mLiveActivities) {
for (Activity activity : mLiveActivities) {
final String activityName = activity.getClass().getCanonicalName();
final View rootView = activity.getWindow().getDecorView().getRootView();
final List<JSONObject> persistentChanges;
final List<JSONObject> wildcardPersistentChanges;
synchronized (mPersistentChanges) {
persistentChanges = mPersistentChanges.get(activityName);
wildcardPersistentChanges = mPersistentChanges.get(null);
}
applyChangesFromList(rootView, persistentChanges);
applyChangesFromList(rootView, wildcardPersistentChanges);
final List<JSONObject> editorChanges;
final List<JSONObject> wildcardEditorChanges;
synchronized (mEditorChanges) {
editorChanges = mEditorChanges.get(activityName);
wildcardEditorChanges = mEditorChanges.get(null);
}
applyChangesFromList(rootView, editorChanges);
applyChangesFromList(rootView, wildcardEditorChanges);
final List<JSONObject> eventBindings;
final List<JSONObject> wildcardEventBindings;
synchronized (mPersistentEventBindings) {
eventBindings = mPersistentEventBindings.get(activityName);
wildcardEventBindings = mPersistentEventBindings.get(null);
}
applyBindingsFromList(rootView, eventBindings);
applyBindingsFromList(rootView, wildcardEventBindings);
final List<JSONObject> editorBindings;
final List<JSONObject> wildcardEditorBindings;
synchronized (mEditorEventBindings) {
editorBindings = mEditorEventBindings.get(activityName);
wildcardEditorBindings = mEditorEventBindings.get(null);
}
applyBindingsFromList(rootView, editorBindings);
applyBindingsFromList(rootView, wildcardEditorBindings);
}
}
}
// Must be called on UI Thread
private void applyChangesFromList(View rootView, List<JSONObject> changes) {
if (null != changes) {
int size = changes.size();
for (int i = 0; i < size; i++) {
JSONObject desc = changes.get(i);
try {
final ViewVisitor visitor = mProtocol.readEdit(desc);
final EditBinding binding = new EditBinding(rootView, visitor);
binding.performEdit();
} catch (EditProtocol.BadInstructionsException e) {
Log.e(LOGTAG, "Bad change request cannot be applied", e);
}
}
}
}
// Must be called on the UI Thread
private void applyBindingsFromList(View rootView, List<JSONObject> eventBindings) {
if (null != eventBindings) {
int size = eventBindings.size();
for (int i = 0; i < size; i++) {
JSONObject desc = eventBindings.get(i);
try {
final ViewVisitor visitor = mProtocol.readEventBinding(desc, this);
final EditBinding binding = new EditBinding(rootView, visitor);
binding.performEdit();
} catch (EditProtocol.BadInstructionsException e) {
Log.e(LOGTAG, "Bad binding cannot be applied", e);
}
}
}
}
private class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks, FlipGesture.OnFlipGestureListener {
public LifecycleCallbacks() {
mFlipGesture = new FlipGesture(this);
}
@Override
public void onFlipGesture() {
final Message message = mMessageThreadHandler.obtainMessage(MESSAGE_CONNECT_TO_EDITOR);
mMessageThreadHandler.sendMessage(message);
}
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
synchronized (mLiveActivities) {
mLiveActivities.add(activity);
}
applyAllChanges();
}
@Override
public void onActivityResumed(Activity activity) {
final SensorManager sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
final Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(mFlipGesture, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onActivityPaused(Activity activity) {
final SensorManager sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
sensorManager.unregisterListener(mFlipGesture);
}
@Override
public void onActivityStopped(Activity activity) {
synchronized (mLiveActivities) {
mLiveActivities.remove(activity);
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
private final FlipGesture mFlipGesture;
}
private class ViewCrawlerHandler extends Handler {
public ViewCrawlerHandler(Context context, String token, Looper looper) {
super(looper);
mContext = context;
mToken = token;
mSnapshot = null;
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_INITIALIZE_CHANGES:
initializeChanges();
break;
case MESSAGE_CONNECT_TO_EDITOR:
connectToEditor();
break;
case MESSAGE_DISCONNECT_FROM_EDITOR:
disconnectFromEditor();
break;
case MESSAGE_SEND_DEVICE_INFO:
sendDeviceInfo();
break;
case MESSAGE_SEND_STATE_FOR_EDITING:
sendStateForEditing((JSONObject) msg.obj);
break;
case MESSAGE_HANDLE_EDITOR_CHANGES_RECEIVED:
handleEditorChangeReceived((JSONObject) msg.obj);
break;
case MESSAGE_EVENT_BINDINGS_RECEIVED:
handleEventBindingsReceived((JSONArray) msg.obj);
break;
case MESSAGE_HANDLE_EDITOR_BINDINGS_RECEIVED:
handleEditorBindingsReceived((JSONObject) msg.obj);
break;
}
}
private void initializeChanges() {
final SharedPreferences preferences = getSharedPreferences();
final String storedChanges = preferences.getString(SHARED_PREF_CHANGES_KEY, null);
final String storedBindings = preferences.getString(SHARED_PREF_BINDINGS_KEY, null);
try {
if (null != storedChanges) {
final JSONArray changes = new JSONArray(storedChanges);
synchronized(mPersistentChanges) {
mPersistentChanges.clear();
for (int i = 0; i < changes.length(); i++) {
final JSONObject change = changes.getJSONObject(i);
loadChange(mPersistentChanges, change);
}
}
}
if (null != storedBindings) {
final JSONArray bindings = new JSONArray(storedBindings);
synchronized(mPersistentEventBindings) {
mPersistentEventBindings.clear();
for (int i = 0; i < bindings.length(); i++) {
final JSONObject event = bindings.getJSONObject(i);
loadEventBinding(event, mPersistentEventBindings);
}
}
}
} catch (JSONException e) {
Log.i(LOGTAG, "JSON error when initializing saved changes, clearing persistent memory", e);
final SharedPreferences.Editor editor = preferences.edit();
editor.remove(SHARED_PREF_CHANGES_KEY);
editor.remove(SHARED_PREF_BINDINGS_KEY);
editor.apply();
}
}
private void connectToEditor() {
if (MPConfig.DEBUG) {
Log.d(LOGTAG, "connecting to editor");
}
if (mEditorConnection != null && mEditorConnection.isValid()) {
if (MPConfig.DEBUG) {
Log.d(LOGTAG, "There is already a valid connection to an events editor.");
}
return;
}
if (null == mSSLSocketFactory) {
Log.i(LOGTAG, "SSL is not available on this device, no connection will be attempted to the events editor.");
return;
}
final String url = MPConfig.getInstance(mContext).getEditorUrl() + mToken;
try {
final Socket sslSocket = mSSLSocketFactory.createSocket();
mEditorConnection = new EditorConnection(new URI(url), new Editor(), sslSocket);
} catch (URISyntaxException e) {
Log.e(LOGTAG, "Error parsing URI " + url + " for editor websocket", e);
} catch (EditorConnection.EditorConnectionException e) {
Log.e(LOGTAG, "Error connecting to URI " + url, e);
} catch (IOException e) {
Log.i(LOGTAG, "Can't create SSL Socket to connect to editor service", e);
}
}
private void disconnectFromEditor() {
if (MPConfig.DEBUG) {
Log.d(LOGTAG, "disconnecting from editor");
}
if (mEditorConnection == null || !mEditorConnection.isValid()) {
if (MPConfig.DEBUG) {
Log.d(LOGTAG, "Editor is already disconnected.");
}
}
mEditorConnection.disconnect();
}
private void sendError(String errorMessage) {
final JSONObject errorObject = new JSONObject();
try {
errorObject.put("error_message", errorMessage);
} catch (JSONException e) {
Log.e(LOGTAG, "Apparently impossible JSONException", e);
}
final OutputStreamWriter writer = new OutputStreamWriter(mEditorConnection.getBufferedOutputStream());
try {
writer.write("{\"type\": \"error\", ");
writer.write("\"payload\": ");
writer.write(errorObject.toString());
writer.write("}");
} catch (IOException e) {
Log.e(LOGTAG, "Can't write error message to editor", e);
} finally {
try {
writer.close();
} catch (IOException e) {
Log.e(LOGTAG, "Could not close output writer to editor", e);
}
}
}
private void sendDeviceInfo() {
final OutputStream out = mEditorConnection.getBufferedOutputStream();
final OutputStreamWriter writer = new OutputStreamWriter(out);
try {
writer.write("{\"type\": \"device_info_response\",");
writer.write("\"payload\": {");
writer.write("\"device_type\": \"Android\",");
writer.write("\"device_name\": \"" + Build.BRAND + "/" + Build.MODEL + "\",");
writer.write("\"tweaks\":");
writer.write(new JSONObject(mTweaks.getAll()).toString());
writer.write("}"); // payload
writer.write("}");
} catch (IOException e) {
Log.e(LOGTAG, "Can't write device_info to server", e);
} finally {
try {
writer.close();
} catch (IOException e) {
Log.e(LOGTAG, "Can't close websocket writer", e);
}
}
}
private void sendStateForEditing(JSONObject message) {
try {
final JSONObject payload = message.getJSONObject("payload");
if (payload.has("config")) {
mSnapshot = mProtocol.readSnapshotConfig(payload);
}
} catch (JSONException e) {
Log.e(LOGTAG, "Payload with snapshot config required with snapshot request", e);
sendError("Payload with snapshot config required with snapshot request");
return;
} catch (EditProtocol.BadInstructionsException e) {
Log.e(LOGTAG, "Editor sent malformed message with snapshot request", e);
sendError(e.getMessage());
return;
}
// ELSE config is valid:
if (null == mSnapshot) {
sendError("No snapshot configuration was sent.");
Log.w(LOGTAG, "Mixpanel editor is misconfigured, sent a snapshot request without configuration.");
}
final OutputStream out = mEditorConnection.getBufferedOutputStream();
final OutputStreamWriter writer = new OutputStreamWriter(out);
try {
writer.write("{\"type\": \"snapshot_response\",");
writer.write("\"payload\": {");
writer.write("\"activities\": [");
writer.flush();
mSnapshot.snapshots(mLiveActivities, out);
writer.write("]"); // activities
writer.write("}"); // payload
writer.write("}");
} catch (IOException e) {
Log.e(LOGTAG, "Can't write snapshot request to server", e);
} finally {
try {
writer.close();
} catch (IOException e) {
Log.e(LOGTAG, "Can't close writer.", e);
}
}
}
private void handleEditorChangeReceived(JSONObject change) {
try {
loadChange(mEditorChanges, change);
applyAllChangesOnUiThread();
} catch (JSONException e) {
Log.e(LOGTAG, "Bad change request received", e);
}
}
private void handleEventBindingsReceived(JSONArray eventBindings) {
final SharedPreferences preferences = getSharedPreferences();
final SharedPreferences.Editor editor = preferences.edit();
editor.putString(SHARED_PREF_BINDINGS_KEY, eventBindings.toString());
editor.apply();
initializeChanges();
applyAllChangesOnUiThread();
}
private void handleEditorBindingsReceived(JSONObject message) {
final JSONArray eventBindings;
try {
final JSONObject payload = message.getJSONObject("payload");
eventBindings = payload.getJSONArray("events");
} catch (JSONException e) {
Log.e(LOGTAG, "Bad event bindings received", e);
return;
}
int eventCount = eventBindings.length();
for (int i = 0; i < eventCount; i++) {
try {
final JSONObject event = eventBindings.getJSONObject(i);
loadEventBinding(event, mEditorEventBindings);
} catch (JSONException e) {
Log.e(LOGTAG, "Bad event binding received from editor in " + eventBindings.toString(), e);
}
}
}
private void loadChange(Map <String, List<JSONObject>> changes, JSONObject newChange)
throws JSONException {
final String targetActivity = newChange.optString("target", null);
final JSONObject change = newChange.getJSONObject("change");
synchronized (changes) {
final List<JSONObject> changeList;
if (changes.containsKey(targetActivity)) {
changeList = changes.get(targetActivity);
} else {
changeList = new ArrayList<JSONObject>();
changes.put(targetActivity, changeList);
}
changeList.add(change);
}
}
private void loadEventBinding(JSONObject newBinding, Map<String, List<JSONObject>> bindings)
throws JSONException {
final String targetActivity = newBinding.optString("target_activity", null);
synchronized (bindings) {
final List<JSONObject> bindingList;
if (bindings.containsKey(targetActivity)) {
bindingList = bindings.get(targetActivity);
} else {
bindingList = new ArrayList<JSONObject>();
bindings.put(targetActivity, bindingList);
}
bindingList.add(newBinding);
}
}
private SharedPreferences getSharedPreferences() {
final String sharedPrefsName = SHARED_PREF_EDITS_FILE + mToken;
return mContext.getSharedPreferences(sharedPrefsName, Context.MODE_PRIVATE);
}
private EditorConnection mEditorConnection;
private ViewSnapshot mSnapshot;
private final Context mContext;
private final String mToken;
}
private class Editor implements EditorConnection.Editor {
@Override
public void sendSnapshot(JSONObject message) {
Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_SEND_STATE_FOR_EDITING);
msg.obj = message;
mMessageThreadHandler.sendMessage(msg);
}
@Override
public void performEdit(JSONObject message) {
Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_HANDLE_EDITOR_CHANGES_RECEIVED);
msg.obj = message;
mMessageThreadHandler.sendMessage(msg);
}
@Override
public void bindEvents(JSONObject message) {
Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_HANDLE_EDITOR_BINDINGS_RECEIVED);
msg.obj = message;
mMessageThreadHandler.sendMessage(msg);
}
@Override
public void sendDeviceInfo() {
Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_SEND_DEVICE_INFO);
mMessageThreadHandler.sendMessage(msg);
}
}
/* The binding between a bunch of edits and a view. Should be instantiated and live on the UI thread */
private static class EditBinding implements ViewTreeObserver.OnGlobalLayoutListener {
public EditBinding(View viewRoot, ViewVisitor edit) {
mEdit = edit;
mViewRoot = new WeakReference<View>(viewRoot);
ViewTreeObserver observer = viewRoot.getViewTreeObserver();
performEdit();
if (observer.isAlive()) {
observer.addOnGlobalLayoutListener(this);
}
}
@Override
public void onGlobalLayout() {
performEdit();
}
public void performEdit() {
View viewRoot = mViewRoot.get();
if (null == viewRoot) {
return;
}
// ELSE View is alive
mEdit.visit(viewRoot);
}
private final WeakReference<View> mViewRoot;
private final ViewVisitor mEdit;
}
// Map from canonical activity class name to description of changes
// Accessed from Multiple Threads, must be synchronized
// When A/B Test changes are made available from decide, they'll live in mPersistentChanges
private final Map<String, List<JSONObject>> mPersistentChanges;
private final Map<String, List<JSONObject>> mEditorChanges;
private final Map<String, List<JSONObject>> mPersistentEventBindings;
private final Map<String, List<JSONObject>> mEditorEventBindings;
// mLiveActivites is accessed across multiple threads, and must be synchronized.
private final Set<Activity> mLiveActivities = new HashSet<Activity>();
private final SSLSocketFactory mSSLSocketFactory;
private final EditProtocol mProtocol;
private final Tweaks mTweaks = new Tweaks();
private final Handler mUiThreadHandler;
private final ViewCrawlerHandler mMessageThreadHandler;
private final MixpanelAPI mMixpanel;
private static final String SHARED_PREF_EDITS_FILE = "mixpanel.viewcrawler.changes";
private static final String SHARED_PREF_CHANGES_KEY = "mixpanel.viewcrawler.changes";
private static final String SHARED_PREF_BINDINGS_KEY = "mixpanel.viewcrawler.bindings";
private static final int MESSAGE_INITIALIZE_CHANGES = 0;
private static final int MESSAGE_CONNECT_TO_EDITOR = 1;
private static final int MESSAGE_SEND_STATE_FOR_EDITING = 2;
private static final int MESSAGE_HANDLE_EDITOR_CHANGES_RECEIVED = 3;
private static final int MESSAGE_SEND_DEVICE_INFO = 4;
private static final int MESSAGE_EVENT_BINDINGS_RECEIVED = 6;
private static final int MESSAGE_DISCONNECT_FROM_EDITOR = 7;
private static final int MESSAGE_HANDLE_EDITOR_BINDINGS_RECEIVED = 8;
@SuppressWarnings("unused")
private static final String LOGTAG = "MixpanelAPI.ViewCrawler";
}
|
package com.mixpanel.android.viewcrawler;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.IntDef;
import android.util.JsonWriter;
import android.util.Log;
import android.util.Pair;
import com.mixpanel.android.mpmetrics.MPConfig;
import com.mixpanel.android.mpmetrics.MixpanelAPI;
import com.mixpanel.android.mpmetrics.ResourceIds;
import com.mixpanel.android.mpmetrics.ResourceReader;
import com.mixpanel.android.mpmetrics.SuperPropertyUpdate;
import com.mixpanel.android.mpmetrics.Tweaks;
import com.mixpanel.android.util.JSONUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
/**
* This class is for internal use by the Mixpanel API, and should
* not be called directly by your code.
*/
@TargetApi(MPConfig.UI_FEATURES_MIN_API)
public class ViewCrawler implements UpdatesFromMixpanel, TrackingDebug {
public ViewCrawler(Context context, String token, MixpanelAPI mixpanel) {
mConfig = MPConfig.getInstance(context);
String resourcePackage = mConfig.getResourcePackageName();
if (null == resourcePackage) {
resourcePackage = context.getPackageName();
}
final ResourceIds resourceIds = new ResourceReader.Ids(resourcePackage, context);
mProtocol = new EditProtocol(resourceIds);
mEditState = new EditState();
mTweaks = new Tweaks();
mDeviceInfo = mixpanel.getDeviceInfo();
final Application app = (Application) context.getApplicationContext();
app.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
final HandlerThread thread = new HandlerThread(ViewCrawler.class.getCanonicalName());
thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mMessageThreadHandler = new ViewCrawlerHandler(context, token, thread.getLooper());
mTracker = new DynamicEventTracker(mixpanel, mMessageThreadHandler);
mVariantTracker = new VariantTracker(mixpanel);
// We build our own, private SSL context here to prevent things from going
// crazy if client libs are using older versions of OkHTTP, or otherwise doing crazy junk
SSLSocketFactory foundSSLFactory;
try {
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, null, null);
foundSSLFactory = sslContext.getSocketFactory();
} catch (final GeneralSecurityException e) {
Log.i(LOGTAG, "System has no SSL support. Built-in events editor will not be available", e);
foundSSLFactory = null;
}
mSSLSocketFactory = foundSSLFactory;
}
@Override
public void startUpdates() {
mMessageThreadHandler.start();
mMessageThreadHandler.sendMessage(mMessageThreadHandler.obtainMessage(MESSAGE_INITIALIZE_CHANGES));
}
@Override
public Tweaks getTweaks() {
return mTweaks;
}
@Override
public void setEventBindings(JSONArray bindings) {
final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_EVENT_BINDINGS_RECEIVED);
msg.obj = bindings;
mMessageThreadHandler.sendMessage(msg);
}
@Override
public void setVariants(JSONArray variants) {
final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_VARIANTS_RECEIVED);
msg.obj = variants;
mMessageThreadHandler.sendMessage(msg);
}
@Override
public void reportTrack(String eventName) {
final Message m = mMessageThreadHandler.obtainMessage();
m.what = MESSAGE_SEND_EVENT_TRACKED;
m.obj = eventName;
mMessageThreadHandler.sendMessage(m);
}
private class EmulatorConnector implements Runnable {
public EmulatorConnector() {
mStopped = true;
}
@Override
public void run() {
if (! mStopped) {
final Message message = mMessageThreadHandler.obtainMessage(MESSAGE_CONNECT_TO_EDITOR);
mMessageThreadHandler.sendMessage(message);
}
mMessageThreadHandler.postDelayed(this, EMULATOR_CONNECT_ATTEMPT_INTERVAL_MILLIS);
}
public void start() {
mStopped = false;
mMessageThreadHandler.post(this);
}
public void stop() {
mStopped = true;
mMessageThreadHandler.removeCallbacks(this);
}
private volatile boolean mStopped;
}
private class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks, FlipGesture.OnFlipGestureListener {
public LifecycleCallbacks() {
mFlipGesture = new FlipGesture(this);
mEmulatorConnector = new EmulatorConnector();
}
@Override
public void onFlipGesture() {
final Message message = mMessageThreadHandler.obtainMessage(MESSAGE_CONNECT_TO_EDITOR);
mMessageThreadHandler.sendMessage(message);
}
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
installConnectionSensor(activity);
mEditState.add(activity);
}
@Override
public void onActivityPaused(Activity activity) {
mEditState.remove(activity);
if (mEditState.isEmpty()) {
uninstallConnectionSensor(activity);
}
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
private void installConnectionSensor(final Activity activity) {
if (isInEmulator() && !mConfig.getDisableEmulatorBindingUI()) {
mEmulatorConnector.start();
} else if (!mConfig.getDisableGestureBindingUI()) {
final SensorManager sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
final Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(mFlipGesture, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
}
private void uninstallConnectionSensor(final Activity activity) {
if (isInEmulator() && !mConfig.getDisableEmulatorBindingUI()) {
mEmulatorConnector.stop();
} else if (!mConfig.getDisableGestureBindingUI()) {
final SensorManager sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
sensorManager.unregisterListener(mFlipGesture);
}
}
private boolean isInEmulator() {
if (!Build.HARDWARE.equals("goldfish")) {
return false;
}
if (!Build.BRAND.startsWith("generic")) {
return false;
}
if (!Build.DEVICE.startsWith("generic")) {
return false;
}
if (!Build.PRODUCT.contains("sdk")) {
return false;
}
if (!Build.MODEL.toLowerCase().contains("sdk")) {
return false;
}
return true;
}
private final FlipGesture mFlipGesture;
private final EmulatorConnector mEmulatorConnector;
}
private class ViewCrawlerHandler extends Handler {
public ViewCrawlerHandler(Context context, String token, Looper looper) {
super(looper);
mContext = context;
mToken = token;
mSnapshot = null;
mEditorChanges = new ArrayList<Pair<String, JSONObject>>();
mEditorEventBindings = new ArrayList<Pair<String, JSONObject>>();
mPersistentChanges = new ArrayList<VariantChange>();
mPersistentEventBindings = new ArrayList<Pair<String, JSONObject>>();
mSeenExperiments = new HashSet<Pair<Integer, Integer>>();
mStartLock = new ReentrantLock();
mStartLock.lock();
}
public void start() {
mStartLock.unlock();
}
@Override
public void handleMessage(Message msg) {
mStartLock.lock();
try {
final @MessageType int what = msg.what;
switch (what) {
case MESSAGE_INITIALIZE_CHANGES:
loadKnownChanges();
initializeChanges();
break;
case MESSAGE_CONNECT_TO_EDITOR:
connectToEditor();
break;
case MESSAGE_SEND_DEVICE_INFO:
sendDeviceInfo();
break;
case MESSAGE_SEND_STATE_FOR_EDITING:
sendSnapshot((JSONObject) msg.obj);
break;
case MESSAGE_SEND_EVENT_TRACKED:
sendReportTrackToEditor((String) msg.obj);
break;
case MESSAGE_VARIANTS_RECEIVED:
handleVariantsReceived((JSONArray) msg.obj);
break;
case MESSAGE_HANDLE_EDITOR_CHANGES_RECEIVED:
handleEditorChangeReceived((JSONObject) msg.obj);
break;
case MESSAGE_EVENT_BINDINGS_RECEIVED:
handleEventBindingsReceived((JSONArray) msg.obj);
break;
case MESSAGE_HANDLE_EDITOR_BINDINGS_RECEIVED:
handleEditorBindingsReceived((JSONObject) msg.obj);
break;
case MESSAGE_HANDLE_EDITOR_CLOSED:
handleEditorClosed();
break;
}
} finally {
mStartLock.unlock();
}
}
/**
* Load the experiment ids and variants already in persistent storage into
* into our set of seen experiments, so we don't double track them.
*/
private void loadKnownChanges() {
final SharedPreferences preferences = getSharedPreferences();
final String storedChanges = preferences.getString(SHARED_PREF_CHANGES_KEY, null);
if (null != storedChanges) {
try {
final JSONArray variants = new JSONArray(storedChanges);
final int variantsLength = variants.length();
for (int i = 0; i < variantsLength; i++) {
final JSONObject variant = variants.getJSONObject(i);
final int variantId = variant.getInt("id");
final int experimentId = variant.getInt("experiment");
final Pair<Integer,Integer> sight = new Pair<Integer,Integer>(experimentId, variantId);
mSeenExperiments.add(sight);
}
} catch (JSONException e) {
Log.e(LOGTAG, "Malformed variants found in persistent storage, clearing all variants", e);
final SharedPreferences.Editor editor = preferences.edit();
editor.remove(SHARED_PREF_CHANGES_KEY);
editor.remove(SHARED_PREF_BINDINGS_KEY);
editor.commit();
}
}
}
/**
* Load stored changes from persistent storage and apply them to the application.
*/
private void initializeChanges() {
final SharedPreferences preferences = getSharedPreferences();
final String storedChanges = preferences.getString(SHARED_PREF_CHANGES_KEY, null);
final String storedBindings = preferences.getString(SHARED_PREF_BINDINGS_KEY, null);
try {
if (null != storedChanges) {
mPersistentChanges.clear(); // TODO undo/unapply these guys
final JSONArray variants = new JSONArray(storedChanges);
final int variantsLength = variants.length();
for (int variantIx = 0; variantIx < variantsLength; variantIx++) {
final JSONObject nextVariant = variants.getJSONObject(variantIx);
final int variantIdPart = nextVariant.getInt("id");
final int experimentIdPart = nextVariant.getInt("experiment_id");
final Pair<Integer, Integer> variantId = new Pair<Integer, Integer>(experimentIdPart, variantIdPart);
final JSONArray actions = nextVariant.getJSONArray("actions");
for (int i = 0; i < actions.length(); i++) {
final JSONObject change = actions.getJSONObject(i);
final String targetActivity = JSONUtils.optionalStringKey(change, "target_activity");
final VariantChange variantChange = new VariantChange(targetActivity, change, variantId);
mPersistentChanges.add(variantChange);
}
// TODO final JSONArray tweaks = nextVariant.getJSONArray("tweaks");
}
}
if (null != storedBindings) {
final JSONArray bindings = new JSONArray(storedBindings);
mPersistentEventBindings.clear();
for (int i = 0; i < bindings.length(); i++) {
final JSONObject event = bindings.getJSONObject(i);
final String targetActivity = JSONUtils.optionalStringKey(event, "target_activity");
mPersistentEventBindings.add(new Pair<String, JSONObject>(targetActivity, event));
}
}
} catch (final JSONException e) {
Log.i(LOGTAG, "JSON error when initializing saved changes, clearing persistent memory", e);
final SharedPreferences.Editor editor = preferences.edit();
editor.remove(SHARED_PREF_CHANGES_KEY);
editor.remove(SHARED_PREF_BINDINGS_KEY);
editor.commit();
}
updateEditState();
}
/**
* Try to connect to the remote interactive editor, if a connection does not already exist.
*/
private void connectToEditor() {
if (MPConfig.DEBUG) {
Log.v(LOGTAG, "connecting to editor");
}
if (mEditorConnection != null && mEditorConnection.isValid()) {
if (MPConfig.DEBUG) {
Log.v(LOGTAG, "There is already a valid connection to an events editor.");
}
return;
}
if (null == mSSLSocketFactory) {
if (MPConfig.DEBUG) {
Log.v(LOGTAG, "SSL is not available on this device, no connection will be attempted to the events editor.");
}
return;
}
final String url = MPConfig.getInstance(mContext).getEditorUrl() + mToken;
try {
final Socket sslSocket = mSSLSocketFactory.createSocket();
mEditorConnection = new EditorConnection(new URI(url), new Editor(), sslSocket);
} catch (final URISyntaxException e) {
Log.e(LOGTAG, "Error parsing URI " + url + " for editor websocket", e);
} catch (final EditorConnection.EditorConnectionException e) {
Log.e(LOGTAG, "Error connecting to URI " + url, e);
} catch (final IOException e) {
Log.i(LOGTAG, "Can't create SSL Socket to connect to editor service", e);
}
}
/**
* Send a string error message to the connected web UI.
*/
private void sendError(String errorMessage) {
final JSONObject errorObject = new JSONObject();
try {
errorObject.put("error_message", errorMessage);
} catch (final JSONException e) {
Log.e(LOGTAG, "Apparently impossible JSONException", e);
}
final OutputStreamWriter writer = new OutputStreamWriter(mEditorConnection.getBufferedOutputStream());
try {
writer.write("{\"type\": \"error\", ");
writer.write("\"payload\": ");
writer.write(errorObject.toString());
writer.write("}");
} catch (final IOException e) {
Log.e(LOGTAG, "Can't write error message to editor", e);
} finally {
try {
writer.close();
} catch (final IOException e) {
Log.e(LOGTAG, "Could not close output writer to editor", e);
}
}
}
/**
* Report on device info to the connected web UI.
*/
private void sendDeviceInfo() {
final OutputStream out = mEditorConnection.getBufferedOutputStream();
final OutputStreamWriter writer = new OutputStreamWriter(out);
try {
writer.write("{\"type\": \"device_info_response\",");
writer.write("\"payload\": {");
writer.write("\"device_type\": \"Android\",");
writer.write("\"device_name\":");
writer.write(JSONObject.quote(Build.BRAND + "/" + Build.MODEL));
writer.write(",");
writer.write("\"tweaks\": []"); // TODO send tweaks back home
for (final Map.Entry<String, String> entry : mDeviceInfo.entrySet()) {
writer.write(",");
writer.write(JSONObject.quote(entry.getKey()));
writer.write(":");
writer.write(JSONObject.quote(entry.getValue()));
}
writer.write(",");
writer.write("\"scaled_density\":");
writer.write(Float.toString(Resources.getSystem().getDisplayMetrics().scaledDensity));
writer.write("}"); // payload
writer.write("}");
} catch (final IOException e) {
Log.e(LOGTAG, "Can't write device_info to server", e);
} finally {
try {
writer.close();
} catch (final IOException e) {
Log.e(LOGTAG, "Can't close websocket writer", e);
}
}
}
/**
* Send a snapshot response, with crawled views and screenshot image, to the connected web UI.
*/
private void sendSnapshot(JSONObject message) {
final long startSnapshot = System.currentTimeMillis();
try {
final JSONObject payload = message.getJSONObject("payload");
if (payload.has("config")) {
mSnapshot = mProtocol.readSnapshotConfig(payload);
}
} catch (final JSONException e) {
Log.e(LOGTAG, "Payload with snapshot config required with snapshot request", e);
sendError("Payload with snapshot config required with snapshot request");
return;
} catch (final EditProtocol.BadInstructionsException e) {
Log.e(LOGTAG, "Editor sent malformed message with snapshot request", e);
sendError(e.getMessage());
return;
}
if (null == mSnapshot) {
sendError("No snapshot configuration (or a malformed snapshot configuration) was sent.");
Log.w(LOGTAG, "Mixpanel editor is misconfigured, sent a snapshot request without a valid configuration.");
return;
}
// ELSE config is valid:
final OutputStream out = mEditorConnection.getBufferedOutputStream();
final OutputStreamWriter writer = new OutputStreamWriter(out);
try {
writer.write("{");
writer.write("\"type\": \"snapshot_response\",");
writer.write("\"payload\": {");
{
writer.write("\"activities\":");
writer.flush();
mSnapshot.snapshots(mEditState, out);
}
final long snapshotTime = System.currentTimeMillis() - startSnapshot;
writer.write(",\"snapshot_time_millis\": ");
writer.write(Long.toString(snapshotTime));
writer.write("}"); // } payload
writer.write("}"); // } whole message
} catch (final IOException e) {
Log.e(LOGTAG, "Can't write snapshot request to server", e);
} finally {
try {
writer.close();
} catch (final IOException e) {
Log.e(LOGTAG, "Can't close writer.", e);
}
}
}
/**
* Report that a track has occurred to the connected web UI.
*/
private void sendReportTrackToEditor(String eventName) {
if (mEditorConnection == null || !mEditorConnection.isValid()) {
return;
}
final OutputStream out = mEditorConnection.getBufferedOutputStream();
final OutputStreamWriter writer = new OutputStreamWriter(out);
final JsonWriter j = new JsonWriter(writer);
try {
j.beginObject();
j.name("type").value("track_message");
j.name("payload");
{
j.beginObject();
j.name("event_name").value(eventName);
j.endObject();
}
j.endObject();
j.flush();
} catch (final IOException e) {
Log.e(LOGTAG, "Can't write track_message to server", e);
} finally {
try {
j.close();
} catch (final IOException e) {
Log.e(LOGTAG, "Can't close writer.", e);
}
}
}
/**
* Accept and apply a change from the connected UI.
*/
private void handleEditorChangeReceived(JSONObject changeMessage) {
try {
final JSONObject payload = changeMessage.getJSONObject("payload");
final JSONArray actions = payload.getJSONArray("actions");
for (int i = 0; i < actions.length(); i++) {
final JSONObject change = actions.getJSONObject(i);
final String targetActivity = JSONUtils.optionalStringKey(change, "target_activity");
mEditorChanges.add(new Pair<String, JSONObject>(targetActivity, change));
}
updateEditState();
} catch (final JSONException e) {
Log.e(LOGTAG, "Bad change request received", e);
}
}
/**
* Accept and apply variant changes from a non-interactive source.
*/
private void handleVariantsReceived(JSONArray variants) {
final SharedPreferences preferences = getSharedPreferences();
final SharedPreferences.Editor editor = preferences.edit();
editor.putString(SHARED_PREF_CHANGES_KEY, variants.toString());
editor.commit();
// Mark inbound stuff as in
initializeChanges();
}
/**
* Accept and apply a persistent event binding from a non-interactive source.
*/
private void handleEventBindingsReceived(JSONArray eventBindings) {
final SharedPreferences preferences = getSharedPreferences();
final SharedPreferences.Editor editor = preferences.edit();
editor.putString(SHARED_PREF_BINDINGS_KEY, eventBindings.toString());
editor.commit();
initializeChanges();
}
/**
* Accept and apply a temporary event binding from the connected UI.
*/
private void handleEditorBindingsReceived(JSONObject message) {
final JSONArray eventBindings;
try {
final JSONObject payload = message.getJSONObject("payload");
eventBindings = payload.getJSONArray("events");
} catch (final JSONException e) {
Log.e(LOGTAG, "Bad event bindings received", e);
return;
}
final int eventCount = eventBindings.length();
mEditorEventBindings.clear();
for (int i = 0; i < eventCount; i++) {
try {
final JSONObject event = eventBindings.getJSONObject(i);
final String targetActivity = JSONUtils.optionalStringKey(event, "target_activity");
mEditorEventBindings.add(new Pair<String, JSONObject>(targetActivity, event));
} catch (final JSONException e) {
Log.e(LOGTAG, "Bad event binding received from editor in " + eventBindings.toString(), e);
}
}
updateEditState();
}
/**
* Clear state associated with the editor now that the editor is gone.
*/
private void handleEditorClosed() {
mEditorChanges.clear();
mEditorEventBindings.clear();
// Free (or make available) snapshot memory
mSnapshot = null;
updateEditState();
}
/**
* Reads our JSON-stored edits from memory and submits them to our EditState. Overwrites
* any existing edits at the time that it is run.
*
* updateEditState should be called any time we load new edits from disk or
* receive new edits from the interactive UI editor. Changes and event bindings
* from our persistent storage and temporary changes received from interactive editing
* will all be submitted to our EditState
*/
private void updateEditState() {
final List<Pair<String, ViewVisitor>> newEdits = new ArrayList<Pair<String, ViewVisitor>>();
final Set<Pair<Integer, Integer>> toTrack = new HashSet<Pair<Integer, Integer>>();
{
final int size = mPersistentChanges.size();
for (int i = 0; i < size; i++) {
final VariantChange changeInfo = mPersistentChanges.get(i);
try {
final ViewVisitor visitor = mProtocol.readEdit(changeInfo.change);
newEdits.add(new Pair<String, ViewVisitor>(changeInfo.activityName, visitor));
if (! mSeenExperiments.contains(changeInfo.variantId)) {
toTrack.add(changeInfo.variantId);
}
} catch (final EditProtocol.InapplicableInstructionsException e) {
Log.i(LOGTAG, e.getMessage());
} catch (final EditProtocol.BadInstructionsException e) {
Log.e(LOGTAG, "Bad persistent change request cannot be applied.", e);
}
}
}
{
final int size = mEditorChanges.size();
for (int i = 0; i < size; i++) {
final Pair<String, JSONObject> changeInfo = mEditorChanges.get(i);
try {
final ViewVisitor visitor = mProtocol.readEdit(changeInfo.second);
newEdits.add(new Pair<String, ViewVisitor>(changeInfo.first, visitor));
} catch (final EditProtocol.InapplicableInstructionsException e) {
Log.i(LOGTAG, e.getMessage());
} catch (final EditProtocol.BadInstructionsException e) {
Log.e(LOGTAG, "Bad editor change request cannot be applied.", e);
}
}
}
{
final int size = mPersistentEventBindings.size();
for (int i = 0; i < size; i++) {
final Pair<String, JSONObject> changeInfo = mPersistentEventBindings.get(i);
try {
final ViewVisitor visitor = mProtocol.readEventBinding(changeInfo.second, mTracker);
newEdits.add(new Pair<String, ViewVisitor>(changeInfo.first, visitor));
} catch (final EditProtocol.InapplicableInstructionsException e) {
Log.i(LOGTAG, e.getMessage());
} catch (final EditProtocol.BadInstructionsException e) {
Log.e(LOGTAG, "Bad persistent event binding cannot be applied.", e);
}
}
}
{
final int size = mEditorEventBindings.size();
for (int i = 0; i < size; i++) {
final Pair<String, JSONObject> changeInfo = mEditorEventBindings.get(i);
try {
final ViewVisitor visitor = mProtocol.readEventBinding(changeInfo.second, mTracker);
newEdits.add(new Pair<String, ViewVisitor>(changeInfo.first, visitor));
} catch (final EditProtocol.InapplicableInstructionsException e) {
Log.i(LOGTAG, e.getMessage());
} catch (final EditProtocol.BadInstructionsException e) {
Log.e(LOGTAG, "Bad editor event binding cannot be applied.", e);
}
}
}
final Map<String, List<ViewVisitor>> editMap = new HashMap<String, List<ViewVisitor>>();
final int totalEdits = newEdits.size();
for (int i = 0; i < totalEdits; i++) {
final Pair<String, ViewVisitor> next = newEdits.get(i);
final List<ViewVisitor> mapElement;
if (editMap.containsKey(next.first)) {
mapElement = editMap.get(next.first);
} else {
mapElement = new ArrayList<ViewVisitor>();
editMap.put(next.first, mapElement);
}
mapElement.add(next.second);
}
mEditState.setEdits(editMap);
mSeenExperiments.addAll(toTrack);
mVariantTracker.trackVariants(toTrack);
}
private SharedPreferences getSharedPreferences() {
final String sharedPrefsName = SHARED_PREF_EDITS_FILE + mToken;
return mContext.getSharedPreferences(sharedPrefsName, Context.MODE_PRIVATE);
}
private EditorConnection mEditorConnection;
private ViewSnapshot mSnapshot;
private final Context mContext;
private final String mToken;
private final Lock mStartLock;
private final List<Pair<String,JSONObject>> mEditorChanges;
private final List<Pair<String,JSONObject>> mEditorEventBindings;
private final List<VariantChange> mPersistentChanges;
private final List<Pair<String,JSONObject>> mPersistentEventBindings;
private final Set<Pair<Integer, Integer>> mSeenExperiments;
}
private class Editor implements EditorConnection.Editor {
@Override
public void sendSnapshot(JSONObject message) {
final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_SEND_STATE_FOR_EDITING);
msg.obj = message;
mMessageThreadHandler.sendMessage(msg);
}
@Override
public void performEdit(JSONObject message) {
final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_HANDLE_EDITOR_CHANGES_RECEIVED);
msg.obj = message;
mMessageThreadHandler.sendMessage(msg);
}
@Override
public void bindEvents(JSONObject message) {
final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_HANDLE_EDITOR_BINDINGS_RECEIVED);
msg.obj = message;
mMessageThreadHandler.sendMessage(msg);
}
@Override
public void sendDeviceInfo() {
final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_SEND_DEVICE_INFO);
mMessageThreadHandler.sendMessage(msg);
}
@Override
public void cleanup() {
final Message msg = mMessageThreadHandler.obtainMessage(ViewCrawler.MESSAGE_HANDLE_EDITOR_CLOSED);
mMessageThreadHandler.sendMessage(msg);
}
}
private static class VariantChange {
public VariantChange(String anActivityName, JSONObject someChange, Pair<Integer, Integer> aVariantId) {
activityName = anActivityName;
change = someChange;
variantId = aVariantId;
}
public final String activityName;
public final JSONObject change;
public final Pair<Integer, Integer> variantId;
}
private static class VariantTracker {
public VariantTracker(MixpanelAPI mixpanel) {
mMixpanel = mixpanel;
}
public void trackVariants(Set<Pair <Integer, Integer>> variants) {
if (variants.size() == 0) {
return; // Nothing to track
}
final JSONObject variantObject = new JSONObject();
try {
for (Pair <Integer, Integer> variant:variants) {
final int experimentId = variant.first;
final int variantId = variant.second;
final JSONObject trackProps = new JSONObject();
trackProps.put("$experiment_id", experimentId);
trackProps.put("$variant_id", variantId);
mMixpanel.track("$experiment_started", trackProps);
variantObject.put(Integer.toString(experimentId), variantId);
}
} catch (JSONException e) {
Log.wtf(LOGTAG, "Could not build JSON for reporting experiment start", e);
}
mMixpanel.getPeople().merge("$experiments", variantObject);
mMixpanel.updateSuperProperties(new SuperPropertyUpdate() {
public JSONObject update(JSONObject in) {
try {
in.put("$experiments", variantObject);
} catch (JSONException e) {
Log.wtf(LOGTAG, "Can't write $experiments super property", e);
}
return in;
}
});
}
private final MixpanelAPI mMixpanel;
}
private final MPConfig mConfig;
private final DynamicEventTracker mTracker;
private final SSLSocketFactory mSSLSocketFactory;
private final EditProtocol mProtocol;
private final EditState mEditState;
private final Tweaks mTweaks;
private final Map<String, String> mDeviceInfo;
private final ViewCrawlerHandler mMessageThreadHandler;
private final VariantTracker mVariantTracker;
private static final String SHARED_PREF_EDITS_FILE = "mixpanel.viewcrawler.changes";
private static final String SHARED_PREF_CHANGES_KEY = "mixpanel.viewcrawler.changes";
private static final String SHARED_PREF_BINDINGS_KEY = "mixpanel.viewcrawler.bindings";
@IntDef({
MESSAGE_INITIALIZE_CHANGES,
MESSAGE_CONNECT_TO_EDITOR,
MESSAGE_SEND_STATE_FOR_EDITING,
MESSAGE_HANDLE_EDITOR_CHANGES_RECEIVED,
MESSAGE_SEND_DEVICE_INFO,
MESSAGE_EVENT_BINDINGS_RECEIVED,
MESSAGE_HANDLE_EDITOR_BINDINGS_RECEIVED,
MESSAGE_SEND_EVENT_TRACKED,
MESSAGE_HANDLE_EDITOR_CLOSED,
MESSAGE_VARIANTS_RECEIVED
})
public @interface MessageType {}
private static final int MESSAGE_INITIALIZE_CHANGES = 0;
private static final int MESSAGE_CONNECT_TO_EDITOR = 1;
private static final int MESSAGE_SEND_STATE_FOR_EDITING = 2;
private static final int MESSAGE_HANDLE_EDITOR_CHANGES_RECEIVED = 3;
private static final int MESSAGE_SEND_DEVICE_INFO = 4;
private static final int MESSAGE_EVENT_BINDINGS_RECEIVED = 6;
private static final int MESSAGE_HANDLE_EDITOR_BINDINGS_RECEIVED = 8;
private static final int MESSAGE_SEND_EVENT_TRACKED = 9;
private static final int MESSAGE_HANDLE_EDITOR_CLOSED = 10;
private static final int MESSAGE_VARIANTS_RECEIVED = 11;
private static final int EMULATOR_CONNECT_ATTEMPT_INTERVAL_MILLIS = 1000 * 30;
@SuppressWarnings("unused")
private static final String LOGTAG = "MixpanelAPI.ViewCrawler";
}
|
package com.mixpanel.android.viewcrawler;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.mixpanel.android.mpmetrics.MPConfig;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
@TargetApi(MPConfig.UI_FEATURES_MIN_API)
/* package */ abstract class ViewVisitor {
/**
* OnEvent will be fired when whatever the ViewVisitor installed fires
* (For example, if the ViewVisitor installs watches for clicks, then OnEvent will be called
* on click)
*/
public interface OnEventListener {
public void OnEvent(View host, String eventName, boolean debounce);
}
public static class PathElement {
public PathElement(String vClass, int ix, int vId, int fId, String vTag) {
viewClassName = vClass;
index = ix;
viewId = vId;
findId = fId;
tag = vTag;
}
public String toString() {
try {
final JSONObject ret = new JSONObject();
if (null != viewClassName) {
ret.put("viewClassName", viewClassName);
}
if (index > -1) {
ret.put("index", index);
}
if (viewId > -1) {
ret.put("viewId", viewId);
}
if (findId > -1) {
ret.put("findId", findId);
}
if (null != tag) {
ret.put("tag", tag);
}
return ret.toString();
} catch (JSONException e) {
throw new RuntimeException("Can't serialize PathElement to String", e);
}
}
public final String viewClassName;
public final int index;
public final int viewId;
public final int findId;
public final String tag;
}
/**
* Attempts to apply mutator to every matching view. Use this to update properties
* in the view hierarchy. If accessor is non-null, it will be used to attempt to
* prevent calls to the mutator if the property already has the intended value.
*/
public static class PropertySetVisitor extends ViewVisitor {
public PropertySetVisitor(List<PathElement> path, Caller mutator, Caller accessor) {
super(path);
mMutator = mutator;
mAccessor = accessor;
}
@Override
public void cleanup() {
// Do nothing, we don't have any references and we haven't installed any listeners.
}
@Override
public void accumulate(View found) {
if (null != mAccessor) {
final Object[] setArgs = mMutator.getArgs();
if (1 == setArgs.length) {
final Object desiredValue = setArgs[0];
final Object currentValue = mAccessor.applyMethod(found);
if (desiredValue == currentValue) {
return;
}
if (null != desiredValue) {
if (desiredValue instanceof Bitmap && currentValue instanceof Bitmap) {
final Bitmap desiredBitmap = (Bitmap) desiredValue;
final Bitmap currentBitmap = (Bitmap) currentValue;
if (desiredBitmap.sameAs(currentBitmap)) {
return;
}
} else if (desiredValue.equals(currentValue)) {
return;
}
}
}
}
mMutator.applyMethod(found);
}
protected String name() {
return "Property Mutator";
}
private final Caller mMutator;
private final Caller mAccessor;
}
/**
* Adds an accessibility event, which will fire OnEvent, to every matching view.
*/
public static class AddAccessibilityEventVisitor extends EventTriggeringVisitor {
public AddAccessibilityEventVisitor(List<PathElement> path, int accessibilityEventType, String eventName, OnEventListener listener) {
super(path, eventName, listener, false);
mEventType = accessibilityEventType;
mWatching = new WeakHashMap<View, TrackingAccessibilityDelegate>();
}
@Override
public void cleanup() {
for (final Map.Entry<View, TrackingAccessibilityDelegate> entry:mWatching.entrySet()) {
final View v = entry.getKey();
final TrackingAccessibilityDelegate toCleanup = entry.getValue();
final View.AccessibilityDelegate currentViewDelegate = getOldDelegate(v);
if (currentViewDelegate == toCleanup) {
v.setAccessibilityDelegate(toCleanup.getRealDelegate());
} else if (currentViewDelegate instanceof TrackingAccessibilityDelegate) {
final TrackingAccessibilityDelegate newChain = (TrackingAccessibilityDelegate) currentViewDelegate;
newChain.removeFromDelegateChain(toCleanup);
} else {
// Assume we've been replaced, zeroed out, or for some other reason we're already gone.
// (This isn't too weird, for example, it's expected when views get recycled)
}
}
mWatching.clear();
}
@Override
protected void accumulate(View found) {
final View.AccessibilityDelegate realDelegate = getOldDelegate(found);
if (realDelegate instanceof TrackingAccessibilityDelegate) {
final TrackingAccessibilityDelegate currentTracker = (TrackingAccessibilityDelegate) realDelegate;
if (currentTracker.willFireEvent(getEventName())) {
return; // Don't double track
}
}
// We aren't already in the tracking call chain of the view
final TrackingAccessibilityDelegate newDelegate = new TrackingAccessibilityDelegate(realDelegate);
found.setAccessibilityDelegate(newDelegate);
mWatching.put(found, newDelegate);
}
@Override
protected String name() {
return getEventName() + " event when (" + mEventType + ")";
}
private View.AccessibilityDelegate getOldDelegate(View v) {
View.AccessibilityDelegate ret = null;
try {
Class klass = v.getClass();
Method m = klass.getMethod("getAccessibilityDelegate");
ret = (View.AccessibilityDelegate) m.invoke(v);
} catch (NoSuchMethodException e) {
// In this case, we just overwrite the original.
} catch (IllegalAccessException e) {
// In this case, we just overwrite the original.
} catch (InvocationTargetException e) {
Log.w(LOGTAG, "getAccessibilityDelegate threw an exception when called.", e);
}
return ret;
}
private class TrackingAccessibilityDelegate extends View.AccessibilityDelegate {
public TrackingAccessibilityDelegate(View.AccessibilityDelegate realDelegate) {
mRealDelegate = realDelegate;
}
public View.AccessibilityDelegate getRealDelegate() {
return mRealDelegate;
}
public boolean willFireEvent(final String eventName) {
if (getEventName() == eventName) {
return true;
} else if (mRealDelegate instanceof TrackingAccessibilityDelegate) {
return ((TrackingAccessibilityDelegate) mRealDelegate).willFireEvent(eventName);
} else {
return false;
}
}
public void removeFromDelegateChain(final TrackingAccessibilityDelegate other) {
if (mRealDelegate == other) {
mRealDelegate = other.getRealDelegate();
} else if (mRealDelegate instanceof TrackingAccessibilityDelegate) {
final TrackingAccessibilityDelegate child = (TrackingAccessibilityDelegate) mRealDelegate;
child.removeFromDelegateChain(other);
} else {
// We can't see any further down the chain, just return.
}
}
@Override
public void sendAccessibilityEvent(View host, int eventType) {
if (eventType == mEventType) {
fireEvent(host);
}
if (null != mRealDelegate) {
mRealDelegate.sendAccessibilityEvent(host, eventType);
}
}
private View.AccessibilityDelegate mRealDelegate;
}
private final int mEventType;
private final WeakHashMap<View, TrackingAccessibilityDelegate> mWatching;
}
/**
* Installs a TextWatcher in each matching view. Does nothing if matching views are not TextViews.
*/
public static class AddTextChangeListener extends EventTriggeringVisitor {
public AddTextChangeListener(List<PathElement> path, String eventName, OnEventListener listener) {
super(path, eventName, listener, true);
mWatching = new HashMap<TextView, TextWatcher>();
}
@Override
public void cleanup() {
for (final Map.Entry<TextView, TextWatcher> entry:mWatching.entrySet()) {
final TextView v = entry.getKey();
final TextWatcher watcher = entry.getValue();
v.removeTextChangedListener(watcher);
}
mWatching.clear();
}
@Override
protected void accumulate(View found) {
if (mWatching.containsKey(found)) {
; // Do nothing
} else if (found instanceof TextView) {
final TextView foundTextView = (TextView) found;
final TextWatcher watcher = new TrackingTextWatcher(foundTextView);
foundTextView.addTextChangedListener(watcher);
mWatching.put(foundTextView, watcher);
}
}
@Override
protected String name() {
return getEventName() + " on Text Change";
}
private class TrackingTextWatcher implements TextWatcher {
public TrackingTextWatcher(View boundTo) {
mBoundTo = boundTo;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
; // Nothing
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
; // Nothing
}
@Override
public void afterTextChanged(Editable s) {
fireEvent(mBoundTo);
}
private final View mBoundTo;
}
private final Map<TextView, TextWatcher> mWatching;
}
/**
* Monitors the view tree for the appearance of matching views where there were not
* matching views before. Fires only once per traversal.
*/
public static class ViewDetectorVisitor extends EventTriggeringVisitor {
public ViewDetectorVisitor(List<PathElement> path, String eventName, OnEventListener listener) {
super(path, eventName, listener, false);
mSeen = false;
}
@Override
public void cleanup() {
; // Do nothing, we don't have anything to leak :)
}
@Override
protected void accumulate(View found) {
if (found != null && !mSeen) {
fireEvent(found);
}
mSeen = (found != null);
}
@Override
protected String name() {
return getEventName() + " when Detected";
}
private boolean mSeen;
}
private static abstract class EventTriggeringVisitor extends ViewVisitor {
public EventTriggeringVisitor(List<PathElement> path, String eventName, OnEventListener listener, boolean debounce) {
super(path);
mListener = listener;
mEventName = eventName;
mDebounce = debounce;
}
protected void fireEvent(View found) {
mListener.OnEvent(found, mEventName, mDebounce);
}
protected String getEventName() {
return mEventName;
}
private final OnEventListener mListener;
private final String mEventName;
private final boolean mDebounce;
}
/**
* Scans the View hierarchy below rootView, applying it's operation to each matching child view.
*/
public void visit(View rootView) {
findTargetsInRoot(rootView, mPath);
}
/**
* Removes listeners and frees resources associated with the visitor. Once cleanup is called,
* the ViewVisitor should not be used again.
*/
public abstract void cleanup();
protected ViewVisitor(List<PathElement> path) {
mPath = path;
}
protected abstract void accumulate(View found);
protected abstract String name();
private void findTargetsInRoot(View givenRootView, List<PathElement> path) {
if (path.isEmpty()) {
return;
}
final PathElement rootPathElement = path.get(0);
final List<PathElement> childPath = path.subList(1, path.size());
final View rootView = findFrom(rootPathElement, givenRootView);
if (null != rootView &&
rootPathElement.index <= 0 &&
matches(rootPathElement, rootView)) {
findTargetsInMatchedView(rootView, childPath);
}
}
private void findTargetsInMatchedView(View alreadyMatched, List<PathElement> remainingPath) {
// When this is run, alreadyMatched has already been matched to a path prefix.
// path is a possibly empty "remaining path" suffix left over after the match
if (remainingPath.isEmpty()) {
// Nothing left to match- we're found!
accumulate(alreadyMatched);
return;
}
if (!(alreadyMatched instanceof ViewGroup)) {
// Matching a non-empty path suffix is impossible, because we have no children
return;
}
final ViewGroup parent = (ViewGroup) alreadyMatched;
final PathElement matchElement = remainingPath.get(0);
final List<PathElement> nextPath = remainingPath.subList(1, remainingPath.size());
final int matchIndex = matchElement.index;
final int childCount = parent.getChildCount();
int matchCount = 0;
for (int i = 0; i < childCount; i++) {
final View givenChild = parent.getChildAt(i);
final View child = findFrom(matchElement, givenChild);
if (null != child && matches(matchElement, child)) {
if (matchCount == matchIndex || -1 == matchIndex) {
findTargetsInMatchedView(child, nextPath);
}
matchCount++;
if (matchIndex >= 0 && matchCount > matchIndex) {
return;
}
}
}
}
private View findFrom(PathElement findElement, View subject) {
if (findElement.findId > -1) {
// This could still return subject, which is ok.
return subject.findViewById(findElement.findId);
} else {
return subject;
}
}
private boolean matches(PathElement matchElement, View subject) {
final String matchClassName = matchElement.viewClassName;
if (null != matchClassName) {
Class klass = subject.getClass();
while (true) {
if (klass.getCanonicalName().equals(matchClassName)) {
break;
}
if (klass == Object.class) {
return false;
}
klass = klass.getSuperclass();
}
}
final int matchId = matchElement.viewId;
if (-1 != matchId) {
final int subjectId = subject.getId();
if (subjectId != matchId) {
return false;
}
}
final String matchTag = matchElement.tag;
if (null != matchTag) {
final Object subjectTag = subject.getTag();
if (null == subjectTag || ! matchTag.equals(subjectTag.toString())) {
return false;
}
}
return true;
}
private final List<PathElement> mPath;
private static final String LOGTAG = "MixpanelAPI.ViewVisitor";
}
|
package com.redhat.ceylon.compiler.js.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.redhat.ceylon.compiler.js.AttributeGenerator;
import com.redhat.ceylon.compiler.js.GenerateJsVisitor;
import com.redhat.ceylon.compiler.loader.MetamodelGenerator;
import com.redhat.ceylon.compiler.typechecker.model.Annotation;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Constructor;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Generic;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.SiteVariance;
import com.redhat.ceylon.compiler.typechecker.model.TypeAlias;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.Util;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
/** A convenience class to help with the handling of certain type declarations. */
public class TypeUtils {
static final List<String> splitMetamodelAnnotations = Arrays.asList("ceylon.language::doc",
"ceylon.language::throws", "ceylon.language::see", "ceylon.language::by");
/** Prints the type arguments, usually for their reification. */
public static void printTypeArguments(final Node node, final Map<TypeParameter,ProducedType> targs,
final GenerateJsVisitor gen, final boolean skipSelfDecl, final Map<TypeParameter, SiteVariance> overrides) {
gen.out("{");
boolean first = true;
for (Map.Entry<TypeParameter,ProducedType> e : targs.entrySet()) {
if (first) {
first = false;
} else {
gen.out(",");
}
gen.out(e.getKey().getName(), "$", e.getKey().getDeclaration().getName(), ":");
final ProducedType pt = e.getValue();
if (pt == null) {
gen.out("'", e.getKey().getName(), "'");
} else if (!outputTypeList(node, pt, gen, skipSelfDecl)) {
boolean hasParams = pt.getTypeArgumentList() != null && !pt.getTypeArgumentList().isEmpty();
boolean closeBracket = false;
final TypeDeclaration d = pt.getDeclaration();
if (d instanceof TypeParameter) {
resolveTypeParameter(node, (TypeParameter)d, gen, skipSelfDecl);
} else {
closeBracket = pt.getDeclaration() instanceof TypeAlias==false;
if (closeBracket)gen.out("{t:");
outputQualifiedTypename(node,
node != null && gen.isImported(node.getUnit().getPackage(), pt.getDeclaration()),
pt, gen, skipSelfDecl);
}
if (hasParams) {
gen.out(",a:");
printTypeArguments(node, pt.getTypeArguments(), gen, skipSelfDecl, pt.getVarianceOverrides());
}
SiteVariance siteVariance = overrides == null ? null : overrides.get(e.getKey());
if (siteVariance != null) {
gen.out(",", MetamodelGenerator.KEY_US_VARIANCE, ":");
if (siteVariance == SiteVariance.IN) {
gen.out("'in'");
} else {
gen.out("'out'");
}
}
if (closeBracket) {
gen.out("}");
}
}
}
gen.out("}");
}
public static void outputQualifiedTypename(final Node node, final boolean imported, final ProducedType pt,
final GenerateJsVisitor gen, final boolean skipSelfDecl) {
TypeDeclaration t = pt.getDeclaration();
final String qname = t.getQualifiedNameString();
if (qname.equals("ceylon.language::Nothing")) {
//Hack in the model means hack here as well
gen.out(gen.getClAlias(), "Nothing");
} else if (qname.equals("ceylon.language::null") || qname.equals("ceylon.language::Null")) {
gen.out(gen.getClAlias(), "Null");
} else if (pt.isUnknown()) {
if (!gen.isInDynamicBlock()) {
gen.out("/*WARNING unknown type");
gen.location(node);
gen.out("*/");
}
gen.out(gen.getClAlias(), "Anything");
} else {
gen.out(qualifiedTypeContainer(node, imported, t, gen));
boolean _init = (!imported && pt.getDeclaration().isDynamic()) || t.isAnonymous();
if (_init && !pt.getDeclaration().isToplevel()) {
Declaration dynintc = Util.getContainingClassOrInterface(node.getScope());
if (dynintc == null || dynintc instanceof Scope==false ||
!Util.contains((Scope)dynintc, pt.getDeclaration())) {
_init=false;
}
}
if (_init) {
gen.out("$init$");
}
if (!outputTypeList(null, pt, gen, skipSelfDecl)) {
if (t.isAnonymous()) {
gen.out(gen.getNames().objectName(t));
} else {
gen.out(gen.getNames().name(t));
}
}
if (_init && !(t.isAnonymous() && t.isToplevel())) {
gen.out("()");
}
}
}
static String qualifiedTypeContainer(final Node node, final boolean imported, final TypeDeclaration t,
final GenerateJsVisitor gen) {
final String modAlias = imported ? gen.getNames().moduleAlias(t.getUnit().getPackage().getModule()) : null;
final StringBuilder sb = new StringBuilder();
if (modAlias != null && !modAlias.isEmpty()) {
sb.append(modAlias).append('.');
}
if (t.getContainer() instanceof ClassOrInterface) {
final Scope scope = node == null ? null : Util.getContainingClassOrInterface(node.getScope());
ClassOrInterface parent = (ClassOrInterface)t.getContainer();
final List<ClassOrInterface> parents = new ArrayList<>(3);
parents.add(0, parent);
while (parent != scope && parent.getContainer() instanceof ClassOrInterface) {
parent = (ClassOrInterface)parent.getContainer();
parents.add(0, parent);
}
for (ClassOrInterface p : parents) {
if (p==scope) {
if (gen.opts.isOptimize()) {
sb.append(gen.getNames().self(p)).append('.');
}
} else {
sb.append(gen.getNames().name(p));
if (gen.opts.isOptimize()) {
sb.append(".$$.prototype");
}
sb.append('.');
}
}
}
return sb.toString();
}
/** Prints out an object with a type constructor under the property "t" and its type arguments under
* the property "a", or a union/intersection type with "u" or "i" under property "t" and the list
* of types that compose it in an array under the property "l", or a type parameter as a reference to
* already existing params. */
public static void typeNameOrList(final Node node, final ProducedType pt, final GenerateJsVisitor gen, final boolean skipSelfDecl) {
TypeDeclaration type = pt.getDeclaration();
if (!outputTypeList(node, pt, gen, skipSelfDecl)) {
if (type instanceof TypeParameter) {
resolveTypeParameter(node, (TypeParameter)type, gen, skipSelfDecl);
} else if (type instanceof TypeAlias) {
outputQualifiedTypename(node, node != null && gen.isImported(node.getUnit().getPackage(), type),
pt, gen, skipSelfDecl);
} else {
gen.out("{t:");
outputQualifiedTypename(node, node != null && gen.isImported(node.getUnit().getPackage(), type),
pt, gen, skipSelfDecl);
if (!pt.getTypeArgumentList().isEmpty()) {
final Map<TypeParameter,ProducedType> targs;
if (pt.getDeclaration().isToplevel()) {
targs = pt.getTypeArguments();
} else {
//Gather all type parameters from containers
Scope scope = node.getScope();
final HashSet<TypeParameter> parenttp = new HashSet<>();
while (scope != null) {
if (scope instanceof Generic) {
for (TypeParameter tp : ((Generic)scope).getTypeParameters()) {
parenttp.add(tp);
}
}
scope = scope.getScope();
}
targs = new HashMap<>();
targs.putAll(pt.getTypeArguments());
Declaration cd = Util.getContainingDeclaration(pt.getDeclaration());
while (cd != null) {
if (cd instanceof Generic) {
for (TypeParameter tp : ((Generic)cd).getTypeParameters()) {
if (parenttp.contains(tp)) {
targs.put(tp, tp.getType());
}
}
}
cd = Util.getContainingDeclaration(cd);
}
}
gen.out(",a:");
printTypeArguments(node, targs, gen, skipSelfDecl, pt.getVarianceOverrides());
}
gen.out("}");
}
}
}
/** Appends an object with the type's type and list of union/intersection types. */
public static boolean outputTypeList(final Node node, final ProducedType pt, final GenerateJsVisitor gen, final boolean skipSelfDecl) {
TypeDeclaration d = pt.getDeclaration();
final List<ProducedType> subs;
int seq=0;
if (d instanceof IntersectionType) {
gen.out(gen.getClAlias(), "mit$([");
subs = d.getSatisfiedTypes();
} else if (d instanceof UnionType) {
gen.out(gen.getClAlias(), "mut$([");
subs = d.getCaseTypes();
} else if ("ceylon.language::Tuple".equals(d.getQualifiedNameString())) {
subs = d.getUnit().getTupleElementTypes(pt);
final ProducedType lastType = subs.get(subs.size()-1);
if (lastType.isUnknown() || lastType.getDeclaration() instanceof TypeParameter) {
//Revert to outputting normal Tuple with its type arguments
gen.out("{t:", gen.getClAlias(), "Tuple,a:");
printTypeArguments(node, pt.getTypeArguments(), gen, skipSelfDecl, pt.getVarianceOverrides());
gen.out("}");
return true;
}
if (!d.getUnit().getEmptyDeclaration().equals(lastType.getDeclaration())) {
if (d.getUnit().getSequentialDeclaration().equals(lastType.getDeclaration())) {
seq = 1;
}
if (d.getUnit().getSequenceDeclaration().equals(lastType.getDeclaration())) {
seq = 2;
}
}
if (seq > 0) {
//Non-empty, non-tuple tail; union it with its type parameter
UnionType utail = new UnionType(d.getUnit());
utail.setCaseTypes(Arrays.asList(lastType.getTypeArgumentList().get(0), lastType));
subs.remove(subs.size()-1);
subs.add(utail.getType());
}
gen.out(gen.getClAlias(), "mtt$([");
} else {
return false;
}
boolean first = true;
for (ProducedType t : subs) {
if (!first) gen.out(",");
if (t==subs.get(subs.size()-1) && seq>0) {
//The non-empty, non-tuple tail
gen.out("{t:'u',l:[");
typeNameOrList(node, t.getCaseTypes().get(0), gen, skipSelfDecl);
gen.out(",");
typeNameOrList(node, t.getCaseTypes().get(1), gen, skipSelfDecl);
gen.out("],seq:", Integer.toString(seq), "}");
} else {
typeNameOrList(node, t, gen, skipSelfDecl);
}
first = false;
}
gen.out("])");
return true;
}
/** Finds the owner of the type parameter and outputs a reference to the corresponding type argument. */
static void resolveTypeParameter(final Node node, final TypeParameter tp,
final GenerateJsVisitor gen, final boolean skipSelfDecl) {
Scope parent = Util.getRealScope(node.getScope());
int outers = 0;
while (parent != null && parent != tp.getContainer()) {
if (parent instanceof TypeDeclaration &&
!(parent instanceof Constructor || ((TypeDeclaration) parent).isAnonymous())) {
outers++;
}
parent = parent.getScope();
}
if (tp.getContainer() instanceof ClassOrInterface) {
if (parent == tp.getContainer()) {
if (!skipSelfDecl) {
TypeDeclaration ontoy = Util.getContainingClassOrInterface(node.getScope());
while (ontoy.isAnonymous())ontoy=Util.getContainingClassOrInterface(ontoy.getScope());
gen.out(gen.getNames().self(ontoy));
if (ontoy == parent)outers
for (int i = 0; i < outers; i++) {
gen.out(".outer$");
}
gen.out(".");
}
gen.out("$$targs$$.", tp.getName(), "$", tp.getDeclaration().getName());
} else {
//This can happen in expressions such as Singleton(n) when n is dynamic
gen.out("{/*NO PARENT*/t:", gen.getClAlias(), "Anything}");
}
} else if (tp.getContainer() instanceof TypeAlias) {
if (parent == tp.getContainer()) {
gen.out("'", tp.getName(), "$", tp.getDeclaration().getName(), "'");
} else {
//This can happen in expressions such as Singleton(n) when n is dynamic
gen.out("{/*NO PARENT ALIAS*/t:", gen.getClAlias(), "Anything}");
}
} else {
//it has to be a method, right?
//We need to find the index of the parameter where the argument occurs
//...and it could be null...
int plistCount = -1;
ProducedType type = null;
for (Iterator<ParameterList> iter0 = ((Method)tp.getContainer()).getParameterLists().iterator();
type == null && iter0.hasNext();) {
plistCount++;
for (Iterator<Parameter> iter1 = iter0.next().getParameters().iterator();
type == null && iter1.hasNext();) {
if (type == null) {
type = typeContainsTypeParameter(iter1.next().getType(), tp);
}
}
}
//The ProducedType that we find corresponds to a parameter, whose type can be:
//A type parameter in the method, in which case we just use the argument's type (may be null)
//A component of a union/intersection type, in which case we just use the argument's type (may be null)
//A type argument of the argument's type, in which case we must get the reified generic from the argument
if (tp.getContainer() == parent) {
gen.out("$$$mptypes.", tp.getName(), "$", tp.getDeclaration().getName());
} else {
if (parent == null && node instanceof Tree.StaticMemberOrTypeExpression) {
if (tp.getContainer() == ((Tree.StaticMemberOrTypeExpression)node).getDeclaration()) {
type = ((Tree.StaticMemberOrTypeExpression)node).getTarget().getTypeArguments().get(tp);
typeNameOrList(node, type, gen, skipSelfDecl);
return;
}
}
gen.out("/*METHOD TYPEPARM plist ", Integer.toString(plistCount), "#",
tp.getName(), "*/'", type.getProducedTypeQualifiedName(), "' container " + tp.getContainer() + " y yo estoy en " + node);
}
}
}
static ProducedType typeContainsTypeParameter(ProducedType td, TypeParameter tp) {
TypeDeclaration d = td.getDeclaration();
if (d == tp) {
return td;
} else if (d instanceof UnionType || d instanceof IntersectionType) {
List<ProducedType> comps = td.getCaseTypes();
if (comps == null) comps = td.getSupertypes();
for (ProducedType sub : comps) {
td = typeContainsTypeParameter(sub, tp);
if (td != null) {
return td;
}
}
} else if (d instanceof ClassOrInterface) {
for (ProducedType sub : td.getTypeArgumentList()) {
if (typeContainsTypeParameter(sub, tp) != null) {
return td;
}
}
}
return null;
}
/** Find the type with the specified declaration among the specified type's supertypes, case types, satisfied types, etc. */
public static ProducedType findSupertype(TypeDeclaration d, ProducedType pt) {
if (pt.getDeclaration().equals(d)) {
return pt;
}
List<ProducedType> list = pt.getSupertypes() == null ? pt.getCaseTypes() : pt.getSupertypes();
for (ProducedType t : list) {
if (t.getDeclaration().equals(d)) {
return t;
}
}
return null;
}
public static Map<TypeParameter, ProducedType> matchTypeParametersWithArguments(List<TypeParameter> params, List<ProducedType> targs) {
if (params != null && targs != null && params.size() == targs.size()) {
HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>();
for (int i = 0; i < targs.size(); i++) {
r.put(params.get(i), targs.get(i));
}
return r;
}
return null;
}
public static Map<TypeParameter, ProducedType> wrapAsIterableArguments(ProducedType pt) {
HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>();
final TypeDeclaration iterable = pt.getDeclaration().getUnit().getIterableDeclaration();
r.put(iterable.getTypeParameters().get(0), pt);
r.put(iterable.getTypeParameters().get(1), pt.getDeclaration().getUnit().getNullDeclaration().getType());
return r;
}
public static boolean isUnknown(Declaration d) {
return d == null || d.getQualifiedNameString().equals("UnknownType");
}
public static void spreadArrayCheck(final Tree.Term term, final GenerateJsVisitor gen) {
String tmp = gen.getNames().createTempVariable();
gen.out("(", tmp, "=");
term.visit(gen);
gen.out(",Array.isArray(", tmp, ")?", tmp);
gen.out(":function(){throw new TypeError('Expected JS Array (",
term.getUnit().getFilename(), " ", term.getLocation(), ")')}())");
}
/** Generates the code to throw an Exception if a dynamic object is not of the specified type. */
public static void generateDynamicCheck(final Tree.Term term, ProducedType t,
final GenerateJsVisitor gen, final boolean skipSelfDecl,
final Map<TypeParameter,ProducedType> typeArguments) {
if (t.getDeclaration().isDynamic()) {
gen.out(gen.getClAlias(), "dre$$(");
term.visit(gen);
gen.out(",");
TypeUtils.typeNameOrList(term, t, gen, skipSelfDecl);
gen.out(",'", term.getUnit().getFilename(), " ", term.getLocation(), "')");
} else {
final boolean checkFloat = term.getUnit().getFloatDeclaration().equals(t.getDeclaration());
final boolean checkInt = checkFloat ? false : term.getUnit().getIntegerDeclaration().equals(t.getDeclaration());
String tmp = gen.getNames().createTempVariable();
gen.out("(", tmp, "=");
term.visit(gen);
final String errmsg;
if (checkFloat) {
gen.out(",typeof(", tmp, ")==='number'?", gen.getClAlias(), "Float(", tmp, ")");
errmsg = "Expected Float";
} else if (checkInt) {
gen.out(",typeof(", tmp, ")==='number'?Math.floor(", tmp, ")");
errmsg = "Expected Integer";
} else {
gen.out(",", gen.getClAlias(), "is$(", tmp, ",");
if (t.getDeclaration() instanceof TypeParameter && typeArguments != null
&& typeArguments.containsKey(t.getDeclaration())) {
t = typeArguments.get(t.getDeclaration());
}
TypeUtils.typeNameOrList(term, t, gen, skipSelfDecl);
gen.out(")?", tmp);
errmsg = "Expected " + t.getProducedTypeQualifiedName();
}
gen.out(":function(){throw new TypeError('", errmsg, " (",
term.getUnit().getFilename(), " ", term.getLocation(), ")')}())");
}
}
public static void encodeParameterListForRuntime(Node n, ParameterList plist, GenerateJsVisitor gen) {
boolean first = true;
gen.out("[");
for (Parameter p : plist.getParameters()) {
if (first) first=false; else gen.out(",");
gen.out("{", MetamodelGenerator.KEY_NAME, ":'", p.getName(), "',");
gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',");
ProducedType ptype = p.getType();
if (p.getModel() instanceof Method) {
gen.out("$pt:'f',");
ptype = ((Method)p.getModel()).getTypedReference().getFullType();
}
if (p.isSequenced()) {
gen.out("seq:1,");
}
if (p.isDefaulted()) {
gen.out(MetamodelGenerator.KEY_DEFAULT, ":1,");
}
gen.out(MetamodelGenerator.KEY_TYPE, ":");
metamodelTypeNameOrList(n, gen.getCurrentPackage(), ptype, gen);
if (p.getModel().getAnnotations() != null && !p.getModel().getAnnotations().isEmpty()) {
new ModelAnnotationGenerator(gen, p.getModel(), n).generateAnnotations();
}
gen.out("}");
}
gen.out("]");
}
/** Turns a Tuple type into a parameter list. */
public static List<Parameter> convertTupleToParameters(ProducedType _tuple) {
ArrayList<Parameter> rval = new ArrayList<>();
int pos = 0;
TypeDeclaration tdecl = _tuple.getDeclaration();
final TypeDeclaration empty = tdecl.getUnit().getEmptyDeclaration();
final TypeDeclaration tuple = tdecl.getUnit().getTupleDeclaration();
while (!(empty.equals(tdecl) || tdecl instanceof TypeParameter)) {
Parameter _p = null;
if (tuple.equals(tdecl) || (tdecl.getCaseTypeDeclarations() != null
&& tdecl.getCaseTypeDeclarations().size()==2
&& tdecl.getCaseTypeDeclarations().contains(tuple))) {
_p = new Parameter();
_p.setModel(new Value());
if (tuple.equals(tdecl)) {
_p.getModel().setType(_tuple.getTypeArgumentList().get(1));
_tuple = _tuple.getTypeArgumentList().get(2);
} else {
//Handle union types for defaulted parameters
for (ProducedType mt : _tuple.getCaseTypes()) {
if (tuple.equals(mt.getDeclaration())) {
_p.getModel().setType(mt.getTypeArgumentList().get(1));
_tuple = mt.getTypeArgumentList().get(2);
break;
}
}
_p.setDefaulted(true);
}
} else if (tdecl.inherits(tdecl.getUnit().getSequentialDeclaration())) {
//Handle Sequence, for nonempty variadic parameters
_p = new Parameter();
_p.setModel(new Value());
_p.getModel().setType(_tuple.getTypeArgumentList().get(0));
_p.setSequenced(true);
_tuple = empty.getType();
}
else {
if (pos > 100) {
return rval;
}
}
if (_tuple != null) tdecl = _tuple.getDeclaration();
if (_p != null) {
_p.setName("arg" + pos);
rval.add(_p);
}
pos++;
}
return rval;
}
/** This method encodes the type parameters of a Tuple in the same way
* as a parameter list for runtime. */
private static void encodeTupleAsParameterListForRuntime(final Node node,
ProducedType _tuple, boolean nameAndMetatype, GenerateJsVisitor gen) {
gen.out("[");
int pos = 1;
TypeDeclaration tdecl = _tuple.getDeclaration();
final TypeDeclaration empty = tdecl.getUnit().getEmptyDeclaration();
final TypeDeclaration tuple = tdecl.getUnit().getTupleDeclaration();
while (!(empty.equals(tdecl) || tdecl instanceof TypeParameter)) {
if (pos > 1) gen.out(",");
gen.out("{");
pos++;
if (nameAndMetatype) {
gen.out(MetamodelGenerator.KEY_NAME, ":'p", Integer.toString(pos), "',");
gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',");
}
gen.out(MetamodelGenerator.KEY_TYPE, ":");
if (tuple.equals(tdecl) || (tdecl.getCaseTypeDeclarations() != null
&& tdecl.getCaseTypeDeclarations().size()==2
&& tdecl.getCaseTypeDeclarations().contains(tuple))) {
if (tuple.equals(tdecl)) {
metamodelTypeNameOrList(node, gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(1), gen);
_tuple = _tuple.getTypeArgumentList().get(2);
} else {
//Handle union types for defaulted parameters
for (ProducedType mt : _tuple.getCaseTypes()) {
if (tuple.equals(mt.getDeclaration())) {
metamodelTypeNameOrList(node, gen.getCurrentPackage(), mt.getTypeArgumentList().get(1), gen);
_tuple = mt.getTypeArgumentList().get(2);
break;
}
}
gen.out(",", MetamodelGenerator.KEY_DEFAULT,":1");
}
} else if (tdecl.inherits(tdecl.getUnit().getSequentialDeclaration())) {
ProducedType _t2 = _tuple.getSupertype(tdecl.getUnit().getSequentialDeclaration());
//Handle Sequence, for nonempty variadic parameters
metamodelTypeNameOrList(node, gen.getCurrentPackage(), _t2.getTypeArgumentList().get(0), gen);
gen.out(",seq:1");
_tuple = empty.getType();
} else if (tdecl instanceof UnionType) {
metamodelTypeNameOrList(node, gen.getCurrentPackage(), _tuple, gen);
tdecl = empty; _tuple=null;
} else {
gen.out("\n/*WARNING3! Tuple is actually ", _tuple.getProducedTypeQualifiedName(), ", ", tdecl.getName(),"*/");
if (pos > 100) {
break;
}
}
gen.out("}");
if (_tuple != null) tdecl = _tuple.getDeclaration();
}
gen.out("]");
}
/** This method encodes the Arguments type argument of a Callable the same way
* as a parameter list for runtime. */
public static void encodeCallableArgumentsAsParameterListForRuntime(final Node node,
ProducedType _callable, GenerateJsVisitor gen) {
if (_callable.getCaseTypes() != null) {
for (ProducedType pt : _callable.getCaseTypes()) {
if (pt.getProducedTypeQualifiedName().startsWith("ceylon.language::Callable<")) {
_callable = pt;
break;
}
}
} else if (_callable.getSatisfiedTypes() != null) {
for (ProducedType pt : _callable.getSatisfiedTypes()) {
if (pt.getProducedTypeQualifiedName().startsWith("ceylon.language::Callable<")) {
_callable = pt;
break;
}
}
}
if (!_callable.getProducedTypeQualifiedName().contains("ceylon.language::Callable<")) {
gen.out("[/*WARNING1: got ", _callable.getProducedTypeQualifiedName(), " instead of Callable*/]");
return;
}
List<ProducedType> targs = _callable.getTypeArgumentList();
if (targs == null || targs.size() != 2) {
gen.out("[/*WARNING2: missing argument types for Callable*/]");
return;
}
encodeTupleAsParameterListForRuntime(node, targs.get(1), true, gen);
}
public static void encodeForRuntime(Node that, final Declaration d, final GenerateJsVisitor gen) {
if (d.getAnnotations() == null || d.getAnnotations().isEmpty() ||
(d instanceof com.redhat.ceylon.compiler.typechecker.model.Class && d.isAnonymous())) {
encodeForRuntime(that, d, gen, null);
} else {
encodeForRuntime(that, d, gen, new ModelAnnotationGenerator(gen, d, that));
}
}
/** Output a metamodel map for runtime use. */
public static void encodeForRuntime(final Declaration d, final Tree.AnnotationList annotations, final GenerateJsVisitor gen) {
encodeForRuntime(annotations, d, gen, new RuntimeMetamodelAnnotationGenerator() {
@Override public void generateAnnotations() {
outputAnnotationsFunction(annotations, d, gen);
}
});
}
/** Returns the list of keys to get from the package to the declaration, in the model. */
public static List<String> generateModelPath(final Declaration d) {
final ArrayList<String> sb = new ArrayList<>();
final String pkgName = d.getUnit().getPackage().getNameAsString();
sb.add(Module.LANGUAGE_MODULE_NAME.equals(pkgName)?"$":pkgName);
if (d.isToplevel()) {
sb.add(d.getName());
if (d instanceof Setter) {
sb.add("$set");
}
} else {
Declaration p = d;
final int i = sb.size();
while (p instanceof Declaration) {
if (p instanceof Setter) {
sb.add(i, "$set");
}
sb.add(i, TypeUtils.modelName(p));
//Build the path in reverse
if (!p.isToplevel()) {
if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
sb.add(i, p.isAnonymous() ? MetamodelGenerator.KEY_OBJECTS : MetamodelGenerator.KEY_CLASSES);
} else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
sb.add(i, MetamodelGenerator.KEY_INTERFACES);
} else if (p instanceof Method) {
sb.add(i, MetamodelGenerator.KEY_METHODS);
} else if (p instanceof TypeAlias || p instanceof Setter) {
sb.add(i, MetamodelGenerator.KEY_ATTRIBUTES);
} else if (p instanceof Constructor) {
sb.add(i, MetamodelGenerator.KEY_CONSTRUCTORS);
} else { //It's a value
TypeDeclaration td=((TypedDeclaration)p).getTypeDeclaration();
sb.add(i, (td!=null&&td.isAnonymous())? MetamodelGenerator.KEY_OBJECTS
: MetamodelGenerator.KEY_ATTRIBUTES);
}
}
p = Util.getContainingDeclaration(p);
}
}
return sb;
}
static void outputModelPath(final Declaration d, GenerateJsVisitor gen) {
List<String> parts = generateModelPath(d);
gen.out("[");
boolean first = true;
for (String p : parts) {
if (p.startsWith("anon$") || p.startsWith("anonymous#"))continue;
if (first)first=false;else gen.out(",");
gen.out("'", p, "'");
}
gen.out("]");
}
public static void encodeForRuntime(final Node that, final Declaration d, final GenerateJsVisitor gen,
final RuntimeMetamodelAnnotationGenerator annGen) {
gen.out("function(){return{mod:$CCMM$");
List<TypeParameter> tparms = d instanceof Generic ? ((Generic)d).getTypeParameters() : null;
List<ProducedType> satisfies = null;
List<ProducedType> caseTypes = null;
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
com.redhat.ceylon.compiler.typechecker.model.Class _cd = (com.redhat.ceylon.compiler.typechecker.model.Class)d;
if (_cd.getExtendedType() != null) {
gen.out(",'super':");
metamodelTypeNameOrList(that, d.getUnit().getPackage(), _cd.getExtendedType(), gen);
}
//Parameter types
if (_cd.getParameterList()!=null) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
encodeParameterListForRuntime(that, _cd.getParameterList(), gen);
}
satisfies = _cd.getSatisfiedTypes();
caseTypes = _cd.getCaseTypes();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes();
caseTypes = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getCaseTypes();
} else if (d instanceof MethodOrValue) {
gen.out(",", MetamodelGenerator.KEY_TYPE, ":");
//This needs a new setting to resolve types but not type parameters
metamodelTypeNameOrList(that, d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen);
if (d instanceof Method) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
//Parameter types of the first parameter list
encodeParameterListForRuntime(that, ((Method)d).getParameterLists().get(0), gen);
tparms = ((Method) d).getTypeParameters();
}
} else if (d instanceof Constructor) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
encodeParameterListForRuntime(that, ((Constructor)d).getParameterLists().get(0), gen);
}
if (!d.isToplevel()) {
//Find the first container that is a Declaration
Declaration _cont = Util.getContainingDeclaration(d);
gen.out(",$cont:");
boolean generateName = true;
if (_cont.getName() != null && _cont.getName().startsWith("anonymous
//Anon functions don't have metamodel so go up until we find a non-anon container
Declaration _supercont = Util.getContainingDeclaration(_cont);
while (_supercont != null && _supercont.getName() != null
&& _supercont.getName().startsWith("anonymous
_supercont = Util.getContainingDeclaration(_supercont);
}
if (_supercont == null) {
//If the container is a package, add it because this isn't really toplevel
generateName = false;
gen.out("0");
} else {
_cont = _supercont;
}
}
if (generateName) {
if (_cont instanceof Value) {
if (AttributeGenerator.defineAsProperty(_cont)) {
gen.qualify(that, _cont);
}
gen.out(gen.getNames().getter(_cont, true));
} else if (_cont instanceof Setter) {
gen.out("{setter:");
if (AttributeGenerator.defineAsProperty(_cont)) {
gen.qualify(that, _cont);
gen.out(gen.getNames().getter(((Setter) _cont).getGetter(), true), ".set");
} else {
gen.out(gen.getNames().setter(((Setter) _cont).getGetter()));
}
gen.out("}");
} else {
boolean inProto = gen.opts.isOptimize()
&& (_cont.getContainer() instanceof TypeDeclaration);
final String path = gen.qualifiedPath(that, _cont, inProto);
if (path != null && !path.isEmpty()) {
gen.out(path, ".");
}
gen.out(gen.getNames().name(_cont));
}
}
}
if (tparms != null && !tparms.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{");
encodeTypeParametersForRuntime(that, d, tparms, true, gen);
gen.out("}");
}
if (satisfies != null && !satisfies.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_SATISFIES, ":[");
boolean first = true;
for (ProducedType st : satisfies) {
if (!first)gen.out(",");
first=false;
metamodelTypeNameOrList(that, d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (caseTypes != null && !caseTypes.isEmpty()) {
gen.out(",of:[");
boolean first = true;
for (ProducedType st : caseTypes) {
if (!first)gen.out(",");
first=false;
if (st.getDeclaration().isAnonymous()) {
gen.out(gen.getNames().getter(st.getDeclaration(), true));
} else {
metamodelTypeNameOrList(that, d.getUnit().getPackage(), st, gen);
}
}
gen.out("]");
}
if (annGen != null) {
annGen.generateAnnotations();
}
//Path to its model
gen.out(",d:");
outputModelPath(d, gen);
gen.out("};}");
}
static boolean encodeTypeParametersForRuntime(final Node node, final Declaration d,
final List<TypeParameter> tparms, boolean first, final GenerateJsVisitor gen) {
for(TypeParameter tp : tparms) {
boolean comma = false;
if (!first)gen.out(",");
first=false;
gen.out(tp.getName(), "$", tp.getDeclaration().getName(), ":{");
if (tp.isCovariant()) {
gen.out(MetamodelGenerator.KEY_DS_VARIANCE, ":'out'");
comma = true;
} else if (tp.isContravariant()) {
gen.out(MetamodelGenerator.KEY_DS_VARIANCE, ":'in'");
comma = true;
}
List<ProducedType> typelist = tp.getSatisfiedTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out(MetamodelGenerator.KEY_SATISFIES, ":[");
boolean first2 = true;
for (ProducedType st : typelist) {
if (!first2)gen.out(",");
first2=false;
metamodelTypeNameOrList(node, d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
typelist = tp.getCaseTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("of:[");
boolean first3 = true;
for (ProducedType st : typelist) {
if (!first3)gen.out(",");
first3=false;
metamodelTypeNameOrList(node, d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
if (tp.getDefaultTypeArgument() != null) {
if (comma)gen.out(",");
gen.out("def:");
metamodelTypeNameOrList(node, d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen);
}
gen.out("}");
}
return first;
}
/** Prints out an object with a type constructor under the property "t" and its type arguments under
* the property "a", or a union/intersection type with "u" or "i" under property "t" and the list
* of types that compose it in an array under the property "l", or a type parameter as a reference to
* already existing params. */
static void metamodelTypeNameOrList(final Node node,
final com.redhat.ceylon.compiler.typechecker.model.Package pkg,
ProducedType pt, GenerateJsVisitor gen) {
if (pt == null) {
//In dynamic blocks we sometimes get a null producedType
pt = node.getUnit().getAnythingDeclaration().getType();
}
if (!outputMetamodelTypeList(node, pkg, pt, gen)) {
TypeDeclaration type = pt.getDeclaration();
if (type instanceof TypeParameter) {
gen.out("'", type.getNameAsString(), "$", ((TypeParameter)type).getDeclaration().getName(), "'");
} else if (type instanceof TypeAlias) {
outputQualifiedTypename(node, gen.isImported(pkg, type), pt, gen, false);
} else {
gen.out("{t:");
outputQualifiedTypename(node, gen.isImported(pkg, type), pt, gen, false);
//Type Parameters
if (!pt.getTypeArgumentList().isEmpty()) {
gen.out(",a:{");
boolean first = true;
for (Map.Entry<TypeParameter, ProducedType> e : pt.getTypeArguments().entrySet()) {
if (first) first=false; else gen.out(",");
gen.out(e.getKey().getNameAsString(), "$", e.getKey().getDeclaration().getName(), ":");
metamodelTypeNameOrList(node, pkg, e.getValue(), gen);
}
gen.out("}");
}
gen.out("}");
}
}
}
/** Appends an object with the type's type and list of union/intersection types; works only with union,
* intersection and tuple types.
* @return true if output was generated, false otherwise (it was a regular type) */
static boolean outputMetamodelTypeList(final Node node,
final com.redhat.ceylon.compiler.typechecker.model.Package pkg,
ProducedType pt, GenerateJsVisitor gen) {
TypeDeclaration type = pt.getDeclaration();
final List<ProducedType> subs;
if (type instanceof IntersectionType) {
gen.out("{t:'i");
subs = type.getSatisfiedTypes();
} else if (type instanceof UnionType) {
//It still could be a Tuple with first optional type
List<TypeDeclaration> cts = type.getCaseTypeDeclarations();
if (cts.size()==2 && cts.contains(type.getUnit().getEmptyDeclaration())
&& cts.contains(type.getUnit().getTupleDeclaration())) {
//yup...
gen.out("{t:'T',l:");
encodeTupleAsParameterListForRuntime(node, pt,false,gen);
gen.out("}");
return true;
}
gen.out("{t:'u");
subs = type.getCaseTypes();
} else if (type.getQualifiedNameString().equals("ceylon.language::Tuple")) {
gen.out("{t:'T',l:");
encodeTupleAsParameterListForRuntime(node, pt,false, gen);
gen.out("}");
return true;
} else {
return false;
}
gen.out("',l:[");
boolean first = true;
for (ProducedType t : subs) {
if (!first) gen.out(",");
metamodelTypeNameOrList(node, pkg, t, gen);
first = false;
}
gen.out("]}");
return true;
}
static String pathToModelDoc(final Declaration d) {
if (d == null)return null;
final StringBuilder sb = new StringBuilder();
for (String p : generateModelPath(d)) {
sb.append(sb.length() == 0 ? '\'' : ':').append(p);
}
sb.append('\'');
return sb.toString();
}
/** Outputs a function that returns the specified annotations, so that they can be loaded lazily.
* @param annotations The annotations to be output.
* @param d The declaration to which the annotations belong.
* @param gen The generator to use for output. */
public static void outputAnnotationsFunction(final Tree.AnnotationList annotations, final Declaration d,
final GenerateJsVisitor gen) {
List<Tree.Annotation> anns = annotations == null ? null : annotations.getAnnotations();
if (d != null) {
int mask = MetamodelGenerator.encodeAnnotations(d, null);
if (mask > 0) {
gen.out(",", MetamodelGenerator.KEY_PACKED_ANNS, ":", Integer.toString(mask));
}
if (annotations == null || (anns.isEmpty() && annotations.getAnonymousAnnotation() == null)) {
return;
}
anns = new ArrayList<>(annotations.getAnnotations().size());
anns.addAll(annotations.getAnnotations());
for (Iterator<Tree.Annotation> iter = anns.iterator(); iter.hasNext();) {
final String qn = ((Tree.StaticMemberOrTypeExpression)iter.next().getPrimary()).getDeclaration().getQualifiedNameString();
if (qn.startsWith("ceylon.language::") && MetamodelGenerator.annotationBits.contains(qn.substring(17))) {
iter.remove();
}
}
if (anns.isEmpty() && annotations.getAnonymousAnnotation() == null) {
return;
}
gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":");
}
if (annotations == null || (anns.isEmpty() && annotations.getAnonymousAnnotation()==null)) {
gen.out("[]");
} else {
gen.out("function(){return[");
boolean first = true;
//Leave the annotation but remove the doc from runtime for brevity
if (annotations.getAnonymousAnnotation() != null) {
first = false;
final Tree.StringLiteral lit = annotations.getAnonymousAnnotation().getStringLiteral();
final String ptmd = pathToModelDoc(d);
if (ptmd != null && ptmd.length() < lit.getText().length()) {
gen.out(gen.getClAlias(), "doc$($CCMM$,", ptmd);
} else {
gen.out(gen.getClAlias(), "doc(");
lit.visit(gen);
}
gen.out(")");
}
for (Tree.Annotation a : anns) {
if (first) first=false; else gen.out(",");
gen.getInvoker().generateInvocation(a);
}
gen.out("];}");
}
}
/** Abstraction for a callback that generates the runtime annotations list as part of the metamodel. */
public static interface RuntimeMetamodelAnnotationGenerator {
public void generateAnnotations();
}
static class ModelAnnotationGenerator implements RuntimeMetamodelAnnotationGenerator {
private final GenerateJsVisitor gen;
private final Declaration d;
private final Node node;
ModelAnnotationGenerator(GenerateJsVisitor generator, Declaration decl, Node n) {
gen = generator;
d = decl;
node = n;
}
@Override public void generateAnnotations() {
List<Annotation> anns = d.getAnnotations();
final int bits = MetamodelGenerator.encodeAnnotations(d, null);
if (bits > 0) {
gen.out(",", MetamodelGenerator.KEY_PACKED_ANNS, ":", Integer.toString(bits));
//Remove these annotations from the list
anns = new ArrayList<Annotation>(d.getAnnotations().size());
anns.addAll(d.getAnnotations());
for (Iterator<Annotation> iter = anns.iterator(); iter.hasNext();) {
final Annotation a = iter.next();
final Declaration ad = d.getUnit().getPackage().getMemberOrParameter(d.getUnit(), a.getName(), null, false);
final String qn = ad.getQualifiedNameString();
if (qn.startsWith("ceylon.language::") && MetamodelGenerator.annotationBits.contains(qn.substring(17))) {
iter.remove();
}
}
if (anns.isEmpty()) {
return;
}
}
gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":function(){return[");
boolean first = true;
for (Annotation a : anns) {
Declaration ad = d.getUnit().getPackage().getMemberOrParameter(d.getUnit(), a.getName(), null, false);
if (ad instanceof Method) {
if (first) first=false; else gen.out(",");
final boolean isDoc = "ceylon.language::doc".equals(ad.getQualifiedNameString());
if (!isDoc) {
gen.qualify(node, ad);
gen.out(gen.getNames().name(ad), "(");
}
if (a.getPositionalArguments() == null) {
for (Parameter p : ((Method)ad).getParameterLists().get(0).getParameters()) {
String v = a.getNamedArguments().get(p.getName());
gen.out(v == null ? "undefined" : v);
}
} else {
if (isDoc) {
//Use ref if it's too long
final String ref = pathToModelDoc(d);
final String doc = a.getPositionalArguments().get(0);
if (ref != null && ref.length() < doc.length()) {
gen.out(gen.getClAlias(), "doc$($CCMM$,", ref);
} else {
gen.out(gen.getClAlias(), "doc(\"", JsUtils.escapeStringLiteral(doc), "\"");
}
} else {
boolean farg = true;
for (String s : a.getPositionalArguments()) {
if (farg)farg=false; else gen.out(",");
gen.out("\"", JsUtils.escapeStringLiteral(s), "\"");
}
}
}
gen.out(")");
} else {
gen.out("/*MISSING DECLARATION FOR ANNOTATION ", a.getName(), "*/");
}
}
gen.out("];}");
}
}
/** Generates the right type arguments for operators that are sugar for method calls.
* @param left The left term of the operator
* @param right The right term of the operator
* @param methodName The name of the method that is to be invoked
* @param rightTpName The name of the type argument on the right term
* @param leftTpName The name of the type parameter on the method
* @return A map with the type parameter of the method as key
* and the produced type belonging to the type argument of the term on the right. */
public static Map<TypeParameter, ProducedType> mapTypeArgument(final Tree.BinaryOperatorExpression expr,
final String methodName, final String rightTpName, final String leftTpName) {
Method md = (Method)expr.getLeftTerm().getTypeModel().getDeclaration().getMember(methodName, null, false);
if (md == null) {
expr.addUnexpectedError("Left term of intersection operator should have method named " + methodName);
return null;
}
Map<TypeParameter, ProducedType> targs = expr.getRightTerm().getTypeModel().getTypeArguments();
ProducedType otherType = null;
for (TypeParameter tp : targs.keySet()) {
if (tp.getName().equals(rightTpName)) {
otherType = targs.get(tp);
break;
}
}
if (otherType == null) {
expr.addUnexpectedError("Right term of intersection operator should have type parameter named " + rightTpName);
return null;
}
targs = new HashMap<>();
TypeParameter mtp = null;
for (TypeParameter tp : md.getTypeParameters()) {
if (tp.getName().equals(leftTpName)) {
mtp = tp;
break;
}
}
if (mtp == null) {
expr.addUnexpectedError("Left term of intersection should have type parameter named " + leftTpName);
}
targs.put(mtp, otherType);
return targs;
}
/** Returns the qualified name of a declaration, skipping any containing methods. */
public static String qualifiedNameSkippingMethods(Declaration d) {
final StringBuilder p = new StringBuilder(d.getName());
Scope s = d.getContainer();
while (s != null) {
if (s instanceof com.redhat.ceylon.compiler.typechecker.model.Package) {
final String pkname = ((com.redhat.ceylon.compiler.typechecker.model.Package)s).getNameAsString();
if (!pkname.isEmpty()) {
p.insert(0, "::");
p.insert(0, pkname);
}
} else if (s instanceof TypeDeclaration) {
p.insert(0, '.');
p.insert(0, ((TypeDeclaration)s).getName());
}
s = s.getContainer();
}
return p.toString();
}
public static String modelName(Declaration d) {
String dname = d.getName();
if (dname == null && d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) {
dname = "$def";
}
if (dname.startsWith("anonymous
dname = "anon$" + dname.substring(10);
}
if (d.isToplevel() || d.isShared()) {
return dname;
}
if (d instanceof Setter) {
d = ((Setter)d).getGetter();
}
return dname+"$"+Long.toString(Math.abs((long)d.hashCode()), 36);
}
}
|
package com.sandwell.JavaSimulation3D;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import com.jaamsim.controllers.RenderManager;
import com.jaamsim.input.InputAgent;
import com.jaamsim.math.Vec3d;
import com.jaamsim.ui.FrameBox;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.ObjectType;
import com.sandwell.JavaSimulation.Palette;
public class ObjectSelector extends FrameBox {
private static ObjectSelector myInstance;
// Tree view properties
private DefaultMutableTreeNode top;
private final DefaultTreeModel treeModel;
private final JTree tree;
private final JScrollPane treeView;
protected static Entity currentEntity;
private long entSequence;
public ObjectSelector() {
super( "Object Selector" );
setDefaultCloseOperation( FrameBox.HIDE_ON_CLOSE );
top = new DefaultMutableTreeNode( "Defined Objects");
treeModel = new DefaultTreeModel(top);
tree = new JTree();
tree.setModel(treeModel);
tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION );
updateTree();
treeView = new JScrollPane(tree);
treeView.setPreferredSize(new Dimension(220, 400));
getContentPane().add(treeView);
entSequence = 0;
setLocation(0, 510);
setSize(220, 490);
tree.addTreeSelectionListener( new MyTreeSelectionListener() );
treeModel.addTreeModelListener( new MyTreeModelListener(tree) );
tree.addMouseListener(new MyMouseListener());
tree.addKeyListener(new MyKeyListener());
}
@Override
public void setEntity(Entity ent) {
if(ent == currentEntity || ! this.isVisible())
return;
currentEntity = ent;
updateValues();
if (currentEntity == null) {
tree.setSelectionPath(null);
return;
}
// if the entity is an added entity, allow renaming. otherwise, do not.
if (currentEntity.testFlag(Entity.FLAG_ADDED))
tree.setEditable(true);
else
tree.setEditable(false);
DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot();
Enumeration<?> e = root.depthFirstEnumeration();
while (e.hasMoreElements()) {
DefaultMutableTreeNode aNode = (DefaultMutableTreeNode)e.nextElement();
if (aNode.getUserObject() == currentEntity) {
TreePath path = new TreePath(aNode.getPath());
tree.scrollPathToVisible(path);
tree.setSelectionPath(path);
return;
}
}
}
@Override
public void updateValues() {
if (!this.isVisible())
return;
long curSequence = Entity.getEntitySequence();
if (entSequence != curSequence) {
entSequence = curSequence;
updateTree();
}
}
/**
* Returns the only instance of the Object Selector
*/
public static synchronized ObjectSelector getInstance() {
if (myInstance == null)
myInstance = new ObjectSelector();
return myInstance;
}
@Override
public void dispose() {
myInstance = null;
currentEntity = null;
super.dispose();
}
private void updateTree() {
// Make a best-effort attempt to find all used classes...can race with
// object creation/deletion, but that's ok
ArrayList<Class<? extends Entity>> used = new ArrayList<Class<? extends Entity>>();
for (int i = 0; i < Entity.getAll().size(); i++) {
try {
Class<? extends Entity> klass = Entity.getAll().get(i).getClass();
if (!used.contains(klass))
used.add(klass);
}
catch (IndexOutOfBoundsException e) {}
}
for (Palette p : Palette.getAll()) {
DefaultMutableTreeNode palNode = getNodeFor_In(p.getName(), top);
for( ObjectType type : ObjectType.getAll() ) {
if( type.getPalette() != p )
continue;
Class<? extends Entity> proto = type.getJavaClass();
// skip unused classes
DefaultMutableTreeNode classNode = getNodeFor_In(proto.getSimpleName(), palNode);
if (!used.contains(proto)) {
if( classNode != null ) {
classNode.removeAllChildren();
classNode.removeFromParent();
}
continue;
}
for (int i = 0; i < Entity.getAll().size(); i++) {
try {
Entity each = Entity.getAll().get(i);
// Skip all that do not match the current class
if (each.getClass() != proto)
continue;
// skip locked Entities
if (each.testFlag(Entity.FLAG_LOCKED))
continue;
DefaultMutableTreeNode eachNode = getNodeFor_In(each, classNode);
if(classNode.getIndex(eachNode) < 0)
classNode.add(eachNode);
}
catch (IndexOutOfBoundsException e) {
continue;
}
}
// Remove the killed entities from the class node
Enumeration<?> enumeration = classNode.children();
while (enumeration.hasMoreElements ()) {
DefaultMutableTreeNode each = (DefaultMutableTreeNode) enumeration.nextElement();
if (!Entity.getAll().contains(each.getUserObject())) {
classNode.remove(each);
}
}
if(!classNode.isLeaf()) {
// Class node does not exist in the package node
if(palNode.getIndex(classNode) < 0) {
palNode.add(classNode);
}
}
else if( palNode.getIndex(classNode) >= 0) {
palNode.remove(classNode);
}
}
// Palette node is not empty
if(!palNode.isLeaf()) {
if(top.getIndex(palNode) < 0)
top.add(palNode);
}
else if(top.getIndex(palNode) >= 0) {
top.remove(palNode);
}
}
// Store all the expanded paths
Enumeration<TreePath> expandedPaths = tree.getExpandedDescendants(new TreePath(top));
TreePath selectedPath = tree.getSelectionPath();
treeModel.reload(top); // refresh tree
// Restore all expanded paths and the selected path
tree.setSelectionPath(selectedPath);
while (expandedPaths != null && expandedPaths.hasMoreElements())
{
TreePath path = expandedPaths.nextElement();
tree.expandPath(path);
}
}
/**
* Return a node of userObject in parent
*/
private static DefaultMutableTreeNode getNodeFor_In(Object userObject, DefaultMutableTreeNode parent) {
// obtain all the children in parent
Enumeration<?> enumeration = parent.children();
while (enumeration.hasMoreElements ()) {
DefaultMutableTreeNode eachNode = (DefaultMutableTreeNode) enumeration.nextElement();
if( eachNode.getUserObject() == userObject ||
userObject instanceof String && ((String) userObject).equals(eachNode.getUserObject()) ) {
// This child already exists in parent
return eachNode;
}
}
// Child does not exist in parent; create it
return new DefaultMutableTreeNode(userObject, true);
}
static class MyTreeSelectionListener implements TreeSelectionListener {
@Override
public void valueChanged( TreeSelectionEvent e ) {
JTree tree = (JTree) e.getSource();
if(tree.getLastSelectedPathComponent() == null) {
// This occurs when we set no selected entity (null) and then
// force the tree to have a null selected node
return;
}
DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
if (node.getUserObject() instanceof Entity) {
Entity entity = (Entity)node.getUserObject();
FrameBox.setSelectedEntity(entity);
}
else {
FrameBox.setSelectedEntity(null);
}
}
}
static class MyTreeModelListener implements TreeModelListener {
private final JTree tree;
public MyTreeModelListener(JTree tree) {
this.tree = tree;
}
@Override
public void treeNodesChanged( TreeModelEvent e ) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
String newName = (String)node.getUserObject();
currentEntity.setInputName(newName);
node.setUserObject(currentEntity);
FrameBox.valueUpdate();
}
@Override
public void treeNodesInserted(TreeModelEvent e) {}
@Override
public void treeNodesRemoved(TreeModelEvent e) {}
@Override
public void treeStructureChanged(TreeModelEvent e) {}
}
public static abstract class DEMenuItem {
public String menuName;
public DEMenuItem(String name) {
menuName = name;
}
public abstract void action();
}
static class InputMenuItem extends DEMenuItem {
private final Entity ent;
public InputMenuItem(Entity ent) {
super("Input Editor");
this.ent = ent;
}
@Override
public void action() {
EditBox.getInstance().setVisible(true);
EditBox.getInstance().setExtendedState(JFrame.NORMAL);
EditBox.getInstance().toFront();
FrameBox.setSelectedEntity(ent);
}
}
static class PropertyMenuItem extends DEMenuItem {
private final Entity ent;
public PropertyMenuItem(Entity ent) {
super("Property Viewer");
this.ent = ent;
}
@Override
public void action() {
PropertyBox.getInstance().setVisible(true);
PropertyBox.getInstance().setExtendedState(JFrame.NORMAL);
PropertyBox.getInstance().toFront();
FrameBox.setSelectedEntity(ent);
}
}
static class InfoMenuItem extends DEMenuItem {
private final Entity ent;
public InfoMenuItem(Entity ent) {
super("Info Viewer");
this.ent = ent;
}
@Override
public void action() {
InfoBox.getInstance().setVisible(true);
InfoBox.getInstance().setExtendedState(JFrame.NORMAL);
InfoBox.getInstance().toFront();
FrameBox.setSelectedEntity(ent);
}
}
static class OutputMenuItem extends DEMenuItem {
private final Entity ent;
public OutputMenuItem(Entity ent) {
super("Output Viewer");
this.ent = ent;
}
@Override
public void action() {
OutputBox.getInstance().setVisible(true);
OutputBox.getInstance().setExtendedState(JFrame.NORMAL);
OutputBox.getInstance().toFront();
FrameBox.setSelectedEntity(ent);
}
}
static class DuplicateMenuItem extends DEMenuItem {
private final Entity ent;
public DuplicateMenuItem(Entity ent) {
super("Duplicate");
this.ent = ent;
}
@Override
public void action() {
Entity copiedEntity = InputAgent.defineEntityWithUniqueName(ent.getClass(),
String.format("Copy_of_%s", ent.getInputName()), true);
// Match all the inputs
for(Input<?> each: ent.getEditableInputs() ){
String val = each.getValueString();
if (val.isEmpty())
continue;
Input<?> copiedInput = copiedEntity.getInput(each.getKeyword());
InputAgent.processEntity_Keyword_Value(copiedEntity, copiedInput, val);
}
if (copiedEntity instanceof DisplayEntity) {
DisplayEntity dEnt = (DisplayEntity)copiedEntity;
Vec3d pos = dEnt.getPosition();
pos.x += 0.5d * dEnt.getSize().x;
pos.y += 0.5d * dEnt.getSize().y;
dEnt.setPosition(pos);
}
FrameBox.setSelectedEntity(copiedEntity);
}
}
static class DeleteMenuItem extends DEMenuItem {
private final Entity ent;
public DeleteMenuItem(Entity ent) {
super("Delete");
this.ent = ent;
}
@Override
public void action() {
ent.kill();
FrameBox.setSelectedEntity(null);
}
}
static class GraphicsMenuItem extends DEMenuItem {
private final DisplayEntity ent;
private final int x;
private final int y;
public GraphicsMenuItem(DisplayEntity ent, int x, int y) {
super("Change Graphics");
this.ent = ent;
this.x = x;
this.y = y;
}
@Override
public void action() {
// More than one DisplayModel(LOD) or No DisplayModel
if(ent.getDisplayModelList() == null)
return;
GraphicBox graphicBox = GraphicBox.getInstance(ent, x, y);
graphicBox.setVisible( true );
}
}
static class LabelMenuItem extends DEMenuItem {
private final DisplayEntity ent;
public LabelMenuItem(DisplayEntity ent) {
super("Add Label");
this.ent = ent;
}
@Override
public void action() {
TextLabel label = InputAgent.defineEntityWithUniqueName(TextLabel.class,
String.format("Label_for_%s", ent.getInputName()), true);
InputAgent.processEntity_Keyword_Value(label, "RelativeEntity", ent.getInputName() );
if (ent.getCurrentRegion() != null)
InputAgent.processEntity_Keyword_Value(label, "Region", ent.getCurrentRegion().getInputName());
InputAgent.processEntity_Keyword_Value(label, "Position", "0.0 -1.0 0.0 m" );
InputAgent.processEntity_Keyword_Value(label, "Text", ent.getInputName());
FrameBox.setSelectedEntity(label);
}
}
public static ArrayList<DEMenuItem> getMenuItems(Entity ent, int x, int y) {
ArrayList<DEMenuItem> list = new ArrayList<DEMenuItem>();
list.add(new InputMenuItem(ent));
list.add(new PropertyMenuItem(ent));
list.add(new InfoMenuItem(ent));
list.add(new OutputMenuItem(ent));
if (!ent.testFlag(Entity.FLAG_GENERATED))
list.add(new DuplicateMenuItem(ent));
list.add(new DeleteMenuItem(ent));
if (ent instanceof DisplayEntity) {
if (RenderManager.isGood())
list.add(new GraphicsMenuItem((DisplayEntity)ent, x, y));
list.add(new LabelMenuItem((DisplayEntity)ent));
}
if (ent instanceof MenuItemEntity)
((MenuItemEntity)ent).gatherMenuItems(list, x, y);
return list;
}
static class MyMouseListener implements MouseListener {
private final JPopupMenu menu= new JPopupMenu();
@Override
public void mouseClicked(MouseEvent e) {
if(e.getButton() != MouseEvent.BUTTON3)
return;
if(currentEntity == null)
return;
// Right mouse click on a movable DisplayEntity
menu.removeAll();
GUIFrame.populateMenu(menu, getMenuItems(currentEntity, e.getX(), e.getY()));
menu.show(e.getComponent(), e.getX(), e.getX());
}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
}
static class MyKeyListener implements KeyListener {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_DELETE)
return;
if(currentEntity instanceof DisplayEntity ) {
DisplayEntity disp = (DisplayEntity)currentEntity;
if(! disp.isMovable())
return;
// Delete key was released on a movable DisplayEntity
disp.kill();
FrameBox.setSelectedEntity(null);
}
}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
}
}
|
package com.stratio.cucumber.testng;
import com.stratio.tests.utils.ThreadProperty;
import cucumber.runtime.CucumberException;
import cucumber.runtime.Utils;
import cucumber.runtime.io.URLOutputStream;
import cucumber.runtime.io.UTF8OutputStreamWriter;
import gherkin.formatter.Formatter;
import gherkin.formatter.Reporter;
import gherkin.formatter.model.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
public class CucumberReporter implements Formatter, Reporter {
public static final int DURATION_STRING = 1000000;
public static final int DEFAULT_LENGTH = 11;
public static final int DEFAULT_MAX_LENGTH = 140;
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
private final Writer writer, writerJunit;
private final Document document, jUnitDocument;
private final Element results, jUnitResults;
private final Element suite, jUnitSuite;
private final Element test, jUnitTest;
private Element clazz;
private Element root, jUnitRoot;
private TestMethod testMethod;
private Examples tmpExamples;
private List<Result> tmpHooks = new ArrayList<Result>();
private List<Step> tmpSteps = new ArrayList<Step>();
private List<Step> tmpStepsBG = new ArrayList<Step>();
private Integer iteration = 0;
private Integer position = 0;
private String callerClass;
private Background background;
private static final String STATUS = "status";
long time_start, time_end;
String featureName;
/**
* Constructor of cucumberReporter.
*
* @param url
* @param cClass
* @throws IOException
*/
public CucumberReporter(String url, String cClass, String additional) throws IOException {
this.writer = new UTF8OutputStreamWriter(new URLOutputStream(Utils.toURL(url + cClass + additional
+ "TESTNG.xml")));
this.writerJunit = new UTF8OutputStreamWriter(new URLOutputStream(Utils.toURL(url + cClass + additional
+ "JUNIT.xml")));
TestMethod.treatSkippedAsFailure = false;
try {
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
results = document.createElement("testng-results");
suite = document.createElement("suite");
test = document.createElement("test");
callerClass = cClass;
suite.appendChild(test);
results.appendChild(suite);
document.appendChild(results);
jUnitDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jUnitResults = jUnitDocument.createElement("testsuites");
jUnitSuite = jUnitDocument.createElement("testsuite");
jUnitTest = jUnitDocument.createElement("testcase");
jUnitDocument.appendChild(jUnitResults);
jUnitResults.appendChild(jUnitSuite);
} catch (ParserConfigurationException e) {
throw new CucumberException("Error initializing DocumentBuilder.", e);
}
}
@Override
public void syntaxError(String state, String event, List<String> legalEvents, String uri, Integer line) {
}
@Override
public void uri(String uri) {
}
@Override
public void feature(Feature feature) {
featureName = feature.getName();
clazz = document.createElement("class");
clazz.setAttribute("name", callerClass);
test.appendChild(clazz);
}
@Override
public void scenario(Scenario scenario) {
}
@Override
public void scenarioOutline(ScenarioOutline scenarioOutline) {
iteration = 1;
}
@Override
public void examples(Examples examples) {
tmpExamples = examples;
}
@Override
public void startOfScenarioLifeCycle(Scenario scenario) {
root = document.createElement("test-method");
jUnitRoot = jUnitDocument.createElement("testcase");
jUnitSuite.appendChild(jUnitRoot);
clazz.appendChild(root);
testMethod = new TestMethod(featureName, scenario);
testMethod.hooks = tmpHooks;
tmpStepsBG.clear();
if (tmpExamples == null) {
testMethod.steps = tmpSteps;
testMethod.stepsbg = null;
} else {
testMethod.steps = new ArrayList<Step>();
testMethod.stepsbg = tmpStepsBG;
}
testMethod.examplesData = tmpExamples;
testMethod.start(root, iteration, jUnitRoot);
iteration++;
}
@Override
public void background(Background background) {
this.background = background;
}
@Override
public void step(Step step) {
boolean bgstep = false;
if (background != null && (background.getLineRange().getLast() <= step.getLine())
&& (step.getLine() >= background.getLineRange().getFirst())) {
tmpStepsBG.add(step);
bgstep = true;
}
if (step.getClass().toString().contains("ExampleStep") && !bgstep) {
testMethod.steps.add(step);
} else {
tmpSteps.add(step);
}
}
@Override
public void endOfScenarioLifeCycle(Scenario scenario) {
List<Tag> tags = scenario.getTags();
testMethod.finish(document, root, this.position, tags, jUnitDocument, jUnitRoot);
this.position++;
if ((tmpExamples != null) && (iteration >= tmpExamples.getRows().size())) {
tmpExamples = null;
}
tmpHooks.clear();
tmpSteps.clear();
tmpStepsBG.clear();
testMethod = null;
jUnitRoot.setAttribute("classname", callerClass);
}
@Override
public void eof() {
}
@Override
public void done() {
try {
results.setAttribute("total", String.valueOf(getElementsCountByAttribute(suite, STATUS, ".*")));
results.setAttribute("passed", String.valueOf(getElementsCountByAttribute(suite, STATUS, "PASS")));
results.setAttribute("failed", String.valueOf(getElementsCountByAttribute(suite, STATUS, "FAIL")));
results.setAttribute("skipped", String.valueOf(getElementsCountByAttribute(suite, STATUS, "SKIP")));
suite.setAttribute("name", CucumberReporter.class.getName());
suite.setAttribute("duration-ms",
String.valueOf(getTotalDuration(suite.getElementsByTagName("test-method"))));
test.setAttribute("name", CucumberReporter.class.getName());
test.setAttribute("duration-ms",
String.valueOf(getTotalDuration(suite.getElementsByTagName("test-method"))));
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult streamResult = new StreamResult(writer);
DOMSource domSource = new DOMSource(document);
transformer.transform(domSource, streamResult);
jUnitSuite.setAttribute("name", callerClass + "." + featureName);
jUnitSuite.setAttribute("tests", String.valueOf(getElementsCountByAttribute(suite, STATUS, ".*")));
jUnitSuite.setAttribute("failures", String.valueOf(getElementsCountByAttribute(suite, STATUS, "FAIL")));
jUnitSuite.setAttribute("skipped", String.valueOf(getElementsCountByAttribute(suite, STATUS, "SKIP")));
jUnitSuite.setAttribute("timestamp", new java.util.Date().toString());
jUnitSuite.setAttribute("time",
String.valueOf(getTotalDurationMs(suite.getElementsByTagName("test-method"))));
Transformer transformerJunit = TransformerFactory.newInstance().newTransformer();
transformerJunit.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult streamResultJunit = new StreamResult(writerJunit);
DOMSource domSourceJunit = new DOMSource(jUnitDocument);
transformerJunit.transform(domSourceJunit, streamResultJunit);
} catch (TransformerException e) {
throw new CucumberException("Error transforming report.", e);
}
}
@Override
public void close() {
}
// Reporter methods
@Override
public void before(Match match, Result result) {
tmpHooks.add(result);
}
@Override
public void match(Match match) {
}
@Override
public void result(Result result) {
testMethod.results.add(result);
}
@Override
public void embedding(String mimeType, byte[] data) {
}
@Override
public void write(String text) {
}
@Override
public void after(Match match, Result result) {
testMethod.hooks.add(result);
}
private int getElementsCountByAttribute(Node node, String attributeName, String attributeValue) {
int count = 0;
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
count += getElementsCountByAttribute(node.getChildNodes().item(i), attributeName, attributeValue);
}
NamedNodeMap attributes = node.getAttributes();
if (attributes != null) {
Node namedItem = attributes.getNamedItem(attributeName);
if (namedItem != null && namedItem.getNodeValue().matches(attributeValue)) {
count++;
}
}
return count;
}
private double getTotalDuration(NodeList testCaseNodes) {
double totalDuration = 0;
for (int i = 0; i < testCaseNodes.getLength(); i++) {
try {
String duration = "0";
Node durationms = testCaseNodes.item(i).getAttributes().getNamedItem("duration-ms");
if (durationms != null) {
duration = durationms.getNodeValue();
}
totalDuration += Double.parseDouble(duration);
} catch (NumberFormatException e) {
throw new CucumberException(e);
}
}
return totalDuration;
}
private double getTotalDurationMs(NodeList testCaseNodes) {
return getTotalDuration(testCaseNodes) / 1000;
}
private static final class TestMethod {
private Scenario scenario = null;
private String featureName;
private Examples examplesData;
private static boolean treatSkippedAsFailure = false;
private List<Step> steps;
private List<Step> stepsbg;
private final List<Result> results = new ArrayList<Result>();
private List<Result> hooks;
private Integer iteration = 1;
private TestMethod(String feature, Scenario scenario) {
this.featureName = feature;
this.scenario = scenario;
}
private void start(Element element, Integer iteration, Element JunitElement) {
this.iteration = iteration;
if ((examplesData == null) || (this.iteration >= examplesData.getRows().size())) {
element.setAttribute("name", scenario.getName());
JunitElement.setAttribute("name", scenario.getName());
ThreadProperty.set("dataSet", "");
} else {
String data = obtainOutlineScenariosExamples(examplesData.getRows().get(iteration).getCells().toString());
element.setAttribute("name", scenario.getName() + " " + data);
JunitElement.setAttribute("name", scenario.getName() + " " + data);
ThreadProperty.set("dataSet", data);
}
element.setAttribute("started-at", DATE_FORMAT.format(new Date()));
}
public String obtainOutlineScenariosExamples(String examplesData) {
String data = examplesData.replaceAll("\"", "¨");
return data;
}
/**
* Finish.
*
* @param doc
* @param element
* @param position
* @param tags
*/
public void finish(Document doc, Element element, Integer position, List<Tag> tags, Document docJunit,
Element Junit) {
Junit.setAttribute("time", String.valueOf(calculateTotalDurationString() / 1000));
element.setAttribute("duration-ms", String.valueOf(calculateTotalDurationString()));
element.setAttribute("finished-at", DATE_FORMAT.format(new Date()));
StringBuilder stringBuilder = new StringBuilder();
List<Step> mergedsteps = new ArrayList<Step>();
if (stepsbg != null) {
mergedsteps.addAll(stepsbg);
mergedsteps.addAll(steps);
} else {
mergedsteps.addAll(steps);
}
addStepAndResultListing(stringBuilder, mergedsteps);
Result skipped = null;
Result failed = null;
Boolean ignored = false;
Boolean ignoreReason = false;
String exceptionmsg = "Failed";
for (Tag tag : tags) {
if ("@ignore".equals(tag.getName())){
ignored=true;
for (Tag tagNs : tags) {
if (!(tagNs.getName().equals("@ignore"))) {
//@tillFixed
if ((tagNs.getName()).matches("@tillfixed\\(\\w+-\\d+\\)")){
String issueNumb = tagNs.getName().substring(tagNs.getName().lastIndexOf("(") +1);
exceptionmsg = "This scenario was skipped because of https://stratio.atlassian.net/browse/" + (issueNumb.subSequence(0, issueNumb.length() - 1)).toString().toUpperCase();
ignoreReason = true;
break;
}
//@unimplemented
if (tagNs.getName().matches("@unimplemented")) {
exceptionmsg = "This scenario was skipped because of it is not yet implemented";
ignoreReason = true;
break;
}
//@manual
if (tagNs.getName().matches("@manual")) {
ignoreReason = true;
exceptionmsg = "This scenario was skipped because it is marked as manual.";
break;
}
//@toocomplex
if (tagNs.getName().matches("@toocomplex")) {
exceptionmsg = "This scenario was skipped because of being too complex to test";
ignoreReason = true;
break;
}
}
}
}
}
if (ignored && ignoreReason) {
element.setAttribute(STATUS, "SKIP");
Element exception = createException(doc, "skipped",
exceptionmsg, " ");
element.appendChild(exception);
Element skippedElementJunit = docJunit.createElement("skipped");
Junit.appendChild(skippedElementJunit);
Element systemOut = systemOutPrintJunit(docJunit, exceptionmsg);
Junit.appendChild(systemOut);
} else if (ignored && !ignoreReason) {
element.setAttribute(STATUS, "FAIL");
Element exception = createException(doc, "The scenario has no valid reason for being ignored",
"The scenario has no valid reason for being ignored", "The scenario has no valid reason for being ignored. <p>Valid values: @tillfixed(ISSUE-007) @unimplemented @manual @toocomplex</p>");
element.appendChild(exception);
Element systemOut = createExceptionJunit(docJunit,
"The scenario has no valid reason for being ignored", "The scenario has no valid reason for being ignored." ,
"<p>The scenario has no valid reason for being ignored. Valid values: @tillfixed(ISSUE-007) @unimplemented @manual @toocomplex</p>");
Junit.appendChild(systemOut);
} else {
for (Result result : results) {
if ("failed".equals(result.getStatus())) {
failed = result;
} else if ("undefined".equals(result.getStatus()) || "pending".equals(result.getStatus())) {
skipped = result;
}
}
for (Result result : hooks) {
if (failed == null && "failed".equals(result.getStatus())) {
failed = result;
}
}
if (failed != null) {
element.setAttribute(STATUS, "FAIL");
StringWriter stringWriter = new StringWriter();
failed.getError().printStackTrace(new PrintWriter(stringWriter));
Element exception = createException(doc, failed.getError().getClass().getName(),
stringBuilder.toString(), stringWriter.toString());
element.appendChild(exception);
Element exceptionJunit = createExceptionJunit(docJunit, failed.getError().getClass().getName(),
stringBuilder.toString(), stringWriter.toString());
Junit.appendChild(exceptionJunit);
} else if (skipped != null) {
if (treatSkippedAsFailure) {
element.setAttribute(STATUS, "FAIL");
Element exception = createException(doc, "The scenario has pending or undefined step(s)",
stringBuilder.toString(), "The scenario has pending or undefined step(s)");
element.appendChild(exception);
Element exceptionJunit = createExceptionJunit(docJunit,
"The scenario has pending or undefined step(s)", stringBuilder.toString(),
"The scenario has pending or undefined step(s)");
Junit.appendChild(exceptionJunit);
} else {
element.setAttribute(STATUS, "SKIP");
Element skippedElementJunit = docJunit.createElement("skipped");
Junit.appendChild(skippedElementJunit);
Element systemOut = systemOutPrintJunit(docJunit, stringBuilder.toString());
Junit.appendChild(systemOut);
}
} else {
element.setAttribute(STATUS, "PASS");
Element exception = createException(doc, "NonRealException", stringBuilder.toString(), " ");
element.appendChild(exception);
Element systemOut = systemOutPrintJunit(docJunit, stringBuilder.toString());
Junit.appendChild(systemOut);
}
}
}
private double calculateTotalDurationString() {
double totalDurationNanos = 0;
for (Result r : results) {
totalDurationNanos += r.getDuration() == null ? 0 : r.getDuration();
}
for (Result r : hooks) {
totalDurationNanos += r.getDuration() == null ? 0 : r.getDuration();
}
return totalDurationNanos / DURATION_STRING;
}
public void addStepAndResultListing(StringBuilder sb, List<Step> mergedsteps) {
for (int i = 0; i < mergedsteps.size(); i++) {
String resultStatus = "not executed";
String resultStatusWarn = "*";
if (i < results.size()) {
resultStatus = results.get(i).getStatus();
resultStatusWarn = ((results.get(i).getError() != null) && (results.get(i).getStatus()
.equals("passed"))) ? "(W)" : "";
}
sb.append(mergedsteps.get(i).getKeyword());
sb.append(mergedsteps.get(i).getName());
int len = 0;
len = mergedsteps.get(i).getKeyword().length() + mergedsteps.get(i).getName().length();
if (mergedsteps.get(i).getRows() != null) {
for (DataTableRow row : mergedsteps.get(i).getRows()) {
StringBuilder strrowBuilder = new StringBuilder();
strrowBuilder.append("| ");
for (String cell : row.getCells()) {
strrowBuilder.append(cell).append(" | ");
}
String strrow = strrowBuilder.toString();
len = strrow.length() + DEFAULT_LENGTH;
sb.append("\n ");
sb.append(strrow);
}
}
for (int j = 0; j + len < DEFAULT_MAX_LENGTH; j++) {
sb.append(".");
}
sb.append(resultStatus);
sb.append(resultStatusWarn);
sb.append("\n");
}
String cap = "";
if (!("".equals(cap = hasCapture(featureName, scenario.getName())))) {
sb.append("evidence @ " + System.getProperty("BUILD_URL", "") + "/artifact/testsAT/"+ cap.replaceAll("",""));
}
}
private String hasCapture(String feat, String scen) {
File dir =new File("./target/executions/");
final String[] imgext = {"png"};
Collection<File> files = FileUtils.listFiles(dir, imgext, true);
for (File file: files) {
if (file.getPath().contains(featureName.replaceAll(" ", "_") + "." + scenario.getName().replaceAll(" ", "_")) &&
file.getName().contains("assert")) {
return file.toString();
}
}
return "";
}
private Element createException(Document doc, String clazz, String message, String stacktrace) {
Element exceptionElement = doc.createElement("exception");
exceptionElement.setAttribute("class", clazz);
if (message != null) {
Element messageElement = doc.createElement("message");
messageElement.appendChild(doc.createCDATASection("\r\n<pre>\r\n" + message + "\r\n</pre>\r\n"));
exceptionElement.appendChild(messageElement);
}
Element stacktraceElement = doc.createElement("full-stacktrace");
stacktraceElement.appendChild(doc.createCDATASection(stacktrace));
exceptionElement.appendChild(stacktraceElement);
return exceptionElement;
}
private Element createExceptionJunit(Document doc, String clazz, String message, String stacktrace) {
Element exceptionElement = doc.createElement("failure");
if (message != null) {
exceptionElement.setAttribute("message", "\r\n" + message + "\r\n");
}
exceptionElement.appendChild(doc.createCDATASection(stacktrace));
return exceptionElement;
}
private Element systemOutPrintJunit(Document doc, String message) {
Element systemOut = doc.createElement("system-out");
systemOut.appendChild(doc.createCDATASection("\r\n" + message + "\r\n"));
return systemOut;
}
}
}
|
package com.themastergeneral.moglowstone;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.themastergeneral.moglowstone.blocks.ModBlocks;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.IForgeRegistry;
@Mod("moglowstone")
public class MoGlowstone {
public static MoGlowstone instance;
private static final Logger LOGGER = LogManager.getLogger();
public static final String MODID = "moglowstone";
public MoGlowstone() {
instance = this;
// Register the setup method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
// Register ourselves for server, registry and other game events we are interested in
MinecraftForge.EVENT_BUS.register(this);
}
private void setup(final FMLCommonSetupEvent event)
{
LOGGER.info("Mo' Glowstone is launching.");
}
@Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD)
public static class Registration
{
@SubscribeEvent
public static void registerBlocks(final RegistryEvent.Register<Block> event)
{
IForgeRegistry<Block> blockRegistry = event.getRegistry();
blockRegistry.register(ModBlocks.black_gsblock);
blockRegistry.register(ModBlocks.blue_gsblock);
blockRegistry.register(ModBlocks.brown_gsblock);
blockRegistry.register(ModBlocks.brick_gsblock);
blockRegistry.register(ModBlocks.cyan_gsblock);
blockRegistry.register(ModBlocks.gray_gsblock);
blockRegistry.register(ModBlocks.green_gsblock);
blockRegistry.register(ModBlocks.lamp_gsblock);
blockRegistry.register(ModBlocks.lblue_gsblock);
blockRegistry.register(ModBlocks.lgray_gsblock);
blockRegistry.register(ModBlocks.lime_gsblock);
blockRegistry.register(ModBlocks.magenta_gsblock);
blockRegistry.register(ModBlocks.orange_gsblock);
blockRegistry.register(ModBlocks.red_gsblock);
blockRegistry.register(ModBlocks.pink_gsblock);
blockRegistry.register(ModBlocks.purple_gsblock);
blockRegistry.register(ModBlocks.white_gsblock);
blockRegistry.register(ModBlocks.glowstone_ore);
}
@SubscribeEvent
public static void registerItems(final RegistryEvent.Register<Item> event)
{
IForgeRegistry<Item> itemRegistry = event.getRegistry();
}
}
}
|
package com.twitter.finagle.javaapi;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.*;
import org.jboss.netty.buffer.*;
import org.jboss.netty.channel.*;
import org.jboss.netty.handler.codec.http.*;
import com.twitter.finagle.stub.*;
import com.twitter.finagle.builder.*;
import com.twitter.finagle.thrift.*;
import com.twitter.util.*;
import com.twitter.silly.Silly;
public class ThriftServerTest {
public static void runServer() {
ThriftTypes.add(new ThriftCallFactory<Silly.bleep_args, Silly.bleep_result>
("bleep", Silly.bleep_args.class, Silly.bleep_result.class));
Stub<ThriftCall, ThriftReply> stub =
new Stub<ThriftCall, ThriftReply>() {
@Override
public Future<ThriftReply> call(ThriftCall call) {
Promise<ThriftReply> future = new Promise<ThriftReply>();
if (call.getMethod().equals("bleep")) {
Silly.bleep_result result = (Silly.bleep_result)call.newReply();
result.setSuccess("bleepety bleep");
future.update(new Return<ThriftReply>(call.reply(result)));
}
return future;
}
};
ServerBuilder
.get()
.codec(Codec4J.thrift())
.stub(stub)
.bindTo(new InetSocketAddress("localhost", 10000))
.build();
}
public static void main(String args[]) {
try {
runServer();
} catch (Throwable e) {
System.err.println("Caught top level exception: " + e);
e.printStackTrace();
System.exit(-1);
}
}
}
|
// PostHelper.java
// blogwt
package com.willshex.blogwt.client.helper;
import java.util.List;
import java.util.Map;
import org.markdown4j.Plugin;
import org.markdown4j.client.IncludePlugin;
import org.markdown4j.client.MarkdownProcessor;
import org.markdown4j.client.event.PluginContentReadyEventHandler;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.RootPanel;
import com.willshex.blogwt.client.markdown.Processor;
import com.willshex.blogwt.client.markdown.plugin.FormPlugin;
import com.willshex.blogwt.client.markdown.plugin.MapPlugin;
import com.willshex.blogwt.client.markdown.plugin.part.FormPart;
/**
* @author William Shakour (billy1380)
*
*/
public class PostHelper extends com.willshex.blogwt.shared.helper.PostHelper {
private static MarkdownProcessor processor;
private static final PluginContentReadyEventHandler DEFAULT_PLUGIN_READY_HANDLER = new PluginContentReadyEventHandler() {
@Override
public void ready (PluginContentReadyEvent event, Plugin plugin,
List<String> lines, Map<String, String> params, String id,
String content) {
Element el = Document.get().getElementById(id);
if (plugin instanceof IncludePlugin) {
if (el != null && content != null) {
el.setInnerHTML(content);
}
} else if (plugin instanceof MapPlugin) {
if (el != null) {
MapHelper.showMap(el, lines, params);
}
} else if (plugin instanceof FormPlugin) {
if (el != null && content != null) {
el.removeAllChildren();
Composite form = new FormPart();
RootPanel.get().add(form);
el.appendChild(form.getElement());
}
}
}
};
private static MarkdownProcessor processor () {
if (processor == null) {
processor = new Processor();
}
return processor;
}
public static String makeMarkup (String value) {
return processor().process(value);
}
public static String makeHeading (String value) {
if (!value.startsWith("
value = "#" + value;
}
return makeMarkup(value);
}
public static String makeHeading2 (String value) {
if (!value.startsWith("
value = "##" + value;
}
return makeMarkup(value);
}
/**
* @return
*/
public static HandlerRegistration handlePluginContentReady () {
return processor().addPluginContentReadyHandler(
DEFAULT_PLUGIN_READY_HANDLER);
}
public static void resetEmojiTheme () {
((Processor) processor()).resetEmojiTheme();
}
}
|
package de.onyxbits.tradetrax.pages.edit;
import java.util.List;
import java.util.Vector;
import org.apache.tapestry5.alerts.AlertManager;
import org.apache.tapestry5.alerts.Duration;
import org.apache.tapestry5.alerts.Severity;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.beaneditor.PropertyModel;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import de.onyxbits.tradetrax.entities.Stock;
import de.onyxbits.tradetrax.remix.MoneyRepresentation;
import de.onyxbits.tradetrax.remix.WrappedStock;
import de.onyxbits.tradetrax.services.EventLogger;
import de.onyxbits.tradetrax.services.SettingsStore;
/**
* An editor for splitting and merging {@link Stock}.
*
* @author patrick
*
*/
public class UnitsEditor {
@Property
private long stockId;
@Property
private Stock stock;
@Property
private WrappedStock wrappedStock;
@Inject
private BeanModelSource ledgerSource;
@Component(id = "splitForm")
private Form splitform;
@Property
private int size;
@Component(id = "sizeField")
private TextField sizeField;
@Inject
private Session session;
@Inject
private AlertManager alertManager;
@Inject
private Messages messages;
@Inject
private EventLogger eventLogger;
@Inject
private SettingsStore settingsStore;
public List<WrappedStock> getStocks() {
Vector<WrappedStock> ret = new Vector<WrappedStock>();
MoneyRepresentation mr = new MoneyRepresentation(settingsStore);
try {
Criteria crit = session.createCriteria(Stock.class);
List<Criterion> lst = stock.allowedToMergeWith();
for (Criterion c : lst) {
crit.add(c);
}
@SuppressWarnings("unchecked")
List<Stock> it = crit.list();
for (Stock s : it) {
ret.add(new WrappedStock(s, mr));
}
}
catch (Exception e) {
e.printStackTrace();
}
return ret;
}
protected void onActivate(Long StockId) {
this.stockId = StockId;
stock = (Stock) session.get(Stock.class, stockId);
size = 1;
}
public BeanModel<WrappedStock> getLedgerModel() {
BeanModel<WrappedStock> model = ledgerSource.createDisplayModel(WrappedStock.class, messages);
List<String> lst = model.getPropertyNames();
for (String s : lst) {
PropertyModel nameColumn = model.getById(s);
nameColumn.sortable(false);
}
return model;
}
@CommitAfter
protected Object onSuccess() {
try {
Stock offspring = stock.splitStock(size);
session.save(offspring);
session.update(stock);
eventLogger.split(stock, offspring);
}
catch (Exception e) {
alertManager.alert(Duration.SINGLE, Severity.ERROR,
messages.format("exception", e.getMessage()));
e.printStackTrace();
}
return getClass();
}
@CommitAfter
protected void onMerge(long id) {
try {
Stock m = (Stock) session.load(Stock.class, id);
Stock backup = (Stock) session.load(Stock.class, id);
// Hibernate doesn't like an update and a delete in the same transaction
// when this leads to the same row in a OneToMany mapping. Since we are
// deleting "m" anyways, we can stop the cascade simply by setting the
// references to null.
m.setName(null);
m.setVariant(null);
stock.setUnitCount(stock.getUnitCount() + m.getUnitCount());
session.update(stock);
session.delete(m);
eventLogger.merged(stock, backup);
}
catch (Exception e) {
e.printStackTrace();
alertManager.alert(Duration.SINGLE, Severity.ERROR,
messages.format("exception", e.getMessage()));
}
}
protected Long onPassivate() {
return stockId;
}
}
|
package edu.columbia.tjw.item.algo;
import edu.columbia.tjw.item.ItemRegressorReader;
public interface QuantileBreakdown
{
int getSize();
int findBucket(double x_);
int firstStep(double alpha_);
int lastStep(double alpha_);
double[] getXValues();
double getMean();
double getBucketMean(final int index_);
int getTotalCount();
double getMeanStdDev();
QuantileBreakdown rebucket(final int bucketCount_);
static QuantileBreakdown buildApproximation(final ItemRegressorReader xReader_)
{
return new GKQuantileBreakdown(xReader_);
}
}
|
package gov.nasa.jpl.mbee.viewedit;
import gov.nasa.jpl.mbee.DocGen3Profile;
import gov.nasa.jpl.mbee.DocGenUtils;
import gov.nasa.jpl.mbee.ems.ExportUtility;
import gov.nasa.jpl.mbee.lib.Utils;
import gov.nasa.jpl.mbee.model.Section;
import gov.nasa.jpl.mbee.viewedit.PresentationElement.PEType;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBAbstractVisitor;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBBook;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBColSpec;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBImage;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBList;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBParagraph;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBSection;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBSimpleList;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBTable;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBText;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.DocumentElement;
import gov.nasa.jpl.mgss.mbee.docgen.docbook.From;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.nomagic.magicdraw.core.Application;
import com.nomagic.magicdraw.core.GUILog;
import com.nomagic.magicdraw.core.Project;
import com.nomagic.magicdraw.export.image.ImageExporter;
import com.nomagic.magicdraw.uml.symbols.DiagramPresentationElement;
import com.nomagic.uml2.ext.jmi.helpers.ModelHelper;
import com.nomagic.uml2.ext.jmi.helpers.StereotypesHelper;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Classifier;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Comment;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Constraint;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.DirectedRelationship;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.ElementValue;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Expression;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.InstanceSpecification;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.InstanceValue;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.LiteralString;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Property;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Slot;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.ValueSpecification;
import com.nomagic.uml2.ext.magicdraw.mdprofiles.Extension;
import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype;
public class DBAlfrescoVisitor extends DBAbstractVisitor {
protected JSONObject elements;
private JSONObject views;
private Stack<JSONArray> curContains; //MDEV #674 -- change to a Stack of JSONArrays
private Stack<JSONArray> sibviews; //sibling views (array of view ids)
private Stack<Set<String>> viewElements; //ids of view elements
private Map<String, JSONObject> images;
protected boolean recurse;
private GUILog gl;
private static String FILE_EXTENSION = ".svg";
private Stereotype view = Utils.getViewStereotype();
private Stereotype viewpoint = Utils.getViewpointStereotype();
private Map<From, String> sourceMapping;
private JSONObject view2view; //parent view id to array of children view ids (from sibviews)
private JSONArray noSections = new JSONArray();
private boolean doc;
protected Set<Element> elementSet = new HashSet<Element>();
//for ems 2.2 reference tree
// these are linked hash maps to make recursive sense in ViewPresentationGenerator
private Map<Element, JSONArray> view2elements = new LinkedHashMap<Element, JSONArray>();
private Map<Element, List<PresentationElement>> view2pe = new LinkedHashMap<Element, List<PresentationElement>>();
private Map<Element, List<PresentationElement>> view2peOld = new LinkedHashMap<Element, List<PresentationElement>>();
private Stack<Element> currentView = new Stack<Element>();
private Stack<PresentationElement> currentSection = new Stack<PresentationElement>(); //if currently in section, sections cannot cross views
private Stack<List<InstanceSpecification>> currentInstanceList = new Stack<List<InstanceSpecification>>();
private Stack<List<InstanceSpecification>> currentTableInstances = new Stack<List<InstanceSpecification>>();
private Stack<List<InstanceSpecification>> currentListInstances = new Stack<List<InstanceSpecification>>();
private Stack<List<InstanceSpecification>> currentParaInstances = new Stack<List<InstanceSpecification>>();
private Stack<List<InstanceSpecification>> currentSectionInstances = new Stack<List<InstanceSpecification>>();
private Stack<List<InstanceSpecification>> currentImageInstances = new Stack<List<InstanceSpecification>>();
private Stack<List<InstanceSpecification>> currentManualInstances = new Stack<List<InstanceSpecification>>();
private Stack<List<PresentationElement>> newpe = new Stack<List<PresentationElement>>();
private Classifier paraC = Utils.getOpaqueParaClassifier();
private Classifier tableC = Utils.getOpaqueTableClassifier();
private Classifier listC = Utils.getOpaqueListClassifier();
private Classifier imageC = Utils.getOpaqueImageClassifier();
private Classifier sectionC = Utils.getSectionClassifier();
private boolean main = false; //for ems 2.2 reference tree, only consider generated pe from main view and
//not nested tables/lists since those are embedded in json blob, main is false for Table and List Visitor
private Set<Element> notEditable = new HashSet<Element>();
public DBAlfrescoVisitor(boolean recurse) {
this(recurse, false);
}
public DBAlfrescoVisitor(boolean recurse, boolean main) {
elements = new JSONObject();
views = new JSONObject();
curContains = new Stack<JSONArray>();
sibviews = new Stack<JSONArray>();
viewElements = new Stack<Set<String>>();
this.recurse = recurse;
gl = Application.getInstance().getGUILog();
images = new HashMap<String, JSONObject>();
sourceMapping = new HashMap<From, String>();
sourceMapping.put(From.DOCUMENTATION, "documentation");
sourceMapping.put(From.DVALUE, "value");
sourceMapping.put(From.NAME, "name");
view2view = new JSONObject();
this.main = main;
}
public int getNumberOfElements() {
return elements.size();
}
/**
* Simple getter for images
*/
public Map<String, JSONObject> getImages() {
return images;
}
/**
* Utility to remove all the images
*/
public void removeImages() {
for (String key: images.keySet()) {
String filename = (String)images.get(key).get("abspath");
try {
File file = new File(filename);
if (!file.delete()) {
gl.log("[WARNING]: could not delete " + filename);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@SuppressWarnings("unchecked")
@Override
public void visit(DBBook book) {
JSONArray childviews = new JSONArray();
sibviews.push(childviews);
if (book.getFrom() != null) {
doc = true;
Element docview = book.getFrom();
startView(docview);
for (DocumentElement de: book.getChildren()) {
if (de instanceof DBSection && ((DBSection)de).isView()) {
break;
}
de.accept(this);
}
}
if (recurse || !doc) {
for (DocumentElement de: book.getChildren()) {
if (de instanceof DBSection && ((DBSection)de).isView()) {
de.accept(this);
if (!recurse) {
break;
}
}
}
}
if (doc)
endView(book.getFrom());
sibviews.pop();
}
@Override
public void visit(DBColSpec colspec) {
}
@SuppressWarnings("unchecked")
@Override
public void visit(DBImage image) {
//need to populate view elements with elements in image
JSONObject entry = new JSONObject();
JSONObject imageEntry = new JSONObject();
//for (Element e: Project.getProject(image.getImage()).getDiagram(image.getImage()).getUsedModelElements(false)) {
// addToElements(e);
addToElements(image.getImage());
// export image - also keep track of exported images
DiagramPresentationElement diagram = Application.getInstance().getProject()
.getDiagram(image.getImage());
String svgFilename = image.getImage().getID();
// create image file
File directory = new File("images");
if (!directory.exists()) {
directory.mkdirs();
}
// export the image file
File svgDiagramFile = new File(directory, svgFilename);
try {
ImageExporter.export(diagram, ImageExporter.SVG, svgDiagramFile);
} catch (IOException e) {
e.printStackTrace();
}
// calculate the checksum
long cs = 0;
try {
RandomAccessFile f = new RandomAccessFile(svgDiagramFile.getAbsolutePath(), "r");
byte[] data = new byte[(int)f.length()];
f.read(data);
f.close();
Checksum checksum = new CRC32();
checksum.update(data, 0, data.length);
cs = checksum.getValue();
} catch (IOException e) {
gl.log("Could not calculate checksum: " + e.getMessage());
e.printStackTrace();
}
// Lets rename the file to have the hash code
// make sure this matches what's in the View Editor ImageResource.java
String svgCrcFilename = image.getImage().getID() + "_latest" + FILE_EXTENSION;
//gl.log("Exporting diagram to: " + svgDiagramFile.getAbsolutePath());
// keep record of all images found
imageEntry.put("cs", String.valueOf(cs));
imageEntry.put("abspath", svgDiagramFile.getAbsolutePath());
imageEntry.put("extension", FILE_EXTENSION);
images.put(svgFilename, imageEntry);
//MDEV #674 -- Update the type and id: was hard coded.
entry.put("type", "Image");
entry.put("sysmlid", image.getImage().getID());
curContains.peek().add(entry);
//for ems 2.2 reference tree
if (!main)
return;
InstanceSpecification i = null;
if (!currentImageInstances.peek().isEmpty()) {
i = currentImageInstances.peek().remove(0);
currentInstanceList.remove(i);
}
if (i != null && !i.isEditable())
notEditable.add(i);
PresentationElement parentSec = currentSection.isEmpty() ? null : currentSection.peek();
PresentationElement ipe = new PresentationElement(i, entry, PEType.IMAGE, currentView.peek(), "image", parentSec, null);
newpe.peek().add(ipe);
}
@SuppressWarnings("unchecked")
@Override
public void visit(DBList list) {
DBAlfrescoListVisitor l = new DBAlfrescoListVisitor(recurse, elements);
list.accept(l);
curContains.peek().add(l.getObject());
viewElements.peek().addAll(l.getListElements());
elementSet.addAll(l.getElementSet());
//for ems 2.2 reference tree
if (!main)
return;
InstanceSpecification i = null;
if (!currentListInstances.peek().isEmpty()) {
i = currentListInstances.peek().remove(0);
currentInstanceList.remove(i);
}
if (i != null && !i.isEditable())
notEditable.add(i);
PresentationElement parentSec = currentSection.isEmpty() ? null : currentSection.peek();
PresentationElement ipe = new PresentationElement(i, l.getObject(), PEType.LIST, currentView.peek(), "list", parentSec, null);
newpe.peek().add(ipe);
}
@SuppressWarnings("unchecked")
@Override
public void visit(DBParagraph para) {
JSONObject entry = getJSONForDBParagraph(para);
curContains.peek().add(entry);
//for ems 2.2 reference tree
if (!main)
return;
InstanceSpecification i = null;
if (!currentParaInstances.peek().isEmpty()) {
i = currentParaInstances.peek().remove(0);
currentInstanceList.remove(i);
}
if (i != null && !i.isEditable())
notEditable.add(i);
PresentationElement parentSec = currentSection.isEmpty() ? null : currentSection.peek();
PresentationElement ipe = new PresentationElement(i, entry, PEType.PARA, currentView.peek(), "paragraph", parentSec, null);
newpe.peek().add(ipe);
}
@SuppressWarnings("unchecked")
protected JSONObject getJSONForDBParagraph(DBParagraph para) {
JSONObject entry = new JSONObject();
if (para.getFrom() != null && para.getFromProperty() != null) {
this.addToElements(para.getFrom());
entry.put("sourceType", "reference");
entry.put("source", ExportUtility.getElementID(para.getFrom()));
entry.put("sourceProperty", sourceMapping.get(para.getFromProperty()));
} else {
entry.put("sourceType", "text");
entry.put("text", DocGenUtils.addP(DocGenUtils.fixString(para.getText(), false)));
}
entry.put("type", "Paragraph");
return entry;
}
@SuppressWarnings("unchecked")
@Override
public void visit(DBText text) {
JSONObject entry = getJSONForDBText(text);
curContains.peek().add(entry);
//for ems 2.2 reference tree
if (!main)
return;
InstanceSpecification i = null;
if (!currentParaInstances.peek().isEmpty()) {
i = currentParaInstances.peek().remove(0);
currentInstanceList.remove(i);
}
if (i != null && !i.isEditable())
notEditable.add(i);
PresentationElement parentSec = currentSection.isEmpty() ? null : currentSection.peek();
PresentationElement ipe = new PresentationElement(i, entry, PEType.PARA, currentView.peek(), "paragraph", parentSec, null);
newpe.peek().add(ipe);
}
@SuppressWarnings("unchecked")
protected JSONObject getJSONForDBText(DBText text) {
JSONObject entry = new JSONObject();
if (text.getFrom() != null && text.getFromProperty() != null) {
this.addToElements(text.getFrom());
entry.put("sourceType", "reference");
entry.put("source", ExportUtility.getElementID(text.getFrom()));
entry.put("sourceProperty", sourceMapping.get(text.getFromProperty()));
} else {
entry.put("sourceType", "text");
entry.put("text", DocGenUtils.addP(DocGenUtils.fixString(text.getText(), false)));
}
entry.put("type", "Paragraph");
return entry;
}
@SuppressWarnings("unchecked")
@Override
public void visit(DBSection section) {
if (section.isView()) {
Element eview = section.getFrom();
startView(eview);
for (DocumentElement de: section.getChildren()) {
// if (recurse || !(de instanceof DBSection))
if (!recurse && de instanceof DBSection && ((DBSection)de).isView())
break;
de.accept(this);
addManualInstances(false);
}
//sibviews.pop();
if (section.isNoSection())
noSections.add(eview.getID());
endView(eview);
} else {
startSection(section);
for (DocumentElement de: section.getChildren()) {
de.accept(this);
addManualInstances(false);
}
endSection(section);
}
}
@SuppressWarnings("unchecked")
@Override
public void visit(DBSimpleList simplelist) {
DBHTMLVisitor html = new DBHTMLVisitor();
simplelist.accept(html);
JSONObject entry = new JSONObject();
entry.put("sourceType", "text");
entry.put("text", html.getOut());
entry.put("type", "Paragraph"); // just show it as html for now
curContains.peek().add(entry);
}
@SuppressWarnings("unchecked")
@Override
public void visit(DBTable table) {
DBAlfrescoTableVisitor v = new DBAlfrescoTableVisitor(this.recurse, elements);
table.accept(v);
curContains.peek().add(v.getObject());
viewElements.peek().addAll(v.getTableElements());
elementSet.addAll(v.getElementSet());
//for ems 2.2 reference tree
if (!main)
return;
InstanceSpecification i = null;
if (!currentTableInstances.peek().isEmpty()) {
i = currentTableInstances.peek().remove(0);
currentInstanceList.remove(i);
}
if (i != null && !i.isEditable())
notEditable.add(i);
PresentationElement parentSec = currentSection.isEmpty() ? null : currentSection.peek();
PresentationElement ipe = new PresentationElement(i, v.getObject(), PEType.TABLE, currentView.peek(), table.getTitle() != null ? table.getTitle() : "table", parentSec, null);
newpe.peek().add(ipe);
}
@SuppressWarnings("unchecked")
public void startView(Element e) {
JSONObject view = new JSONObject();
JSONObject specialization = new JSONObject();
//MDEV #673
//Update code to create a specialization
//object and then insert appropriate
//sub-elements in that specialization object.
if (StereotypesHelper.hasStereotypeOrDerived(e, Utils.getProductStereotype()))
specialization.put("type", "Product");
else
specialization.put("type", "View");
view.put("specialization", specialization);
String id = e.getID();
view.put("sysmlid", id);
views.put(id, view);
Set<String> viewE = new HashSet<String>();
viewElements.push(viewE);
//JJS : may need to make this a Stack
JSONArray contains = new JSONArray();
specialization.put("contains", contains);
this.curContains.push(contains);
addToElements(e);
//MDEV-443 add view exposed elements to view elements
/*for (Element exposed: Utils.collectDirectedRelatedElementsByRelationshipStereotypeString(e,
DocGen3Profile.queriesStereotype, 1, false, 1))
addToElements(exposed);*/
sibviews.peek().add(e.getID());
JSONArray childViews = new JSONArray();
sibviews.push(childViews);
//for ems 2.2 reference tree
currentView.push(e);
List<PresentationElement> viewChildren = new ArrayList<PresentationElement>();
newpe.push(viewChildren);
view2pe.put(e, viewChildren);
view2peOld.put(e, new ArrayList<PresentationElement>());
Expression ex = null;
Constraint c = findViewConstraint(e);
if (c != null && c.getSpecification() instanceof Expression)
ex = (Expression)c.getSpecification();
processCurrentInstances(ex, e, true);
if (c != null && !c.isEditable())
notEditable.add(c);
if (c == null && !e.isEditable())
notEditable.add(e);
addManualInstances(false);
}
@SuppressWarnings("unchecked")
public void endView(Element e) {
JSONArray viewEs = new JSONArray();
viewEs.addAll(viewElements.pop());
//MDEV #673: update code to use the
//specialization element.
JSONObject view = (JSONObject)views.get(e.getID());
JSONObject specialization = (JSONObject)view.get("specialization");
specialization.put("displayedElements", viewEs);
specialization.put("allowedElements", viewEs);
if (recurse && !doc)
specialization.put("childrenViews", sibviews.peek());
view2view.put(e.getID(), sibviews.pop());
this.curContains.pop();
//for ems 2.2 reference tree
view2elements.put(e, viewEs);
addManualInstances(true);
processUnusedInstances(e);
newpe.pop();
currentView.pop();
currentManualInstances.pop();
currentImageInstances.pop();
currentSectionInstances.pop();
currentParaInstances.pop();
currentListInstances.pop();
currentTableInstances.pop();
currentInstanceList.pop();
}
protected void startSection(DBSection section) {
JSONObject newSection = new JSONObject();
newSection.put("type", "Section");
newSection.put("name", section.getTitle());
JSONArray secArray = new JSONArray();
newSection.put("contains", secArray);
this.curContains.peek().add(newSection);
this.curContains.push(secArray);
//for ems 2.2 reference tree
InstanceSpecification sec = null;
Element loopElement = null;
if (section.getDgElement() instanceof Section) {
if (((Section)section.getDgElement()).getLoopElement() != null) {
loopElement = ((Section)section.getDgElement()).getLoopElement();
sec = findInstanceForSection(loopElement);
} else
sec = findInstanceForSection(null);
}
if (sec != null) {
currentInstanceList.peek().remove(sec);
currentSectionInstances.peek().remove(sec);
}
if (sec != null && !sec.isEditable())
notEditable.add(sec);
PresentationElement parentSec = currentSection.isEmpty() ? null : currentSection.peek();
List<PresentationElement> secChildren = new ArrayList<PresentationElement>();
PresentationElement pe = new PresentationElement(sec, newSection, PEType.SECTION, currentView.peek(), section.getTitle() != null ? section.getTitle() : "section", parentSec, secChildren);
pe.setLoopElement(loopElement);
newpe.peek().add(pe);
currentSection.push(pe);
newpe.push(secChildren);
Expression e = null;
if (sec != null && sec.getSpecification() instanceof Expression)
e = (Expression)sec.getSpecification();
processCurrentInstances(e, currentView.peek(), false);
addManualInstances(false);
}
protected void endSection(DBSection section) {
this.curContains.pop();
//for ems 2.2 reference tree
addManualInstances(true);
processUnusedInstances(currentView.peek());
newpe.pop();
currentSection.pop();
currentManualInstances.pop();
currentImageInstances.pop();
currentSectionInstances.pop();
currentParaInstances.pop();
currentListInstances.pop();
currentTableInstances.pop();
currentInstanceList.pop();
}
@SuppressWarnings("unchecked")
protected void addToElements(Element e) {
if (!ExportUtility.shouldAdd(e))
return;
if (!viewElements.empty())
viewElements.peek().add(ExportUtility.getElementID(e));
if (elements.containsKey(e.getID()))
return;
elementSet.add(e);
JSONObject elementInfo = new JSONObject();
ExportUtility.fillElement(e, elementInfo);
elements.put(e.getID(), elementInfo);
/*if (e instanceof DirectedRelationship) {
JSONObject sourceInfo = new JSONObject();
JSONObject targetInfo = new JSONObject();
Element source = ModelHelper.getClientElement(e);
Element target = ModelHelper.getSupplierElement(e);
ExportUtility.fillElement(source, sourceInfo);
ExportUtility.fillElement(target, targetInfo);
elements.put(source.getID(), sourceInfo);
elements.put(target.getID(), targetInfo);
}*/
//if (e instanceof Property || e instanceof Slot)
// elements.putAll(ExportUtility.getReferencedElements(e));
}
public JSONObject getElements() {
return elements;
}
public JSONObject getViews() {
return views;
}
public JSONObject getHierarchy() {
return view2view;
}
public JSONArray getNosections() {
return noSections;
}
public Map<Element, JSONArray> getView2Elements() {
return view2elements;
}
public Set<Element> getElementSet() {
return elementSet;
}
public Map<Element, List<PresentationElement>> getView2Pe() {
return view2pe;
}
public Map<Element, List<PresentationElement>> getView2Unused() {
return view2peOld;
}
private Constraint findViewConstraint(Element view) {
return Utils.getViewConstraint(view);
}
public Set<Element> getNotEditable() {
return notEditable;
}
private void processCurrentInstances(Expression e, Element view, boolean topLevel) {
List<InstanceSpecification> tables = new ArrayList<InstanceSpecification>();
List<InstanceSpecification> lists = new ArrayList<InstanceSpecification>();
List<InstanceSpecification> sections = new ArrayList<InstanceSpecification>();
List<InstanceSpecification> paras = new ArrayList<InstanceSpecification>();
List<InstanceSpecification> images = new ArrayList<InstanceSpecification>();
List<InstanceSpecification> manuals = new ArrayList<InstanceSpecification>();
List<InstanceSpecification> all = new ArrayList<InstanceSpecification>();
if (e != null) {
for (ValueSpecification vs: e.getOperand()) {
if (vs instanceof InstanceValue) {
InstanceSpecification is = ((InstanceValue)vs).getInstance();
if (is == null)
continue;
if (!is.getClassifier().isEmpty()) {
List<Classifier> iscs = is.getClassifier();
boolean viewinstance = false;
for (Element el: is.getOwnedElement()) {
if (el instanceof Slot && ((Slot)el).getDefiningFeature().getName().equals("generatedFromView") &&
!((Slot)el).getValue().isEmpty() && ((Slot)el).getValue().get(0) instanceof ElementValue &&
((ElementValue)((Slot)el).getValue().get(0)).getElement() == view)
viewinstance = true;
}
if (iscs.contains(paraC) && topLevel && is.getSpecification() instanceof LiteralString) {
try {
JSONObject ob = (JSONObject)(new JSONParser()).parse(((LiteralString)is.getSpecification()).getValue());
if (view.getID().equals(ob.get("source")) && "documentation".equals(ob.get("sourceProperty"))) {
viewinstance = true;
}
} catch (Exception x) {}
}
if (viewinstance) {//instance generated by current view
if (iscs.contains(paraC))
paras.add(is);
else if (iscs.contains(tableC))
tables.add(is);
else if (iscs.contains(listC))
lists.add(is);
else if (iscs.contains(imageC))
images.add(is);
else if (iscs.contains(sectionC))
sections.add(is);
} else {
manuals.add(is);
}
all.add(is);
}
}
}
}
currentInstanceList.push(all);
currentImageInstances.push(images);
currentTableInstances.push(tables);
currentParaInstances.push(paras);
currentListInstances.push(lists);
currentSectionInstances.push(sections);
currentManualInstances.push(manuals);
}
private InstanceSpecification findInstanceForSection(Element e) {
if (e != null) {
for (InstanceSpecification is: currentSectionInstances.peek()) {
for (Element el: is.getOwnedElement()) {
if (el instanceof Slot && ((Slot)el).getDefiningFeature().getName().equals("generatedFromElement") &&
!((Slot)el).getValue().isEmpty() && ((Slot)el).getValue().get(0) instanceof ElementValue &&
((ElementValue)((Slot)el).getValue().get(0)).getElement() == e)
return is;
}
}
return null;
}
for (InstanceSpecification is: currentSectionInstances.peek()) {
boolean loop = false;
for (Element el: is.getOwnedElement()) {
if (el instanceof Slot && ((Slot)el).getDefiningFeature().getName().equals("generatedFromElement"))
loop = true;
break;
}
if (loop)
continue;
return is;
}
return null;
}
private void addManualInstances(boolean all) {
List<InstanceSpecification> instances = currentInstanceList.peek();
List<InstanceSpecification> manuals = currentManualInstances.peek();
while (!instances.isEmpty() && manuals.contains(instances.get(0))) {
InstanceSpecification is = instances.get(0);
PresentationElement pe = new PresentationElement(is, null, null, null, null, null, null);
pe.setManual(true);
newpe.peek().add(pe);
manuals.remove(is);
instances.remove(is);
}
if (all) {
for (InstanceSpecification is: new ArrayList<InstanceSpecification>(manuals)) {
PresentationElement pe = new PresentationElement(is, null, null, null, null, null, null);
pe.setManual(true);
newpe.peek().add(pe);
manuals.remove(is);
instances.remove(is);
}
}
}
private void processUnusedInstances(Element v) {
for (InstanceSpecification is: currentTableInstances.peek()) {
view2peOld.get(v).add(new PresentationElement(is, null, PEType.TABLE, v, is.getName(), null, null));
}
for (InstanceSpecification is: currentListInstances.peek()) {
view2peOld.get(v).add(new PresentationElement(is, null, PEType.LIST, v, is.getName(), null, null));
}
for (InstanceSpecification is: currentParaInstances.peek()) {
view2peOld.get(v).add(new PresentationElement(is, null, PEType.PARA, v, is.getName(), null, null));
}
for (InstanceSpecification is: currentImageInstances.peek()) {
view2peOld.get(v).add(new PresentationElement(is, null, PEType.IMAGE, v, is.getName(), null, null));
}
for (InstanceSpecification is: currentSectionInstances.peek()) {
view2peOld.get(v).add(new PresentationElement(is, null, PEType.SECTION, v, is.getName(), null, null));
}
}
}
|
package io.bootique.job.scheduler.execution;
import io.bootique.job.Job;
import io.bootique.job.JobListener;
import io.bootique.job.runnable.JobResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
class Callback implements Consumer<Consumer<JobResult>> {
private static final Logger LOGGER = LoggerFactory.getLogger(Callback.class);
static JobResult runAndNotify(Job job, Map<String, Object> parameters, Set<JobListener> listeners) {
if (listeners.isEmpty()) {
return job.run(parameters);
}
String jobName = job.getMetadata().getName();
Callback callback = new Callback(jobName);
listeners.forEach(listener -> {
try {
listener.onJobStarted(jobName, parameters, callback);
} catch (Exception e) {
LOGGER.error("Error invoking job listener for job: " + jobName, e);
}
});
JobResult result;
try {
result = job.run(parameters);
} catch (Exception e) {
callback.invoke(JobResult.failure(job.getMetadata(), e));
throw e;
}
if (result == null) {
result = JobResult.unknown(job.getMetadata());
}
callback.invoke(result);
return result;
}
private String jobName;
private List<Consumer<JobResult>> callbacks;
public Callback(String jobName) {
this.jobName = jobName;
}
@Override
public void accept(Consumer<JobResult> callback) {
if (callbacks == null) {
callbacks = new ArrayList<>();
}
callbacks.add(callback);
}
public void invoke(JobResult result) {
callbacks.forEach(cb -> {
try {
cb.accept(result);
} catch (Exception e) {
LOGGER.error("Error invoking completion callback for job: " + jobName, e);
}
});
}
}
|
package io.dropwizard.grpc.client;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import io.dropwizard.setup.Environment;
import io.dropwizard.util.Duration;
import io.dropwizard.validation.MinDuration;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
/**
* A factory for building {@link ManagedChannel}s in dropwizard applications.
* <p>
* <b>Configuration Parameters:</b>
* <table summary="Configuration Parameters">
* <tr>
* <td>Name</td>
* <td>Default</td>
* <td>Description</td>
* </tr>
* <tr>
* <td>{@code hostname}</td>
* <td>(none)</td>
* <td>Hostname of the gRPC server to connect to.</td>
* </tr>
* <tr>
* <td>{@code port}</td>
* <td>-1</td>
* <td>Port of the gRPC server to connect to.</td>
* </tr>
* <tr>
* <td>{@code shutdownPeriod}</td>
* <td>5 seconds</td>
* <td>How long to wait before giving up when the channel is shutdown.</td>
* </tr>
* </table>
*/
// TODO NettyChannelBuilder with client-side TLS validation
// TODO ClientInterceptor to collect dropwizard metrics
// TODO ClientInterceptor to send rpc call and exception events to logback
public class GrpcChannelFactory {
@NotEmpty
private String hostname;
@Min(1)
@Max(65535)
private int port = -1;
@MinDuration(1)
private Duration shutdownPeriod = Duration.seconds(5);
@JsonProperty
public String getHostname() {
return hostname;
}
@JsonProperty
public void setHostname(final String hostname) {
this.hostname = hostname;
}
@JsonProperty
public int getPort() {
return port;
}
@JsonProperty
public void setPort(final int port) {
this.port = port;
}
@JsonProperty
public Duration getShutdownPeriod() {
return shutdownPeriod;
}
@JsonProperty
public void setShutdownPeriod(final Duration duration) {
this.shutdownPeriod = duration;
}
/**
* @return A {@link ManagedChannelBuilder}, with hostname and port set from the configuration and plaintext
* communication enabled. The builder can be customized further, e.g. to add channel-wide interceptors.
*/
public ManagedChannelBuilder builder() {
return ManagedChannelBuilder.forAddress(getHostname(), getPort()).usePlaintext();
}
/**
* @param environment to use
* @return A {@link ManagedChannel} with hostname and port set from the configuration and plaintext communication
* enabled. The returned channel is lifecycle-managed in the given {@link Environment}.
*/
public ManagedChannel build(final Environment environment) {
final ManagedChannel managedChannel;
managedChannel = builder().build();
environment.lifecycle().manage(new ManagedGrpcChannel(managedChannel, shutdownPeriod));
return managedChannel;
}
}
|
package io.fabric8.maven.docker.service;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import io.fabric8.maven.docker.access.DockerAccess;
import io.fabric8.maven.docker.model.Container;
import io.fabric8.maven.docker.model.Network;
import io.fabric8.maven.docker.access.DockerAccessException;
import io.fabric8.maven.docker.util.AutoPullMode;
import org.apache.maven.plugin.MojoExecutionException;
/**
* Query service for getting image and container information from the docker dameon
*
*/
public class QueryService {
// Access to docker daemon & logger
private DockerAccess docker;
/**
* Constructor which gets its dependencies as args)
* @param docker remote access to docker daemon
* */
public QueryService(DockerAccess docker) {
this.docker = docker;
}
/**
* Get container by id
*
* @param containerIdOrName container id or name
* @return container found
* @throws DockerAccessException if an error occurs or no container with this id or name exists
*/
public Container getMandatoryContainer(String containerIdOrName) throws DockerAccessException {
Container container = getContainer(containerIdOrName);
if (container == null) {
throw new DockerAccessException("Cannot find container %s", containerIdOrName);
}
return container;
}
/**
* Get a container running for a given container name.
* @param containerIdOrName name of container to lookup
* @return the container found or <code>null</code> if no container is available.
* @throws DockerAccessException in case of an remote error
*/
public Container getContainer(final String containerIdOrName) throws DockerAccessException {
return docker.getContainer(containerIdOrName);
}
/**
* Get a network for a given network name.
* @param networkName name of network to lookup
* @return the network found or <code>null</code> if no network is available.
* @throws DockerAccessException in case of an remote error
*/
public Network getNetworkByName(final String networkName) throws DockerAccessException {
for (Network el : docker.listNetworks()) {
if (networkName.equals(el.getName())) {
return el;
}
}
return null;
}
/**
* Get all networks.
* @return the network found or <code>null</code> if no network is available.
* @throws DockerAccessException in case of an remote error
*/
public Set<Network> getNetworks() throws DockerAccessException {
return new HashSet<>(docker.listNetworks());
}
/**
* Get name for single container when the id is given
*
* @param containerId id of container to lookup
* @return the name of the container
* @throws DockerAccessException if access to the docker daemon fails
*/
public String getContainerName(String containerId) throws DockerAccessException {
return getMandatoryContainer(containerId).getName();
}
/**
* Get all containers which are build from an image. By default only the last containers are considered but this
* can be tuned with a global parameters.
*
* @param image for which its container are looked up
* @return list of <code>Container</code> objects
* @throws DockerAccessException if the request fails
*/
public List<Container> getContainersForImage(final String image) throws DockerAccessException {
return docker.getContainersForImage(image);
}
/**
* Finds the id of an image.
*
* @param imageName name of the image.
* @return the id of the image
* @throws DockerAccessException if the request fails
*/
public String getImageId(String imageName) throws DockerAccessException {
return docker.getImageId(imageName);
}
/**
* Get the id of the latest container started for an image
*
* @param image for which its container are looked up
* @return container or <code>null</code> if no container has been started for this image.
* @throws DockerAccessException if the request fails
*/
public Container getLatestContainerForImage(String image) throws DockerAccessException {
long newest = 0;
Container result = null;
for (Container container : getContainersForImage(image)) {
long timestamp = container.getCreated();
if (timestamp < newest) {
continue;
}
newest = timestamp;
result = container;
}
return result;
}
/**
* Check whether a container with the given name exists
*
* @param containerName container name
* @return true if a container with this name exists, false otherwise.
* @throws DockerAccessException
*/
public boolean hasContainer(String containerName) throws DockerAccessException {
return getContainer(containerName) != null;
}
/**
* Check whether a network with the given name exists
*
* @param networkName network name
* @return true if a network with this name exists, false otherwise.
* @throws DockerAccessException
*/
public boolean hasNetwork(String networkName) throws DockerAccessException {
return getNetworkByName(networkName) != null;
}
/**
* Check whether the given Image is locally available.
*
* @param name name of image to check, the image can contain a tag, otherwise 'latest' will be appended
* @return true if the image is locally available or false if it must be pulled.
* @throws DockerAccessException if the request fails
*/
public boolean hasImage(String name) throws DockerAccessException {
return docker.hasImage(name);
}
}
|
package io.sigpipe.sing.stat;
import io.sigpipe.sing.serialization.ByteSerializable;
import io.sigpipe.sing.serialization.SerializationInputStream;
import io.sigpipe.sing.serialization.SerializationOutputStream;
import java.io.IOException;
import org.apache.commons.math3.distribution.TDistribution;
import org.apache.commons.math3.util.FastMath;
/**
* Provides an online method for computing mean, variance, and standard
* deviation. Based on "Note on a Method for Calculating Corrected Sums of
* Squares and Products" by B. P. Welford.
*
* @author malensek
*/
public class SimpleRunningStatistics implements ByteSerializable {
private long n;
private double mean;
private double m2;
public static class WelchResult {
/** T-statistic */
public double t;
/** Two-tailed p-value */
public double p;
public WelchResult(double t, double p) {
this.t = t;
this.p = p;
}
}
/**
* Creates an empty running statistics instance.
*/
public SimpleRunningStatistics() {
}
/**
* Creates a copy of a {@link RunningStatistics} instance.
*/
public SimpleRunningStatistics(SimpleRunningStatistics that) {
copyFrom(that);
}
/**
* Create a new {@link RunningStatistics} instance by combining multiple
* existing instances.
*/
public SimpleRunningStatistics(SimpleRunningStatistics... others) {
if (others.length == 0) {
return;
} else if (others.length == 1) {
copyFrom(others[0]);
return;
}
/* Calculate new n */
for (SimpleRunningStatistics rs : others) {
merge(rs);
}
}
/**
* Copies statistics from another RunningStatistics instance.
*/
private void copyFrom(SimpleRunningStatistics that) {
this.n = that.n;
this.mean = that.mean;
this.m2 = that.m2;
}
public void merge(SimpleRunningStatistics that) {
long newN = n + that.n;
double delta = this.mean - that.mean;
mean = (this.n * this.mean + that.n * that.mean) / newN;
m2 = m2 + that.m2 + delta * delta * this.n * that.n / newN;
n = newN;
}
/**
* Creates a running statistics instance with an array of samples.
* Samples are added to the statistics in order.
*/
public SimpleRunningStatistics(double... samples ) {
for (double sample : samples) {
put(sample);
}
}
/**
* Add multiple new samples to the running statistics.
*/
public void put(double... samples) {
for (double sample : samples) {
put(sample);
}
}
/**
* Add a new sample to the running statistics.
*/
public void put(double sample) {
n++;
double delta = sample - mean;
mean = mean + delta / n;
m2 = m2 + delta * (sample - mean);
}
/**
* Removes a previously-added sample from the running statistics. WARNING:
* give careful consideration when using this method. If a value is removed
* that wasn't previously added, the statistics will be meaningless.
* Additionally, if you're keeping track of previous additions, then it
* might be worth evaluating whether a RunningStatistics instance is the
* right thing to be using at all. Caveat emptor, etc, etc.
*/
public void remove(double sample) {
if (n <= 1) {
/* If we're removing the last sample, then just clear the stats. */
clear();
return;
}
double prevMean = (n * mean - sample) / (n - 1);
m2 = m2 - (sample - mean) * (sample - prevMean);
mean = prevMean;
n
}
/**
* Clears all values passed in, returning the RunningStatistics instance to
* its original state.
*/
public void clear() {
n = 0;
mean = 0;
m2 = 0;
}
/**
* Calculates the current running mean for the values observed thus far.
*
* @return mean of all the samples observed thus far.
*/
public double mean() {
return mean;
}
/**
* Calculates the running sample variance.
*
* @return sample variance
*/
public double var() {
return var(1.0);
}
/**
* Calculates the population variance.
*
* @return population variance
*/
public double popVar() {
return var(0.0);
}
/**
* Calculates the running variance, given a bias adjustment.
*
* @param ddof delta degrees-of-freedom to use in the calculation. Use 1.0
* for the sample variance.
*
* @return variance
*/
public double var(double ddof) {
if (n == 0) {
return Double.NaN;
}
return m2 / (n - ddof);
}
/**
* Calculates the standard deviation of the data observed thus far.
*
* @return sample standard deviation
*/
public double std() {
return FastMath.sqrt(var());
}
/**
* Calculates the sample standard deviation of the data observed thus
* far.
*
* @return population standard deviation
*/
public double popStd() {
return FastMath.sqrt(popVar());
}
/**
* Calculates the standard deviation of the values observed thus far, given
* a bias adjustment.
*
* @param ddof delta degrees-of-freedom to use in the calculation.
*
* @return standard deviation
*/
public double std(double ddof) {
return FastMath.sqrt(var(ddof));
}
public double prob(double sample) {
double norm = 1 / FastMath.sqrt(2 * FastMath.PI * this.var());
return norm * FastMath.exp((- FastMath.pow(sample - this.mean, 2))
/ (2 * this.var()));
}
/**
* Retrieves the number of samples submitted to the RunningStatistics
* instance so far.
*
* @return number of samples
*/
public long n() {
return n;
}
public static WelchResult welchT(
RunningStatistics rs1, RunningStatistics rs2) {
double vn1 = rs1.var() / rs1.n();
double vn2 = rs2.var() / rs2.n();
/* Calculate t */
double xbs = rs1.mean() - rs2.mean();
double t = xbs / FastMath.sqrt(vn1 + vn2);
double vn12 = FastMath.pow(vn1, 2);
double vn22 = FastMath.pow(vn2, 2);
/* Calculate degrees of freedom */
double v = FastMath.pow(vn1 + vn2, 2)
/ ((vn12 / (rs1.n() - 1)) + (vn22 / (rs2.n() - 1)));
if (v == Double.NaN) {
v = 1;
}
TDistribution tdist = new TDistribution(v);
double p = tdist.cumulativeProbability(t) * 2;
return new WelchResult(t, p);
}
@Override
public String toString() {
String str = "";
str += "Number of Samples: " + n + System.lineSeparator();
str += "Mean: " + mean + System.lineSeparator();
str += "Variance: " + var() + System.lineSeparator();
str += "Std Dev: " + std() + System.lineSeparator();
return str;
}
@Deserialize
public SimpleRunningStatistics(SerializationInputStream in)
throws IOException {
n = in.readLong();
mean = in.readDouble();
m2 = in.readDouble();
}
@Override
public void serialize(SerializationOutputStream out)
throws IOException {
out.writeLong(n);
out.writeDouble(mean);
out.writeDouble(m2);
}
}
|
package io.sigpipe.sing.stat;
import io.sigpipe.sing.serialization.ByteSerializable;
import io.sigpipe.sing.serialization.SerializationInputStream;
import io.sigpipe.sing.serialization.SerializationOutputStream;
import java.io.IOException;
/**
* Provides an online method for computing mean, variance, and standard
* deviation. Based on "Note on a Method for Calculating Corrected Sums of
* Squares and Products" by B. P. Welford.
*
* @author malensek
*/
public class SimpleRunningStatistics implements ByteSerializable {
private long n;
private double mean;
private double m2;
/**
* Creates an empty running statistics instance.
*/
public SimpleRunningStatistics() {
}
/**
* Creates a running statistics instance with an array of samples.
* Samples are added to the statistics in order.
*/
public SimpleRunningStatistics(double... samples ) {
for (double sample : samples) {
put(sample);
}
}
/**
* Creates a copy of a {@link SimpleRunningStatistics} instance.
*/
public SimpleRunningStatistics(SimpleRunningStatistics that) {
copyFrom(that);
}
/**
* Create a new {@link SimpleRunningStatistics} instance by combining
* multiple existing instances.
*/
public SimpleRunningStatistics(SimpleRunningStatistics... others) {
if (others.length == 0) {
return;
} else if (others.length == 1) {
copyFrom(others[0]);
return;
}
/* Calculate new n */
for (SimpleRunningStatistics rs : others) {
merge(rs);
}
}
/**
* Copies statistics from another SimpleRunningStatistics instance.
*/
private void copyFrom(SimpleRunningStatistics that) {
this.n = that.n;
this.mean = that.mean;
this.m2 = that.m2;
}
/**
* Merges this set of running statistics with another.
*/
public void merge(SimpleRunningStatistics that) {
long newN = n + that.n;
double delta = this.mean - that.mean;
mean = (this.n * this.mean + that.n * that.mean) / newN;
m2 = m2 + that.m2 + delta * delta * this.n * that.n / newN;
n = newN;
}
/**
* Add multiple new samples to the running statistics.
*/
public void put(double... samples) {
for (double sample : samples) {
put(sample);
}
}
/**
* Add a new sample to the running statistics.
*/
public void put(double sample) {
n++;
double delta = sample - mean;
mean = mean + delta / n;
m2 = m2 + delta * (sample - mean);
}
/**
* Removes a previously-added sample from the running statistics. WARNING:
* give careful consideration when using this method. If a value is removed
* that wasn't previously added, the statistics will be meaningless.
* Additionally, if you're keeping track of previous additions, then it
* might be worth evaluating whether a SimpleRunningStatistics instance is
* the right thing to be using at all. Caveat emptor, etc, etc.
*/
public void remove(double sample) {
if (n <= 1) {
/* If we're removing the last sample, then just clear the stats. */
clear();
return;
}
double prevMean = (n * mean - sample) / (n - 1);
m2 = m2 - (sample - mean) * (sample - prevMean);
mean = prevMean;
n
}
/**
* Clears all values passed in, returning the SimpleRunningStatistics
* instance to its original state.
*/
public void clear() {
n = 0;
mean = 0;
m2 = 0;
}
/**
* Calculates the current running mean for the values observed thus far.
*
* @return mean of all the samples observed thus far.
*/
public double mean() {
return mean;
}
/**
* Calculates the running sample variance.
*
* @return sample variance
*/
public double var() {
return var(1.0);
}
/**
* Calculates the population variance.
*
* @return population variance
*/
public double popVar() {
return var(0.0);
}
/**
* Calculates the running variance, given a bias adjustment.
*
* @param ddof delta degrees-of-freedom to use in the calculation. Use 1.0
* for the sample variance.
*
* @return variance
*/
public double var(double ddof) {
if (n == 0) {
return Double.NaN;
}
return m2 / (n - ddof);
}
/**
* Calculates the standard deviation of the data observed thus far.
*
* @return sample standard deviation
*/
public double std() {
return Math.sqrt(var());
}
/**
* Calculates the sample standard deviation of the data observed thus
* far.
*
* @return population standard deviation
*/
public double popStd() {
return Math.sqrt(popVar());
}
/**
* Calculates the standard deviation of the values observed thus far, given
* a bias adjustment.
*
* @param ddof delta degrees-of-freedom to use in the calculation.
*
* @return standard deviation
*/
public double std(double ddof) {
return Math.sqrt(var(ddof));
}
/**
* Retrieves the number of samples submitted to the SimpleRunningStatistics
* instance so far.
*
* @return number of samples
*/
public long count() {
return n;
}
@Override
public String toString() {
String str = "";
str += "Number of Samples: " + n + System.lineSeparator();
str += "Mean: " + mean + System.lineSeparator();
str += "Variance: " + var() + System.lineSeparator();
str += "Std Dev: " + std() + System.lineSeparator();
return str;
}
@Deserialize
public SimpleRunningStatistics(SerializationInputStream in)
throws IOException {
n = in.readLong();
mean = in.readDouble();
m2 = in.readDouble();
}
@Override
public void serialize(SerializationOutputStream out)
throws IOException {
out.writeLong(n);
out.writeDouble(mean);
out.writeDouble(m2);
}
}
|
package mcjty.rftoolsdim.dimensions;
import mcjty.lib.worlddata.AbstractWorldData;
import mcjty.rftoolsdim.config.PowerConfiguration;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.util.Constants;
import java.util.HashMap;
import java.util.Map;
public class DimensionStorage extends AbstractWorldData<DimensionStorage> {
private static final String DIMSTORAGE_NAME = "RFToolsDimensionStorage";
private final Map<Integer,Long> energy = new HashMap<>();
private static DimensionStorage clientInstance = null;
public DimensionStorage(String name) {
super(name);
}
@Override
public void clear() {
energy.clear();
}
public static DimensionStorage getDimensionStorage(World world) {
if (world.isRemote) {
if (clientInstance == null) {
clientInstance = new DimensionStorage(DIMSTORAGE_NAME);
}
return clientInstance;
}
return getData(world, DimensionStorage.class, DIMSTORAGE_NAME);
}
public long getEnergyLevel(int id) {
if (energy.containsKey(id)) {
return energy.get(id);
} else {
return 0;
}
}
public void setEnergyLevel(int id, long energyLevel) {
long old = getEnergyLevel(id);
energy.put(id, energyLevel);
if (PowerConfiguration.freezeUnpowered) {
World world = DimensionManager.getWorld(id);
if (world != null) {
if (old == 0 && energyLevel > 0) {
RfToolsDimensionManager.unfreezeDimension(world);
} else if (energyLevel == 0) {
RfToolsDimensionManager.freezeDimension(world);
}
}
}
}
public void removeDimension(int id) {
energy.remove(id);
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
energy.clear();
NBTTagList lst = tagCompound.getTagList("dimensions", Constants.NBT.TAG_COMPOUND);
for (int i = 0 ; i < lst.tagCount() ; i++) {
NBTTagCompound tc = lst.getCompoundTagAt(i);
int id = tc.getInteger("id");
long rf = tc.getLong("energy");
energy.put(id, rf);
}
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) {
NBTTagList lst = new NBTTagList();
for (Map.Entry<Integer,Long> me : energy.entrySet()) {
NBTTagCompound tc = new NBTTagCompound();
tc.setInteger("id", me.getKey());
tc.setLong("energy", me.getValue());
lst.appendTag(tc);
}
tagCompound.setTag("dimensions", lst);
return tagCompound;
}
}
|
package metricapp.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import metricapp.dto.measurementGoal.MeasurementGoalCrudDTO;
import metricapp.dto.measurementGoal.MeasurementGoalDTO;
import metricapp.exception.BadInputException;
import metricapp.exception.DBException;
import metricapp.exception.IllegalStateTransitionException;
import metricapp.exception.NotFoundException;
import metricapp.service.spec.controller.MeasurementGoalCRUDInterface;
@CrossOrigin
@RestController
@RequestMapping("/measurementgoal")
public class MeasurementGoalRestController {
@Autowired
private MeasurementGoalCRUDInterface controller;
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<MeasurementGoalCrudDTO> getMeasurementGoalDTO(@RequestParam(value="id", defaultValue = "NA") String id,
@RequestParam(value = "version", defaultValue = "NA") String version,
@RequestParam(value = "userid", defaultValue = "NA") String userId,
@RequestParam(value = "approved", defaultValue = "false") String approved,
@RequestParam(value = "questionerId", defaultValue = "NA") String questionerId,
@RequestParam(value = "state", defaultValue = "NA") String state,
@RequestParam(value="qualityFocus", defaultValue="NA") String qualityFocus,
@RequestParam(value="object", defaultValue="NA") String object,
@RequestParam(value="viewPoint", defaultValue="NA") String viewPoint,
@RequestParam(value="purpose", defaultValue="NA") String purpose,
@RequestParam(value="tag", defaultValue="NA") String tag){
MeasurementGoalCrudDTO dto = new MeasurementGoalCrudDTO();
try {
if (!userId.equals("NA") && id.equals("NA") && state.equals("NA")) {
dto = controller.getMeasurementGoalByUser(userId);
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.OK);
}
else if (!id.equals("NA") && approved.equals("true")) {
dto = controller.getMeasurementGoalByIdAndLastApprovedVersion(id);
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.OK);
}
else if (!version.equals("NA") && !id.equals("NA")) {
dto = controller.getMeasurementGoalByIdAndVersion(userId, version);
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.OK);
}
else if (!userId.equals("NA") && !state.equals("NA")) {
dto = controller.getMeasurementGoalByState(state, userId);
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.OK);
}
else if(userId.equals("NA") && !qualityFocus.equals("NA")){
dto = controller.getMeasurementGoalByQualityFocus(qualityFocus);
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.OK);
}
else if(userId.equals("NA") && !object.equals("NA")){
dto = controller.getMeasurementGoalByObject(object);
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.OK);
}
else if(userId.equals("NA") && !purpose.equals("NA")){
dto = controller.getMeasurementGoalByPurpose(purpose);
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.OK);
}
else if(userId.equals("NA") && !viewPoint.equals("NA")){
dto = controller.getMeasurementGoalByViewPoint(viewPoint);
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.OK);
}
else if(userId.equals("NA") && !tag.equals("NA")){
dto = controller.getMeasurementGoalByTag(tag);
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.OK);
}
else if (!id.equals("NA") && questionerId.equals("NA")) {
dto = controller.getMeasurementGoalById(id);
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.OK);
}
else if (!questionerId.equals("NA")){
dto = controller.getMeasurementGoalByQuestionerId(questionerId);
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.OK);
}
else {
return new ResponseEntity<MeasurementGoalCrudDTO>(HttpStatus.BAD_REQUEST);
}
} catch (BadInputException e) {
dto.setError(e.getMessage());
e.printStackTrace();
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.BAD_REQUEST);
} catch (NotFoundException e) {
dto.setError(e.getMessage());
e.printStackTrace();
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.NOT_FOUND);
} catch (Exception e) {
dto.setError(e.getMessage());
e.printStackTrace();
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@RequestMapping(value="/count",method = RequestMethod.GET)
public ResponseEntity<MeasurementGoalCrudDTO> getCountMeasurementGoalDTOByState(@RequestParam(value="state") String state,
@RequestParam(value="userid") String userId){
MeasurementGoalCrudDTO dto = new MeasurementGoalCrudDTO();
try {
dto.setCount(controller.countMeasurementGoalByState(state,userId));
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.OK);
} catch (BadInputException | NotFoundException e) {
e.printStackTrace();
dto.setError(e.getMessage());
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.BAD_REQUEST);
}
}
@RequestMapping(method = RequestMethod.DELETE)
public ResponseEntity<MeasurementGoalCrudDTO> deleteMeasurementGoalDTO(@RequestParam String id){
MeasurementGoalCrudDTO dto = new MeasurementGoalCrudDTO();
try {
controller.deleteMeasurementGoalById(id);
} catch (BadInputException e) {
e.printStackTrace();
dto.setError(e.getMessage());
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.BAD_REQUEST);
} catch (IllegalStateTransitionException e) {
e.printStackTrace();
dto.setError(e.getMessage());
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.FORBIDDEN);
} catch (Exception e){
e.printStackTrace();
dto.setError(e.getMessage());
return new ResponseEntity<MeasurementGoalCrudDTO>(dto, HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<MeasurementGoalCrudDTO>(HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.PUT)
public ResponseEntity<MeasurementGoalCrudDTO> putMeasurementGoalDTO(@RequestBody MeasurementGoalDTO dto, @RequestParam(value = "onlychangestate", defaultValue = "false") String onlyChangeState) {
MeasurementGoalCrudDTO rensponseDTO = new MeasurementGoalCrudDTO();
try {
if (onlyChangeState.equals("false")) {
return new ResponseEntity<MeasurementGoalCrudDTO>(controller.updateMeasurementGoal(dto), HttpStatus.OK);
} else {
return new ResponseEntity<MeasurementGoalCrudDTO>(controller.changeStateMeasurementGoal(dto), HttpStatus.OK);
}
} catch (NotFoundException e) {
rensponseDTO.setError(e.getMessage());
e.printStackTrace();
return new ResponseEntity<MeasurementGoalCrudDTO>(rensponseDTO, HttpStatus.NOT_FOUND);
} catch (DBException e) {
rensponseDTO.setError(e.getMessage());
e.printStackTrace();
return new ResponseEntity<MeasurementGoalCrudDTO>(rensponseDTO, HttpStatus.CONFLICT);
} catch (BadInputException e) {
rensponseDTO.setError(e.getMessage());
e.printStackTrace();
return new ResponseEntity<MeasurementGoalCrudDTO>(rensponseDTO, HttpStatus.BAD_REQUEST);
} catch (IllegalStateTransitionException e) {
rensponseDTO.setError(e.getMessage());
e.printStackTrace();
return new ResponseEntity<MeasurementGoalCrudDTO>(rensponseDTO, HttpStatus.FORBIDDEN);
}
catch (Exception e){
rensponseDTO.setError(e.getMessage());
e.printStackTrace();
return new ResponseEntity<MeasurementGoalCrudDTO>(rensponseDTO, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<MeasurementGoalCrudDTO> postMeasurementGoalDTO(@RequestBody MeasurementGoalDTO dto){
MeasurementGoalCrudDTO rensponseDTO = new MeasurementGoalCrudDTO();
try {
return new ResponseEntity<MeasurementGoalCrudDTO>(controller.createMeasurementGoal(dto),HttpStatus.CREATED);
} catch (BadInputException e) {
rensponseDTO.setError(e.getMessage());
e.printStackTrace();
return new ResponseEntity<MeasurementGoalCrudDTO>(rensponseDTO, HttpStatus.BAD_REQUEST);
} catch (Exception e){
rensponseDTO.setError(e.getMessage());
e.printStackTrace();
return new ResponseEntity<MeasurementGoalCrudDTO>(rensponseDTO, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
|
package net.avcompris.tools.diagrammer;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import net.avcompris.tools.diagrammer.SVGDiagrammer.Shape;
import com.avcompris.lang.NotImplementedException;
public abstract class AvcDiagrammer {
/**
* Override this method and add directives to output the SVG.
*/
protected abstract void body() throws Exception;
private int borderWidth = 0;
/**
* Set a border. You may call this method prior to call
* {@link run(int, int)}.
*/
protected final AvcDiagrammer border(final int borderWidth) {
this.borderWidth = borderWidth;
return this;
}
private final List<File> outputFiles = new ArrayList<File>();
public final AvcDiagrammer addOutputFile(final File outputFile) throws IOException {
checkNotNull(outputFile, "outputFile");
outputFiles.add(outputFile);
return this;
}
private SVGDiagrammer diagrammer = null;
private SVGDiagrammer diagrammer() {
final SVGDiagrammer d = diagrammer;
if (d == null) {
throw new IllegalStateException(
"diagrammer (SVGDiagrammer) has not been initialized.");
}
return d;
}
/**
* The method responsible to output the generated SVG.
* If you want to add a border, call {@link border(int)} before calling
* this methid.
*/
public final void run(final int width, final int height) {
if (diagrammer != null) {
throw new IllegalStateException(
"diagrammer (SVGDiagrammer) has already been initialized.");
}
diagrammer = new SVGDiagrammer() {
@Override
protected void body() throws Exception {
if (borderWidth != 0) {
rect().x(0).y(0).width(width).height(height).stroke("#000")
.fill("none").close();
}
final Shape marker = marker().property("id", "arrow")
.property("markerWidth", 6).property("markerHeight", 6)
.property("viewBox", "-3 -3 6 6").property("refX", 2)
.property("refY", 0)
.property("markerUnits", "strokeWidth")
.property("orient", "auto");
polygon().points("-1,0 -3,3 3,0 -3,-3").fill("#000").close();
marker.close();
AvcDiagrammer.this.body();
}
};
for (final File outputFile : outputFiles) {
try {
diagrammer.addOutputFile(outputFile);
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
diagrammer().run(width, height);
diagrammer = null;
}
private static final int DEPTH_DX = 20;
private static final int DEPTH_DY = 10;
protected static final int BOX_OFFSET = 10;
protected static final int LINE_HEIGHT = 20;
protected final Node box(final double x, final double y,
final double width, final double height, final String fillColor,
final String... labels) {
diagrammer().path().moveTo(x, y + height).h(width)
.l(DEPTH_DX, DEPTH_DY).h(-width).l(-DEPTH_DX, -DEPTH_DY)
.fill(darkenColor(fillColor)).stroke("#000").close();
diagrammer().path().moveTo(x + width, y + height).v(-height)
.l(DEPTH_DX, DEPTH_DY).v(height).l(-DEPTH_DX, -DEPTH_DY)
.fill(lightenColor(lightenColor(fillColor))).stroke("#000")
.close();
diagrammer().rect()
.fill(lightenColor(lightenColor(lightenColor(fillColor))))
.stroke("#000").x(x).y(y).width(width).height(height).close();
int i = 0;
for (final String label : labels) {
final Shape text;
if (label.startsWith("*") && label.endsWith("*")
&& label.length() >= 2) {
text = diagrammer()
.text(label.substring(1, label.length() - 1))
.fontWeight("bold");
} else {
text = diagrammer().text(label);
}
text.x(x + width / 2).y(y + 14 + i * LINE_HEIGHT).fontSize(14)
.fill("#000").textAnchor("middle").close();
++i;
}
return new NodeBox(x, y, width, height);
}
protected final Node box(final double x, final double y,
final double width, final String fillColor, final String... labels) {
return box(x, y, width, labels.length * LINE_HEIGHT + 2, fillColor,
labels);
}
protected final Node database(final double x, final double y,
final double width, final double height, final String fillColor,
final String... labels) {
final double rx = width / 2;
final double ry = 1.3 * DEPTH_DY / 2;
diagrammer().path().moveTo(x, y + height).v(-height)
.arc(rx, ry, 0, true, true, width, 0).v(height)
.fill(lightenColor(lightenColor(lightenColor(fillColor))))
.stroke("#000").close();
diagrammer().ellipse().cx(x + width / 2).cy(y + height).rx(rx).ry(ry)
.fill(darkenColor(fillColor)).stroke("#000").close();
int i = 0;
for (final String label : labels) {
final Shape text;
if (label.startsWith("*") && label.endsWith("*")
&& label.length() >= 2) {
text = diagrammer()
.text(label.substring(1, label.length() - 1))
.fontWeight("bold");
} else {
text = diagrammer().text(label);
}
text.x(x + width / 2 - 1).y(y + 8 + i * LINE_HEIGHT).fontSize(14)
.fill("#000").textAnchor("middle").close();
++i;
}
return new NodeDatabase(x, y, width, height);
}
protected final Node database(final double x, final double y,
final double width, final String fillColor, final String... labels) {
return database(x, y, width, labels.length * LINE_HEIGHT + 2,
fillColor, labels);
}
protected final Node queue(final double x, final double y,
final double width, final double height, final String fillColor,
final String... labels) {
final double rx = DEPTH_DX / 2 / 1.3;
final double ry = height / 2;
diagrammer().path().moveTo(x + width + rx, y).h(-width)
.arc(rx, ry, 0, false, false, 0, height).h(width)
.fill(lightenColor(lightenColor(lightenColor(fillColor))))
.stroke("#000").close();
diagrammer().ellipse().cx(x + width + rx).cy(y + height / 2).rx(rx)
.ry(ry).fill(lightenColor(lightenColor(fillColor)))
.stroke("#000").close();
final double wi = 5;
final double rxi = 5;
final double ryi = ry * rxi / rx;
final double hi = height * rxi / rx;
final double yi = y + height / 2 - 7;
for (int i = 0; i < 4; ++i) {
final double xi = x + width / 2 + (i - 1.5) * 12;
diagrammer().path().moveTo(xi + wi + rxi, yi).h(-wi)
.arc(rxi, ryi, 0, false, false, 0, hi).h(wi)
.fill(lightenColor(fillColor)).stroke("#000").close();
diagrammer().ellipse().cx(xi + wi + rxi).cy(yi + hi / 2).rx(rxi)
.ry(ryi).fill(darkenColor(fillColor)).stroke("#000")
.close();
}
int i = 0;
for (final String label : labels) {
final Shape text;
if (label.startsWith("*") && label.endsWith("*")
&& label.length() >= 2) {
text = diagrammer()
.text(label.substring(1, label.length() - 1))
.fontWeight("bold");
} else {
text = diagrammer().text(label);
}
text.x(x + width / 2 + 10).y(y + 38 + i * LINE_HEIGHT).fontSize(14)
.fill("#000").textAnchor("middle").close();
++i;
}
return new NodeQueue(x, y, width, height);
}
protected final Node queue(final double x, final double y,
final double width, final String fillColor, final String... labels) {
return queue(x, y, width, LINE_HEIGHT + 2, fillColor, labels);
}
private static String darkenColor(final String color) {
if (!color.startsWith("
return color;
}
final StringBuilder sb = new StringBuilder("
for (final char c : color.substring(1).toCharArray()) {
final char c2;
if (c > '0' && c <= '9') {
c2 = (char) ((int) c - 1);
} else if (c == 'a') {
c2 = '9';
} else if (c > 'a' && c <= 'f') {
c2 = (char) ((int) c - 1);
} else {
c2 = c;
}
sb.append(c2);
}
return sb.toString();
}
private static String lightenColor(final String color) {
if (!color.startsWith("
return color;
}
final StringBuilder sb = new StringBuilder("
for (final char c : color.substring(1).toCharArray()) {
final char c2;
if (c >= '0' && c < '9') {
c2 = (char) ((int) c + 1);
} else if (c == '9') {
c2 = 'a';
} else if (c >= 'a' && c < 'f') {
c2 = (char) ((int) c + 1);
} else {
c2 = c;
}
sb.append(c2);
}
return sb.toString();
}
private final Stack<Box> boxStack = new Stack<Box>();
private static class Box {
public final double x;
public final double y;
public final double width;
public final double height;
public String fillColor;
public Box(
final double x,
final double y,
final double width,
final double height,
final String fillColor) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.fillColor = fillColor;
}
}
protected final void inside_of_box(final int x, final int y,
final int width, final int height, final String fillColor) {
final double stroke_opacity = 0.3;
diagrammer().path().fillOpacity(0.2).stroke_opacity(stroke_opacity)
.moveTo(x + BOX_OFFSET, y + BOX_OFFSET)
.h(width - BOX_OFFSET - BOX_OFFSET).l(DEPTH_DX, DEPTH_DY)
.h(-width + BOX_OFFSET + BOX_OFFSET).l(-DEPTH_DX, -DEPTH_DY)
.fill(darkenColor(fillColor)).stroke("#000").close();
diagrammer().path().fillOpacity(0.2).stroke_opacity(stroke_opacity)
.moveTo(x + BOX_OFFSET, y + BOX_OFFSET).l(DEPTH_DX, DEPTH_DY)
.v(height - BOX_OFFSET - BOX_OFFSET).l(-DEPTH_DX, -DEPTH_DY)
.v(-height + BOX_OFFSET + BOX_OFFSET)
.fill(lightenColor(lightenColor(fillColor))).stroke("#000")
.close();
diagrammer().path().fillOpacity(0.2).stroke_opacity(stroke_opacity)
.moveTo(x + BOX_OFFSET + DEPTH_DX, y + BOX_OFFSET + DEPTH_DY)
.h(width - BOX_OFFSET - BOX_OFFSET)
.v(height - BOX_OFFSET - BOX_OFFSET)
.h(-width + BOX_OFFSET + BOX_OFFSET)
.v(-height + BOX_OFFSET + BOX_OFFSET)
.fill(lightenColor(lightenColor(lightenColor(fillColor))))
.stroke("#000").close();
boxStack.push(new Box(x, y, width, height, fillColor));
}
protected final void outside_of_box(final String... labels) {
final Box box = boxStack.pop();
int labelWidth = 0;
for (final String label : labels) {
final int textWidth = getTextWidth(label);
if (textWidth > labelWidth) {
labelWidth = textWidth;
}
}
final int metaHeight = LINE_HEIGHT * labels.length;
diagrammer().path().moveTo(box.x, box.y + box.height + metaHeight)
.h(labelWidth).l(DEPTH_DX, DEPTH_DY).h(-labelWidth)
.l(-DEPTH_DX, -DEPTH_DY).fill(darkenColor(box.fillColor))
.stroke("#000").close();
diagrammer().path()
.moveTo(box.x + labelWidth, box.y + box.height + metaHeight)
.v(-metaHeight).l(DEPTH_DX, DEPTH_DY).v(metaHeight)
.l(-DEPTH_DX, -DEPTH_DY)
.fill(lightenColor(lightenColor(box.fillColor))).stroke("#000")
.close();
diagrammer().path().moveTo(box.x + labelWidth, box.y + box.height)
.h(box.width - labelWidth).l(DEPTH_DX, DEPTH_DY)
.h(-box.width + labelWidth).l(-DEPTH_DX, -DEPTH_DY)
.fill(darkenColor(box.fillColor)).stroke("#000").close();
diagrammer().path().moveTo(box.x + box.width, box.y + box.height)
.v(-box.height).l(DEPTH_DX, DEPTH_DY).v(box.height)
.l(-DEPTH_DX, -DEPTH_DY)
.fill(lightenColor(lightenColor(box.fillColor))).stroke("#000")
.close();
diagrammer().path().property("fill-rule", "evenodd")
.moveTo(box.x, box.y).h(box.width).v(box.height)
.h(-box.width + labelWidth).v(metaHeight).h(-labelWidth)
.v(-box.height - metaHeight).cut()
.move(BOX_OFFSET, BOX_OFFSET)
.v(box.height - BOX_OFFSET - BOX_OFFSET)
.h(box.width - BOX_OFFSET - BOX_OFFSET)
.v(-box.height + BOX_OFFSET + BOX_OFFSET)
.h(-box.width + BOX_OFFSET + BOX_OFFSET).close()
.fill(lightenColor(lightenColor(lightenColor(box.fillColor))))
.stroke("#000").close();
int i = 0;
for (final String label : labels) {
++i;
diagrammer().text(label).x(box.x + labelWidth / 2)
.y(box.y + box.height + i * LINE_HEIGHT - 12).fontSize(14)
.fill("#000").textAnchor("middle").close();
}
}
private static int getTextWidth(final String text) {
return 14 + 7 * text.length();
}
protected static abstract class Node {
public abstract double top();
public abstract double right();
public abstract double bottom();
public abstract double left();
public abstract double middle_x_top();
public abstract double middle_x_bottom();
public abstract double middle_y_left();
public abstract double middle_y_right();
}
private static class NodeBox extends Node {
public NodeBox(
final double x,
final double y,
final double width,
final double height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
private final double x;
private final double y;
private final double width;
private final double height;
@Override
public double top() {
return y;
}
@Override
public double right() {
return x + width + DEPTH_DX / 2;
}
@Override
public double bottom() {
return y + height + DEPTH_DY / 2;
}
@Override
public double left() {
return x;
}
@Override
public double middle_x_top() {
return x + width / 2;
}
@Override
public double middle_x_bottom() {
return x + width / 2 + DEPTH_DX / 2;
}
@Override
public double middle_y_left() {
return y + height / 2 + DEPTH_DY / 2;
}
@Override
public double middle_y_right() {
return y + height / 2 + DEPTH_DY / 2;
}
}
private static class NodeDatabase extends Node {
public NodeDatabase(
final double x,
final double y,
final double width,
final double height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
private final double x;
private final double y;
private final double width;
private final double height;
@Override
public double top() {
return y;
}
@Override
public double right() {
return x + width + DEPTH_DX / 2;
}
@Override
public double bottom() {
return y + height + 2;
}
@Override
public double left() {
return x;
}
@Override
public double middle_x_top() {
return x + width / 2;
}
@Override
public double middle_x_bottom() {
return x + width / 2;
}
@Override
public double middle_y_left() {
return y + height / 2;
}
@Override
public double middle_y_right() {
return y + height / 2;
}
}
private static class NodeQueue extends Node {
public NodeQueue(
final double x,
final double y,
final double width,
final double height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
private final double x;
private final double y;
private final double width;
private final double height;
@Override
public double top() {
return y;
}
@Override
public double right() {
return x + width + DEPTH_DX / 2 / 1.3;
}
@Override
public double bottom() {
return y + height;
}
@Override
public double left() {
return x;
}
@Override
public double middle_x_top() {
return x + width / 2;
}
@Override
public double middle_x_bottom() {
return x + width / 2;
}
@Override
public double middle_y_left() {
return y + height / 2;
}
@Override
public double middle_y_right() {
return y + height / 2;
}
}
public enum NodeSide {
TOP, RIGHT, BOTTOM, LEFT;
}
protected final void arrow(final Node from, final Node to) {
arrow(from, to, "solid");
}
protected final void arrow(final Node from, final Node to,
final String style) {
final double x1;
final double y1;
final double x2;
final double y2;
if (from.right() < to.left()) {
x1 = from.right();
x2 = to.left() - 2.5;
if (from.top() >= to.top() && from.bottom() <= to.bottom()) {
y1 = from.middle_y_right();
} else if (from.top() <= to.top() && from.bottom() >= to.bottom()) {
y1 = to.middle_y_left();
} else {
throw new NotImplementedException();
}
y2 = y1;
} else if (from.left() > to.right()) {
throw new NotImplementedException();
} else if (from.top() > to.bottom()) {
y1 = from.top();
y2 = to.bottom();
if (from.left() <= to.left() && from.right() >= from.right()) {
x1 = to.middle_x_bottom();
} else if (from.left() >= to.left() && from.right() <= to.right()) {
x1 = from.middle_x_top();
} else {
throw new NotImplementedException();
}
x2 = x1;
} else {
throw new NotImplementedException();
}
final Shape shape = diagrammer().path().stroke("#000").opacity(0.8)
.strokeWidth(3).fill("none");
if ("dashed".equals(style)) {
shape.property("stroke-dasharray", "6,4");
}
shape.moveTo(x1, y1).l(x2 - x1, y2 - y1).leaveOpen()
.property("marker-end", "url(#arrow)").close();
}
protected final void arrow(final Node from, final NodeSide fromSide,
final Node to, final NodeSide toSide) {
final double x1;
final double y1;
final double qx;
final double qy;
final double x2;
final double y2;
if (fromSide == NodeSide.BOTTOM && toSide == NodeSide.LEFT) {
x1 = from.middle_x_bottom();
y1 = from.bottom();
x2 = to.left() - 2.5;
y2 = to.middle_y_left();
qx = x1;
if ((y2 - y1) > 3 * (x2 - x1)) {
qy = y1 + 3 * (x2 - x1);
} else {
qy = y2;
}
} else if (fromSide == NodeSide.TOP && toSide == NodeSide.RIGHT) {
x1 = from.middle_x_top();
y1 = from.top();
x2 = to.right() + 2.5;
y2 = to.middle_y_right();
qx = x1;
if ((y1 - y2) > 3 * (x1 - x2)) {
qy = y1 - 3 * (x1 - x2);
} else {
qy = y2;
}
} else if (fromSide == NodeSide.BOTTOM && toSide == NodeSide.RIGHT) {
x1 = from.middle_x_bottom();
y1 = from.bottom();
x2 = to.right() + 2.5;
y2 = to.middle_y_right();
qx = x1;
if ((y2 - y1) > 3 * (x1 - x2)) {
qy = y1 + 3 * (x1 - x2);
} else {
qy = y2;
}
} else {
throw new NotImplementedException();
}
diagrammer().path().stroke("#000").opacity(0.8).strokeWidth(3)
.fill("none").moveTo(x1, y1)
.q(qx - x1, qy - y1, x2 - x1, y2 - y1).leaveOpen()
.property("marker-end", "url(#arrow)").close();
}
}
|
package net.minecraftforge.client.model.obj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import javax.vecmath.Matrix3f;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector2f;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4f;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.resources.IResource;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.client.resources.model.IBakedModel;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.IFlexibleBakedModel;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.IModelCustomData;
import net.minecraftforge.client.model.IModelPart;
import net.minecraftforge.client.model.IModelState;
import net.minecraftforge.client.model.IPerspectiveAwareModel;
import net.minecraftforge.client.model.IRetexturableModel;
import net.minecraftforge.client.model.ISmartBlockModel;
import net.minecraftforge.client.model.ISmartItemModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.TRSRTransformation;
import net.minecraftforge.client.model.pipeline.LightUtil;
import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
import net.minecraftforge.fml.common.FMLLog;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
@SuppressWarnings("deprecation")
public class OBJModel implements IRetexturableModel, IModelCustomData
{
//private Gson GSON = new GsonBuilder().create();
private MaterialLibrary matLib;
private final ResourceLocation modelLocation;
private CustomData customData;
public OBJModel(MaterialLibrary matLib, ResourceLocation modelLocation)
{
this(matLib, modelLocation, new CustomData());
}
public OBJModel(MaterialLibrary matLib, ResourceLocation modelLocation, CustomData customData)
{
this.matLib = matLib;
this.modelLocation = modelLocation;
this.customData = customData;
}
@Override
public Collection<ResourceLocation> getDependencies()
{
return Collections.emptyList();
}
@Override
public Collection<ResourceLocation> getTextures()
{
Iterator<Material> materialIterator = this.matLib.materials.values().iterator();
List<ResourceLocation> textures = Lists.newArrayList();
while (materialIterator.hasNext())
{
Material mat = materialIterator.next();
ResourceLocation textureLoc = new ResourceLocation(mat.getTexture().getPath());
if (!textures.contains(textureLoc) && !mat.isWhite())
textures.add(textureLoc);
}
return textures;
}
@Override
public IFlexibleBakedModel bake(IModelState state, VertexFormat format, Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter)
{
ImmutableMap.Builder<String, TextureAtlasSprite> builder = ImmutableMap.builder();
builder.put(ModelLoader.White.loc.toString(), ModelLoader.White.instance);
TextureAtlasSprite missing = bakedTextureGetter.apply(new ResourceLocation("missingno"));
for (Map.Entry<String, Material> e : matLib.materials.entrySet())
{
if (e.getValue().getTexture().getTextureLocation().getResourcePath().startsWith("
{
FMLLog.severe("OBJLoader: Unresolved texture '%s' for obj model '%s'", e.getValue().getTexture().getTextureLocation().getResourcePath(), modelLocation);
builder.put(e.getKey(), missing);
}
else
{
builder.put(e.getKey(), bakedTextureGetter.apply(e.getValue().getTexture().getTextureLocation()));
}
}
builder.put("missingno", missing);
return new OBJBakedModel(this, state, format, builder.build());
}
public MaterialLibrary getMatLib()
{
return this.matLib;
}
@Override
public IModel process(ImmutableMap<String, String> customData)
{
OBJModel ret = new OBJModel(this.matLib, this.modelLocation, new CustomData(this.customData, customData));
return ret;
}
@Override
public IModel retexture(ImmutableMap<String, String> textures)
{
OBJModel ret = new OBJModel(this.matLib.makeLibWithReplacements(textures), this.modelLocation, this.customData);
return ret;
}
static class CustomData
{
public boolean ambientOcclusion = true;
public boolean gui3d = true;
// should be an enum, TODO
//public boolean modifyUVs = false;
public boolean flipV = false;
public CustomData(CustomData parent, ImmutableMap<String, String> customData)
{
this.ambientOcclusion = parent.ambientOcclusion;
this.gui3d = parent.gui3d;
this.flipV = parent.flipV;
this.process(customData);
}
public CustomData() {}
public void process(ImmutableMap<String, String> customData)
{
for (Map.Entry<String, String> e : customData.entrySet())
{
if (e.getKey().equals("ambient"))
this.ambientOcclusion = Boolean.valueOf(e.getValue());
else if (e.getKey().equals("gui3d"))
this.gui3d = Boolean.valueOf(e.getValue());
/*else if (e.getKey().equals("modifyUVs"))
this.modifyUVs = Boolean.valueOf(e.getValue());*/
else if (e.getKey().equals("flip-v"))
this.flipV = Boolean.valueOf(e.getValue());
}
}
}
public static class Parser
{
private static final Pattern WHITE_SPACE = Pattern.compile("\\s+");
private static Set<String> unknownObjectCommands = new HashSet<String>();
public MaterialLibrary materialLibrary = new MaterialLibrary();
private IResourceManager manager;
private InputStreamReader objStream;
private BufferedReader objReader;
private ResourceLocation objFrom;
private List<String> groupList = Lists.newArrayList();
private List<Vertex> vertices = Lists.newArrayList();
private List<Normal> normals = Lists.newArrayList();
private List<TextureCoordinate> texCoords = Lists.newArrayList();
public Parser(IResource from, IResourceManager manager) throws IOException
{
this.manager = manager;
this.objFrom = from.getResourceLocation();
this.objStream = new InputStreamReader(from.getInputStream(), Charsets.UTF_8);
this.objReader = new BufferedReader(objStream);
}
public List<String> getElements()
{
return this.groupList;
}
public OBJModel parse() throws IOException
{
String currentLine = "";
Material material = new Material();
material.setName(Material.DEFAULT_NAME);
int usemtlCounter = 0;
// float[] minUVBounds = new float[] {0.0f, 0.0f};
// float[] maxUVBounds = new float[] {1.0f, 1.0f};
for (;;)
{
currentLine = objReader.readLine();
if (currentLine == null) break;
currentLine.trim();
if (currentLine.isEmpty() || currentLine.startsWith("#")) continue;
String[] fields = WHITE_SPACE.split(currentLine, 2);
String key = fields[0];
String data = fields[1];
String[] splitData = WHITE_SPACE.split(data);
if (key.equalsIgnoreCase("mtllib"))
this.materialLibrary.parseMaterials(manager, data, objFrom);
else if (key.equalsIgnoreCase("usemtl"))
{
material = this.materialLibrary.materials.get(data);
usemtlCounter++;
}
else if (key.equalsIgnoreCase("v"))
{
float[] floatSplitData = new float[splitData.length];
for (int i = 0; i < splitData.length; i++)
floatSplitData[i] = Float.parseFloat(splitData[i]);
Vector4f pos = new Vector4f(floatSplitData[0], floatSplitData[1], floatSplitData[2], floatSplitData.length == 4 ? floatSplitData[3] : 1);
Vertex vertex = new Vertex(pos, material);
this.vertices.add(vertex);
}
else if (key.equalsIgnoreCase("vn"))
{
float[] floatSplitData = new float[splitData.length];
for (int i = 0; i < splitData.length; i++)
floatSplitData[i] = Float.parseFloat(splitData[i]);
Normal normal = new Normal(floatSplitData);
this.normals.add(normal);
}
else if (key.equalsIgnoreCase("vt"))
{
float[] floatSplitData = new float[splitData.length];
for (int i = 0; i < splitData.length; i++)
floatSplitData[i] = Float.parseFloat(splitData[i]);
TextureCoordinate texCoord = new TextureCoordinate(new Vector3f(floatSplitData[0], floatSplitData[1], floatSplitData.length == 3 ? floatSplitData[2] : 1));
if (texCoord.u < 0.0f || texCoord.u > 1.0f || texCoord.v < 0.0f || texCoord.v > 1.0f)
throw new UVsOutOfBoundsException(this.objFrom);
// this.UVsOutOfBounds = (texCoord.u < 0.0f || texCoord.u > 1.0f || texCoord.v < 0.0f || texCoord.v > 1.0f);
// if (texCoord.u < 0.0f || texCoord.u > 1.0f || texCoord.v < 0.0f || texCoord.v > 1.0f)
// this.UVsOutOfBounds = true;
// texCoord.u -= Math.floor(texCoord.u);
// texCoord.v -= Math.floor(texCoord.v);
// minUVBounds[0] = floatSplitData[0] < minUVBounds[0] ? floatSplitData[0] : minUVBounds[0];
// minUVBounds[1] = floatSplitData[1] < minUVBounds[1] ? floatSplitData[1] : minUVBounds[1];
// maxUVBounds[0] = floatSplitData[0] > maxUVBounds[0] ? floatSplitData[0] : maxUVBounds[0];
// maxUVBounds[1] = floatSplitData[1] > maxUVBounds[1] ? floatSplitData[1] : maxUVBounds[1];
// FMLLog.info("u: [%f, %f] v: [%f, %f]", minUVBounds[]);
this.texCoords.add(texCoord);
}
else if (key.equalsIgnoreCase("f"))
{
String[][] splitSlash = new String[splitData.length][];
if (splitData.length > 4) FMLLog.warning("OBJModel.Parser: found a face ('f') with more than 4 vertices, only the first 4 of these vertices will be rendered!");
int vert = 0;
int texCoord = 0;
int norm = 0;
List<Vertex> v = Lists.newArrayListWithCapacity(splitData.length);
// List<TextureCoordinate> t = Lists.newArrayListWithCapacity(splitData.length);
// List<Normal> n = Lists.newArrayListWithCapacity(splitData.length);
for (int i = 0; i < splitData.length; i++)
{
if (splitData[i].contains("
{
splitSlash[i] = splitData[i].split("
vert = Integer.parseInt(splitSlash[i][0]);
vert = vert < 0 ? this.vertices.size() - 1 : vert - 1;
norm = Integer.parseInt(splitSlash[i][1]);
norm = norm < 0 ? this.normals.size() - 1 : norm - 1;
Vertex newV = new Vertex(new Vector4f(this.vertices.get(vert).getPos()), this.vertices.get(vert).getMaterial());
newV.setNormal(this.normals.get(norm));
v.add(newV);
// n.add(this.normals.get(norm));
}
else if (splitData[i].contains("/"))
{
splitSlash[i] = splitData[i].split("/");
vert = Integer.parseInt(splitSlash[i][0]);
vert = vert < 0 ? this.vertices.size() - 1 : vert - 1;
texCoord = Integer.parseInt(splitSlash[i][1]);
texCoord = texCoord < 0 ? this.texCoords.size() - 1 : texCoord - 1;
if (splitSlash[i].length > 2)
{
norm = Integer.parseInt(splitSlash[i][2]);
norm = norm < 0 ? this.normals.size() - 1 : norm - 1;
}
Vertex newV = new Vertex(new Vector4f(this.vertices.get(vert).getPos()), this.vertices.get(vert).getMaterial());
newV.setTextureCoordinate(this.texCoords.get(texCoord));
newV.setNormal(splitSlash[i].length > 2 ? this.normals.get(norm) : null);
v.add(newV);
// t.add(this.texCoords.get(texCoord));
// if (splitSlash[i].length > 2) n.add(this.normals.get(norm));
}
else
{
splitSlash[i] = splitData[i].split("");
vert = Integer.parseInt(splitSlash[i][0]);
vert = vert < 0 ? this.vertices.size() - 1 : vert - 1;
Vertex newV = new Vertex(new Vector4f(this.vertices.get(vert).getPos()), this.vertices.get(vert).getMaterial());
v.add(newV);
}
}
Vertex[] va = new Vertex[v.size()];
v.toArray(va);
// TextureCoordinate[] ta = new TextureCoordinate[t.size()];
// t.toArray(ta);
// Normal[] na = new Normal[n.size()];
// n.toArray(na);
Face face = new Face(va, material.name);
if (usemtlCounter < this.vertices.size())
{
for (Vertex ver : face.getVertices())
{
ver.setMaterial(material);
}
}
if (groupList.isEmpty())
{
if (this.materialLibrary.getGroups().containsKey(Group.DEFAULT_NAME))
{
this.materialLibrary.getGroups().get(Group.DEFAULT_NAME).addFace(face);
}
else
{
Group def = new Group(Group.DEFAULT_NAME, null);
def.addFace(face);
this.materialLibrary.getGroups().put(Group.DEFAULT_NAME, def);
}
}
else
{
for (String s : groupList)
{
if (this.materialLibrary.getGroups().containsKey(s))
{
this.materialLibrary.getGroups().get(s).addFace(face);
}
else
{
Group e = new Group(s, null);
e.addFace(face);
this.materialLibrary.getGroups().put(s, e);
}
}
}
}
else if (key.equalsIgnoreCase("g") || key.equalsIgnoreCase("o"))
{
groupList.clear();
if (key.equalsIgnoreCase("g"))
{
String[] splitSpace = data.split(" ");
for (String s : splitSpace)
groupList.add(s);
}
else
{
groupList.add(data);
}
}
else
{
if (!unknownObjectCommands.contains(key))
{
unknownObjectCommands.add(key);
FMLLog.info("OBJLoader.Parser: command '%s' (model: '%s') is not currently supported, skipping", key, objFrom);
}
}
}
OBJModel model = new OBJModel(this.materialLibrary, this.objFrom);
// model.getMatLib().setUVBounds(minUVBounds[0], maxUVBounds[0], minUVBounds[1], maxUVBounds[1]);
return model;
}
}
public static class MaterialLibrary
{
private static final Pattern WHITE_SPACE = Pattern.compile("\\s+");
private Set<String> unknownMaterialCommands = new HashSet<String>();
private Map<String, Material> materials = new HashMap<String, Material>();
private Map<String, Group> groups = new HashMap<String, Group>();
private InputStreamReader mtlStream;
private BufferedReader mtlReader;
// private float[] minUVBounds = new float[] {0.0f, 0.0f};
// private float[] maxUVBounds = new float[] {1.0f, 1.0f};
public MaterialLibrary()
{
this.groups.put(Group.DEFAULT_NAME, new Group(Group.DEFAULT_NAME, null));
Material def = new Material();
def.setName(Material.DEFAULT_NAME);
this.materials.put(Material.DEFAULT_NAME, def);
}
public MaterialLibrary makeLibWithReplacements(ImmutableMap<String, String> replacements)
{
Map<String, Material> mats = new HashMap<String, Material>();
for (Map.Entry<String, Material> e : this.materials.entrySet())
{
// key for the material name, with # added if missing
String keyMat = e.getKey();
if(!keyMat.startsWith("#")) keyMat = "#" + keyMat;
// key for the texture name, with ".png" stripped and # added if missing
String keyTex = e.getValue().getTexture().getPath();
if(keyTex.endsWith(".png")) keyTex = keyTex.substring(0, keyTex.length() - ".png".length());
if(!keyTex.startsWith("#")) keyTex = "#" + keyTex;
if (replacements.containsKey(keyMat))
{
Texture currentTexture = e.getValue().texture;
Texture replacementTexture = new Texture(replacements.get(keyMat), currentTexture.position, currentTexture.scale, currentTexture.rotation);
Material replacementMaterial = new Material(e.getValue().color, replacementTexture, e.getValue().name);
mats.put(e.getKey(), replacementMaterial);
}
else if (replacements.containsKey(keyTex))
{
Texture currentTexture = e.getValue().texture;
Texture replacementTexture = new Texture(replacements.get(keyTex), currentTexture.position, currentTexture.scale, currentTexture.rotation);
Material replacementMaterial = new Material(e.getValue().color, replacementTexture, e.getValue().name);
mats.put(e.getKey(), replacementMaterial);
}
else
{
mats.put(e.getKey(), e.getValue());
}
}
MaterialLibrary ret = new MaterialLibrary();
ret.unknownMaterialCommands = this.unknownMaterialCommands;
ret.materials = mats;
ret.groups = this.groups;
ret.mtlStream = this.mtlStream;
ret.mtlReader = this.mtlReader;
// ret.minUVBounds = this.minUVBounds;
// ret.maxUVBounds = this.maxUVBounds;
return ret;
}
// public float[] getMinUVBounds()
// return this.minUVBounds;
// public float[] getMaxUVBounds()
// return this.maxUVBounds;
// public void setUVBounds(float minU, float maxU, float minV, float maxV)
// this.minUVBounds[0] = minU;
// this.maxUVBounds[0] = maxU;
// this.minUVBounds[1] = minV;
// this.maxUVBounds[1] = maxV;
public Map<String, Group> getGroups()
{
return this.groups;
}
public List<Group> getGroupsContainingFace(Face f)
{
List<Group> groupList = Lists.newArrayList();
for (Group g : this.groups.values())
{
if (g.faces.contains(f)) groupList.add(g);
}
return groupList;
}
public void changeMaterialColor(String name, int color)
{
Vector4f colorVec = new Vector4f();
colorVec.w = (color >> 24 & 255) / 255;
colorVec.x = (color >> 16 & 255) / 255;
colorVec.y = (color >> 8 & 255) / 255;
colorVec.z = (color & 255) / 255;
this.materials.get(name).setColor(colorVec);
}
public Material getMaterial(String name)
{
return this.materials.get(name);
}
public ImmutableList<String> getMaterialNames()
{
return ImmutableList.copyOf(this.materials.keySet());
}
public void parseMaterials(IResourceManager manager, String path, ResourceLocation from) throws IOException
{
this.materials.clear();
boolean hasSetTexture = false;
boolean hasSetColor = false;
String domain = from.getResourceDomain();
if (!path.contains("/"))
path = from.getResourcePath().substring(0, from.getResourcePath().lastIndexOf("/") + 1) + path;
mtlStream = new InputStreamReader(manager.getResource(new ResourceLocation(domain, path)).getInputStream(), Charsets.UTF_8);
mtlReader = new BufferedReader(mtlStream);
String currentLine = "";
Material material = new Material();
material.setName(Material.WHITE_NAME);
material.setTexture(Texture.WHITE);
this.materials.put(Material.WHITE_NAME, material);
this.materials.put(Material.DEFAULT_NAME, new Material(Texture.WHITE));
for (;;)
{
currentLine = mtlReader.readLine();
if (currentLine == null) break;
currentLine.trim();
if (currentLine.isEmpty() || currentLine.startsWith("#")) continue;
String[] fields = WHITE_SPACE.split(currentLine, 2);
String key = fields[0];
String data = fields[1];
if (key.equalsIgnoreCase("newmtl"))
{
hasSetColor = false;
hasSetTexture = false;
material = new Material();
material.setName(data);
this.materials.put(data, material);
}
else if (key.equalsIgnoreCase("Ka") || key.equalsIgnoreCase("Kd") || key.equalsIgnoreCase("Ks"))
{
if (key.equalsIgnoreCase("Kd") || !hasSetColor)
{
String[] rgbStrings = WHITE_SPACE.split(data, 3);
Vector4f color = new Vector4f(Float.parseFloat(rgbStrings[0]), Float.parseFloat(rgbStrings[1]), Float.parseFloat(rgbStrings[2]), 1.0f);
hasSetColor = true;
material.setColor(color);
}
else
{
FMLLog.info("OBJModel: A color has already been defined for material '%s' in '%s'. The color defined by key '%s' will not be applied!", material.getName(), new ResourceLocation(domain, path).toString(), key);
}
}
else if (key.equalsIgnoreCase("map_Ka") || key.equalsIgnoreCase("map_Kd") || key.equalsIgnoreCase("map_Ks"))
{
if (key.equalsIgnoreCase("map_Kd") || !hasSetTexture)
{
if (data.contains(" "))
{
String[] mapStrings = WHITE_SPACE.split(data);
String texturePath = mapStrings[mapStrings.length - 1];
Texture texture = new Texture(texturePath);
hasSetTexture = true;
material.setTexture(texture);
}
else
{
Texture texture = new Texture(data);
hasSetTexture = true;
material.setTexture(texture);
}
}
else
{
FMLLog.info("OBJModel: A texture has already been defined for material '%s' in '%s'. The texture defined by key '%s' will not be applied!", material.getName(), new ResourceLocation(domain, path).toString(), key);
}
}
else if (key.equalsIgnoreCase("d") || key.equalsIgnoreCase("Tr"))
{
//d <-optional key here> float[0.0:1.0, 1.0]
//Tr r g b OR Tr spectral map file OR Tr xyz r g b (CIEXYZ colorspace)
String[] splitData = WHITE_SPACE.split(data);
float alpha = Float.parseFloat(splitData[splitData.length - 1]);
material.getColor().setW(alpha);
}
else
{
if (!unknownMaterialCommands.contains(key))
{
unknownMaterialCommands.add(key);
FMLLog.info("OBJLoader.MaterialLibrary: key '%s' (model: '%s') is not currently supported, skipping", key, new ResourceLocation(domain, path));
}
}
}
}
}
public static class Material
{
public static final String WHITE_NAME = "OBJModel.White.Texture.Name";
public static final String DEFAULT_NAME = "OBJModel.Default.Texture.Name";
private Vector4f color;
private Texture texture = Texture.WHITE;
private String name = DEFAULT_NAME;
public Material()
{
this(new Vector4f(1f, 1f, 1f, 1f));
}
public Material(Vector4f color)
{
this(color, Texture.WHITE, WHITE_NAME);
}
public Material(Texture texture)
{
this(new Vector4f(1f, 1f, 1f, 1f), texture, DEFAULT_NAME);
}
public Material(Vector4f color, Texture texture, String name)
{
this.color = color;
this.texture = texture;
this.name = name != null ? name : DEFAULT_NAME;
}
public void setName(String name)
{
this.name = name != null ? name : DEFAULT_NAME;
}
public String getName()
{
return this.name;
}
public void setColor(Vector4f color)
{
this.color = color;
}
public Vector4f getColor()
{
return this.color;
}
public void setTexture(Texture texture)
{
this.texture = texture;
}
public Texture getTexture()
{
return this.texture;
}
public boolean isWhite()
{
return this.texture.equals(Texture.WHITE);
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder(String.format("%nMaterial:%n"));
builder.append(String.format(" Name: %s%n", this.name));
builder.append(String.format(" Color: %s%n", this.color.toString()));
builder.append(String.format(" Is White: %b%n", this.isWhite()));
return builder.toString();
}
}
public static class Texture
{
public static Texture WHITE = new Texture("builtin/white", new Vector2f(0, 0), new Vector2f(1, 1), 0);
private String path;
private Vector2f position;
private Vector2f scale;
private float rotation;
public Texture(String path)
{
this(path, new Vector2f(0, 0), new Vector2f(1, 1), 0);
}
public Texture(String path, Vector2f position, Vector2f scale, float rotation)
{
this.path = path;
this.position = position;
this.scale = scale;
this.rotation = rotation;
}
public ResourceLocation getTextureLocation()
{
ResourceLocation loc = new ResourceLocation(this.path);
return loc;
}
public void setPath(String path)
{
this.path = path;
}
public String getPath()
{
return this.path;
}
public void setPosition(Vector2f position)
{
this.position = position;
}
public Vector2f getPosition()
{
return this.position;
}
public void setScale(Vector2f scale)
{
this.scale = scale;
}
public Vector2f getScale()
{
return this.scale;
}
public void setRotation(float rotation)
{
this.rotation = rotation;
}
public float getRotation()
{
return this.rotation;
}
}
public static class Face
{
private Vertex[] verts = new Vertex[4];
// private Normal[] norms = new Normal[4];
// private TextureCoordinate[] texCoords = new TextureCoordinate[4];
private String materialName = Material.DEFAULT_NAME;
private boolean isTri = false;
public Face(Vertex[] verts)
{
this(verts, Material.DEFAULT_NAME);
}
public Face(Vertex[] verts, String materialName) {
this.verts = verts != null && verts.length > 2 ? verts : null;
setMaterialName(materialName);
checkData();
}
// public Face(Vertex[] verts, Normal[] norms)
// this(verts, norms, null);
// public Face(Vertex[] verts, TextureCoordinate[] texCoords)
// this(verts, null, texCoords);
// public Face(Vertex[] verts, Normal[] norms, TextureCoordinate[] texCoords)
// this(verts, norms, texCoords, Material.DEFAULT_NAME);
// public Face(Vertex[] verts, Normal[] norms, TextureCoordinate[] texCoords, String materialName)
// this.verts = verts != null && verts.length > 2 ? verts : null;
// this.norms = norms != null && norms.length > 2 ? norms : null;
// this.texCoords = texCoords != null && texCoords.length > 2 ? texCoords : null;
// setMaterialName(materialName);
// checkData();
private void checkData()
{
if (this.verts != null && this.verts.length == 3)
{
this.isTri = true;
this.verts = new Vertex[]{this.verts[0], this.verts[1], this.verts[2], this.verts[2]};
}
}
public void setMaterialName(String materialName)
{
this.materialName = materialName != null && !materialName.isEmpty() ? materialName : this.materialName;
}
public String getMaterialName()
{
return this.materialName;
}
public boolean isTriangles()
{
return isTri;
}
public boolean setVertices(Vertex[] verts)
{
if (verts == null) return false;
else this.verts = verts;
checkData();
return true;
}
public Vertex[] getVertices()
{
return this.verts;
}
// public boolean areUVsNormalized()
// for (Vertex v : this.verts)
// if (!v.hasNormalizedUVs())
// return false;
// return true;
// public void normalizeUVs(float[] min, float[] max)
// if (!this.areUVsNormalized())
// for (int i = 0; i < this.verts.length; i++) {
// TextureCoordinate texCoord = this.verts[i].getTextureCoordinate();
// min[0] = texCoord.u < min[0] ? texCoord.u : min[0];
// max[0] = texCoord.u > max[0] ? texCoord.u : max[0];
// min[1] = texCoord.v < min[1] ? texCoord.v : min[1];
// max[1] = texCoord.v > max[1] ? texCoord.v : max[1];
// for (Vertex v : this.verts) {
// v.texCoord.u = (v.texCoord.u - min[0]) / (max[0] - min[0]);
// v.texCoord.v = (v.texCoord.v - min[1]) / (max[1] - max[1]);
public Face bake(TRSRTransformation transform)
{
Matrix4f m = transform.getMatrix();
Matrix3f mn = null;
Vertex[] vertices = new Vertex[verts.length];
// Normal[] normals = norms != null ? new Normal[norms.length] : null;
// TextureCoordinate[] textureCoords = texCoords != null ? new TextureCoordinate[texCoords.length] : null;
for (int i = 0; i < verts.length; i++)
{
Vertex v = verts[i];
// Normal n = norms != null ? norms[i] : null;
// TextureCoordinate t = texCoords != null ? texCoords[i] : null;
Vector4f pos = new Vector4f(v.getPos()), newPos = new Vector4f();
pos.w = 1;
m.transform(pos, newPos);
vertices[i] = new Vertex(newPos, v.getMaterial());
if (v.hasNormal())
{
if(mn == null)
{
mn = new Matrix3f();
m.getRotationScale(mn);
mn.invert();
mn.transpose();
}
Vector3f normal = new Vector3f(v.getNormal().getData()), newNormal = new Vector3f();
mn.transform(normal, newNormal);
newNormal.normalize();
vertices[i].setNormal(new Normal(newNormal));
}
if (v.hasTextureCoordinate()) vertices[i].setTextureCoordinate(v.getTextureCoordinate());
else v.setTextureCoordinate(TextureCoordinate.getDefaultUVs()[i]);
//texCoords TODO
// if (t != null) textureCoords[i] = t;
}
return new Face(vertices, this.materialName);
}
public Normal getNormal()
{
Vector3f a = this.verts[2].getPos3();
a.sub(this.verts[0].getPos3());
Vector3f b = this.verts[3].getPos3();
b.sub(this.verts[1].getPos3());
a.cross(a, b);
a.normalize();
return new Normal(a);
}
}
public static class Vertex
{
private Vector4f position;
private Normal normal;
private TextureCoordinate texCoord;
private Material material = new Material();
public Vertex(Vector4f position, Material material)
{
this.position = position;
this.material = material;
}
public void setPos(Vector4f position)
{
this.position = position;
}
public Vector4f getPos()
{
return this.position;
}
public Vector3f getPos3()
{
return new Vector3f(this.position.x, this.position.y, this.position.z);
}
public boolean hasNormal()
{
return this.normal != null;
}
public void setNormal(Normal normal)
{
this.normal = normal;
}
public Normal getNormal()
{
return this.normal;
}
public boolean hasTextureCoordinate()
{
return this.texCoord != null;
}
public void setTextureCoordinate(TextureCoordinate texCoord)
{
this.texCoord = texCoord;
}
public TextureCoordinate getTextureCoordinate()
{
return this.texCoord;
}
// public boolean hasNormalizedUVs()
// return this.texCoord.u >= 0.0f && this.texCoord.u <= 1.0f && this.texCoord.v >= 0.0f && this.texCoord.v <= 1.0f;
public void setMaterial(Material material)
{
this.material = material;
}
public Material getMaterial()
{
return this.material;
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append(String.format("v:%n"));
builder.append(String.format(" position: %s %s %s%n", position.x, position.y, position.z));
builder.append(String.format(" material: %s %s %s %s %s%n", material.getName(), material.getColor().x, material.getColor().y, material.getColor().z, material.getColor().w));
return builder.toString();
}
}
public static class Normal
{
public float x, y, z;
public Normal()
{
this(0.0f, 0.0f, 0.0f);
}
public Normal(float[] data)
{
this(data[0], data[1], data[2]);
}
public Normal(Vector3f vector3f)
{
this(vector3f.x, vector3f.y, vector3f.z);
}
public Normal(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector3f getData()
{
return new Vector3f(this.x, this.y, this.z);
}
}
public static class TextureCoordinate
{
public float u, v, w;
public TextureCoordinate()
{
this(0.0f, 0.0f, 1.0f);
}
public TextureCoordinate(float[] data)
{
this(data[0], data[1], data[2]);
}
public TextureCoordinate(Vector3f data)
{
this(data.x, data.y, data.z);
}
public TextureCoordinate(float u, float v, float w)
{
this.u = u;
this.v = v;
this.w = w;
}
public Vector3f getData()
{
return new Vector3f(this.u, this.v, this.w);
}
public static TextureCoordinate[] getDefaultUVs()
{
TextureCoordinate[] texCoords = new TextureCoordinate[4];
texCoords[0] = new TextureCoordinate(0.0f, 0.0f, 1.0f);
texCoords[1] = new TextureCoordinate(1.0f, 0.0f, 1.0f);
texCoords[2] = new TextureCoordinate(1.0f, 1.0f, 1.0f);
texCoords[3] = new TextureCoordinate(0.0f, 1.0f, 1.0f);
return texCoords;
}
}
public static class Group implements IModelPart
{
public static final String DEFAULT_NAME = "OBJModel.Default.Element.Name";
public static final String ALL = "OBJModel.Group.All.Key";
public static final String ALL_EXCEPT = "OBJModel.Group.All.Except.Key";
private String name = DEFAULT_NAME;
private LinkedHashSet<Face> faces = new LinkedHashSet<Face>();
public float[] minUVBounds = new float[] {0.0f, 0.0f};
public float[] maxUVBounds = new float[] {1.0f, 1.0f};
// public float[] minUVBounds = new float[] {0.0f, 0.0f};
// public float[] maxUVBounds = new float[] {1.0f, 1.0f};
public Group(String name, LinkedHashSet<Face> faces)
{
this.name = name != null ? name : DEFAULT_NAME;
this.faces = faces == null ? new LinkedHashSet<Face>() : faces;
}
public LinkedHashSet<Face> applyTransform(Optional<TRSRTransformation> transform)
{
LinkedHashSet<Face> faceSet = new LinkedHashSet<Face>();
for (Face f : this.faces)
{
// if (minUVBounds != null && maxUVBounds != null) f.normalizeUVs(minUVBounds, maxUVBounds);
faceSet.add(f.bake(transform.or(TRSRTransformation.identity())));
}
return faceSet;
}
public String getName()
{
return this.name;
}
public LinkedHashSet<Face> getFaces()
{
return this.faces;
}
public void setFaces(LinkedHashSet<Face> faces)
{
this.faces = faces;
}
public void addFace(Face face)
{
this.faces.add(face);
}
public void addFaces(List<Face> faces)
{
this.faces.addAll(faces);
}
}
public static class OBJState implements IModelState
{
protected Map<String, Boolean> visibilityMap = Maps.newHashMap();
public IModelState parent;
protected Operation operation = Operation.SET_TRUE;
public OBJState(List<String> visibleGroups, boolean visibility)
{
this(visibleGroups, visibility, TRSRTransformation.identity());
}
public OBJState(List<String> visibleGroups, boolean visibility, IModelState parent)
{
this.parent = parent;
for (String s : visibleGroups) this.visibilityMap.put(s, visibility);
}
public IModelState getParent(IModelState parent)
{
if (parent == null) return null;
else if (parent instanceof OBJState) return ((OBJState) parent).parent;
return parent;
}
public Optional<TRSRTransformation> apply(Optional<? extends IModelPart> part)
{
if (parent != null) return parent.apply(part);
return Optional.absent();
}
public Map<String, Boolean> getVisibilityMap()
{
return this.visibilityMap;
}
public List<String> getGroupsWithVisibility(boolean visibility)
{
List<String> ret = Lists.newArrayList();
for (Map.Entry<String, Boolean> e : this.visibilityMap.entrySet())
{
if (e.getValue() == visibility)
{
ret.add(e.getKey());
}
}
return ret;
}
public List<String> getGroupNamesFromMap()
{
return Lists.newArrayList(this.visibilityMap.keySet());
}
public void changeGroupVisibilities(List<String> names, Operation operation)
{
if (names == null || names.isEmpty()) return;
this.operation = operation;
if (names.get(0).equals(Group.ALL))
{
for (String s : this.visibilityMap.keySet())
{
this.visibilityMap.put(s, this.operation.performOperation(this.visibilityMap.get(s)));
}
}
else if (names.get(0).equals(Group.ALL_EXCEPT))
{
for (String s : this.visibilityMap.keySet())
{
if (!names.subList(1, names.size()).contains(s))
{
this.visibilityMap.put(s, this.operation.performOperation(this.visibilityMap.get(s)));
}
}
}
else
{
for (String s : names)
{
this.visibilityMap.put(s, this.operation.performOperation(this.visibilityMap.get(s)));
}
}
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder("OBJState: ");
builder.append(String.format("%n parent: %s%n", this.parent.toString()));
builder.append(String.format(" visibility map: %n"));
for (Map.Entry<String, Boolean> e : this.visibilityMap.entrySet())
{
builder.append(String.format(" name: %s visible: %b%n", e.getKey(), e.getValue()));
}
return builder.toString();
}
@Override
public int hashCode()
{
return Objects.hash(visibilityMap, parent, operation);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OBJState other = (OBJState) obj;
return Objects.equals(visibilityMap, other.visibilityMap) &&
Objects.equals(parent, other.parent) &&
operation == other.operation;
}
public enum Operation
{
SET_TRUE,
SET_FALSE,
TOGGLE;
Operation(){}
public boolean performOperation(boolean valueToToggle)
{
switch(this)
{
default:
case SET_TRUE: return true;
case SET_FALSE: return false;
case TOGGLE: return !valueToToggle;
}
}
}
}
public enum OBJProperty implements IUnlistedProperty<OBJState>
{
instance;
public String getName()
{
return "OBJPropery";
}
@Override
public boolean isValid(OBJState value)
{
return value instanceof OBJState;
}
@Override
public Class<OBJState> getType()
{
return OBJState.class;
}
@Override
public String valueToString(OBJState value)
{
return value.toString();
}
}
public class OBJBakedModel implements IFlexibleBakedModel, ISmartBlockModel, ISmartItemModel, IPerspectiveAwareModel
{
private final OBJModel model;
private IModelState state;
private final VertexFormat format;
private Set<BakedQuad> quads;
private ImmutableMap<String, TextureAtlasSprite> textures;
private TextureAtlasSprite sprite = ModelLoader.White.instance;
public OBJBakedModel(OBJModel model, IModelState state, VertexFormat format, ImmutableMap<String, TextureAtlasSprite> textures)
{
this.model = model;
this.state = state;
if (this.state instanceof OBJState) this.updateStateVisibilityMap((OBJState) this.state);
this.format = format;
this.textures = textures;
}
public void scheduleRebake()
{
this.quads = null;
}
@Override
public List<BakedQuad> getFaceQuads(EnumFacing side)
{
return Collections.emptyList();
}
@Override
public List<BakedQuad> getGeneralQuads()
{
if (quads == null)
{
quads = Collections.synchronizedSet(new LinkedHashSet<BakedQuad>());
Set<Face> faces = Collections.synchronizedSet(new LinkedHashSet<Face>());
Optional<TRSRTransformation> transform = Optional.absent();
for (Group g : this.model.getMatLib().getGroups().values())
{
// g.minUVBounds = this.model.getMatLib().minUVBounds;
// g.maxUVBounds = this.model.getMatLib().maxUVBounds;
// FMLLog.info("Group: %s u: [%f, %f] v: [%f, %f]", g.name, g.minUVBounds[0], g.maxUVBounds[0], g.minUVBounds[1], g.maxUVBounds[1]);
if (this.state instanceof OBJState)
{
OBJState state = (OBJState) this.state;
if (state.parent != null)
{
transform = state.parent.apply(Optional.<IModelPart>absent());
}
//TODO: can this be replaced by updateStateVisibilityMap(OBJState)?
if (state.getGroupNamesFromMap().contains(Group.ALL))
{
state.visibilityMap.clear();
for (String s : this.model.getMatLib().getGroups().keySet())
{
state.visibilityMap.put(s, state.operation.performOperation(true));
}
}
else if (state.getGroupNamesFromMap().contains(Group.ALL_EXCEPT))
{
List<String> exceptList = state.getGroupNamesFromMap().subList(1, state.getGroupNamesFromMap().size());
state.visibilityMap.clear();
for (String s : this.model.getMatLib().getGroups().keySet())
{
if (!exceptList.contains(s))
{
state.visibilityMap.put(s, state.operation.performOperation(true));
}
}
}
else
{
for (String s : state.visibilityMap.keySet())
{
state.visibilityMap.put(s, state.operation.performOperation(state.visibilityMap.get(s)));
}
}
if (state.getGroupsWithVisibility(true).contains(g.getName()))
{
faces.addAll(g.applyTransform(transform));
}
}
else
{
transform = state.apply(Optional.<IModelPart>absent());
faces.addAll(g.applyTransform(transform));
}
}
for (Face f : faces)
{
if (this.model.getMatLib().materials.get(f.getMaterialName()).isWhite())
{
for (Vertex v : f.getVertices())
{//update material in each vertex
if (!v.getMaterial().equals(this.model.getMatLib().getMaterial(v.getMaterial().getName())))
{
v.setMaterial(this.model.getMatLib().getMaterial(v.getMaterial().getName()));
}
}
sprite = ModelLoader.White.instance;
} else sprite = this.textures.get(f.getMaterialName());
UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder(format);
builder.setQuadOrientation(EnumFacing.getFacingFromVector(f.getNormal().x, f.getNormal().y, f.getNormal().z));
builder.setQuadColored();
Normal faceNormal = f.getNormal();
putVertexData(builder, f.verts[0], faceNormal, TextureCoordinate.getDefaultUVs()[0], sprite);
putVertexData(builder, f.verts[1], faceNormal, TextureCoordinate.getDefaultUVs()[1], sprite);
putVertexData(builder, f.verts[2], faceNormal, TextureCoordinate.getDefaultUVs()[2], sprite);
putVertexData(builder, f.verts[3], faceNormal, TextureCoordinate.getDefaultUVs()[3], sprite);
quads.add(builder.build());
}
}
List<BakedQuad> quadList = Collections.synchronizedList(Lists.newArrayList(quads));
return quadList;
}
private final void putVertexData(UnpackedBakedQuad.Builder builder, Vertex v, Normal faceNormal, TextureCoordinate defUV, TextureAtlasSprite sprite)
{
for (int e = 0; e < format.getElementCount(); e++)
{
switch (format.getElement(e).getUsage())
{
case POSITION:
builder.put(e, v.getPos().x, v.getPos().y, v.getPos().z, v.getPos().w);
break;
case COLOR:
float d;
if (v.hasNormal())
d = LightUtil.diffuseLight(v.getNormal().x, v.getNormal().y, v.getNormal().z);
else
d = LightUtil.diffuseLight(faceNormal.x, faceNormal.y, faceNormal.z);
if (v.getMaterial() != null)
builder.put(e,
d * v.getMaterial().getColor().x,
d * v.getMaterial().getColor().y,
d * v.getMaterial().getColor().z,
v.getMaterial().getColor().w);
else
builder.put(e, d, d, d, 1);
break;
case UV:
if (!v.hasTextureCoordinate())
builder.put(e,
sprite.getInterpolatedU(defUV.u * 16),
sprite.getInterpolatedV((model.customData.flipV ? 1 - defUV.v: defUV.v) * 16),
0, 1);
else
builder.put(e,
sprite.getInterpolatedU(v.getTextureCoordinate().u * 16),
sprite.getInterpolatedV((model.customData.flipV ? 1 - v.getTextureCoordinate().v : v.getTextureCoordinate().v) * 16),
0, 1);
break;
case NORMAL:
if (!v.hasNormal())
builder.put(e, faceNormal.x, faceNormal.y, faceNormal.z, 0);
else
builder.put(e, v.getNormal().x, v.getNormal().y, v.getNormal().z, 0);
break;
default:
builder.put(e);
}
}
}
@Override
public boolean isAmbientOcclusion()
{
return model != null ? model.customData.ambientOcclusion : true;
}
@Override
public boolean isGui3d()
{
return model != null ? model.customData.gui3d : true;
}
@Override
public boolean isBuiltInRenderer()
{
return false;
}
@Override
public TextureAtlasSprite getParticleTexture()
{
return this.sprite;
}
@Override
public ItemCameraTransforms getItemCameraTransforms()
{
return ItemCameraTransforms.DEFAULT;
}
@Override
public VertexFormat getFormat()
{
return format;
}
@Override
public IBakedModel handleItemState(ItemStack stack)
{
return this;
}
@Override
public OBJBakedModel handleBlockState(IBlockState state)
{
if (state instanceof IExtendedBlockState)
{
IExtendedBlockState exState = (IExtendedBlockState) state;
if (exState.getUnlistedNames().contains(OBJProperty.instance))
{
OBJState s = exState.getValue(OBJProperty.instance);
if (s != null)
{
if (s.visibilityMap.containsKey(Group.ALL) || s.visibilityMap.containsKey(Group.ALL_EXCEPT))
{
this.updateStateVisibilityMap(s);
}
return getCachedModel(s);
}
}
}
return this;
}
private void updateStateVisibilityMap(OBJState state)
{
if (state.visibilityMap.containsKey(Group.ALL))
{
boolean operation = state.visibilityMap.get(Group.ALL);
state.visibilityMap.clear();
for (String s : this.model.getMatLib().getGroups().keySet())
{
state.visibilityMap.put(s, state.operation.performOperation(operation));
}
}
else if (state.visibilityMap.containsKey(Group.ALL_EXCEPT))
{
List<String> exceptList = state.getGroupNamesFromMap().subList(1, state.getGroupNamesFromMap().size());
state.visibilityMap.remove(Group.ALL_EXCEPT);
for (String s : this.model.getMatLib().getGroups().keySet())
{
if (!exceptList.contains(s))
{
state.visibilityMap.put(s, state.operation.performOperation(state.visibilityMap.get(s)));
}
}
}
else
{
for (String s : state.visibilityMap.keySet())
{
state.visibilityMap.put(s, state.operation.performOperation(state.visibilityMap.get(s)));
}
}
}
private final LoadingCache<IModelState, OBJBakedModel> cache = CacheBuilder.newBuilder().maximumSize(20).build(new CacheLoader<IModelState, OBJBakedModel>()
{
public OBJBakedModel load(IModelState state) throws Exception
{
return new OBJBakedModel(model, state, format, textures);
}
});
public OBJBakedModel getCachedModel(IModelState state)
{
return cache.getUnchecked(state);
}
public OBJModel getModel()
{
return this.model;
}
public IModelState getState()
{
return this.state;
}
public OBJBakedModel getBakedModel()
{
return new OBJBakedModel(this.model, this.state, this.format, this.textures);
}
@Override
public Pair<? extends IFlexibleBakedModel, Matrix4f> handlePerspective(TransformType cameraTransformType)
{
return IPerspectiveAwareModel.MapWrapper.handlePerspective(this, state, cameraTransformType);
}
@Override
public String toString()
{
return this.model.modelLocation.toString();
}
}
@SuppressWarnings("serial")
public static class UVsOutOfBoundsException extends RuntimeException
{
public ResourceLocation modelLocation;
public UVsOutOfBoundsException(ResourceLocation modelLocation)
{
super(String.format("Model '%s' has UVs ('vt') out of bounds 0-1! The missing model will be used instead. Support for UV processing will be added to the OBJ loader in the future.", modelLocation));
this.modelLocation = modelLocation;
}
}
@Override
public IModelState getDefaultState()
{
return TRSRTransformation.identity();
}
}
|
package net.openhft.chronicle.network;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.core.util.Time;
import net.openhft.chronicle.network.api.TcpHandler;
import net.openhft.chronicle.network.api.session.SessionDetailsProvider;
import net.openhft.chronicle.network.connection.WireOutPublisher;
import net.openhft.chronicle.wire.Wire;
import net.openhft.chronicle.wire.WireIn;
import net.openhft.chronicle.wire.WireOut;
import net.openhft.chronicle.wire.Wires;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.StreamCorruptedException;
import java.nio.BufferOverflowException;
import java.util.function.Function;
public abstract class WireTcpHandler implements TcpHandler {
public static final int SIZE_OF_SIZE = 4;
private static final Logger LOG = LoggerFactory.getLogger(WireTcpHandler.class);
// this is the point at which it is worth doing more work to get more data.
static final int SMALL_WRITE_BUFFER = 32 << 10;
@NotNull
private final Function<Bytes, Wire> bytesToWire;
protected Wire inWire, outWire;
private boolean recreateWire;
protected final WireOutPublisher publisher = new WireOutPublisher();
public WireTcpHandler(@NotNull final Function<Bytes, Wire> bytesToWire) {
this.bytesToWire = bytesToWire;
}
@Override
public void process(@NotNull Bytes in, @NotNull Bytes out, @NotNull SessionDetailsProvider sessionDetails) {
checkWires(in, out);
publisher.applyAction(outWire, () -> {
if (in.readRemaining() >= SIZE_OF_SIZE && out.writePosition() < SMALL_WRITE_BUFFER)
read(in, out, sessionDetails);
});
}
public void sendHeartBeat(Bytes out, SessionDetailsProvider sessionDetails) {
final WireOut outWire = bytesToWire.apply(out);
outWire.writeDocument(true, w -> w.write(() -> "tid").int64(0));
outWire.writeDocument(false, w -> w.writeEventName(() -> "heartbeat").int64(Time.currentTimeMillis()));
}
@Override
public void onEndOfConnection(boolean heartbeatTimeOut) {
publisher.close();
}
/**
* process all messages in this batch, provided there is plenty of output space.
*
* @param in the source bytes
* @param out the destination bytes
* @return true if we can read attempt the next
*/
private boolean read(@NotNull Bytes in, @NotNull Bytes out, @NotNull SessionDetailsProvider sessionDetails) {
final long header = in.readInt(in.readPosition());
long length = Wires.lengthOf(header);
assert length >= 0 && length < 1 << 23 : "in=" + in + ", hex=" + in.toHexString();
// we don't return on meta data of zero bytes as this is a system message
if (length == 0 && Wires.isData(header)) {
in.readSkip(SIZE_OF_SIZE);
return false;
}
if (in.readRemaining() < length) {
// we have to first read more data before this can be processed
if (LOG.isDebugEnabled())
LOG.debug(String.format("required length=%d but only got %d bytes, " +
"this is short by %d bytes", length, in.readRemaining(),
length - in.readRemaining()));
return false;
}
long limit = in.readLimit();
long end = in.readPosition() + length + SIZE_OF_SIZE;
assert end <= limit;
long outPos = out.writePosition();
try {
in.readLimit(end);
final long position = inWire.bytes().readPosition();
try {
process(inWire, outWire, sessionDetails);
} finally {
try {
inWire.bytes().readPosition(position + length);
} catch (BufferOverflowException e) {
//noinspection ThrowFromFinallyBlock
throw new IllegalStateException("Unexpected error position: " + position + ", length: " + length + " limit(): " + inWire.bytes().readLimit(), e);
}
}
long written = out.writePosition() - outPos;
if (written > 0)
return false;
} catch (Throwable e) {
LOG.error("", e);
} finally {
in.readLimit(limit);
try {
in.readPosition(end);
} catch (Exception e) {
throw new IllegalStateException("position: " + end
+ ", limit:" + limit + ", readLimit: " + in.readLimit() + " " + in.toDebugString(), e);
}
}
return true;
}
private void checkWires(Bytes in, Bytes out) {
if (recreateWire) {
recreateWire = false;
inWire = bytesToWire.apply(in);
outWire = bytesToWire.apply(out);
return;
}
if ((inWire == null || inWire.bytes() != in)) {
inWire = bytesToWire.apply(in);
recreateWire = false;
}
if ((outWire == null || outWire.bytes() != out)) {
outWire = bytesToWire.apply(out);
recreateWire = false;
}
}
/**
* Process an incoming request
*/
/**
* @param in the wire to be processed
* @param out the result of processing the {@code in}
* @throws StreamCorruptedException if the wire is corrupt
*/
protected abstract void process(@NotNull WireIn in,
@NotNull WireOut out,
@NotNull SessionDetailsProvider sessionDetails)
throws StreamCorruptedException;
}
|
package nl.hsac.fitnesse.fixture.util;
import org.openqa.selenium.*;
import org.openqa.selenium.internal.Base64Encoder;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.ScreenshotException;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Helper to work with Selenium.
*/
public class SeleniumHelper {
/** Default time in seconds the wait web driver waits unit throwing TimeOutException. */
public static final int DEFAULT_TIMEOUT_SECONDS = 10;
private DriverFactory factory;
private WebDriver webDriver;
private WebDriverWait webDriverWait;
private boolean shutdownHookEnabled = false;
/**
* Sets up webDriver to be used.
* @param aWebDriver web driver to use.
*/
public void setWebDriver(WebDriver aWebDriver) {
if (webDriver != null && !webDriver.equals(aWebDriver)) {
webDriver.quit();
}
webDriver = aWebDriver;
if (webDriver == null) {
webDriverWait = null;
} else {
webDriverWait = new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS);
}
if (!shutdownHookEnabled) {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
close();
}
});
shutdownHookEnabled = true;
}
}
/**
* Shuts down selenium web driver.
*/
public void close() {
setWebDriver(null);
}
/**
* @return current page title.
*/
public String getPageTitle() {
return driver().getTitle();
}
/**
* @return Selenium's navigation.
*/
public WebDriver.Navigation navigate() {
return driver().navigate();
}
/**
* Finds element, by searching in multiple locations.
* @param place identifier for element.
* @return first element found, null if none could be found.
*/
public WebElement getElement(String place) {
WebElement element = null;
if (element == null) {
element = getElementByLabelOccurrence(place, 1);
}
if (element == null) {
element = findElement(byCss("input[placeholder='%s']", place));
}
if (element == null) {
element = findElement(byCss("input[value='%s']:not([type='hidden'])", place));
}
if (element == null) {
element = findElement(byXpath("//button/descendant-or-self::text()[normalize-space(.)='%s']/ancestor-or-self::button", place));
}
if (element == null) {
element = findElement(By.linkText(place));
}
if (element == null) {
element = findElement(byCss("textarea[placeholder='%s']", place));
}
if (element == null) {
element = findElement(byXpath("//th/descendant-or-self::text()[normalize-space(.)='%s']/ancestor-or-self::th/../td ", place));
}
if (element == null) {
element = findElement(By.name(place));
}
if (element == null) {
element = findElement(By.id(place));
}
if (element == null) {
element = getElementByPartialLabelOccurrence(place, 1);
}
if (element == null) {
element = findElement(byCss("input[placeholder~='%s']", place));
}
if (element == null) {
element = findElement(byCss("input[value~='%s']:not([type='hidden'])", place));
}
if (element == null) {
element = findElement(By.partialLinkText(place));
}
if (element == null) {
element = findElement(byCss("textarea[placeholder~='%s']", place));
}
if (element == null) {
element = findElement(byXpath("//th/descendant-or-self::text()[contains(normalize-space(.), '%s')]/ancestor-or-self::th/../td ", place));
}
return element;
}
/**
* Finds element based on the exact (aria-)label text.
* @param labelText text for label.
* @param index occurrence of label (first is 1).
* @return element found if any, null otherwise.
*/
public WebElement getElementByLabelOccurrence(String labelText, int index) {
return getElementByLabel(labelText, index,
"//label/descendant-or-self::text()[normalize-space(.)='%s']/ancestor-or-self::label",
"");
}
/**
* Finds element based on the start of the (aria-)label text.
* @param labelText text for label.
* @param index occurrence of label (first is 1).
* @return element found if any, null otherwise.
*/
public WebElement getElementByStartLabelOccurrence(String labelText, int index) {
return getElementByLabel(labelText, index,
"//label/descendant-or-self::text()[starts-with(normalize-space(.), '%s')]/ancestor-or-self::label",
"|");
}
/**
* Finds element based on part of the (aria-)label text.
* @param labelText text for label.
* @param index occurrence of label (first is 1).
* @return element found if any, null otherwise.
*/
public WebElement getElementByPartialLabelOccurrence(String labelText, int index) {
return getElementByLabel(labelText, index,
"//label/descendant-or-self::text()[contains(normalize-space(.), '%s')]/ancestor-or-self::label",
"~");
}
private String indexedXPath(String xpathBase, int index) {
return String.format("(%s)[%s]", xpathBase, index);
}
private WebElement getElementByLabel(String labelText, int index, String xPath, String cssSelectorModifier) {
WebElement element = null;
String labelPattern = indexedXPath(xPath, index);
WebElement label = findElement(byXpath(labelPattern, labelText));
if (label != null) {
String forAttr = label.getAttribute("for");
if (forAttr == null || "".equals(forAttr)) {
element = findElement(label, true, byCss("input"));
if (element == null) {
element = findElement(label, true, byCss("select"));
if (element == null) {
element = findElement(label, true, byCss("textarea"));
}
}
} else {
element = findElement(By.id(forAttr));
}
}
if (element == null) {
element = findElement(byCss("[aria-label%s='%s']", cssSelectorModifier, labelText), index - 1);
}
return element;
}
/**
* Sets value of hidden input field.
* @param idOrName id or name of input field to set.
* @param value value to set.
* @return whether input field was found.
*/
public boolean setHiddenInputValue(String idOrName, String value) {
WebElement element = findElement(By.id(idOrName));
if (element != null) {
executeJavascript("document.getElementById('%s').value='%s'", idOrName, value);
}
if (element == null) {
element = findElement(By.name(idOrName));
if (element != null) {
executeJavascript("document.getElementsByName('%s')[0].value='%s'", idOrName, value);
}
}
return element != null;
}
public Object executeJavascript(String statementPattern, Object... parameters) {
Object result;
String script = String.format(statementPattern, parameters);
JavascriptExecutor jse = (JavascriptExecutor) driver();
if (statementPattern.contains("arguments")) {
result = jse.executeScript(script, parameters);
} else {
result = jse.executeScript(script);
}
return result;
}
public Object waitForJavascriptCallback(String statementPattern, Object... parameters) {
Object result;
String script = "var callback = arguments[arguments.length - 1];"
+ String.format(statementPattern, parameters);
JavascriptExecutor jse = (JavascriptExecutor) driver();
if (statementPattern.contains("arguments")) {
result = jse.executeAsyncScript(script, parameters);
} else {
result = jse.executeAsyncScript(script);
}
return result;
}
/**
* Creates By based on CSS selector, supporting placeholder replacement.
* @param pattern basic CSS selectot, possibly with placeholders.
* @param parameters values for placeholders.
* @return ByCssSelector.
*/
public By byCss(String pattern, String... parameters) {
String selector = fillPattern(pattern, parameters);
return By.cssSelector(selector);
}
/**
* Creates By based on xPath, supporting placeholder replacement.
* @param pattern basic XPATH, possibly with placeholders.
* @param parameters values for placeholders.
* @return ByXPath.
*/
public By byXpath(String pattern, String... parameters) {
String xpath = fillPattern(pattern, parameters);
return By.xpath(xpath);
}
/**
* Fills in placeholders in pattern using the supplied parameters.
* @param pattern pattern to fill (in String.format style).
* @param parameters parameters to use.
* @return filled in pattern.
*/
protected String fillPattern(String pattern, String[] parameters) {
boolean containsSingleQuote = false;
boolean containsDoubleQuote = false;
Object[] escapedParams = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
String param = parameters[i];
containsSingleQuote = containsSingleQuote || param.contains("'");
containsDoubleQuote = containsDoubleQuote || param.contains("\"");
escapedParams[i] = param;
}
if (containsDoubleQuote && containsSingleQuote) {
throw new RuntimeException("Unsupported combination of single and double quotes");
}
String patternToUse;
if (containsSingleQuote) {
patternToUse = pattern.replace("'", "\"");
} else {
patternToUse = pattern;
}
return String.format(patternToUse, escapedParams);
}
/**
* Sets how long to wait before deciding an element does not exists.
* @param implicitWait time in milliseconds to wait.
*/
public void setImplicitlyWait(int implicitWait) {
driver().manage().timeouts().implicitlyWait(implicitWait, TimeUnit.MILLISECONDS);
}
/**
* Sets how long to wait when executing asynchronous script calls.
* @param scriptTimeout time in milliseconds to wait.
*/
public void setScriptWait(int scriptTimeout) {
driver().manage().timeouts().setScriptTimeout(scriptTimeout, TimeUnit.MILLISECONDS);
}
/**
* Sets how long to wait on opening a page.
* @param pageLoadWait time in milliseconds to wait.
*/
public void setPageLoadWait(int pageLoadWait) {
try {
driver().manage().timeouts().pageLoadTimeout(pageLoadWait, TimeUnit.MILLISECONDS);
} catch (Exception e) {
System.err.println("Unable to set page load timeout (known issue for Safari): " + e.getMessage());
}
}
/**
* @return currently active element.
*/
public WebElement getActiveElement() {
return driver().switchTo().activeElement();
}
/**
* Finds first element matching the By supplied.
* @param by criteria.
* @return element if found, null if none could be found.
*/
public WebElement findElement(By by) {
return findElement(false, by);
}
/**
* Finds element matching the By supplied.
* @param atMostOne true indicates multiple matching elements should trigger an exception
* @param by criteria.
* @return element if found, null if none could be found.
* @throws RuntimeException if atMostOne is true and multiple elements match by.
*/
public WebElement findElement(boolean atMostOne, By by) {
return findElement(driver(), atMostOne, by);
}
/**
* Finds the nth element matching the By supplied.
* @param by criteria.
* @param index (zero based) matching element to return.
* @return element if found, null if none could be found.
*/
public WebElement findElement(By by, int index) {
WebElement element = null;
List<WebElement> elements = driver().findElements(by);
if (elements.size() > index) {
element = elements.get(index);
}
return element;
}
/**
* @return the session id from the current driver (if available).
*/
public String getSessionId() {
String result = null;
WebDriver d = driver();
if (d instanceof RemoteWebDriver) {
Object s = ((RemoteWebDriver) d).getSessionId();
if (s != null) {
result = s.toString();
}
}
return result;
}
/**
* Allows direct access to WebDriver. If possible please use methods of this class to facilitate testing.
* @return selenium web driver.
*/
public WebDriver driver() {
if (webDriver == null && factory != null) {
factory.createDriver();
}
return webDriver;
}
/**
* Allows clients to wait until a certain condition is true.
* @return wait using the driver in this helper.
*/
public WebDriverWait waitDriver() {
return webDriverWait;
}
/**
* Finds element matching the By supplied.
* @param context context to find element in.
* @param atMostOne true indicates multiple matching elements should trigger an exception
* @param by criteria.
* @return element if found, null if none could be found.
* @throws RuntimeException if atMostOne is true and multiple elements match by.
*/
public WebElement findElement(SearchContext context, boolean atMostOne, By by) {
WebElement element = null;
List<WebElement> elements = context.findElements(by);
if (elements.size() == 1) {
element = elements.get(0);
} else if (elements.size() > 1) {
if (!atMostOne) {
element = elements.get(0);
} else {
elements = elementsWithId(elements);
if (elements.size() == 1) {
element = elements.get(0);
} else {
throw new RuntimeException("Multiple elements with id found for: " + by
+ ":\n" + elementsAsString(elements));
}
}
}
return element;
}
private List<WebElement> elementsWithId(List<WebElement> elements) {
List<WebElement> result = new ArrayList<WebElement>(1);
for (WebElement e : elements) {
String attr = e.getAttribute("id");
if (attr != null && !attr.isEmpty()) {
result.add(e);
}
}
return result;
}
private String elementsAsString(Collection<WebElement> elements) {
StringBuilder b = new StringBuilder();
b.append("[");
boolean first = true;
for (WebElement e : elements) {
if (first) {
first = false;
} else {
b.append(", ");
}
b.append(e.getAttribute("id"));
}
b.append("]");
return b.toString();
}
/**
* Takes screenshot of current page (as .png).
* @param baseName name for file created (without extension),
* if a file already exists with the supplied name an
* '_index' will be added.
* @return absolute path of file created.
*/
public String takeScreenshot(String baseName) {
String result = null;
WebDriver d = driver();
if (!(d instanceof TakesScreenshot)) {
d = new Augmenter().augment(d);
}
if (d instanceof TakesScreenshot) {
TakesScreenshot ts = (TakesScreenshot) d;
byte[] png = ts.getScreenshotAs(OutputType.BYTES);
result = writeScreenshot(baseName, png);
}
return result;
}
/**
* Finds screenshot embedded in throwable, if any.
* @param t exception to search in.
* @return content of screenshot (if any is present), null otherwise.
*/
public byte[] findScreenshot(Throwable t) {
byte[] result = null;
if (t != null) {
if (t instanceof ScreenshotException) {
String encodedScreenshot = ((ScreenshotException)t).getBase64EncodedScreenshot();
result = new Base64Encoder().decode(encodedScreenshot);
} else {
result = findScreenshot(t.getCause());
}
}
return result;
}
/**
* Saves screenshot (as .png).
* @param baseName name for file created (without extension),
* if a file already exists with the supplied name an
* '_index' will be added.
* @return absolute path of file created.
*/
public String writeScreenshot(String baseName, byte[] png) {
return FileUtil.saveToFile(baseName, "png", png);
}
public int getCurrentTabIndex(List<String> tabHandles) {
try {
String currentHandle = driver().getWindowHandle();
return tabHandles.indexOf(currentHandle);
} catch (NoSuchWindowException e) {
return -1;
}
}
public void goToTab(List<String> tabHandles, int indexToGoTo) {
driver().switchTo().window(tabHandles.get(indexToGoTo));
}
public List<String> getTabHandles() {
return new ArrayList<String>(driver().getWindowHandles());
}
/**
* @return current browser's cookies.
*/
public Set<Cookie> getCookies() {
return driver().manage().getCookies();
}
public void setDriverFactory(DriverFactory aFactory) {
factory = aFactory;
}
public static interface DriverFactory {
public void createDriver();
}
}
|
package nl.topicus.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.RowIdLifetime;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Types;
import nl.topicus.jdbc.statement.CloudSpannerPreparedStatement;
public class CloudSpannerDatabaseMetaData extends AbstractCloudSpannerDatabaseMetaData
{
private static final int JDBC_MAJOR_VERSION = 4;
private static final int JDBC_MINOR_VERSION = 2;
private static final String FROM_STATEMENT_WITHOUT_RESULTS = " FROM INFORMATION_SCHEMA.TABLES WHERE 1=2 ";
private CloudSpannerConnection connection;
CloudSpannerDatabaseMetaData(CloudSpannerConnection connection)
{
this.connection = connection;
}
@Override
public boolean allProceduresAreCallable() throws SQLException
{
return true;
}
@Override
public boolean allTablesAreSelectable() throws SQLException
{
return true;
}
@Override
public String getURL() throws SQLException
{
return connection.getUrl();
}
@Override
public String getUserName() throws SQLException
{
return connection.getClientId();
}
@Override
public boolean isReadOnly() throws SQLException
{
return false;
}
@Override
public boolean nullsAreSortedHigh() throws SQLException
{
return false;
}
@Override
public boolean nullsAreSortedLow() throws SQLException
{
return true;
}
@Override
public boolean nullsAreSortedAtStart() throws SQLException
{
return true;
}
@Override
public boolean nullsAreSortedAtEnd() throws SQLException
{
return false;
}
@Override
public String getDatabaseProductName() throws SQLException
{
return connection.getProductName();
}
@Override
public String getDatabaseProductVersion() throws SQLException
{
return getDatabaseMajorVersion() + "." + getDatabaseMinorVersion();
}
@Override
public String getDriverName() throws SQLException
{
return CloudSpannerDriver.class.getName();
}
@Override
public String getDriverVersion() throws SQLException
{
return getDriverMajorVersion() + "." + getDriverMinorVersion();
}
@Override
public int getDriverMajorVersion()
{
return CloudSpannerDriver.MAJOR_VERSION;
}
@Override
public int getDriverMinorVersion()
{
return CloudSpannerDriver.MINOR_VERSION;
}
@Override
public boolean usesLocalFiles() throws SQLException
{
return false;
}
@Override
public boolean usesLocalFilePerTable() throws SQLException
{
return false;
}
@Override
public boolean supportsMixedCaseIdentifiers() throws SQLException
{
return false;
}
@Override
public boolean storesUpperCaseIdentifiers() throws SQLException
{
return false;
}
@Override
public boolean storesLowerCaseIdentifiers() throws SQLException
{
return false;
}
@Override
public boolean storesMixedCaseIdentifiers() throws SQLException
{
return true;
}
@Override
public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException
{
return false;
}
@Override
public boolean storesUpperCaseQuotedIdentifiers() throws SQLException
{
return false;
}
@Override
public boolean storesLowerCaseQuotedIdentifiers() throws SQLException
{
return false;
}
@Override
public boolean storesMixedCaseQuotedIdentifiers() throws SQLException
{
return true;
}
@Override
public String getIdentifierQuoteString() throws SQLException
{
return "`";
}
@Override
public String getSQLKeywords() throws SQLException
{
return "INTERLEAVE, PARENT";
}
@Override
public String getNumericFunctions() throws SQLException
{
return "";
}
@Override
public String getStringFunctions() throws SQLException
{
return "";
}
@Override
public String getSystemFunctions() throws SQLException
{
return "";
}
@Override
public String getTimeDateFunctions() throws SQLException
{
return "";
}
@Override
public String getSearchStringEscape() throws SQLException
{
return "\\";
}
@Override
public String getExtraNameCharacters() throws SQLException
{
return "";
}
@Override
public boolean supportsAlterTableWithAddColumn() throws SQLException
{
return true;
}
@Override
public boolean supportsAlterTableWithDropColumn() throws SQLException
{
return true;
}
@Override
public boolean supportsColumnAliasing() throws SQLException
{
return true;
}
@Override
public boolean nullPlusNonNullIsNull() throws SQLException
{
return true;
}
@Override
public boolean supportsConvert() throws SQLException
{
return false;
}
@Override
public boolean supportsConvert(int fromType, int toType) throws SQLException
{
return false;
}
@Override
public boolean supportsTableCorrelationNames() throws SQLException
{
return true;
}
@Override
public boolean supportsDifferentTableCorrelationNames() throws SQLException
{
return false;
}
@Override
public boolean supportsExpressionsInOrderBy() throws SQLException
{
return true;
}
@Override
public boolean supportsOrderByUnrelated() throws SQLException
{
return true;
}
@Override
public boolean supportsGroupBy() throws SQLException
{
return true;
}
@Override
public boolean supportsGroupByUnrelated() throws SQLException
{
return true;
}
@Override
public boolean supportsGroupByBeyondSelect() throws SQLException
{
return true;
}
@Override
public boolean supportsLikeEscapeClause() throws SQLException
{
return true;
}
@Override
public boolean supportsMultipleResultSets() throws SQLException
{
return false;
}
@Override
public boolean supportsMultipleTransactions() throws SQLException
{
return true;
}
@Override
public boolean supportsNonNullableColumns() throws SQLException
{
return true;
}
@Override
public boolean supportsMinimumSQLGrammar() throws SQLException
{
return false;
}
@Override
public boolean supportsCoreSQLGrammar() throws SQLException
{
return false;
}
@Override
public boolean supportsExtendedSQLGrammar() throws SQLException
{
return false;
}
@Override
public boolean supportsANSI92EntryLevelSQL() throws SQLException
{
return false;
}
@Override
public boolean supportsANSI92IntermediateSQL() throws SQLException
{
return false;
}
@Override
public boolean supportsANSI92FullSQL() throws SQLException
{
return false;
}
@Override
public boolean supportsIntegrityEnhancementFacility() throws SQLException
{
return false;
}
@Override
public boolean supportsOuterJoins() throws SQLException
{
return true;
}
@Override
public boolean supportsFullOuterJoins() throws SQLException
{
return true;
}
@Override
public boolean supportsLimitedOuterJoins() throws SQLException
{
return true;
}
@Override
public String getSchemaTerm() throws SQLException
{
return null;
}
@Override
public String getProcedureTerm() throws SQLException
{
return null;
}
@Override
public String getCatalogTerm() throws SQLException
{
return null;
}
@Override
public boolean isCatalogAtStart() throws SQLException
{
return false;
}
@Override
public String getCatalogSeparator() throws SQLException
{
return null;
}
@Override
public boolean supportsSchemasInDataManipulation() throws SQLException
{
return false;
}
@Override
public boolean supportsSchemasInProcedureCalls() throws SQLException
{
return false;
}
@Override
public boolean supportsSchemasInTableDefinitions() throws SQLException
{
return false;
}
@Override
public boolean supportsSchemasInIndexDefinitions() throws SQLException
{
return false;
}
@Override
public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException
{
return false;
}
@Override
public boolean supportsCatalogsInDataManipulation() throws SQLException
{
return false;
}
@Override
public boolean supportsCatalogsInProcedureCalls() throws SQLException
{
return false;
}
@Override
public boolean supportsCatalogsInTableDefinitions() throws SQLException
{
return false;
}
@Override
public boolean supportsCatalogsInIndexDefinitions() throws SQLException
{
return false;
}
@Override
public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException
{
return false;
}
@Override
public boolean supportsPositionedDelete() throws SQLException
{
return false;
}
@Override
public boolean supportsPositionedUpdate() throws SQLException
{
return false;
}
@Override
public boolean supportsSelectForUpdate() throws SQLException
{
return false;
}
@Override
public boolean supportsStoredProcedures() throws SQLException
{
return false;
}
@Override
public boolean supportsSubqueriesInComparisons() throws SQLException
{
return true;
}
@Override
public boolean supportsSubqueriesInExists() throws SQLException
{
return true;
}
@Override
public boolean supportsSubqueriesInIns() throws SQLException
{
return true;
}
@Override
public boolean supportsSubqueriesInQuantifieds() throws SQLException
{
return true;
}
@Override
public boolean supportsCorrelatedSubqueries() throws SQLException
{
return true;
}
@Override
public boolean supportsUnion() throws SQLException
{
return true;
}
@Override
public boolean supportsUnionAll() throws SQLException
{
return true;
}
@Override
public boolean supportsOpenCursorsAcrossCommit() throws SQLException
{
return false;
}
@Override
public boolean supportsOpenCursorsAcrossRollback() throws SQLException
{
return false;
}
@Override
public boolean supportsOpenStatementsAcrossCommit() throws SQLException
{
return true;
}
@Override
public boolean supportsOpenStatementsAcrossRollback() throws SQLException
{
return true;
}
@Override
public int getMaxBinaryLiteralLength() throws SQLException
{
return 0;
}
@Override
public int getMaxCharLiteralLength() throws SQLException
{
return 0;
}
@Override
public int getMaxColumnNameLength() throws SQLException
{
return 128;
}
@Override
public int getMaxColumnsInGroupBy() throws SQLException
{
return 0;
}
@Override
public int getMaxColumnsInIndex() throws SQLException
{
return 0;
}
@Override
public int getMaxColumnsInOrderBy() throws SQLException
{
return 0;
}
@Override
public int getMaxColumnsInSelect() throws SQLException
{
return 0;
}
@Override
public int getMaxColumnsInTable() throws SQLException
{
return 0;
}
@Override
public int getMaxConnections() throws SQLException
{
return 0;
}
@Override
public int getMaxCursorNameLength() throws SQLException
{
return 0;
}
@Override
public int getMaxIndexLength() throws SQLException
{
return 0;
}
@Override
public int getMaxSchemaNameLength() throws SQLException
{
return 0;
}
@Override
public int getMaxProcedureNameLength() throws SQLException
{
return 0;
}
@Override
public int getMaxCatalogNameLength() throws SQLException
{
return 0;
}
@Override
public int getMaxRowSize() throws SQLException
{
return 0;
}
@Override
public boolean doesMaxRowSizeIncludeBlobs() throws SQLException
{
return false;
}
@Override
public int getMaxStatementLength() throws SQLException
{
return 0;
}
@Override
public int getMaxStatements() throws SQLException
{
return 0;
}
@Override
public int getMaxTableNameLength() throws SQLException
{
return 128;
}
@Override
public int getMaxTablesInSelect() throws SQLException
{
return 0;
}
@Override
public int getMaxUserNameLength() throws SQLException
{
return 0;
}
@Override
public int getDefaultTransactionIsolation() throws SQLException
{
return Connection.TRANSACTION_SERIALIZABLE;
}
@Override
public boolean supportsTransactions() throws SQLException
{
return true;
}
@Override
public boolean supportsTransactionIsolationLevel(int level) throws SQLException
{
return Connection.TRANSACTION_SERIALIZABLE == level;
}
@Override
public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException
{
return false;
}
@Override
public boolean supportsDataManipulationTransactionsOnly() throws SQLException
{
return true;
}
@Override
public boolean dataDefinitionCausesTransactionCommit() throws SQLException
{
return true;
}
@Override
public boolean dataDefinitionIgnoredInTransactions() throws SQLException
{
return false;
}
@Override
public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern)
throws SQLException
{
String sql = "SELECT '' AS PROCEDURE_CAT, '' AS PROCEDURE_SCHEM, '' AS PROCEDURE_NAME, NULL AS RES1, NULL AS RES2, NULL AS RES3, "
+ "'' AS REMARKS, 0 AS PROCEDURE_TYPE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS;
PreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern,
String columnNamePattern) throws SQLException
{
String sql = "SELECT '' AS PROCEDURE_CAT, '' AS PROCEDURE_SCHEM, '' AS PROCEDURE_NAME, '' AS COLUMN_NAME, 0 AS COLUMN_TYPE, "
+ "0 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS PRECISION, 0 AS LENGTH, 0 AS SCALE, 0 AS RADIX, "
+ "0 AS NULLABLE, '' AS REMARKS, '' AS COLUMN_DEF, 0 AS SQL_DATA_TYPE, 0 AS SQL_DATATIME_SUB, "
+ "0 AS CHAR_OCTET_LENGTH, 0 AS ORDINAL_POSITION, '' AS IS_NULLABLE, '' AS SPECIFIC_NAME "
+ FROM_STATEMENT_WITHOUT_RESULTS;
PreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
private CloudSpannerPreparedStatement prepareStatement(String sql, String... params) throws SQLException
{
CloudSpannerPreparedStatement statement = connection.prepareStatement(sql);
statement.setForceSingleUseReadContext(true);
int paramIndex = 1;
for (String param : params)
{
if (param != null)
{
statement.setString(paramIndex, param.toUpperCase());
paramIndex++;
}
}
return statement;
}
@Override
public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)
throws SQLException
{
String sql = "select CASE WHEN TABLE_CATALOG='' THEN NULL ELSE TABLE_CATALOG END AS TABLE_CAT, CASE WHEN TABLE_SCHEMA='' THEN NULL ELSE TABLE_SCHEMA END AS TABLE_SCHEM, TABLE_NAME, 'TABLE' AS TABLE_TYPE, NULL AS REMARKS, NULL AS TYPE_CAT, NULL AS TYPE_SCHEM, NULL AS TYPE_NAME, NULL AS SELF_REFERENCING_COL_NAME, NULL AS REF_GENERATION "
+ CloudSpannerDatabaseMetaDataConstants.FROM_TABLES_T
+ CloudSpannerDatabaseMetaDataConstants.WHERE_1_EQUALS_1;
if (catalog != null)
sql = sql + "AND UPPER(T.TABLE_CATALOG) like ? ";
if (schemaPattern != null)
sql = sql + "AND UPPER(T.TABLE_SCHEMA) like ? ";
if (tableNamePattern != null)
sql = sql + "AND UPPER(T.TABLE_NAME) like ? ";
sql = sql + "ORDER BY TABLE_NAME";
CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schemaPattern, tableNamePattern);
return statement.executeQuery();
}
@Override
public ResultSet getSchemas() throws SQLException
{
String sql = "SELECT '' AS TABLE_SCHEM, '' AS TABLE_CAT " + FROM_STATEMENT_WITHOUT_RESULTS;
CloudSpannerPreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getCatalogs() throws SQLException
{
String sql = "SELECT '' AS TABLE_CAT " + FROM_STATEMENT_WITHOUT_RESULTS;
CloudSpannerPreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getTableTypes() throws SQLException
{
String sql = "SELECT 'TABLE' AS TABLE_TYPE";
return prepareStatement(sql).executeQuery();
}
@Override
public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern)
throws SQLException
{
String sql = CloudSpannerDatabaseMetaDataConstants.GET_COLUMNS;
if (catalog != null)
sql = sql + "AND UPPER(TABLE_CATALOG) like ? ";
if (schemaPattern != null)
sql = sql + "AND UPPER(TABLE_SCHEMA) like ? ";
if (tableNamePattern != null)
sql = sql + "AND UPPER(TABLE_NAME) like ? ";
if (columnNamePattern != null)
sql = sql + "AND UPPER(COLUMN_NAME) LIKE ? ";
sql = sql + "ORDER BY TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION ";
CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schemaPattern, tableNamePattern,
columnNamePattern);
return statement.executeQuery();
}
@Override
public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern)
throws SQLException
{
String sql = "SELECT '' AS TABLE_CAT, '' AS TABLE_SCHEM, '' AS TABLE_NAME, '' AS COLUMN_NAME, '' AS GRANTOR, '' AS GRANTEE, '' AS PRIVILEGE, 'NO' AS IS_GRANTABLE "
+ FROM_STATEMENT_WITHOUT_RESULTS;
CloudSpannerPreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern)
throws SQLException
{
String sql = "SELECT '' AS TABLE_CAT, '' AS TABLE_SCHEM, '' AS TABLE_NAME, '' AS GRANTOR, '' AS GRANTEE, '' AS PRIVILEGE, 'NO' AS IS_GRANTABLE "
+ FROM_STATEMENT_WITHOUT_RESULTS;
CloudSpannerPreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable)
throws SQLException
{
String sql = "SELECT 0 AS SCOPE, '' AS COLUMN_NAME, 0 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS COLUMN_SIZE, 0 AS BUFFER_LENGTH, "
+ "0 AS DECIMAL_DIGITS, 0 AS PSEUDO_COLUMN " + FROM_STATEMENT_WITHOUT_RESULTS;
CloudSpannerPreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException
{
String sql = "SELECT 0 AS SCOPE, '' AS COLUMN_NAME, 0 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS COLUMN_SIZE, 0 AS BUFFER_LENGTH, "
+ "0 AS DECIMAL_DIGITS, 0 AS PSEUDO_COLUMN " + FROM_STATEMENT_WITHOUT_RESULTS;
CloudSpannerPreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException
{
String sql = "SELECT IDX.TABLE_CATALOG AS TABLE_CAT, IDX.TABLE_SCHEMA AS TABLE_SCHEM, IDX.TABLE_NAME AS TABLE_NAME, COLS.COLUMN_NAME AS COLUMN_NAME, ORDINAL_POSITION AS KEY_SEQ, IDX.INDEX_NAME AS PK_NAME "
+ "FROM INFORMATION_SCHEMA.INDEXES IDX "
+ "INNER JOIN INFORMATION_SCHEMA.INDEX_COLUMNS COLS ON IDX.TABLE_CATALOG=COLS.TABLE_CATALOG AND IDX.TABLE_SCHEMA=COLS.TABLE_SCHEMA AND IDX.TABLE_NAME=COLS.TABLE_NAME AND IDX.INDEX_NAME=COLS.INDEX_NAME "
+ "WHERE IDX.INDEX_TYPE='PRIMARY_KEY' ";
if (catalog != null)
sql = sql + "AND UPPER(IDX.TABLE_CATALOG) like ? ";
if (schema != null)
sql = sql + "AND UPPER(IDX.TABLE_SCHEMA) like ? ";
if (table != null)
sql = sql + "AND UPPER(IDX.TABLE_NAME) like ? ";
sql = sql + "ORDER BY COLS.ORDINAL_POSITION ";
PreparedStatement statement = prepareStatement(sql, catalog, schema, table);
return statement.executeQuery();
}
@Override
public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException
{
String sql = "SELECT PARENT.TABLE_CATALOG AS PKTABLE_CAT, PARENT.TABLE_SCHEMA AS PKTABLE_SCHEM, PARENT.TABLE_NAME AS PKTABLE_NAME, COL.COLUMN_NAME AS PKCOLUMN_NAME, CHILD.TABLE_CATALOG AS FKTABLE_CAT, CHILD.TABLE_SCHEMA AS FKTABLE_SCHEM, CHILD.TABLE_NAME AS FKTABLE_NAME, COL.COLUMN_NAME FKCOLUMN_NAME, COL.ORDINAL_POSITION AS KEY_SEQ, 3 AS UPDATE_RULE, CASE WHEN CHILD.ON_DELETE_ACTION = 'CASCADE' THEN 0 ELSE 3 END AS DELETE_RULE, NULL AS FK_NAME, INDEXES.INDEX_NAME AS PK_NAME, 7 AS DEFERRABILITY "
+ "FROM INFORMATION_SCHEMA.TABLES CHILD "
+ "INNER JOIN INFORMATION_SCHEMA.TABLES PARENT ON CHILD.TABLE_CATALOG=PARENT.TABLE_CATALOG AND CHILD.TABLE_SCHEMA=PARENT.TABLE_SCHEMA AND CHILD.PARENT_TABLE_NAME=PARENT.TABLE_NAME "
+ "INNER JOIN INFORMATION_SCHEMA.INDEXES ON PARENT.TABLE_CATALOG=INDEXES.TABLE_CATALOG AND PARENT.TABLE_SCHEMA=INDEXES.TABLE_SCHEMA AND PARENT.TABLE_NAME=INDEXES.TABLE_NAME AND INDEXES.INDEX_TYPE='PRIMARY_KEY' "
+ "INNER JOIN INFORMATION_SCHEMA.INDEX_COLUMNS COL ON INDEXES.TABLE_CATALOG=COL.TABLE_CATALOG AND INDEXES.TABLE_SCHEMA=COL.TABLE_SCHEMA AND INDEXES.TABLE_NAME=COL.TABLE_NAME AND INDEXES.INDEX_NAME=COL.INDEX_NAME "
+ "WHERE CHILD.PARENT_TABLE_NAME IS NOT NULL ";
if (catalog != null)
sql = sql + "AND UPPER(CHILD.TABLE_CATALOG) like ? ";
if (schema != null)
sql = sql + "AND UPPER(CHILD.TABLE_SCHEMA) like ? ";
if (table != null)
sql = sql + "AND UPPER(CHILD.TABLE_NAME) like ? ";
sql = sql + "ORDER BY PARENT.TABLE_CATALOG, PARENT.TABLE_SCHEMA, PARENT.TABLE_NAME, COL.ORDINAL_POSITION ";
PreparedStatement statement = prepareStatement(sql, catalog, schema, table);
return statement.executeQuery();
}
@Override
public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException
{
String sql = "SELECT "
+ "NULL AS PKTABLE_CAT, NULL AS PKTABLE_SCHEM, PARENT.TABLE_NAME AS PKTABLE_NAME, PARENT_INDEX_COLUMNS.COLUMN_NAME AS PKCOLUMN_NAME, "
+ "NULL AS FKTABLE_CAT, NULL AS FKTABLE_SCHEM, CHILD.TABLE_NAME AS FKTABLE_NAME, PARENT_INDEX_COLUMNS.COLUMN_NAME AS FKCOLUMN_NAME, "
+ "PARENT_INDEX_COLUMNS.ORDINAL_POSITION AS KEY_SEQ, 3 AS UPDATE_RULE, CASE WHEN CHILD.ON_DELETE_ACTION='CASCADE' THEN 0 ELSE 3 END AS DELETE_RULE, "
+ "NULL AS FK_NAME, 'PRIMARY_KEY' AS PK_NAME, 7 AS DEFERRABILITY "
+ "FROM INFORMATION_SCHEMA.TABLES PARENT "
+ "INNER JOIN INFORMATION_SCHEMA.TABLES CHILD ON CHILD.PARENT_TABLE_NAME=PARENT.TABLE_NAME "
+ "INNER JOIN INFORMATION_SCHEMA.INDEX_COLUMNS PARENT_INDEX_COLUMNS ON PARENT_INDEX_COLUMNS.TABLE_NAME=PARENT.TABLE_NAME AND PARENT_INDEX_COLUMNS.INDEX_NAME='PRIMARY_KEY' "
+ CloudSpannerDatabaseMetaDataConstants.WHERE_1_EQUALS_1;
if (catalog != null)
sql = sql + "AND UPPER(PARENT.TABLE_CATALOG) like ? ";
if (schema != null)
sql = sql + "AND UPPER(PARENT.TABLE_SCHEMA) like ? ";
if (table != null)
sql = sql + "AND UPPER(PARENT.TABLE_NAME) like ? ";
sql = sql
+ "ORDER BY CHILD.TABLE_CATALOG, CHILD.TABLE_SCHEMA, CHILD.TABLE_NAME, PARENT_INDEX_COLUMNS.ORDINAL_POSITION ";
CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schema, table);
return statement.executeQuery();
}
@Override
public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable,
String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public ResultSet getTypeInfo() throws SQLException
{
String sql = CloudSpannerDatabaseMetaDataConstants.GET_TYPE_INFO;
CloudSpannerPreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate)
throws SQLException
{
String sql = "select idx.TABLE_CATALOG AS TABLE_CAT, idx.TABLE_SCHEMA AS TABLE_SCHEM, idx.TABLE_NAME, CASE WHEN IS_UNIQUE THEN FALSE ELSE TRUE END AS NON_UNIQUE, NULL AS INDEX_QUALIFIER, idx.INDEX_NAME, 3 AS TYPE, ORDINAL_POSITION, COLUMN_NAME, SUBSTR(COLUMN_ORDERING, 0, 1) AS ASC_OR_DESC, -1 AS CARDINALITY, -1 AS PAGES, NULL AS FILTER_CONDITION "
+ "FROM information_schema.indexes idx "
+ "INNER JOIN information_schema.index_columns col on idx.table_catalog=col.table_catalog and idx.table_schema=col.table_schema and idx.table_name=col.table_name and idx.index_name=col.index_name "
+ CloudSpannerDatabaseMetaDataConstants.WHERE_1_EQUALS_1;
if (catalog != null)
sql = sql + "AND UPPER(idx.TABLE_CATALOG) like ? ";
if (schema != null)
sql = sql + "AND UPPER(idx.TABLE_SCHEMA) like ? ";
if (table != null)
sql = sql + "AND UPPER(idx.TABLE_NAME) like ? ";
if (unique)
sql = sql + "AND IS_UNIQUE ";
sql = sql + "ORDER BY IS_UNIQUE, INDEX_NAME, ORDINAL_POSITION ";
PreparedStatement statement = prepareStatement(sql, catalog, schema, table);
return statement.executeQuery();
}
@Override
public boolean supportsResultSetType(int type) throws SQLException
{
return type == ResultSet.TYPE_FORWARD_ONLY;
}
@Override
public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException
{
return type == ResultSet.TYPE_FORWARD_ONLY && concurrency == ResultSet.CONCUR_READ_ONLY;
}
@Override
public boolean ownUpdatesAreVisible(int type) throws SQLException
{
return false;
}
@Override
public boolean ownDeletesAreVisible(int type) throws SQLException
{
return false;
}
@Override
public boolean ownInsertsAreVisible(int type) throws SQLException
{
return false;
}
@Override
public boolean othersUpdatesAreVisible(int type) throws SQLException
{
return false;
}
@Override
public boolean othersDeletesAreVisible(int type) throws SQLException
{
return false;
}
@Override
public boolean othersInsertsAreVisible(int type) throws SQLException
{
return false;
}
@Override
public boolean updatesAreDetected(int type) throws SQLException
{
return false;
}
@Override
public boolean deletesAreDetected(int type) throws SQLException
{
return false;
}
@Override
public boolean insertsAreDetected(int type) throws SQLException
{
return false;
}
@Override
public boolean supportsBatchUpdates() throws SQLException
{
return false;
}
@Override
public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types)
throws SQLException
{
String sql = CloudSpannerDatabaseMetaDataConstants.GET_UDTS;
CloudSpannerPreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public Connection getConnection() throws SQLException
{
return connection;
}
@Override
public boolean supportsSavepoints() throws SQLException
{
return false;
}
@Override
public boolean supportsNamedParameters() throws SQLException
{
return true;
}
@Override
public boolean supportsMultipleOpenResults() throws SQLException
{
return false;
}
@Override
public boolean supportsGetGeneratedKeys() throws SQLException
{
return false;
}
@Override
public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException
{
String sql = "SELECT '' AS TYPE_CAT, '' AS TYPE_SCHEM, '' AS TYPE_NAME, "
+ "'' AS SUPERTYPE_CAT, '' AS SUPERTYPE_SCHEM, '' AS SUPERTYPE_NAME " + FROM_STATEMENT_WITHOUT_RESULTS;
CloudSpannerPreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException
{
String sql = "SELECT '' AS TABLE_CAT, '' AS TABLE_SCHEM, '' AS TABLE_NAME, '' AS SUPERTABLE_NAME "
+ FROM_STATEMENT_WITHOUT_RESULTS;
CloudSpannerPreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern,
String attributeNamePattern) throws SQLException
{
String sql = "SELECT '' AS TYPE_CAT, '' AS TYPE_SCHEM, '' AS TYPE_NAME, '' AS ATTR_NAME, 0 AS DATA_TYPE, "
+ "'' AS ATTR_TYPE_NAME, 0 AS ATTR_SIZE, 0 AS DECIMAL_DIGITS, 0 AS NUM_PREC_RADIX, 0 AS NULLABLE, "
+ "'' AS REMARKS, '' AS ATTR_DEF, 0 AS SQL_DATA_TYPE, 0 AS SQL_DATETIME_SUB, 0 AS CHAR_OCTET_LENGTH, "
+ "0 AS ORDINAL_POSITION, 'NO' AS IS_NULLABLE, '' AS SCOPE_CATALOG, '' AS SCOPE_SCHEMA, '' AS SCOPE_TABLE, "
+ "0 AS SOURCE_DATA_TYPE " + FROM_STATEMENT_WITHOUT_RESULTS;
CloudSpannerPreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public boolean supportsResultSetHoldability(int holdability) throws SQLException
{
return holdability == ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
@Override
public int getResultSetHoldability() throws SQLException
{
return ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
@Override
public int getDatabaseMajorVersion() throws SQLException
{
return 1;
}
@Override
public int getDatabaseMinorVersion() throws SQLException
{
return 0;
}
@Override
public int getJDBCMajorVersion() throws SQLException
{
return JDBC_MAJOR_VERSION;
}
@Override
public int getJDBCMinorVersion() throws SQLException
{
return JDBC_MINOR_VERSION;
}
@Override
public int getSQLStateType() throws SQLException
{
return sqlStateSQL;
}
@Override
public boolean locatorsUpdateCopy() throws SQLException
{
return false;
}
@Override
public boolean supportsStatementPooling() throws SQLException
{
return false;
}
@Override
public RowIdLifetime getRowIdLifetime() throws SQLException
{
return RowIdLifetime.ROWID_UNSUPPORTED;
}
@Override
public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException
{
String sql = "SELECT '' AS TABLE_SCHEM, '' AS TABLE_CATALOG " + FROM_STATEMENT_WITHOUT_RESULTS;
sql = sql + " ORDER BY TABLE_SCHEM ";
PreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException
{
return false;
}
@Override
public boolean autoCommitFailureClosesAllResultSets() throws SQLException
{
return false;
}
@Override
public ResultSet getClientInfoProperties() throws SQLException
{
String sql = "SELECT '' AS NAME, 0 AS MAX_LEN, '' AS DEFAULT_VALUE, '' AS DESCRIPTION "
+ FROM_STATEMENT_WITHOUT_RESULTS;
sql = sql + " ORDER BY NAME ";
PreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException
{
String sql = "SELECT '' AS FUNCTION_CAT, '' AS FUNCTION_SCHEM, '' AS FUNCTION_NAME, '' AS REMARKS, 0 AS FUNCTION_TYPE, '' AS SPECIFIC_NAME "
+ FROM_STATEMENT_WITHOUT_RESULTS;
sql = sql + " ORDER BY FUNCTION_CAT, FUNCTION_SCHEM, FUNCTION_NAME, SPECIFIC_NAME ";
PreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern,
String columnNamePattern) throws SQLException
{
String sql = "SELECT '' AS FUNCTION_CAT, '' AS FUNCTION_SCHEM, '' AS FUNCTION_NAME, '' AS COLUMN_NAME, 0 AS COLUMN_TYPE, 1111 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS PRECISION, 0 AS LENGTH, 0 AS SCALE, 0 AS RADIX, 0 AS NULLABLE, '' AS REMARKS, 0 AS CHAR_OCTET_LENGTH, 0 AS ORDINAL_POSITION, '' AS IS_NULLABLE, '' AS SPECIFIC_NAME "
+ FROM_STATEMENT_WITHOUT_RESULTS;
sql = sql + " ORDER BY FUNCTION_CAT, FUNCTION_SCHEM, FUNCTION_NAME, SPECIFIC_NAME ";
PreparedStatement statement = prepareStatement(sql);
return statement.executeQuery();
}
@Override
public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern,
String columnNamePattern) throws SQLException
{
String sql = "select TABLE_CATALOG AS TABLE_CAT, TABLE_SCHEMA AS TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, "
+ "CASE " + " WHEN SPANNER_TYPE = 'ARRAY' THEN " + Types.ARRAY + " "
+ " WHEN SPANNER_TYPE = 'BOOL' THEN " + Types.BOOLEAN + " " + " WHEN SPANNER_TYPE = 'BYTES' THEN "
+ Types.BINARY + " " + " WHEN SPANNER_TYPE = 'DATE' THEN " + Types.DATE + " "
+ " WHEN SPANNER_TYPE = 'FLOAT64' THEN " + Types.DOUBLE + " " + " WHEN SPANNER_TYPE = 'INT64' THEN "
+ Types.BIGINT + " " + " WHEN SPANNER_TYPE = 'STRING' THEN " + Types.NVARCHAR + " "
+ " WHEN SPANNER_TYPE = 'STRUCT' THEN " + Types.STRUCT + " "
+ " WHEN SPANNER_TYPE = 'TIMESTAMP' THEN " + Types.TIMESTAMP + " " + "END AS DATA_TYPE, "
+ "0 AS COLUMN_SIZE, NULL AS DECIMAL_DIGITS, 0 AS NUM_PREC_RADIX, 'USAGE_UNKNOWN' AS COLUMN_USAGE, NULL AS REMARKS, 0 AS CHAR_OCTET_LENGTH, IS_NULLABLE "
+ FROM_STATEMENT_WITHOUT_RESULTS;
if (catalog != null)
sql = sql + "AND UPPER(TABLE_CATALOG) like ? ";
if (schemaPattern != null)
sql = sql + "AND UPPER(TABLE_SCHEMA) like ? ";
if (tableNamePattern != null)
sql = sql + "AND UPPER(TABLE_NAME) like ? ";
if (columnNamePattern != null)
sql = sql + "AND UPPER(COLUMN_NAME) LIKE ? ";
sql = sql + "ORDER BY TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION ";
CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schemaPattern, tableNamePattern,
columnNamePattern);
return statement.executeQuery();
}
@Override
public boolean generatedKeyAlwaysReturned() throws SQLException
{
return false;
}
}
|
package no.finn.unleash.repository;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import no.finn.unleash.UnleashException;
final class HttpToggleFetcher implements ToggleFetcher {
public static final int CONNECT_TIMEOUT = 10000;
private String etag = "";
private final URL toggleUrl;
public HttpToggleFetcher(URI repo) {
try {
toggleUrl = repo.toURL();
} catch (MalformedURLException|IllegalArgumentException ex) {
throw new UnleashException("Invalid unleash repository uri [" + repo.toString() + "]", ex);
}
}
@Override
public Response fetchToggles() throws UnleashException {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) toggleUrl.openConnection();
connection.setConnectTimeout(CONNECT_TIMEOUT);
connection.setReadTimeout(CONNECT_TIMEOUT);
connection.setRequestProperty("If-None-Match", etag);
connection.setUseCaches(true);
connection.connect();
int responseCode = connection.getResponseCode();
if(responseCode < 300) {
return getToggleResponse(connection);
} else {
return new Response(Response.Status.NOT_CHANGED);
}
} catch (IOException e) {
throw new UnleashException("Could not fetch toggles", e);
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
private Response getToggleResponse(HttpURLConnection request) throws IOException {
etag = request.getHeaderField("ETag");
try(BufferedReader reader = new BufferedReader(
new InputStreamReader((InputStream) request.getContent(), StandardCharsets.UTF_8))) {
ToggleCollection toggles = JsonToggleParser.fromJson(reader);
return new Response(Response.Status.CHANGED, toggles);
}
}
}
|
package org.andidev.applicationname.config;
import java.util.Arrays;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import org.andidev.applicationname.config.logging.MDC;
import org.andidev.applicationname.entity.Group;
import org.andidev.applicationname.entity.User;
import org.andidev.applicationname.entity.enums.Role;
import org.andidev.applicationname.service.GroupService;
import org.andidev.applicationname.service.UserService;
import static org.andidev.applicationname.util.ApplicationUtils.getUsername;
import static org.andidev.applicationname.util.StringUtils.quote;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
public class ImportSql implements ApplicationListener<ContextRefreshedEvent> {
@Inject
private GroupService groupService;
@Inject
UserService userService;
@Inject
UserDetailsService userDetailsService;
@Override
@Transactional
public void onApplicationEvent(ContextRefreshedEvent event) {
log.info("Creating initial database data");
// Create root user and group
User rootUser = createRootUser();
Group rootGroup = createRootGroup();
rootGroup.getUsers().add(rootUser);
// Create anonymous user and group
User anonymousUser = createAnonymousUser();
// Login as root user
login("root");
// Create dev user and group
User developerUser = createDeveloperUser();
Group developerGroup = createDeveloperGroup();
developerGroup.getUsers().add(developerUser);
// Create admin user and group
User adminUser = createAdminUser();
Group adminGroup = createAdminGroup();
adminGroup.getUsers().add(adminUser);
// Create normal user and group
User user = createUser();
Group userGroup = createUserGroup();
userGroup.getUsers().add(user);
// Logout root user
logout();
log.info("Initial database data created!");
log.info("Creating test data");
// Add create test data methods here
log.info("Test data created!");
}
private User createRootUser() {
User user = new User("root", "");
return userService.create(user);
}
private Group createRootGroup() {
Group group = new Group("root");
group.getGroupRoles().addAll(Arrays.asList(Role.values()));
return groupService.create(group);
}
private User createAnonymousUser() {
User user = new User("anonymousUser", "");
return userService.create(user);
}
private User createDeveloperUser() {
User user = new User("developer", "");
return userService.create(user);
}
private Group createDeveloperGroup() {
Group group = new Group("developer");
group.getGroupRoles().add(Role.ROLE_DEVELOPER);
group.getGroupRoles().add(Role.ROLE_ADMIN);
group.getGroupRoles().add(Role.ROLE_USER);
return groupService.create(group);
}
private User createAdminUser() {
User user = new User("admin", "");
return userService.create(user);
}
private Group createAdminGroup() {
Group group = new Group("admin");
group.getGroupRoles().add(Role.ROLE_ADMIN);
group.getGroupRoles().add(Role.ROLE_USER);
return groupService.create(group);
}
private User createUser() {
User user = new User("user", "");
return userService.create(user);
}
private Group createUserGroup() {
Group group = new Group("user");
group.getGroupRoles().add(Role.ROLE_USER);
return groupService.create(group);
}
private void login(String username) throws UsernameNotFoundException {
UserDetails user = userDetailsService.loadUserByUsername(username);
Authentication auth = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
}
private void logout() {
log.info("Logging out {} user", quote(getUsername()));
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(null);
SecurityContextHolder.clearContext();
MDC.removeUsername();
}
}
|
package org.animotron.graph.builder;
import org.animotron.exception.AnimoException;
import org.animotron.graph.index.Cache;
import org.animotron.statement.Statement;
import org.animotron.statement.operator.DEF;
import org.animotron.utils.MessageDigester;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import static org.animotron.expression.Expression.__;
import static org.animotron.graph.AnimoGraph.*;
import static org.animotron.graph.Properties.*;
import static org.animotron.utils.MessageDigester.cloneMD;
import static org.animotron.utils.MessageDigester.md;
import static org.animotron.utils.MessageDigester.updateMD;
/**
* Animo graph builder, it do optimization/compression and
* inform listeners on store/delete events.
*
* Direct graph as input from top element to bottom processing strategy.
*
* Methods to use:
*
* startGraph()
* endGraph()
*
* start(VALUE prefix, VALUE ns, VALUE reference, VALUE value)
* start(Statement statement, VALUE prefix, VALUE ns, VALUE reference, VALUE value)
* end()
*
* relationship()
*
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*/
public class FastGraphBuilder extends GraphBuilder {
private List<Object[]> flow = new LinkedList<Object[]>();
private byte[] hash;
public FastGraphBuilder () {
super();
}
public FastGraphBuilder (boolean ignoreNotFound) {
super(ignoreNotFound);
}
@Override
public Relationship endGraph() throws AnimoException {
Relationship r = null;
Iterator<Object[]> it = flow.iterator();
if (it.hasNext()) {
Object[] o = it.next();
if (o[1] instanceof DEF) {
if (o[2] == null) {
o[2] = MessageDigester.byteArrayToHex(hash);
}
r = build(o, it);
Node def = r.getEndNode();
NAME.set(def, o[2]);
DEFID.set(def, r.getId());
DEF._.add(r, o[2]);
modificative(r);
preparative(r);
} else {
r = Cache.RELATIONSHIP.get(hash);
if (r == null) {
o[6] = Cache.NODE.get(hash) != null;
r= build(o, it);
Cache.RELATIONSHIP.add(r, hash);
modificative(r);
HASH.set(r, hash);
preparative(r);
}
}
}
return r;
}
private Relationship build(Object[] o, Iterator<Object[]> it) throws AnimoException {
Relationship r = ((Statement) o[1]).build(getROOT(), o[2], hash, true, ignoreNotFound);
final Node end = r.getEndNode();
o[3] = r;
o[4] = end;
step();
while (it.hasNext()) {
build(it.next());
step();
}
return r;
}
@Override
protected Object[] start(Statement statement, Object reference, boolean hasChild) throws AnimoException {
Object[] parent = hasParent() ? peekParent() : null;
MessageDigest md = md();
byte[] hash = null;
boolean ready = !hasChild && reference != null;
if (ready) {
updateMD(md, reference);
hash = cloneMD(md).digest();
updateMD(md, statement);
} else if (reference != null) {
updateMD(md, reference);
}
Object[] o = {
md, // 0 message digest
statement, // 1 statement
reference, // 2 name or value
null, // 3 current relationship
null, // 4 current node
parent, // 5 parent item
false, // 6 is done?
ready, // 7 is ready?
hash // 8 hash
};
flow.add(o);
return o;
}
@Override
protected byte[] end(Object[] o) {
MessageDigest md = (MessageDigest) o[0];
if (!(Boolean) o[7]) {
updateMD(md, (Statement) o[1]);
}
o[8] = hash = md.digest();
return hash;
}
@Override
public void bind(Relationship r, Object[] p, byte[] hash) throws IOException {
step();
Object[] o = {p, r};
flow.add(o);
}
private void build(Object[] item) throws AnimoException {
Relationship r;
if (item.length == 2) {
Node n = (Node) ((Object[]) item[0])[4];
r = copy(n, (Relationship) item[1]);
CONTEXT.set(n, true);
} else {
Object[] p = (Object[]) item[5];
if (p != null) {
if ((Boolean) p[6]) {
item[6] = true;
return;
}
}
Statement statement = (Statement) item[1];
Object reference = item[2];
byte[] hash = (byte[]) item[8];
Node parent = (Node) p[4];
item[6] = Cache.NODE.get(hash) != null;
r = statement.build(parent, reference, hash, true, ignoreNotFound);
item[3] = r;
item[4] = r.getEndNode();
}
order(r);
}
}
|
package org.dnwiebe.orienteer.lookups;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;
import java.util.Map;
/**
* Looks up configuration values in a JSON object. Method name abcDEFGhi becomes abc.def.ghi.
*/
public class JsonFlatLookup extends JsonLookup {
/**
* Create a JsonNestingLookup from a Reader containing JSON.
* @param rdr Reader containing a complete JSON structure with an unnamed JSON object at the top level.
* @param configRoot JavaScript notation for the location in the JSON structure of the object containing the
* configuration.
*/
public JsonFlatLookup (Reader rdr, String configRoot) {
super (rdr, configRoot);
}
/**
* Create a JsonNestingLookup from an InputStream containing JSON.
* @param istr InputStream containing a complete JSON structure with an unnamed JSON object at the top level.
* @param configRoot JavaScript notation for the location in the JSON structure of the object containing the
* configuration.
*/
public JsonFlatLookup (InputStream istr, String configRoot) {
super (istr, configRoot);
}
/**
* Create a JsonNestingLookup from JSON in a resource file.
* @param resourceName Name of a resource file containing a JSON structure with an unnamed JSON object at the top level.
* @param configRoot JavaScript notation for the location in the JSON structure of the object containing the
* configuration.
*/
public JsonFlatLookup (String resourceName, String configRoot) {
super (resourceName, configRoot);
}
public String nameFromFragments (List<String> fragments) {
StringBuilder buf = new StringBuilder ();
for (String fragment: fragments) {
if (buf.length () > 0) {buf.append (".");}
buf.append (fragment.toLowerCase ());
}
return buf.toString ();
}
public String valueFromName (String name, Class singletonType) {
Object obj = tree.get (name);
if (obj == null) {
return null;
}
else if (obj instanceof Map || obj instanceof List) {
return null;
}
else {
return obj.toString ();
}
}
}
|
package dpmproject;
/*
* File: Navigation.java
* Written by: Sean Lawlor
* ECSE 211 - Design Principles and Methods, Head TA
* Fall 2011
* Ported to EV3 by: Francois Ouellet Delorme
* Fall 2015
*
* Movement control class (turnTo, travelTo, flt, localize)
*/
import lejos.hardware.motor.EV3LargeRegulatedMotor;
public class Navigation {
final static int FAST = (int) GlobalDefinitions.FORWARD_SPEED, SLOW = (int) GlobalDefinitions.TURN_SPEED, ACCELERATION = (int) GlobalDefinitions.ACCELERATION;
final static double DEG_ERR = GlobalDefinitions.DEG_ERR, CM_ERR = GlobalDefinitions.LIN_ERR;
private Odometer odometer;
private EV3LargeRegulatedMotor leftMotor, rightMotor;
public Navigation(Odometer odo) {
this.odometer = odo;
EV3LargeRegulatedMotor[] motors = this.odometer.getMotors();
this.leftMotor = motors[0];
this.rightMotor = motors[1];
// set acceleration
this.leftMotor.setAcceleration(ACCELERATION);
this.rightMotor.setAcceleration(ACCELERATION);
}
/*
* Functions to set the motor speeds jointly
*/
public void setSpeeds(float lSpd, float rSpd) {
this.leftMotor.setSpeed(lSpd);
this.rightMotor.setSpeed(rSpd);
if (lSpd < 0)
this.leftMotor.backward();
else
this.leftMotor.forward();
if (rSpd < 0)
this.rightMotor.backward();
else
this.rightMotor.forward();
}
public void setSpeeds(int lSpd, int rSpd) {
this.leftMotor.setSpeed(lSpd);
this.rightMotor.setSpeed(rSpd);
if (lSpd < 0)
this.leftMotor.backward();
else
this.leftMotor.forward();
if (rSpd < 0)
this.rightMotor.backward();
else
this.rightMotor.forward();
}
/*
* Float the two motors jointly
*/
public void setFloat() {
this.leftMotor.stop();
this.rightMotor.stop();
this.leftMotor.flt(true);
this.rightMotor.flt(true);
}
/*
* TravelTo function which takes as arguments the x and y position in cm Will travel to designated position, while
* constantly updating it's heading
*/
public void travelTo(double x, double y) {
double minAng;
while (Math.abs(x - odometer.getX()) > CM_ERR || Math.abs(y - odometer.getY()) > CM_ERR) {
minAng = (Math.atan2(y - odometer.getY(), x - odometer.getX())) * (180.0 / Math.PI);
if (minAng < 0)
minAng += 360.0;
this.turnTo(minAng, true);
this.setSpeeds(FAST, FAST);
}
this.setSpeeds(0, 0);
}
/*
* TurnTo function which takes an angle and boolean as arguments The boolean controls whether or not to stop the
* motors when the turn is completed
*/
public void turnTo(double angle, boolean stop) {
double error = angle - this.odometer.getAng();
while (Math.abs(error) > DEG_ERR) {
error = angle - this.odometer.getAng();
if (error < -180.0) {
this.setSpeeds(-SLOW, SLOW);
} else if (error < 0.0) {
this.setSpeeds(SLOW, -SLOW);
} else if (error > 180.0) {
this.setSpeeds(SLOW, -SLOW);
} else {
this.setSpeeds(-SLOW, SLOW);
}
}
if (stop) {
this.setSpeeds(0, 0);
}
}
/*
* Go foward a set distance in cm
*/
public void goForward(double distance) {
this.travelTo(Math.cos(Math.toRadians(this.odometer.getAng())) * distance, Math.cos(Math.toRadians(this.odometer.getAng())) * distance);
}
public void halt() {
this.setSpeeds(0, 0);
}
}
|
package org.gbif.ws.server.guice;
import org.gbif.ws.json.JacksonJsonContextResolver;
import org.gbif.ws.util.PropertiesUtil;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.annotation.Nullable;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.servlet.GuiceServletContextListener;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
/**
* A basic servlet listener for all our webservices.
* Note that the request filters will be ordered as follows if provided:
* <ol>
* <li>The default filters will always be first</li>
* <li>The authentication filter will be next if enabled (installAuth=true)</li>
* <li>The provided filters will be last in the given order</li>
* </ol>
*/
public abstract class GbifServletListener extends GuiceServletContextListener {
private final Properties properties;
private final String resourcePackages;
private final boolean installAuth;
private final List<Class<? extends ContainerResponseFilter>> responseFilters = Lists.newArrayList();
private final List<Class<? extends ContainerRequestFilter>> requestFilters = Lists.newArrayList();
private Injector injector;
/**
* @param properties The properties to load
* @param resourcePackages packages to scan for jersey resources,
* for example "org.gbif.registry.ws,org.gbif.registry.common.ws"
* @param installAuthenticationFilters if true installs support for authentication. Requires an implementation of
* UserService to be installed by one of the additional modules.
*/
protected GbifServletListener(Properties properties, String resourcePackages, boolean installAuthenticationFilters) {
this(properties, resourcePackages, installAuthenticationFilters, null);
}
/**
* @param properties The properties to load
* @param resourcePackages packages to scan for jersey resources,
* for example "org.gbif.registry.ws,org.gbif.registry.common.ws"
* @param installAuthenticationFilters if true installs support for authentication. Requires an implementation of
* UserService to be installed by one of the additional modules.
* @param responseFilters A list of response filters that are applied to the requests.
*/
protected GbifServletListener(Properties properties, String resourcePackages, boolean installAuthenticationFilters,
@Nullable List<Class<? extends ContainerResponseFilter>> responseFilters) {
this(properties, resourcePackages, installAuthenticationFilters, responseFilters, null);
}
/**
* @param properties The properties to load
* @param resourcePackages packages to scan for jersey resources,
* for example "org.gbif.registry.ws,org.gbif.registry.common.ws"
* @param installAuthenticationFilters if true installs support for authentication. Requires an implementation of
* UserService to be installed by one of the additional modules.
* @param responseFilters A list of response filters that are applied to the requests.
* @param requestFilters A list of request filters that are applied to the requests. Note: read constructor
* documentation on {@link WsJerseyModule}
*/
protected GbifServletListener(Properties properties, String resourcePackages, boolean installAuthenticationFilters,
@Nullable List<Class<? extends ContainerResponseFilter>> responseFilters,
@Nullable List<Class<? extends ContainerRequestFilter>> requestFilters) {
this.properties = properties;
this.resourcePackages = resourcePackages;
this.installAuth = installAuthenticationFilters;
if (responseFilters != null) {
this.responseFilters.addAll(responseFilters);
}
if (requestFilters != null) {
this.requestFilters.addAll(requestFilters);
}
}
/**
* @param propertyFileName Fully qualified filename that must be on the classpath
* @param resourcePackages packages to scan for jersey resources,
* for example "org.gbif.registry.ws,org.gbif.registry.common.ws"
* @param installAuthenticationFilters if true installs support for authentication. Requires an implementation of
* UserService to be installed by one of the additional modules.
* @param responseFilters A list of response filters that are applied to the requests.
*/
protected GbifServletListener(String propertyFileName, String resourcePackages, boolean installAuthenticationFilters,
@Nullable List<Class<? extends ContainerResponseFilter>> responseFilters) {
this(readProperties(propertyFileName), resourcePackages, installAuthenticationFilters,
responseFilters);
}
/**
* Hides the checked exception that can be thrown when reading a file.
*/
private static Properties readProperties(String propertyFileName) {
Properties properties = null;
try {
properties = PropertiesUtil.readFromClasspath(propertyFileName);
} catch (IOException e) {
new IllegalArgumentException("Error reading properties file", e);
}
return properties;
}
/**
* @param propertyFileName Fully qualified filename that must be on the classpath
* @param resourcePackages packages to scan for jersey resources,
* for example "org.gbif.registry.ws,org.gbif.registry.common.ws"
* @param installAuthenticationFilters if true installs support for authentication. Requires an implementation of
* UserService to be installed by one of the additional modules.
*/
protected GbifServletListener(String propertyFileName, String resourcePackages,
boolean installAuthenticationFilters) {
this(propertyFileName, resourcePackages, installAuthenticationFilters, null);
}
/**
* Implement this to return the list of all additional modules needed to be installed.
*
* @return a list of modules, never null.
*/
protected abstract List<Module> getModules(Properties properties);
/**
* The Jackson JSON configuration needs to know about how to (de)serialize polymorphic classes.
* Override this method to pass a map of mixIn classes into the Jackson context resolver.
*
* @return the mixIn class map. Defaults to an empty map.
*/
protected Map<Class<?>, Class<?>> getPolymorphicClassMap() {
return Maps.newHashMap();
}
@Override
protected synchronized Injector getInjector() {
if (injector == null) {
// configure jsonMixIns
JacksonJsonContextResolver.addMixIns(getPolymorphicClassMap());
List<Module> modules = getModules(properties);
modules.add(new WsJerseyModule(resourcePackages, installAuth, responseFilters, requestFilters));
injector = Guice.createInjector(modules);
}
return injector;
}
}
|
package org.jenkinsci.plugins.p4.client;
import com.perforce.p4java.client.IClient;
import com.perforce.p4java.client.IClientSummary.IClientOptions;
import com.perforce.p4java.core.IChangelist;
import com.perforce.p4java.core.IChangelistSummary;
import com.perforce.p4java.core.IRepo;
import com.perforce.p4java.core.file.FileAction;
import com.perforce.p4java.core.file.FileSpecBuilder;
import com.perforce.p4java.core.file.FileSpecOpStatus;
import com.perforce.p4java.core.file.IFileSpec;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.exception.RequestException;
import com.perforce.p4java.impl.generic.client.ClientView;
import com.perforce.p4java.impl.generic.core.Changelist;
import com.perforce.p4java.impl.generic.core.file.FileSpec;
import com.perforce.p4java.impl.mapbased.server.Parameters;
import com.perforce.p4java.option.changelist.SubmitOptions;
import com.perforce.p4java.option.client.AddFilesOptions;
import com.perforce.p4java.option.client.ParallelSyncOptions;
import com.perforce.p4java.option.client.ReconcileFilesOptions;
import com.perforce.p4java.option.client.ReopenFilesOptions;
import com.perforce.p4java.option.client.ResolveFilesAutoOptions;
import com.perforce.p4java.option.client.RevertFilesOptions;
import com.perforce.p4java.option.client.SyncOptions;
import com.perforce.p4java.option.server.ChangelistOptions;
import com.perforce.p4java.option.server.GetChangelistsOptions;
import com.perforce.p4java.option.server.GetDepotFilesOptions;
import com.perforce.p4java.option.server.GetFileContentsOptions;
import com.perforce.p4java.option.server.OpenedFilesOptions;
import com.perforce.p4java.server.CmdSpec;
import hudson.AbortException;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.TaskListener;
import jenkins.model.Jenkins;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.p4.changes.P4ChangeRef;
import org.jenkinsci.plugins.p4.changes.P4GraphRef;
import org.jenkinsci.plugins.p4.changes.P4LabelRef;
import org.jenkinsci.plugins.p4.changes.P4Ref;
import org.jenkinsci.plugins.p4.credentials.P4BaseCredentials;
import org.jenkinsci.plugins.p4.populate.AutoCleanImpl;
import org.jenkinsci.plugins.p4.populate.CheckOnlyImpl;
import org.jenkinsci.plugins.p4.populate.ForceCleanImpl;
import org.jenkinsci.plugins.p4.populate.GraphHybridImpl;
import org.jenkinsci.plugins.p4.populate.ParallelSync;
import org.jenkinsci.plugins.p4.populate.Populate;
import org.jenkinsci.plugins.p4.populate.SyncOnlyImpl;
import org.jenkinsci.plugins.p4.publish.CommitImpl;
import org.jenkinsci.plugins.p4.publish.Publish;
import org.jenkinsci.plugins.p4.publish.ShelveImpl;
import org.jenkinsci.plugins.p4.publish.SubmitImpl;
import org.jenkinsci.plugins.p4.tasks.TimeTask;
import org.jenkinsci.plugins.p4.workspace.StaticWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.TemplateWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.Workspace;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
public class ClientHelper extends ConnectionHelper {
private static Logger logger = Logger.getLogger(ClientHelper.class.getName());
private IClient iclient;
@Deprecated
public ClientHelper(String credential, TaskListener listener, String client) {
super(Jenkins.getActiveInstance(), credential, listener);
clientLogin(client, "none");
}
@Deprecated
public ClientHelper(String credential, TaskListener listener, String client, String charset) {
super(Jenkins.getActiveInstance(), credential, listener);
clientLogin(client, charset);
}
public ClientHelper(ItemGroup context, String credential, TaskListener listener, String client, String charset) {
super(context, credential, listener);
clientLogin(client, charset);
}
public ClientHelper(Item context, String credential, TaskListener listener, String client, String charset) {
super(context, credential, listener);
clientLogin(client, charset);
}
public ClientHelper(P4BaseCredentials credential, TaskListener listener, String client, String charset) {
super(credential, listener);
clientLogin(client, charset);
}
private void clientLogin(String client, String charset) {
// Exit early if no connection
if (connection == null) {
return;
}
// Find workspace and set as current
try {
iclient = connection.getClient(client);
connection.setCurrentClient(iclient);
} catch (Exception e) {
String err = "P4: Unable to use Workspace: " + e;
logger.severe(err);
log(err);
e.printStackTrace();
}
if (isUnicode()) {
connection.setCharsetName(charset);
}
}
public void setClient(Workspace workspace) throws Exception {
// Setup/Create workspace based on type
iclient = workspace.setClient(connection, authorisationConfig.getUsername());
// Exit early if client is not defined
if (!isClientValid(workspace)) {
String err = "P4: Undefined workspace: " + workspace.getFullName();
throw new AbortException(err);
}
// Exit early if client is Static
if (workspace instanceof StaticWorkspaceImpl) {
connection.setCurrentClient(iclient);
return;
}
// Ensure root and host fields are not null
if (workspace.getRootPath() != null) {
iclient.setRoot(workspace.getRootPath());
}
if (workspace.getHostName() != null) {
iclient.setHostName(workspace.getHostName());
}
// Set clobber on to ensure workspace is always good
IClientOptions options = iclient.getOptions();
options.setClobber(true);
iclient.setOptions(options);
// Save client spec
iclient.update();
// Set active client for this connection
connection.setCurrentClient(iclient);
return;
}
/**
* Sync files to workspace at the specified change/label.
*
* @param buildChange Change to sync from
* @param populate Populate strategy
* @throws Exception push up stack
*/
public void syncFiles(P4Ref buildChange, Populate populate) throws Exception {
TimeTask timer = new TimeTask();
// test label is valid
if (buildChange.isLabel()) {
String label = buildChange.toString();
try {
int change = Integer.parseInt(label);
log("P4 Task: label is a number! syncing files at change: " + change);
} catch (NumberFormatException e) {
if (!label.equals("now") && !isLabel(label) && !isClient(label) && !isCounter(label)) {
String msg = "P4: Unable to find client/label/counter: " + label;
log(msg);
logger.warning(msg);
throw new AbortException(msg);
} else {
log("P4 Task: syncing files at client/label: " + label);
}
}
} else {
log("P4 Task: syncing files at change: " + buildChange);
}
// Sync changes/labels
if (buildChange instanceof P4ChangeRef || buildChange instanceof P4LabelRef) {
// build file revision spec
String path = iclient.getRoot() + "/...";
String revisions = path + "@" + buildChange;
// Sync files
if (populate instanceof CheckOnlyImpl) {
syncHaveList(revisions, populate);
} else {
syncFiles(revisions, populate);
}
}
// Sync graph repos
if (buildChange instanceof P4GraphRef && populate instanceof GraphHybridImpl) {
String rev = ((P4GraphRef) buildChange).getRepo() + "/...";
syncFiles(rev, populate);
}
log("duration: " + timer.toString() + "\n");
}
/**
* Test to see if workspace is at the latest revision.
*
* @throws Exception
*/
private boolean syncHaveList(String revisions, Populate populate) throws Exception {
// Preview (sync -k)
SyncOptions syncOpts = new SyncOptions();
syncOpts.setClientBypass(true);
syncOpts.setQuiet(populate.isQuiet());
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(revisions);
List<IFileSpec> syncMsg = iclient.sync(files, syncOpts);
validate.check(syncMsg, "file(s) up-to-date.", "file does not exist", "no file(s) as of that date");
for (IFileSpec fileSpec : syncMsg) {
if (fileSpec.getOpStatus() != FileSpecOpStatus.VALID) {
String msg = fileSpec.getStatusMessage();
if (msg.contains("file(s) up-to-date.")) {
return true;
}
}
}
return false;
}
private void syncFiles(String revisions, Populate populate) throws Exception {
// set MODTIME if populate options is used only required before 15.1
if (populate.isModtime() && !checkVersion(20151)) {
IClientOptions options = iclient.getOptions();
if (!options.isModtime()) {
options.setModtime(true);
iclient.setOptions(options);
iclient.update(); // Save client spec
}
}
// sync options
SyncOptions syncOpts = new SyncOptions();
// setServerBypass (-p no have list)
syncOpts.setServerBypass(!populate.isHave());
// setForceUpdate (-f only if no -p is set)
syncOpts.setForceUpdate(populate.isForce() && populate.isHave());
syncOpts.setQuiet(populate.isQuiet());
// Sync files with asynchronous callback and parallel if enabled to
SyncStreamingCallback callback = new SyncStreamingCallback(iclient.getServer(), listener);
synchronized (callback) {
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(revisions);
ParallelSync parallel = populate.getParallel();
if (parallel != null && parallel.isEnable()) {
ParallelSyncOptions parallelOpts = parallel.getParallelOptions();
iclient.syncParallel(files, syncOpts, callback, 0, parallelOpts);
} else {
iclient.sync(files, syncOpts, callback, 0);
}
while (!callback.isDone()) {
callback.wait();
}
if (callback.isFail()) {
throw new P4JavaException(callback.getException());
}
}
}
private int CheckNativeUse(String revisions, SyncOptions syncOpts, ParallelSync parallel) {
try {
String p4 = parallel.getPath();
List<String> command = new ArrayList<String>();
String p4port = p4credential.getP4port();
p4port = (p4credential.isSsl()) ? "ssl:" + p4port : p4port;
command.add(p4);
command.add("-c" + iclient.getName());
command.add("-p" + p4port);
command.add("-u" + p4credential.getUsername());
String p4host = p4credential.getP4host();
if (p4host != null && !p4host.isEmpty()) {
command.add("-H" + p4host);
}
command.add("sync");
if (syncOpts.isForceUpdate()) {
command.add("-f");
}
if (syncOpts.isQuiet()) {
command.add("-q");
}
if (syncOpts.isClientBypass()) {
command.add("-k");
}
if (syncOpts.isSafetyCheck()) {
command.add("-s");
}
if (syncOpts.isServerBypass()) {
command.add("-p");
}
if (syncOpts.isNoUpdate()) {
command.add("-n");
}
String threads = parallel.getThreads();
String minfiles = parallel.getMinfiles();
String minbytes = parallel.getMinbytes();
command.add("--parallel");
command.add("threads=" + threads + ",min=" + minfiles + ",minsize=" + minbytes);
command.add(revisions);
ProcessBuilder builder = new ProcessBuilder(command);
final Process process = builder.start();
InputStream inputStream = process.getInputStream();
InputStream errorStream = process.getErrorStream();
BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
BufferedReader errorStreamReader = new BufferedReader(new InputStreamReader(errorStream, "UTF-8"));
// Log commands
log("(p4):cmd:... " + StringUtils.join(command, " "));
log("");
String line;
while ((line = inputStreamReader.readLine()) != null) {
log(line);
}
while ((line = errorStreamReader.readLine()) != null) {
log(line);
}
int exitCode = process.waitFor();
inputStreamReader.close();
errorStreamReader.close();
log("exitCode=" + Integer.toString(exitCode));
log("(p4):stop:0");
return exitCode;
} catch (UnsupportedEncodingException e) {
log(e.getMessage());
} catch (IOException e) {
log(e.getMessage());
} catch (InterruptedException e) {
log(e.getMessage());
}
return 1;
}
/**
* Cleans up the Perforce workspace after a previous build. Removes all
* pending and abandoned files (equivalent to 'p4 revert -w').
*
* @param populate Jelly populate options
* @throws Exception push up stack
*/
public void tidyWorkspace(Populate populate) throws Exception {
// relies on workspace view for scope.
log("");
String path = iclient.getRoot() + "/...";
if (populate instanceof AutoCleanImpl) {
tidyAutoCleanImpl(path, populate);
}
if (populate instanceof ForceCleanImpl) {
tidyForceSyncImpl(path, populate);
}
if (populate instanceof GraphHybridImpl) {
tidyForceSyncImpl(path, populate);
}
if (populate instanceof SyncOnlyImpl) {
tidySyncOnlyImpl(path, populate);
}
}
private void tidySyncOnlyImpl(String path, Populate populate) throws Exception {
SyncOnlyImpl syncOnly = (SyncOnlyImpl) populate;
if (syncOnly.isRevert()) {
tidyPending(path);
}
}
private void tidyForceSyncImpl(String path, Populate populate) throws Exception {
// remove all pending files within workspace
tidyPending(path);
// remove all versioned files (clean have list)
String revisions = iclient.getRoot() + "/...
// Only use quiet populate option to insure a clean sync
boolean quiet = populate.isQuiet();
Populate clean = new AutoCleanImpl(false, false, false, quiet, null, null);
syncFiles(revisions, clean);
// remove all files from workspace
String root = URLDecoder.decode(iclient.getRoot(), "UTF-8");
log("... rm -rf " + root);
log("");
silentlyForceDelete(root);
}
private void silentlyForceDelete(String root) throws IOException {
try {
FileUtils.forceDelete(new File(root));
} catch (FileNotFoundException ignored) {
}
}
private void tidyAutoCleanImpl(String path, Populate populate) throws Exception {
// remove all pending files within workspace
tidyPending(path);
// clean files within workspace
tidyClean(populate, path);
}
private void tidyPending(String path) throws Exception {
TimeTask timer = new TimeTask();
log("P4 Task: reverting all pending and shelved revisions.");
// revert all pending and shelved revisions
RevertFilesOptions rOpts = new RevertFilesOptions();
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(path);
List<IFileSpec> list = iclient.revertFiles(files, rOpts);
validate.check(list, "not opened on this client");
// check for added files and remove...
log("... rm [abandoned files]");
for (IFileSpec file : list) {
if (file.getAction() == FileAction.ABANDONED) {
// first check if we have the local path
String local = file.getLocalPathString();
if (local == null) {
local = depotToLocal(file);
}
if (local != null) {
File unlink = new File(local);
boolean ok = unlink.delete();
if (!ok) {
log("Not able to delete: " + local);
}
}
}
}
log("duration: " + timer.toString() + "\n");
}
private void tidyClean(Populate populate, String path) throws Exception {
// Use old method if 'p4 clean' is not supported
if (!checkVersion(20141)) {
tidyRevisions(path, populate);
return;
}
// Set options
boolean delete = ((AutoCleanImpl) populate).isDelete();
boolean replace = ((AutoCleanImpl) populate).isReplace();
String[] base = {"-w", "-f"};
List<String> list = new ArrayList<String>();
list.addAll(Arrays.asList(base));
if (delete && !replace) {
list.add("-a");
}
if (replace && !delete) {
list.add("-e");
list.add("-d");
}
if (!replace && !delete) {
log("P4 Task: skipping clean, no options set.");
return;
}
// set MODTIME if populate options is used and server supports flag
if (populate.isModtime()) {
if (checkVersion(20141)) {
list.add("-m");
} else {
log("P4: Resolving files by MODTIME not supported (requires 2014.1 or above)");
}
}
TimeTask timer = new TimeTask();
log("P4 Task: cleaning workspace to match have list.");
String[] args = list.toArray(new String[list.size()]);
ReconcileFilesOptions cleanOpts = new ReconcileFilesOptions(args);
// Reconcile with asynchronous callback
ReconcileStreamingCallback callback = new ReconcileStreamingCallback(iclient.getServer(), listener);
synchronized (callback) {
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(path);
String[] params = Parameters.processParameters(cleanOpts, files, connection);
connection.execStreamingMapCommand(CmdSpec.RECONCILE.toString(), params, null, callback, 0);
while (!callback.isDone()) {
callback.wait();
}
}
log("duration: " + timer.toString() + "\n");
}
private void tidyRevisions(String path, Populate populate) throws Exception {
TimeTask timer = new TimeTask();
log("P4 Task: tidying workspace to match have list.");
boolean delete = ((AutoCleanImpl) populate).isDelete();
boolean replace = ((AutoCleanImpl) populate).isReplace();
// check status - find all missing, changed or added files
String[] base = {"-n", "-a", "-e", "-d", "-l", "-f"};
List<String> list = new ArrayList<String>();
list.addAll(Arrays.asList(base));
String[] args = list.toArray(new String[list.size()]);
ReconcileFilesOptions statusOpts = new ReconcileFilesOptions(args);
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(path);
List<IFileSpec> status = iclient.reconcileFiles(files, statusOpts);
validate.check(status, "also opened by", "no file(s) to reconcile", "must sync/resolve",
"exclusive file already opened", "cannot submit from stream", "instead of", "empty, assuming text");
// Add missing, modified or locked files to a list, and delete the
// unversioned files.
List<IFileSpec> update = new ArrayList<IFileSpec>();
for (IFileSpec s : status) {
if (s.getOpStatus() == FileSpecOpStatus.VALID) {
String local = s.getLocalPathString();
if (local == null) {
local = depotToLocal(s);
}
switch (s.getAction()) {
case ADD:
if (local != null && delete) {
File unlink = new File(local);
boolean ok = unlink.delete();
if (!ok) {
log("Not able to delete: " + local);
}
}
break;
default:
update.add(s);
break;
}
} else {
String msg = s.getStatusMessage();
if (msg.contains("exclusive file already opened")) {
String rev = msg.substring(0, msg.indexOf(" - can't "));
IFileSpec spec = new FileSpec(rev);
update.add(spec);
}
}
}
// Force sync missing and modified files
if (!update.isEmpty() && replace) {
SyncOptions syncOpts = new SyncOptions();
syncOpts.setForceUpdate(true);
syncOpts.setQuiet(populate.isQuiet());
List<IFileSpec> syncMsg = iclient.sync(update, syncOpts);
validate.check(syncMsg, "file(s) up-to-date.", "file does not exist");
}
log("duration: " + timer.toString() + "\n");
}
public void revertAllFiles(boolean virtual) throws Exception {
String path = iclient.getRoot() + "/...";
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(path);
// revert all pending and shelved revisions
RevertFilesOptions rOpts = new RevertFilesOptions();
rOpts.setNoClientRefresh(virtual);
List<IFileSpec> list = iclient.revertFiles(files, rOpts);
validate.check(list, "not opened on this client");
}
public void versionFile(String file, Publish publish) throws Exception {
// build file revision spec
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(file);
findChangeFiles(files, publish.isDelete());
// Exit early if no change
if (!isOpened(files)) {
return;
}
// create changelist with files
IChangelist change = createChangeList(files, publish);
// submit changelist
submitFiles(change, false);
}
public boolean buildChange(Publish publish) throws Exception {
TimeTask timer = new TimeTask();
log("P4 Task: reconcile files to changelist.");
List<IFileSpec> files;
if (publish instanceof CommitImpl) {
CommitImpl commit = (CommitImpl) publish;
files = FileSpecBuilder.makeFileSpecList(commit.getFiles());
AddFilesOptions opts = new AddFilesOptions();
iclient.addFiles(files, opts);
} else {
// build file revision spec
String ws = "//" + iclient.getName() + "/...";
files = FileSpecBuilder.makeFileSpecList(ws);
findChangeFiles(files, publish.isDelete());
}
// Check if file is open
boolean open = isOpened(files);
log("duration: " + timer.toString() + "\n");
return open;
}
private void findChangeFiles(List<IFileSpec> files, boolean delete) throws Exception {
// cleanup pending changes (revert -k)
RevertFilesOptions revertOpts = new RevertFilesOptions();
revertOpts.setNoClientRefresh(true);
List<IFileSpec> revertStat = iclient.revertFiles(files, revertOpts);
validate.check(revertStat, "file(s) not opened on this client.");
// flush client to populate have (sync -k)
SyncOptions syncOpts = new SyncOptions();
syncOpts.setClientBypass(true);
List<IFileSpec> syncStat = iclient.sync(files, syncOpts);
validate.check(syncStat, "file(s) up-to-date.", "no such file(s).");
// check status - find all changes to files
ReconcileFilesOptions statusOpts = new ReconcileFilesOptions();
statusOpts.setUseWildcards(true);
statusOpts.setOutsideAdd(true);
statusOpts.setOutsideEdit(true);
statusOpts.setRemoved(delete);
List<IFileSpec> status = iclient.reconcileFiles(files, statusOpts);
validate.check(status, "- no file(s) to reconcile", "instead of", "empty, assuming text", "also opened by");
}
public void publishChange(Publish publish) throws Exception {
TimeTask timer = new TimeTask();
log("P4 Task: publish files to Perforce.");
// build file revision spec
String ws = "//" + iclient.getName() + "/...";
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(ws);
// create changelist and open files
IChangelist change = createChangeList(files, publish);
// logging
OpenedFilesOptions openOps = new OpenedFilesOptions();
List<IFileSpec> open = iclient.openedFiles(files, openOps);
for (IFileSpec f : open) {
FileAction action = f.getAction();
String path = f.getDepotPathString();
log("... ... " + action + " " + path);
}
// if SUBMIT
if (publish instanceof SubmitImpl) {
SubmitImpl submit = (SubmitImpl) publish;
boolean reopen = submit.isReopen();
submitFiles(change, reopen);
}
// if SHELVE
if (publish instanceof ShelveImpl) {
ShelveImpl shelve = (ShelveImpl) publish;
boolean revert = shelve.isRevert();
shelveFiles(change, files, revert);
}
// if COMMIT
if (publish instanceof CommitImpl) {
CommitImpl commit = (CommitImpl) publish;
commitFiles(change);
}
log("duration: " + timer.toString() + "\n");
}
private IChangelist createChangeList(List<IFileSpec> files, Publish publish) throws Exception {
String desc = publish.getExpandedDesc();
// create new pending change and add description
IChangelist change = new Changelist();
change.setDescription(desc);
change = iclient.createChangelist(change);
log("... pending change: " + change.getId());
// move files from default change
ReopenFilesOptions reopenOpts = new ReopenFilesOptions();
reopenOpts.setChangelistId(change.getId());
// set purge if required
if (publish instanceof SubmitImpl) {
SubmitImpl submit = (SubmitImpl) publish;
int purge = submit.getPurgeValue();
if (purge > 0) {
reopenOpts.setFileType("+S" + purge);
}
}
iclient.reopenFiles(files, reopenOpts);
return change;
}
private void submitFiles(IChangelist change, boolean reopen) throws Exception {
log("... submitting files");
SubmitOptions submitOpts = new SubmitOptions();
submitOpts.setReOpen(reopen);
// submit with asynchronous callback
SubmitStreamingCallback callback = new SubmitStreamingCallback(iclient.getServer(), listener);
synchronized (callback) {
change.submit(submitOpts, callback, 0);
while (!callback.isDone()) {
callback.wait();
}
}
long cngNumber = callback.getChange();
if (cngNumber > 0) {
log("... submitted in change: " + cngNumber);
} else {
throw new P4JavaException("Unable to submit change.");
}
}
private void commitFiles(IChangelist change) throws Exception {
log("... committing files");
List<String> opts = new ArrayList<>();
opts.add("-c");
opts.add(String.valueOf(change.getId()));
String[] args = opts.toArray(new String[opts.size()]);
Map<String, Object>[] results = connection.execMapCmd(CmdSpec.SUBMIT.name(), args, null);
for (Map<String, Object> map : results) {
if (map.containsKey("submittedCommit")) {
String sha = (String) map.get("submittedCommit");
log("... committing SHA: " + sha);
return;
}
}
throw new P4JavaException("Unable to commit change.");
}
private void shelveFiles(IChangelist change, List<IFileSpec> files, boolean revert) throws Exception {
log("... shelving files");
List<IFileSpec> shelved = iclient.shelveChangelist(change);
validate.check(shelved, "");
// post shelf cleanup
RevertFilesOptions revertOpts = new RevertFilesOptions();
revertOpts.setChangelistId(change.getId());
revertOpts.setNoClientRefresh(!revert);
String r = (revert) ? "(revert)" : "(revert -k)";
log("... reverting open files " + r);
iclient.revertFiles(files, revertOpts);
}
private boolean isOpened(List<IFileSpec> files) throws Exception {
OpenedFilesOptions openOps = new OpenedFilesOptions();
List<IFileSpec> open = iclient.openedFiles(files, openOps);
for (IFileSpec file : open) {
if (file != null && file.getAction() != null) {
return true;
}
}
return false;
}
/**
* Workaround for p4java bug. The 'setLocalSyntax(true)' option does not
* provide local syntax, so I have to use 'p4 where' to translate through
* the client view.
*
* @param fileSpec Perforce file spec
* @return Local syntax
* @throws Exception push up stack
*/
private String depotToLocal(IFileSpec fileSpec) throws Exception {
String depotPath = fileSpec.getDepotPathString();
if (depotPath == null) {
depotPath = fileSpec.getOriginalPathString();
}
if (depotPath == null) {
return null;
}
List<IFileSpec> dSpec = FileSpecBuilder.makeFileSpecList(depotPath);
List<IFileSpec> lSpec = iclient.where(dSpec);
String path = lSpec.get(0).getLocalPathString();
return path;
}
private void printFile(String rev) throws Exception {
byte[] buf = new byte[1024 * 64];
List<IFileSpec> file = FileSpecBuilder.makeFileSpecList(rev);
GetFileContentsOptions printOpts = new GetFileContentsOptions();
printOpts.setNoHeaderLine(true);
InputStream ins = connection.getFileContents(file, printOpts);
String localPath = depotToLocal(file.get(0));
File target = new File(localPath);
if (target.exists()) {
target.setWritable(true);
}
FileOutputStream outs = new FileOutputStream(target);
BufferedOutputStream bouts = new BufferedOutputStream(outs);
int len;
while ((len = ins.read(buf)) > 0) {
bouts.write(buf, 0, len);
}
ins.close();
bouts.close();
}
/**
* Unshelve review into workspace. Workspace is sync'ed to head first then
* review unshelved.
*
* @param review Review number (perhaps long?)
* @throws Exception push up stack
*/
public void unshelveFiles(int review) throws Exception {
// skip if review is 0 or less
if (review < 1) {
log("P4 Task: skipping review: " + review);
return;
}
TimeTask timer = new TimeTask();
log("P4 Task: unshelve review: " + review);
// Unshelve change for review
List<IFileSpec> shelveMsg;
shelveMsg = iclient.unshelveChangelist(review, null, 0, true, false);
validate.check(shelveMsg, false, "also opened by", "No such file(s)",
"exclusive file already opened", "no file(s) to unshelve");
// force sync any files missed due to INFO messages e.g. exclusive files
for (IFileSpec spec : shelveMsg) {
if (spec.getOpStatus() != FileSpecOpStatus.VALID) {
String msg = spec.getStatusMessage();
if (msg.contains("exclusive file already opened")) {
String rev = msg.substring(0, msg.indexOf(" - can't "));
printFile(rev);
}
} else {
log(spec.getDepotPathString());
}
}
log("... duration: " + timer.toString());
}
/**
* Resolve files in workspace with the specified option.
*
* @param mode Resolve mode
* @throws Exception push up stack
*/
public void resolveFiles(String mode) throws Exception {
if ("none".equals(mode)) {
return;
}
TimeTask timer = new TimeTask();
log("P4 Task: resolve: -" + mode);
// build file revision spec
List<IFileSpec> files;
String path = iclient.getRoot() + "/...";
files = FileSpecBuilder.makeFileSpecList(path);
// Unshelve change for review
ResolveFilesAutoOptions rsvOpts = new ResolveFilesAutoOptions();
rsvOpts.setAcceptTheirs("at".equals(mode));
rsvOpts.setAcceptYours("ay".equals(mode));
rsvOpts.setSafeMerge("as".equals(mode));
rsvOpts.setForceResolve("af".equals(mode));
List<IFileSpec> rsvMsg = iclient.resolveFilesAuto(files, rsvOpts);
validate.check(rsvMsg, "no file(s) to resolve");
log("... duration: " + timer.toString());
}
/**
* Get the latest change on the given path
*
* @param path Perforce depot path //foo/...
* @return change number
* @throws Exception push up stack
*/
public long getHead(String path) throws Exception {
List<IFileSpec> spec = FileSpecBuilder.makeFileSpecList(path);
GetChangelistsOptions opts = new GetChangelistsOptions();
opts.setMaxMostRecent(1);
List<IChangelistSummary> changes = connection.getChangelists(spec, opts);
if (!changes.isEmpty()) {
return changes.get(0).getId();
}
return -1;
}
/**
* Gets the Changelist (p4 describe -s); shouldn't need a client, but
* p4-java throws an exception if one is not set.
*
* @param id Change number (long perhaps)
* @return Perforce Changelist
* @throws Exception push up stack
*/
public Changelist getChange(int id) throws Exception {
try {
return (Changelist) connection.getChangelist(id);
} catch (RequestException e) {
ChangelistOptions opts = new ChangelistOptions();
opts.setOriginalChangelist(true);
return (Changelist) connection.getChangelist(id, opts);
}
}
/**
* Get the change number for the last change within the scope of the
* workspace view.
*
* @return Perforce change
* @throws Exception push up stack
*/
public int getClientHead() throws Exception {
// get last change in server
// This will returned the also shelved CLs
String latestChange = connection.getCounter("change");
int change = Integer.parseInt(latestChange);
// build file revision spec
String ws = "//" + iclient.getName() + "/...";
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(ws);
GetChangelistsOptions opts = new GetChangelistsOptions();
// Question do we only want the last submmited change ? (not a shelved
// one?)
opts.setType(IChangelist.Type.SUBMITTED);
opts.setMaxMostRecent(1);
List<IChangelistSummary> list = connection.getChangelists(files, opts);
if (!list.isEmpty() && list.get(0) != null) {
change = list.get(0).getId();
} else {
log("P4: no revisions under " + ws + " using latest change: " + change);
}
return change;
}
/**
* List of Graph Repos within the client's view
*
* @return A list of Graph Repos, empty list on error.
*/
public List<IRepo> listRepos() {
List<IRepo> repos = new ArrayList<>();
try {
repos = iclient.getRepos();
} catch (Exception e) {
logger.fine("No repos found: " + e.getMessage());
}
return repos;
}
/**
* Show all changes within the scope of the client, between the 'from' and
* 'to' change limits.
*
* @param fromRefs list of from revisions (change or label)
* @param to To revision (change or label)
* @return List of changes
* @throws Exception push up stack
*/
public List<P4Ref> listChanges(List<P4Ref> fromRefs, P4Ref to) throws Exception {
P4Ref from = getSingleChange(fromRefs);
// return empty array, if from and to are equal, or Perforce will report
// a change
if (from.equals(to)) {
return new ArrayList<P4Ref>();
}
String ws = "//" + iclient.getName() + "/...@" + from + "," + to;
List<P4Ref> list = listChanges(ws);
if (!from.isLabel()) {
list.remove(from);
}
return list;
}
private P4Ref getSingleChange(List<P4Ref> refs) {
// fetch single change and ignore commits
for (P4Ref ref : refs) {
if (!ref.isCommit()) {
return ref;
}
}
return null;
}
/**
* Show all changes within the scope of the client, from the 'from' change
* limits.
*
* @param from From revision (change or label)
* @return List of changes
* @throws Exception push up stack
*/
public List<P4Ref> listChanges(P4Ref from) throws Exception {
String ws = "//" + iclient.getName() + "/...@" + from + ",now";
List<P4Ref> list = listChanges(ws);
if (!from.isLabel()) {
list.remove(from);
}
return list;
}
/**
* Show all changes within the scope of the client.
*
* @return List of changes
* @throws Exception push up stack
*/
public List<P4Ref> listChanges() throws Exception {
String ws = "//" + iclient.getName() + "/...";
return listChanges(ws);
}
private List<P4Ref> listChanges(String ws) throws Exception {
List<P4Ref> list = new ArrayList<P4Ref>();
GetChangelistsOptions opts = new GetChangelistsOptions();
opts.setMaxMostRecent(getMaxChangeLimit());
List<IFileSpec> spec = FileSpecBuilder.makeFileSpecList(ws);
List<IChangelistSummary> cngs = connection.getChangelists(spec, opts);
if (cngs != null) {
for (IChangelistSummary c : cngs) {
// don't try to add null or -1 changes
if (c != null && c.getId() != -1) {
P4Ref rev = new P4ChangeRef(c.getId());
// don't add change entries already in the list
if (!(list.contains(rev))) {
list.add(rev);
}
}
}
}
Collections.sort(list);
Collections.reverse(list);
return list;
}
/**
* Fetches a list of changes needed to update the workspace to head.
*
* @param fromRefs List from revisions
* @return List of changes
* @throws Exception push up stack
*/
public List<P4Ref> listHaveChanges(List<P4Ref> fromRefs) throws Exception {
P4Ref from = getSingleChange(fromRefs);
if (from.getChange() > 0) {
log("P4: Polling with range: " + from + ",now");
return listChanges(from);
}
String path = "//" + iclient.getName() + "/...";
return listHaveChanges(path);
}
/**
* Fetches a list of changes needed to update the workspace to the specified
* limit. The limit could be a Perforce change number or label.
*
* @param fromRefs List of from revisions
* @param changeLimit To Revision
* @return List of changes
* @throws Exception push up stack
*/
public List<P4Ref> listHaveChanges(List<P4Ref> fromRefs, P4Ref changeLimit) throws Exception {
P4Ref from = getSingleChange(fromRefs);
if (from.getChange() > 0) {
log("P4: Polling with range: " + from + "," + changeLimit);
return listChanges(fromRefs, changeLimit);
}
String path = "//" + iclient.getName() + "/...";
String fileSpec = path + "@" + changeLimit;
return listHaveChanges(fileSpec);
}
private List<P4Ref> listHaveChanges(String fileSpec) throws Exception {
log("P4: Polling with cstat: " + fileSpec);
List<P4Ref> haveChanges = new ArrayList<P4Ref>();
Map<String, Object>[] map;
map = connection.execMapCmd("cstat", new String[]{fileSpec}, null);
for (Map<String, Object> entry : map) {
String status = (String) entry.get("status");
if (status != null) {
if (status.startsWith("have")) {
String value = (String) entry.get("change");
int change = Integer.parseInt(value);
haveChanges.add(new P4ChangeRef(change));
}
}
}
Collections.sort(haveChanges);
Collections.reverse(haveChanges);
return haveChanges;
}
public ClientView getClientView() {
return iclient.getClientView();
}
public boolean isClientValid(Workspace workspace) {
if (iclient == null) {
String msg;
if (workspace instanceof TemplateWorkspaceImpl) {
TemplateWorkspaceImpl template = ((TemplateWorkspaceImpl) workspace);
String name = template.getTemplateName();
msg = "P4: Template workspace not found: " + name;
} else {
String name = workspace.getFullName();
msg = "P4: Unable to use workspace: " + name;
}
logger.severe(msg);
if (listener != null) {
log(msg);
}
return false;
}
return true;
}
public IClient getClient() {
return iclient;
}
public boolean hasFile(String depotPath) throws Exception {
List<IFileSpec> files = FileSpecBuilder.makeFileSpecList(depotPath);
GetDepotFilesOptions opts = new GetDepotFilesOptions();
List<IFileSpec> specs = connection.getDepotFiles(files, opts);
return validate.checkCatch(specs, "");
}
}
|
// File: $Id$
// Representation of a SAT problem in CNF form.
import java.io.*;
/**
* A <code>SATProblem</code> object represents a SAT problem in
* Conjunctive Normal Form (CNF).
*
* @author Kees van Reeuwijk
* @version $Revision$
*/
public final class SATProblem implements Cloneable, java.io.Serializable {
/** Symbolic value for a conflicting problem. */
public static final int CONFLICTING = -1;
/** Symbolic value for a satisfied problem. */
public static final int SATISFIED = 1;
/** Symbolic value for an as-yet undetermined problem. */
public static final int UNDETERMINED = 0;
/** The number of variables in the problem. */
private int vars;
/** The number of known variables of the problem. */
private int knownVars;
/** The number of clauses of the problem. */
private int clauseCount;
/** The clauses of the problem. */
Clause clauses[];
/** The variables of the problem. */
private SATVar variables[];
/** The number of deleted clauses. */
private int deletedClauseCount;
private static final boolean traceSimplification = false;
private static final boolean tracePropagation = false;
private static final boolean traceNewCode = true;
private static final boolean traceStats = true;
private int label = 0;
public ClauseReviewer reviewer = null;
/**
* Constructs an empty SAT Problem.
*/
private SATProblem()
{
vars = 0;
knownVars = 0;
createVarArray( 0 );
clauses = new Clause[0];
}
/**
* Constructs a SAT Problem with the given fields.
*/
private SATProblem(
int vars,
int knownVars,
int clauseCount,
Clause clauses[],
SATVar variables[],
int deletedClauseCount,
int label,
ClauseReviewer r
)
{
this.vars = vars;
this.knownVars = knownVars;
this.clauseCount = clauseCount;
this.clauses = clauses;
this.variables = variables;
this.deletedClauseCount = deletedClauseCount;
this.label = label;
reviewer = r;
}
public void setReviewer( ClauseReviewer r )
{
reviewer = r;
}
/** Returns a clone of this SAT problem. The newly created SATProblem
* also has cloned clauses and variables.
*/
public Object clone()
{
Clause cl[] = null;
SATVar vl[] = null;
if( clauses != null ){
cl = new Clause[clauseCount];
for( int i=0; i<clauseCount; i++ ){
if( clauses[i] == null ){
cl[i] = null;
}
else {
cl[i] = (Clause) clauses[i].clone();
}
}
}
if( variables != null ){
vl = new SATVar[vars];
for( int i=0; i<vars; i++ ){
vl[i] = (SATVar) variables[i].clone();
}
}
return new SATProblem(
vars,
knownVars,
clauseCount,
cl,
vl,
deletedClauseCount,
label,
reviewer
);
}
/**
* Constructs a SAT problem with the given number of variables and
* the given list of clauses.
*
* @param v the number of variables in the problem
* @param cl the clauses of the problem
*/
public SATProblem( int v, Clause cl[] ){
vars = v;
createVarArray( v );
clauses = cl;
clauseCount = cl.length;
}
/**
* Constructs a SAT problem with a given number of variables and
* a given number of clauses.
*
* @param v the number of variables in the problem
* @param n the number of clauses of the problem
*/
private SATProblem( int v, int n ){
vars = v;
clauses = new Clause[n];
createVarArray( v );
clauseCount = 0;
}
/**
* Sets {@link variables} to an array of variables with the given
* length.
*
* @param n The number of variables.
*/
private void createVarArray( int n )
{
variables = new SATVar[n];
for( int i=0; i<n; i++ ){
variables[i] = new SATVar( i );
}
}
/** Returns the number of variables used in the problem. */
public int getVariableCount()
{
return vars;
}
/** Returns the number of known variables in the problem. */
public int getKnownVariableCount()
{
return knownVars;
}
/** Returns the number of clauses of the problem. */
public int getClauseCount()
{
return clauseCount;
}
/**
* Given a clause 'i', deletes it from the list.
* @param i the index of the clause to delete
*/
private void deleteClause( int i )
{
clauseCount
clauses[i] = clauses[clauseCount];
deletedClauseCount++;
}
/**
* Adds the specified clause to the problem.
* @param cl the clause to add
* @return the label of the added clause, or -1 if the clause is redundant
*/
public int addClause( Clause cl )
{
if( clauseCount>=clauses.length ){
// Resize the clauses array. Even works for array of length 0.
Clause nw[] = new Clause[1+clauses.length*2];
System.arraycopy( clauses, 0, nw, 0, clauses.length );
clauses = nw;
}
int clauseno = clauseCount++;
clauses[clauseno] = cl;
return cl.label;
}
/**
* Adds a new clause to the problem. The clause is constructed
* from <em>copies</em> of the arrays of positive and negative variables
* that are given as parameters.
* @param pos the array of positive variables
* @param possz the number of elements in <code>pos</code> to use
* @param neg the array of negative variables
* @param negsz the number of elements in <code>neg</code> to use
* @return the label of the added clause, or -1 if the clause is redundant
*/
public int addClause( int pos[], int possz, int neg[], int negsz )
{
int apos[] = Helpers.cloneIntArray( pos, possz );
int aneg[] = Helpers.cloneIntArray( neg, negsz );
Helpers.sortIntArray( apos );
Helpers.sortIntArray( aneg );
Clause cl = new Clause( apos, aneg, label++ );
return addClause( cl );
}
/**
* Adds a new clause to the problem. The clause is constructed
* from <em>copies</em> of the arrays of positive and negative variables
* that are given as parameters.
* @param pos the array of positive variables
* @param neg the array of negative variables
* @return the label of the added clause
*/
public int addClause( int pos[], int neg[] )
{
return addClause( pos, pos.length, neg, neg.length );
}
/**
* Adds a new conflict clause to the problem, and updates the
* conflict administration.
* @param cl The conflict clause to add.
*/
public void addConflictClause( Clause cl )
{
int cno = clauseCount;
addClause( cl );
registerClauseVariables( cl, cno );
}
/**
* Given a list of variables and a clause, registers all uses
* of the variables in the clause.
* @param cl the clause to register
* @param clauseno the index of the clause to register
*/
private void registerClauseVariables( Clause cl, int clauseno )
{
if( cl == null ){
return;
}
int arr[] = cl.pos;
for( int ix=0; ix<arr.length; ix++ ){
int var = arr[ix];
variables[var].registerPosClause( clauseno );
}
arr = cl.neg;
for( int ix=0; ix<arr.length; ix++ ){
int var = arr[ix];
variables[var].registerNegClause( clauseno );
}
}
/**
* Given a variable number, returns a vector of clauses in which this
* variable occurs positively.
*
* @param var The variable to return the vector for.
* @return a vector of clause indices
*/
public int[] getPosClauses( int var )
{
return variables[var].getPosClauses();
}
/**
* Given a variable number, returns a vector of clauses in which this
* variable occurs negatively.
*
* @param var The variable to return the vector for.
* @return a vector of clause indices
*/
public int[] getNegClauses( int var )
{
return variables[var].getNegClauses();
}
/**
* Given a clause index, return the label of that clause.
* @param n The index of the clause.
* @return The label of the clause.
*/
public int getClauseLabel( int n ){
return clauses[n].label;
}
/**
* Given a list of assignments, returns the index of a clause that
* is not satisfied, or -1 if they all are satisfied.
* @param assignments the variable assignments
* @return The index of an unsatisfied clause, or -1 if there are none.
*/
public int getUnsatisfied( byte assignments[] )
{
for( int ix=0; ix<clauseCount; ix++ ){
if( !clauses[ix].isSatisfied( assignments ) ){
return ix;
}
}
return -1;
}
/**
* Given a list of assignments, returns true iff the assignments
* satisfy this problem.
* @param assignments the variable assignments
* @return <code>true</code> iff the assignments satisfy the problem
*/
public boolean isSatisfied( byte assignments[] )
{
for( int ix=0; ix<clauseCount; ix++ ){
if( !clauses[ix].isSatisfied( assignments ) ){
return false;
}
}
return true;
}
/**
* Given a list of assignments, returns true iff the assignments
* conflict with this problem. An assignment is conflicting if any
* further assignments to unassigned variables cannot possibly satisfy
* the problem.
* @param assignments the variable assignments
* @return <code>true</code> iff the assignments conflict with the problem
*/
public boolean isConflicting( byte assignments[] )
{
for( int ix=0; ix<clauseCount; ix++ ){
if( clauses[ix].isConflicting( assignments ) ){
return true;
}
}
return false;
}
/**
* Returns true iff this problem is known to be conflicting for
* all assignments.
*/
public boolean isConflicting()
{
// For now, I know nothing.
return false;
}
/**
* Returns true iff this problem is known to be satisfied for
* all assignments.
*/
public boolean isSatisfied() { return clauseCount == 0; }
/**
* Propagates the fact that the specified variable is true to the
* specified vector of clauses.
* @param cl the vector of clauses that contain the variable
* @param var the variable to propagate
* @param val the value of the variable
*/
private boolean propagateAssignment( int l[], int var, boolean val )
{
boolean changed = false;
for( int ix=0; ix<l.length; ix++ ){
int cno = l[ix];
Clause c = clauses[cno];
if( c == null ){
continue;
}
boolean sat;
if( val ){
sat = c.propagatePosAssignment( var );
}
else {
sat = c.propagateNegAssignment( var );
}
if( sat ){
// This clause is satisfied by the assignment. Remove it.
clauses[cno] = null;
changed = true;
if( traceSimplification ){
System.err.println( "Clause " + c + " is satisfied by var[" + var + "]=" + val );
}
}
}
return changed;
}
/**
* Given a variable and a value, propagates this
* assignment.
* @param var the variable
* @param val the value of the variable
* @return <code>true</code> iff the propagation deleted any clauses
*/
public boolean propagateAssignment( int var, boolean val )
{
boolean changed = false;
int oldAssignment = variables[var].getAssignment();
if( oldAssignment != -1 ){
boolean oldVal = (oldAssignment == 1);
if( oldVal != val ){
System.err.println( "Cannot propagate val[" + var + "]=" + val + ", since it contradicts an existing assignment" );
}
return false;
}
knownVars++;
SATVar v = variables[var];
v.setAssignment( val );
if( v.getUseCount() == 0 ){
System.err.println( "Error: zero use count of variable " + v );
}
changed |= propagateAssignment( v.getPosClauses(), var, val );
changed |= propagateAssignment( v.getNegClauses(), var, val );
return changed;
}
/** Removes null clauses from the clauses array. */
private void compactClauses()
{
int ix = clauseCount;
while( ix>0 ){
ix
if( clauses[ix] == null ){
deleteClause( ix );
}
}
}
/** Builds the variable use administration. */
public void buildAdministration()
{
for( int ix=0; ix<variables.length; ix++ ){
SATVar v = variables[ix];
v.clearClauseRegister();
}
for( int i=0; i<clauseCount; i++ ){
registerClauseVariables( clauses[i], i );
}
}
/** Optimizes the problem for solving. */
public void optimize()
{
boolean changed;
int unitClauses = 0;
int iters = 0;
int purevars = 0;
int subsumptions = 0;
do {
changed = false;
iters++;
buildAdministration();
for( int ix=0; ix<variables.length; ix++ ){
SATVar v = variables[ix];
if( !v.isUsed() ){
continue;
}
if( v.isPosOnly() ){
// Variable 'v' only occurs in positive terms, we may as
// well assign to this variable, and propagate this
// assignment.
if( traceSimplification ){
System.err.println( "Variable " + v + " only occurs as positive term" );
}
changed |= propagateAssignment( ix, true );
purevars++;
}
else if( v.isNegOnly() ){
// Variable 'v' only occurs in negative terms, we may as
// well assign to this variable, and propagate this
// assignment.
if( traceSimplification ){
System.err.println( "Variable " + v + " only occurs as negative term" );
}
changed |= propagateAssignment( ix, false );
purevars++;
}
}
for( int i=0; i<clauseCount; i++ ){
Clause cl = clauses[i];
if( cl == null ){
continue;
}
int var = cl.getPosUnitVar();
if( var>=0 ){
// This is a positive unit clause. Propagate.
if( traceSimplification ){
System.err.println( "Propagating pos. unit clause " + cl );
}
changed |= propagateAssignment( var, true );
if( clauses[i] != null ){
System.err.println( "Error: positive unit propagation didn't eliminate originating clause " + cl );
}
unitClauses++;
continue;
}
else {
var = cl.getNegUnitVar();
if( var>=0 ){
// This is a negative unit clause. Propagate.
if( traceSimplification ){
System.err.println( "Propagating neg. unit clause " + cl );
}
propagateAssignment( var, false );
if( clauses[i] != null ){
System.err.println( "Error: negative unit propagation didn't eliminate originating clause " + cl );
}
unitClauses++;
continue;
}
}
}
} while( changed );
compactClauses();
// For the moment, sort the clauses into shortest-first order.
java.util.Arrays.sort( clauses, 0, clauseCount );
buildAdministration();
if( traceStats ){
System.err.println( "Propagated " + unitClauses + " unit clauses" );
System.err.println( "Propagated " + purevars + " pure variables" );
System.err.println( "Did " + iters + " optimization iterations" );
}
}
/**
* Returns the initial assignment array for this problem.
* @return an array of assignments for the variables of this problem
*/
byte [] buildInitialAssignments()
{
byte res[] = new byte[vars];
for( int ix=0; ix<vars; ix++ ){
res[ix] = variables[ix].getAssignment();
}
return res;
}
/**
* Returns a new array that contains the number of terms in
* each clause.
*/
int [] buildTermCounts()
{
int res[] = new int[clauseCount];
for( int i=0; i<clauseCount; i++ ){
res[i] = clauses[i].getTermCount();
}
return res;
}
/**
* Returns a new array that contains the number of clauses in which
* a variable occurs positively.
*/
int [] buildPosClauses()
{
int res[] = new int[vars];
for( int ix=0; ix<vars; ix++ ){
res[ix] = variables[ix].getPosCount();
}
return res;
}
/**
* Returns a new array that contains the number of clauses in which
* a variable occurs negatively.
*/
int [] buildNegClauses()
{
int res[] = new int[vars];
for( int ix=0; ix<vars; ix++ ){
res[ix] = variables[ix].getNegCount();
}
return res;
}
/**
* Returns a new array that contains the information of the
* positive assignment of each variable.
*/
float [] buildPosInfo()
{
float res[] = new float[vars];
for( int ix=0; ix<vars; ix++ ){
res[ix] = variables[ix].getPosInfo( clauses, reviewer );
}
return res;
}
/**
* Returns a new array that contains the information of the
* negative assignment of each variable.
*/
float [] buildNegInfo()
{
float res[] = new float[vars];
for( int ix=0; ix<vars; ix++ ){
res[ix] = variables[ix].getNegInfo( clauses, reviewer );
}
return res;
}
/**
* Returns the most frequently used variable of this problem.
* Assigned variables are not considered.
* @return the index of the most frequently used variable, or -1 if there are no unassigned variables
*/
int getMFUVariable()
{
SATVar bestvar = null;
int bestuse = 0;
for( int i=0; i<vars; i++ ){
SATVar v = variables[i];
if( v != null && v.getAssignment() == -1 ){
int use = v.getUseCount();
if( bestuse<use ){
bestvar = v;
bestuse = use;
}
}
}
return (bestvar == null) ? -1 : bestvar.getIndex();
}
/**
* Returns a list of variables for this problem, ordered to be
* most effective in solving the problem as fast as possible.
* @return an ordered list of variables
*/
int [] buildOrderedVarList()
{
int varix = 0;
SATVar sorted_vars[] = new SATVar[vars];
for( int i=0; i<vars; i++ ){
SATVar v = variables[i];
if( v != null && v.getAssignment() == -1 ){
sorted_vars[varix++] = v;
}
}
java.util.Arrays.sort( sorted_vars, 0, varix );
int res[] = new int[varix];
for( int i=0; i<varix; i++ ){
int ix = sorted_vars[i].getIndex();
res[i] = ix;
}
return res;
}
public static SATProblem parseDIMACSStream( Reader in ) throws java.io.IOException
{
int varcount = 0;
int promisedClauseCount = 0;
// We keep two arrays of size varcount to store terms of
// the currently parsed clause. Once a clause is terminated, we
// then copy them into arrays that are exactly large enough to
// hold the terms.
// Note that in theory these arrays are too small if a clause
// contains repeats of the same term. That would be silly to do,
// but is not explicitly forbidden by the DIMACS file format.
int pos[] = null;
int neg[] = null;
int posix = 0;
int negix = 0;
boolean done = false;
SATProblem res = null;
StreamTokenizer tok = new StreamTokenizer( in );
tok.eolIsSignificant( true ); // Because of 'c' and 'p' lines.
tok.lowerCaseMode( false ); // Don't fold UC to LC.
while( !done ){
int t = tok.nextToken();
boolean startOfLine = true;
boolean nextStartOfLine = false;
// System.out.println( "Token [" + tok.sval + "," + tok.nval + "] startOfLine=" + startOfLine );
switch( t ){
case StreamTokenizer.TT_EOF:
done = true;
break;
case StreamTokenizer.TT_EOL:
nextStartOfLine = true;
break;
case StreamTokenizer.TT_NUMBER:
if( res == null ){
System.err.println( tok.lineno() + ": clause given before `p' line" );
return null;
}
if( tok.nval == 0 ){
if( posix != 0 || negix != 0 ){
// Only add a real clause. Some naughty people
// put empty clauses in the problem, usually
// at the end of the input file. Strictly speaking
// this makes the entire problem unsatisfiable, but
// this is clearly not the intention.
res.addClause( pos, posix, neg, negix );
posix = 0;
negix = 0;
}
}
else if( tok.nval<0 ){
neg[negix++] = ((int) -tok.nval) - 1;
}
else {
pos[posix++] = ((int) tok.nval) - 1;
}
break;
case StreamTokenizer.TT_WORD:
// We got a word. This should only happen for
// 'c' and 'f' lines.
if( startOfLine ){
if( tok.sval.equals( "c" ) ){
// A comment line.
// Eat all remaining tokens on this line.
do {
t = tok.nextToken();
} while( t != StreamTokenizer.TT_EOF && t != StreamTokenizer.TT_EOL );
nextStartOfLine = true;
}
else if( tok.sval.equals( "p" ) ){
// A format line. Read the information.
if( res != null ){
System.err.println( tok.lineno() + ": duplicate `p' line" );
return null;
}
t = tok.nextToken();
if( t != StreamTokenizer.TT_WORD || !tok.sval.equals( "cnf" ) ){
System.err.println( tok.lineno() + ": expected \"cnf\", but got \"" + tok.sval + "\"" );
return null;
}
t = tok.nextToken();
if( t != StreamTokenizer.TT_NUMBER ){
System.err.println( tok.lineno() + ": expected a number" );
return null;
}
varcount = (int) tok.nval;
t = tok.nextToken();
if( t != StreamTokenizer.TT_NUMBER ){
System.err.println( tok.lineno() + ": expected a number" );
return null;
}
promisedClauseCount = (int) tok.nval;
t = tok.nextToken();
if( t != StreamTokenizer.TT_EOL ){
System.err.println( tok.lineno() + ": spurious text after `f' line" );
return null;
}
nextStartOfLine = true;
res = new SATProblem( varcount, promisedClauseCount );
pos = new int[varcount];
neg = new int[varcount];
posix = 0;
negix = 0;
}
else {
System.err.println( tok.lineno() + ": unexpected word \"" + tok.sval + "\" at start of line" );
return null;
}
}
else {
System.err.println( tok.lineno() + ": unexpected word \"" + tok.sval + "\"" );
return null;
}
break;
default:
if( t == '%' ){
// A comment line.
// Eat all remaining tokens on this line.
do {
t = tok.nextToken();
} while( t != StreamTokenizer.TT_EOF && t != StreamTokenizer.TT_EOL );
nextStartOfLine = true;
}
else {
System.err.println( tok.lineno() + ": ignoring unexpected character '" + (char) t + "'" );
}
break;
}
startOfLine = nextStartOfLine;
}
if( posix != 0 || negix != 0 ){
// There are some pending terms, flush the clause.
res.addClause( pos, posix, neg, negix );
}
if( res.clauseCount+res.deletedClauseCount<promisedClauseCount ){
System.out.println( "There are only " + (res.clauseCount+res.deletedClauseCount) + " clauses, although " + promisedClauseCount + " were promised" );
}
return res;
}
/**
* A CNF problem parser. Given a problem in DIMACS format, returns
* a SATProblem instance for it.
* @param f the file to parse
* @return the parsed problem
*/
public static SATProblem parseDIMACSStream( File f ) throws java.io.IOException
{
String fnm = f.getName();
InputStream s = new FileInputStream( f );
if( fnm.endsWith( ".gz" ) ){
s = new java.util.zip.GZIPInputStream( s );
}
return parseDIMACSStream( new InputStreamReader( s ) );
}
/**
* Given an output stream, prints the problem to it in DIMACS format.
* @param s the stream to print to
*/
public void printDIMACS( PrintStream s )
{
s.println( "p cnf " + vars + " " + clauses.length );
for( int ix=0; ix<clauses.length; ix++ ){
clauses[ix].printDIMACS( s );
}
}
/** Returns a string representation of the SAT problem. */
public String toString()
{
String res = "";
for( int ix=0; ix<clauseCount; ix++ ){
res += "(" + clauses[ix] + ")";
}
return res;
}
/**
* Print a statistics line for this problem to the specified
* PrintStream.
* @param s the stream to print to
* */
public void report( java.io.PrintStream s )
{
String knownString = "";
if( knownVars != 0 ){
knownString = " (" + knownVars + " known)";
}
s.println( "Problem has " + vars + " variables" + knownString + " and " + clauseCount + " clauses" );
}
}
|
package org.jenkinsci.plugins.p4.scm;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.EnvVars;
import hudson.Extension;
import hudson.model.Item;
import hudson.model.Run;
import hudson.scm.SCM;
import hudson.util.LogTaskListener;
import jenkins.scm.api.SCMFile;
import jenkins.scm.api.SCMFileSystem;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMSource;
import org.jenkinsci.plugins.p4.PerforceScm;
import org.jenkinsci.plugins.p4.client.TempClientHelper;
import org.jenkinsci.plugins.p4.workspace.Workspace;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class P4SCMFileSystem extends SCMFileSystem {
private static Logger logger = Logger.getLogger(P4SCMFileSystem.class.getName());
private TempClientHelper p4;
protected P4SCMFileSystem(@NonNull Item owner, @NonNull PerforceScm scm, @CheckForNull P4SCMRevision rev) throws Exception {
super(rev);
String credential = scm.getCredential();
Workspace ws = scm.getWorkspace().deepClone();
// Set environment in Workspace
if (owner instanceof WorkflowJob) {
WorkflowJob _job = (WorkflowJob) owner;
Run<?,?> build = _job.getLastBuild();
EnvVars env = build.getEnvironment(new LogTaskListener(logger, Level.INFO));
ws.setExpand(env);
}
this.p4 = new TempClientHelper(owner, credential, null, ws);
}
@Override
public void close() throws IOException {
p4.close();
}
@Override
public long lastModified() throws IOException, InterruptedException {
return 0;
}
@Override
public SCMFile getRoot() {
return new P4SCMFile(this);
}
@Extension
public static class BuilderImpl extends SCMFileSystem.Builder {
@Override
public boolean supports(SCM source) {
if (source instanceof PerforceScm) {
return true;
}
return false;
}
@Override
public boolean supports(SCMSource source) {
if (source instanceof AbstractP4ScmSource) {
return true;
}
return false;
}
@Override
public SCMFileSystem build(@NonNull Item owner, SCM scm, @CheckForNull SCMRevision rev) throws IOException, InterruptedException {
if (scm == null || !(scm instanceof PerforceScm)) {
return null;
}
PerforceScm p4scm = (PerforceScm) scm;
if (rev != null && !(rev instanceof P4SCMRevision)) {
return null;
}
P4SCMRevision p4rev = (P4SCMRevision) rev;
try {
return new P4SCMFileSystem(owner, p4scm, p4rev);
} catch (Exception e) {
throw new IOException(e);
}
}
}
public TempClientHelper getConnection() {
return p4;
}
}
|
package org.ligoj.app.plugin.prov;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.transaction.Transactional;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.commons.lang3.BooleanUtils;
import org.hibernate.Hibernate;
import org.ligoj.app.plugin.prov.dao.ProvBudgetRepository;
import org.ligoj.app.plugin.prov.model.AbstractInstanceType;
import org.ligoj.app.plugin.prov.model.AbstractQuoteVm;
import org.ligoj.app.plugin.prov.model.AbstractTermPriceVm;
import org.ligoj.app.plugin.prov.model.ProvBudget;
import org.ligoj.app.plugin.prov.model.ProvQuote;
import org.ligoj.app.plugin.prov.model.ProvQuoteContainer;
import org.ligoj.app.plugin.prov.model.ProvQuoteDatabase;
import org.ligoj.app.plugin.prov.model.ProvQuoteFunction;
import org.ligoj.app.plugin.prov.model.ProvQuoteInstance;
import org.ligoj.app.plugin.prov.model.ResourceScope;
import org.ligoj.app.plugin.prov.model.ResourceType;
import org.ligoj.bootstrap.resource.system.configuration.ConfigurationResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.jnellis.binpack.LinearBin;
import net.jnellis.binpack.LinearBinPacker;
/**
* Budget part of provisioning.
*/
@Service
@Path(ProvResource.SERVICE_URL + "/{subscription:\\d+}/budget")
@Produces(MediaType.APPLICATION_JSON)
@Transactional
@Slf4j
public class ProvBudgetResource extends AbstractMultiScopedResource<ProvBudget, ProvBudgetRepository, BudgetEditionVo> {
private static final String CODE = " (code=";
@Autowired
@Getter
private ProvBudgetRepository repository;
@Autowired
private ConfigurationResource configuration;
/**
* Create a budget initiated without any cost.
*/
public ProvBudgetResource() {
super(ResourceScope::getBudget, ResourceScope::setBudget, ProvBudget::new);
}
@Override
protected UpdatedCost saveOrUpdate(final ProvBudget entity, final BudgetEditionVo vo) {
// Check the associations and copy attributes to the entity
entity.setName(vo.getName());
entity.setInitialCost(vo.getInitialCost());
// Fetch the budgets of this quotes
final var quote = entity.getConfiguration();
Hibernate.initialize(quote.getBudgets());
// Prepare the updated cost of updated instances
final var relatedCosts = Collections
.synchronizedMap(new EnumMap<ResourceType, Map<Integer, FloatingCost>>(ResourceType.class));
// Prevent useless computation, check the relations
if (entity.getId() != null) {
// This is an update, update the cost of all related instances
lean(entity, relatedCosts);
}
repository.saveAndFlush(entity);
// Update accordingly the support costs
final var cost = new UpdatedCost(entity.getId());
cost.setRelated(relatedCosts);
final var updateCost = resource.refreshSupportCost(cost, quote);
log.info("Total2 monthly cost: {}", updateCost.getTotal().getMin());
log.info("Total2 initial cost: {}", updateCost.getTotal().getInitial());
return updateCost;
}
/**
* Refresh the whole quote budgets.
*
* @param quote The quote owning the related budget.
* @param costs The updated costs and resources.
*/
public void lean(final ProvQuote quote, final Map<ResourceType, Map<Integer, FloatingCost>> costs) {
final var instances = qiRepository.findAll(quote);
final var databases = qbRepository.findAll(quote);
final var containers = qcRepository.findAll(quote);
final var functions = qfRepository.findAll(quote);
Hibernate.initialize(quote.getUsages());
Hibernate.initialize(quote.getBudgets());
lean(quote, instances, databases, containers, functions, costs);
// Reset the orphan budgets
final var usedBudgets = Stream.concat(instances.stream(), databases.stream())
.map(AbstractQuoteVm::getResolvedBudget).filter(Objects::nonNull).distinct().map(ProvBudget::getId)
.collect(Collectors.toSet());
repository.findAll(quote).stream().filter(b -> !usedBudgets.contains(b.getId()))
.forEach(b -> b.setRequiredInitialCost(0d));
}
/**
* Detect the related budgets having an initial cost and involved in the given instances/databases collections, lean
* them. A refresh is also applied to all resources related to these budgets. This means that some resources not
* included in the initial set may be refreshed.
*
* @param quote The quote owning the related budget.
* @param instances The instances implied in the current change.
* @param databases The databases implied in the current change.
* @param containers The containers implied in the current change.
* @param functions The functions implied in the current change.
* @param costs The updated costs and resources.
*/
public void lean(final ProvQuote quote, final List<ProvQuoteInstance> instances,
final List<ProvQuoteDatabase> databases, final List<ProvQuoteContainer> containers,
final List<ProvQuoteFunction> functions, final Map<ResourceType, Map<Integer, FloatingCost>> costs) {
synchronized (quote) {
// Lean all relevant budgets
final var budgets = Stream
.concat(instances.stream(),
Stream.concat(databases.stream(), Stream.concat(containers.stream(), functions.stream())))
.map(AbstractQuoteVm::getResolvedBudget).filter(Objects::nonNull)
.filter(b -> b.getInitialCost() > 0).distinct().collect(Collectors.toList());
budgets.forEach(b -> lean(b, costs));
// Refresh also all remaining resources unrelated to the updated budgets
refreshNoBudget(instances, ResourceType.INSTANCE, costs, qiResource);
refreshNoBudget(databases, ResourceType.DATABASE, costs, qbResource);
refreshNoBudget(containers, ResourceType.CONTAINER, costs, qcResource);
refreshNoBudget(functions, ResourceType.FUNCTION, costs, qfResource);
}
}
private <T extends AbstractInstanceType, P extends AbstractTermPriceVm<T>, C extends AbstractQuoteVm<P>> void refreshNoBudget(
final List<C> instances, final ResourceType type, final Map<ResourceType, Map<Integer, FloatingCost>> costs,
final AbstractProvQuoteVmResource<T, P, C, ?, ?, ?> resource) {
this.resource.newStream(instances)
.filter(i -> Optional.ofNullable(i.getResolvedBudget()).map(ProvBudget::getInitialCost).orElse(0d) == 0)
.forEach(i -> costs.computeIfAbsent(type, k -> new HashMap<>()).put(i.getId(),
resource.addCost(i, resource::refresh)));
}
/**
* Detect the related resources to the given budget and refresh them according to the budget constraints.
*
* @param budget The budget to lean.
* @param costs The updated costs and resources.
*/
public void lean(final ProvBudget budget, final Map<ResourceType, Map<Integer, FloatingCost>> costs) {
if (budget == null) {
// Ignore, no lean to do
return;
}
// Get all related resources
log.info("Lean budget {} in subscription {}", budget.getName(),
budget.getConfiguration().getSubscription().getId());
final var instances = getRelated(getRepository()::findRelatedInstances, budget);
final var databases = getRelated(getRepository()::findRelatedDatabases, budget);
final var containers = getRelated(getRepository()::findRelatedContainers, budget);
final var functions = getRelated(getRepository()::findRelatedFunctions, budget);
// Reset the remaining initial cost
budget.setRemainingBudget(budget.getInitialCost());
budget.setRequiredInitialCost(leanRecursive(budget, instances, databases, containers, functions, costs));
budget.setRemainingBudget(null);
logLean(c -> {
log.info("Monthly costs:{}", c.stream().map(i -> i.getPrice().getCost()).collect(Collectors.toList()));
log.info("Monthly cost: {}", c.stream().mapToDouble(i -> i.getPrice().getCost()).sum());
log.info("Initial cost: {}", c.stream().mapToDouble(i -> i.getPrice().getInitialCost()).sum());
}, instances, databases);
}
/**
* Logger as needed.
*/
private void logLean(final Consumer<List<? extends AbstractQuoteVm<?>>> logger,
final List<ProvQuoteInstance> instances, final List<ProvQuoteDatabase> databases) {
if (BooleanUtils.toBoolean(configuration.get(ProvResource.SERVICE_KEY + ":log"))) {
List.of(instances, databases).stream().forEach(logger::accept);
}
}
private <C> void logLean(final Consumer<C> logger, C object) {
if (BooleanUtils.toBoolean(configuration.get(ProvResource.SERVICE_KEY + ":log"))) {
logger.accept(object);
}
}
/**
* Price priority for packing.
*/
private Comparator<? super Entry<Double, AbstractQuoteVm<?>>> priceOrder(
final Map<AbstractQuoteVm<?>, FloatingPrice<?>> prices) {
return (e1, e2) -> {
// Priority to the most expensive price
final var c1 = prices.get(e1.getValue()).getPrice().getCost();
final var c2 = prices.get(e2.getValue()).getPrice().getCost();
var compare = (int) (c2 - c1);
if (compare == 0) {
// Then natural naming order
compare = e1.getValue().getName().compareTo(e2.getValue().getName());
}
return compare;
};
}
private double leanRecursive(final ProvBudget budget, final List<ProvQuoteInstance> instances,
final List<ProvQuoteDatabase> databases, final List<ProvQuoteContainer> containers,
final List<ProvQuoteFunction> functions, final Map<ResourceType, Map<Integer, FloatingCost>> costs) {
logLean(c -> log.info("Start lean: {}",
c.stream().map(i -> i.getName() + CODE + i.getPrice().getCode() + ")").collect(Collectors.toList())),
instances, databases);
// Lookup the best prices
// And build the pack candidates
final var packToQr = new IdentityHashMap<Double, AbstractQuoteVm<?>>();
final var prices = new HashMap<AbstractQuoteVm<?>, FloatingPrice<?>>();
final var validatedQi = lookup(instances, prices, qiResource, packToQr);
final var validatedQb = lookup(databases, prices, qbResource, packToQr);
final var validatedQc = lookup(containers, prices, qcResource, packToQr);
final var validatedQf = lookup(functions, prices, qfResource, packToQr);
log.info("Lookup result: {}",
prices.entrySet().stream().map(e -> e.getKey().getName() + CODE + e.getKey().getPrice().getCode()
+ " -> " + e.getValue().getPrice().getCode() + ")").collect(Collectors.toList()));
// Pack the prices having an initial cost
var init = pack(budget, packToQr, prices, validatedQi, validatedQb, validatedQc, costs);
// Commit this pack
commitPrices(validatedQi, prices, ResourceType.INSTANCE, costs, qiResource);
commitPrices(validatedQb, prices, ResourceType.DATABASE, costs, qbResource);
commitPrices(validatedQc, prices, ResourceType.CONTAINER, costs, qcResource);
commitPrices(validatedQf, prices, ResourceType.FUNCTION, costs, qfResource);
logLean(t -> {
log.info("Lean: {}", t.stream().map(i -> i.getName() + CODE + i.getPrice().getCode() + ")")
.collect(Collectors.toList()));
log.info("Lean monthly costs:{}", t.stream().map(i -> i.getPrice().getCost()).collect(Collectors.toList()));
log.info("Lean monthly cost: {}", t.stream().mapToDouble(i -> i.getPrice().getCost()).sum());
log.info("Lean initial cost: {}", t.stream().mapToDouble(i -> i.getPrice().getInitialCost()).sum());
}, validatedQi, validatedQb);
logLean(c -> log.info("Total intitialCost:{}", c), init);
return FloatingCost.round(init);
}
private double pack(final ProvBudget budget, final Map<Double, AbstractQuoteVm<?>> packToQr,
final Map<AbstractQuoteVm<?>, FloatingPrice<?>> prices, final List<ProvQuoteInstance> validatedQi,
final List<ProvQuoteDatabase> validatedQb, final List<ProvQuoteContainer> validatedQc,
final Map<ResourceType, Map<Integer, FloatingCost>> costs) {
if (packToQr.isEmpty()) {
return 0d;
}
// At least one initial cost is implied, use bin packing strategy
final var packStart = System.currentTimeMillis();
final var packer = new LinearBinPacker();
final var bins = packer.packAll(
packToQr.entrySet().stream().sorted(priceOrder(prices)).map(Entry::getKey).collect(Collectors.toList()),
new ArrayList<>(List.of(new LinearBin(budget.getRemainingBudget()))),
new ArrayList<>(List.of(Double.MAX_VALUE)));
final var bin = bins.get(0);
bin.getPieces().stream().map(packToQr::get).forEach(i -> {
if (i.getResourceType() == ResourceType.INSTANCE) {
validatedQi.add((ProvQuoteInstance) i);
} else if (i.getResourceType() == ResourceType.DATABASE) {
validatedQb.add((ProvQuoteDatabase) i);
} else {
validatedQc.add((ProvQuoteContainer) i);
}
});
logLean(b -> {
log.info("Packing result: {}", b.get(0).getPieces().stream().map(packToQr::get)
.map(i -> i.getName() + CODE + i.getPrice().getCode() + ")").collect(Collectors.toList()));
log.info("Packing result: {}", b);
}, bins);
logPack(packStart, packToQr, budget);
var init = bin.getTotal();
if (bins.size() > 1) {
// Extra bin needs to make a new pass
budget.setRemainingBudget(FloatingCost.round(budget.getRemainingBudget() - bin.getTotal()));
final List<ProvQuoteInstance> subQi = newSubPack(packToQr, bins, ResourceType.INSTANCE);
final List<ProvQuoteDatabase> subQb = newSubPack(packToQr, bins, ResourceType.DATABASE);
final List<ProvQuoteContainer> subQc = newSubPack(packToQr, bins, ResourceType.CONTAINER);
final List<ProvQuoteFunction> subQf = newSubPack(packToQr, bins, ResourceType.FUNCTION);
init += leanRecursive(budget, subQi, subQb, subQc, subQf, costs);
} else {
// Pack is completed
}
return init;
}
/**
* Log packing statistics.
*
* @param packStart Starting timestamp.
* @param packToQr The packed resources.
* @param budget The related budget.
*/
protected void logPack(final long packStart, final Map<Double, AbstractQuoteVm<?>> packToQr,
final ProvBudget budget) {
// Log packing statistic
final var packTime = System.currentTimeMillis() - packStart;
if (packTime > 500) {
// Enough duration to be logged
log.info("Packing of {} resources for subscription {} took {}", packToQr.size(),
budget.getConfiguration().getSubscription().getId(), Duration.ofMillis(packTime));
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <T extends AbstractInstanceType, P extends AbstractTermPriceVm<T>, C extends AbstractQuoteVm<P>> List<C> newSubPack(
final Map<Double, AbstractQuoteVm<?>> packToQr, final List<LinearBin> bins, final ResourceType type) {
return (List) bins.get(1).getPieces().stream().map(packToQr::get).filter(i -> i.getResourceType() == type)
.collect(Collectors.toList());
}
private <T extends AbstractInstanceType, P extends AbstractTermPriceVm<T>, C extends AbstractQuoteVm<P>> void commitPrices(
final List<C> nodes, final Map<AbstractQuoteVm<?>, FloatingPrice<?>> prices, final ResourceType type,
final Map<ResourceType, Map<Integer, FloatingCost>> costs,
final AbstractProvQuoteVmResource<T, P, C, ?, ?, ?> resource) {
nodes.forEach(i -> {
@SuppressWarnings("unchecked")
final var price = (FloatingPrice<P>) prices.get(i);
costs.computeIfAbsent(type, k -> new HashMap<>()).put(i.getId(), resource.addCost(i, qi -> {
qi.setPrice(price.getPrice());
return resource.updateCost(qi);
}));
});
}
/**
* Execute a lookup for each resources, and store the resolved price in the "prices" parameter. Then separate the
* resolved prices having an initial cost from the one without. These excluded resources are returned. The prices
* having an initial cost are put in the given identity map where the key corresponds to this cost, and the value
* corresponds to the resource.
*/
private <T extends AbstractInstanceType, P extends AbstractTermPriceVm<T>, C extends AbstractQuoteVm<P>> List<C> lookup(
final List<C> nodes, final Map<AbstractQuoteVm<?>, FloatingPrice<?>> prices,
final AbstractProvQuoteVmResource<T, P, C, ?, ?, ?> resource,
final IdentityHashMap<Double, AbstractQuoteVm<?>> packToQi) {
final var validatedQi = new ArrayList<C>();
this.resource.newStream(nodes).forEach(i -> {
final var price = resource.getNewPrice(i);
prices.put(i, price);
if (price.getCost().getInitial() > 0) {
// Add this price to the pack
packToQi.put(price.getCost().getInitial(), i);
} else {
// Add this price to the commit stage
validatedQi.add(i);
}
});
return validatedQi;
}
}
|
package org.osiam.auth.login;
import javax.inject.Inject;
import org.osiam.auth.oauth_client.OsiamAuthServerClientProvider;
import org.osiam.auth.token.OsiamAccessTokenProvider;
import org.osiam.client.OsiamConnector;
import org.osiam.client.query.Query;
import org.osiam.client.query.QueryBuilder;
import org.osiam.resources.scim.SCIMSearchResult;
import org.osiam.resources.scim.UpdateUser;
import org.osiam.resources.scim.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class ResourceServerConnector {
@Value("${org.osiam.resource-server.home}")
private String resourceServerHome;
@Value("${org.osiam.auth-server.home}")
private String authServerHome;
@Inject
private OsiamAccessTokenProvider osiamAccessTokenProvider;
@Inject
private OsiamAuthServerClientProvider authServerClientProvider;
public User getUserByUsername(final String userName) {
OsiamConnector osiamConnector = createOsiamConnector();
Query query = new QueryBuilder().filter("userName eq \"" + userName + "\""
+ " and active eq \"true\"").build();
SCIMSearchResult<User> result = osiamConnector.searchUsers(query,
osiamAccessTokenProvider.createAccessToken());
if (result.getTotalResults() != 1) {
return null;
} else {
return result.getResources().get(0);
}
}
public User createUser(User user) {
OsiamConnector osiamConnector = createOsiamConnector();
return osiamConnector.createUser(user, osiamAccessTokenProvider.createAccessToken());
}
public User updateUser(String userId, UpdateUser user) {
OsiamConnector osiamConnector = createOsiamConnector();
return osiamConnector.updateUser(userId, user, osiamAccessTokenProvider.createAccessToken());
}
public User searchUserByUserNameAndPassword(String userName, String hashedPassword) {
OsiamConnector osiamConnector = createOsiamConnector();
Query query = new QueryBuilder().filter("userName eq \"" + userName + "\""
+ " and password eq \"" + hashedPassword + "\"").build();
SCIMSearchResult<User> result = osiamConnector.searchUsers(query,
osiamAccessTokenProvider.createAccessToken());
if (result.getTotalResults() != 1) {
return null;
} else {
return result.getResources().get(0);
}
}
private OsiamConnector createOsiamConnector() {
OsiamConnector.Builder oConBuilder = new OsiamConnector.Builder().
setAuthServerEndpoint(authServerHome).
setResourceServerEndpoint(resourceServerHome).
setClientId(OsiamAuthServerClientProvider.AUTH_SERVER_CLIENT_ID).
setClientSecret(authServerClientProvider.getClientSecret());
return oConBuilder.build();
}
}
|
package oshi.software.os.linux.proc;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sun.jna.LastErrorException;
import com.sun.jna.Native;
import oshi.hardware.Processor;
import oshi.software.os.linux.Libc;
import oshi.software.os.linux.Libc.Sysinfo;
import oshi.util.FileUtil;
import oshi.util.ParseUtil;
/**
* A CPU as defined in Linux /proc.
*
* @author alessandro[at]perucchi[dot]org
* @author alessio.fachechi[at]gmail[dot]com
* @author widdis[at]gmail[dot]com
*/
@SuppressWarnings("restriction")
public class CentralProcessor implements Processor {
// Determine whether MXBean supports Oracle JVM methods
private static final java.lang.management.OperatingSystemMXBean OS_MXBEAN = ManagementFactory
.getOperatingSystemMXBean();;
private static boolean sunMXBean;
static {
try {
Class.forName("com.sun.management.OperatingSystemMXBean");
// Initialize CPU usage
((com.sun.management.OperatingSystemMXBean) OS_MXBEAN).getSystemCpuLoad();
sunMXBean = true;
} catch (ClassNotFoundException e) {
sunMXBean = false;
}
}
// Maintain two sets of previous ticks to be used for calculating usage
// between them.
// System ticks (static)
private static long tickTime = System.currentTimeMillis();
private static long[] prevTicks = new long[4];
private static long[] curTicks = new long[4];
static {
updateSystemTicks();
System.arraycopy(curTicks, 0, prevTicks, 0, curTicks.length);
}
// Maintain similar arrays for per-processor ticks (class variables)
private long procTickTime = System.currentTimeMillis();
private long[] prevProcTicks = new long[4];
private long[] curProcTicks = new long[4];
// Initialize numCPU
private static int numCPU = 0;
static {
try {
List<String> procCpu = FileUtil.readFile("/proc/cpuinfo");
for (String cpu : procCpu) {
if (cpu.startsWith("processor")) {
numCPU++;
}
}
} catch (IOException e) {
System.err.println("Problem with: /proc/cpuinfo");
System.err.println(e.getMessage());
}
// Force at least one processor
if (numCPU < 1)
numCPU = 1;
}
// Set up array to maintain current ticks for rapid reference. This array
// will be updated in place and used as a cache to avoid rereading file
// while iterating processors
private static long[][] allProcessorTicks = new long[numCPU][4];
private static long allProcTickTime = 0;
private int processorNumber;
private String cpuVendor;
private String cpuName;
private String cpuIdentifier = null;
private String cpuStepping;
private String cpuModel;
private String cpuFamily;
private Long cpuVendorFreq = null;
private Boolean cpu64;
/**
* Create a Processor with the given number
*
* @param procNo
*/
public CentralProcessor(int procNo) {
if (procNo >= numCPU)
throw new IllegalArgumentException("Processor number (" + procNo
+ ") must be less than the number of CPUs: " + numCPU);
this.processorNumber = procNo;
updateProcessorTicks();
System.arraycopy(allProcessorTicks[processorNumber], 0, curProcTicks, 0, curProcTicks.length);
}
/**
* {@inheritDoc}
*/
@Override
public int getProcessorNumber() {
return processorNumber;
}
/**
* Vendor identifier, eg. GenuineIntel.
*
* @return Processor vendor.
*/
@Override
public String getVendor() {
return this.cpuVendor;
}
/**
* Set processor vendor.
*
* @param vendor
* Vendor.
*/
@Override
public void setVendor(String vendor) {
this.cpuVendor = vendor;
}
/**
* Name, eg. Intel(R) Core(TM)2 Duo CPU T7300 @ 2.00GHz
*
* @return Processor name.
*/
@Override
public String getName() {
return this.cpuName;
}
/**
* Set processor name.
*
* @param name
* Name.
*/
@Override
public void setName(String name) {
this.cpuName = name;
}
/**
* Vendor frequency (in Hz), eg. for processor named Intel(R) Core(TM)2 Duo
* CPU T7300 @ 2.00GHz the vendor frequency is 2000000000.
*
* @return Processor frequency or -1 if unknown.
*/
@Override
public long getVendorFreq() {
if (this.cpuVendorFreq == null) {
Pattern pattern = Pattern.compile("@ (.*)$");
Matcher matcher = pattern.matcher(getName());
if (matcher.find()) {
String unit = matcher.group(1);
this.cpuVendorFreq = Long.valueOf(ParseUtil.parseHertz(unit));
} else {
this.cpuVendorFreq = Long.valueOf(-1L);
}
}
return this.cpuVendorFreq.longValue();
}
/**
* Set vendor frequency.
*
* @param freq
* Frequency.
*/
@Override
public void setVendorFreq(long freq) {
this.cpuVendorFreq = Long.valueOf(freq);
}
/**
* Identifier, eg. x86 Family 6 Model 15 Stepping 10.
*
* @return Processor identifier.
*/
@Override
public String getIdentifier() {
if (this.cpuIdentifier == null) {
StringBuilder sb = new StringBuilder();
if (getVendor().contentEquals("GenuineIntel"))
sb.append(isCpu64bit() ? "Intel64" : "x86");
else
sb.append(getVendor());
sb.append(" Family ");
sb.append(getFamily());
sb.append(" Model ");
sb.append(getModel());
sb.append(" Stepping ");
sb.append(getStepping());
this.cpuIdentifier = sb.toString();
}
return this.cpuIdentifier;
}
/**
* Set processor identifier.
*
* @param identifier
* Identifier.
*/
@Override
public void setIdentifier(String identifier) {
this.cpuIdentifier = identifier;
}
/**
* Is CPU 64bit?
*
* @return True if cpu is 64bit.
*/
@Override
public boolean isCpu64bit() {
return this.cpu64.booleanValue();
}
/**
* Set flag is cpu is 64bit.
*
* @param cpu64
* True if cpu is 64.
*/
@Override
public void setCpu64(boolean cpu64) {
this.cpu64 = Boolean.valueOf(cpu64);
}
/**
* @return the stepping
*/
@Override
public String getStepping() {
return this.cpuStepping;
}
/**
* @param stepping
* the stepping to set
*/
@Override
public void setStepping(String stepping) {
this.cpuStepping = stepping;
}
/**
* @return the model
*/
@Override
public String getModel() {
return this.cpuModel;
}
/**
* @param model
* the model to set
*/
@Override
public void setModel(String model) {
this.cpuModel = model;
}
/**
* @return the family
*/
@Override
public String getFamily() {
return this.cpuFamily;
}
/**
* @param family
* the family to set
*/
@Override
public void setFamily(String family) {
this.cpuFamily = family;
}
/**
* {@inheritDoc}
*/
@Override
@Deprecated
public float getLoad() {
// TODO Remove in 2.0
return (float) getSystemCpuLoadBetweenTicks() * 100;
}
/**
* {@inheritDoc}
*/
@Override
public double getSystemCpuLoadBetweenTicks() {
// Check if > ~ 0.95 seconds since last tick count.
long now = System.currentTimeMillis();
boolean update = (now - tickTime > 950);
if (update) {
// Enough time has elapsed.
// Update latest
updateSystemTicks();
tickTime = now;
}
// Calculate total
long total = 0;
for (int i = 0; i < curTicks.length; i++) {
total += (curTicks[i] - prevTicks[i]);
}
// Calculate idle from last field [3]
long idle = curTicks[3] - prevTicks[3];
// Copy latest ticks to earlier position for next call
if (update) {
System.arraycopy(curTicks, 0, prevTicks, 0, curTicks.length);
}
// return
if (total > 0 && idle >= 0) {
return (double) (total - idle) / total;
}
return 0d;
}
/**
* {@inheritDoc}
*/
@Override
public long[] getSystemCpuLoadTicks() {
updateSystemTicks();
// Make a copy
long[] ticks = new long[curTicks.length];
System.arraycopy(curTicks, 0, ticks, 0, curTicks.length);
return ticks;
}
/**
* Updates system tick information from parsing /proc/stat. Array with four
* elements representing clock ticks or milliseconds (platform dependent)
* spent in User (0), Nice (1), System (2), and Idle (3) states. By
* measuring the difference between ticks across a time interval, CPU load
* over that interval may be calculated.
*
* @return An array of 4 long values representing time spent in User,
* Nice(if applicable), System, and Idle states.
*/
private static void updateSystemTicks() {
// /proc/stat expected format
// first line is overall user,nice,system,idle, etc.
// cpu 3357 0 4313 1362393 ...
String tickStr = "";
try {
List<String> procStat = FileUtil.readFile("/proc/stat");
if (!procStat.isEmpty())
tickStr = procStat.get(0);
} catch (IOException e) {
System.err.println("Problem with: /proc/stat");
System.err.println(e.getMessage());
return;
}
String[] tickArr = tickStr.split("\\s+");
if (tickArr.length < 5)
return;
for (int i = 0; i < 4; i++) {
curTicks[i] = Long.parseLong(tickArr[i + 1]);
}
}
/**
* {@inheritDoc}
*/
@Override
public double getSystemCpuLoad() {
if (sunMXBean) {
return ((com.sun.management.OperatingSystemMXBean) OS_MXBEAN).getSystemCpuLoad();
}
return getSystemCpuLoadBetweenTicks();
}
/**
* {@inheritDoc}
*/
@Override
public double getSystemLoadAverage() {
return OS_MXBEAN.getSystemLoadAverage();
}
/**
* {@inheritDoc}
*/
@Override
public double getProcessorCpuLoadBetweenTicks() {
// Check if > ~ 0.95 seconds since last tick count.
long now = System.currentTimeMillis();
if (now - procTickTime > 950) {
// Enough time has elapsed. Update array in place
updateProcessorTicks();
// Copy arrays in place
System.arraycopy(curProcTicks, 0, prevProcTicks, 0, curProcTicks.length);
System.arraycopy(allProcessorTicks[processorNumber], 0, curProcTicks, 0, curProcTicks.length);
procTickTime = now;
}
long total = 0;
for (int i = 0; i < curProcTicks.length; i++) {
total += (curProcTicks[i] - prevProcTicks[i]);
}
// Calculate idle from last field [3]
long idle = curProcTicks[3] - prevProcTicks[3];
// update
return (total > 0 && idle >= 0) ? (double) (total - idle) / total : 0d;
}
/**
* {@inheritDoc}
*/
public long[] getProcessorCpuLoadTicks() {
updateProcessorTicks();
return allProcessorTicks[processorNumber];
}
/**
* Updates the tick array for all processors if more than 100ms has elapsed
* since the last update. This permits using the allProcessorTicks as a
* cache when iterating over processors so that the /proc/stat file is only
* read once
*/
private static void updateProcessorTicks() {
// Update no more frequently than 100ms so this is only triggered once
// during iteration over Processors
long now = System.currentTimeMillis();
if (now - allProcTickTime < 100)
return;
// /proc/stat expected format
// first line is overall user,nice,system,idle, etc.
// cpu 3357 0 4313 1362393 ...
// per-processor subsequent lines for cpu0, cpu1, etc.
try {
int cpu = 0;
List<String> procStat = FileUtil.readFile("/proc/stat");
for (String stat : procStat) {
if (stat.startsWith("cpu") && !stat.startsWith("cpu ")) {
String[] tickArr = stat.split("\\s+");
if (tickArr.length < 5)
break;
for (int i = 0; i < 4; i++) {
allProcessorTicks[cpu][i] = Long.parseLong(tickArr[i + 1]);
}
if (++cpu >= numCPU)
break;
}
}
} catch (IOException e) {
System.err.println("Problem with: /proc/stat");
System.err.println(e.getMessage());
}
allProcTickTime = now;
}
/**
* {@inheritDoc}
*/
public long getSystemUptime() {
Sysinfo info = new Sysinfo();
if (0 != Libc.INSTANCE.sysinfo(info))
throw new LastErrorException("Error code: " + Native.getLastError());
return info.uptime.longValue();
}
@Override
public String toString() {
return getName();
}
}
|
package programminglife.gui.controller;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import jp.uphy.javafx.console.ConsoleView;
import programminglife.ProgrammingLife;
import programminglife.model.GenomeGraph;
import programminglife.model.exception.UnknownTypeException;
import programminglife.parser.GraphParser;
import programminglife.utility.Alerts;
import programminglife.utility.FileProgressCounter;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.util.Observable;
import java.util.Observer;
import java.util.Scanner;
/**
* The controller for the GUI that is used in the application.
* The @FXML tag is needed in initialize so that javaFX knows what to do.
*/
public class GuiController implements Observer {
//static finals
private static final String INITIAL_CENTER_NODE = "1";
private static final String INITIAL_MAX_DRAW_DEPTH = "10";
//FXML imports.
@FXML private MenuItem btnOpen;
@FXML private MenuItem btnQuit;
@FXML private MenuItem btnBookmarks;
@FXML private MenuItem btnAbout;
@FXML private MenuItem btnInstructions;
@FXML private Menu menuRecent;
@FXML private RadioMenuItem btnToggle;
@FXML private Button btnZoomIn;
@FXML private Button btnZoomOut;
@FXML private Button btnZoomReset;
@FXML private Button btnTranslate;
@FXML private Button btnTranslateReset;
@FXML private Button btnDraw;
@FXML private Button btnDrawRandom;
@FXML private Button btnBookmark;
@FXML private ProgressBar progressBar;
@FXML private TextField txtMaxDrawDepth;
@FXML private TextField txtCenterNode;
@FXML private Group grpDrawArea;
@FXML private AnchorPane anchorLeftControlPanel;
private ConsoleView consoleView;
private double orgSceneX, orgSceneY;
private double orgTranslateX, orgTranslateY;
private int translateX;
private int translateY;
private GraphController graphController;
private File file;
private File recentFile = new File("Recent.txt");
private String recentItems = "";
private Thread parseThread;
/**
* The initialize will call the other methods that are run in the .
*/
@FXML
@SuppressWarnings("unused")
private void initialize() {
this.graphController = new GraphController(null, this.grpDrawArea);
initRecent();
initMenubar();
initBookmarkMenu();
initLeftControlpanelScreenModifiers();
initLeftControlpanelDraw();
initMouse();
consoleView = initConsole();
this.graphController.setConsole(consoleView);
}
/**
* Open and parse a file.
* @param file The {@link File} to open.
* @throws IOException if the {@link File} is not found.
* @throws UnknownTypeException if the {@link File} is not compliant with the GFA standard.
*/
public void openFile(File file) throws IOException, UnknownTypeException {
if (file != null) {
disableGraphUIElements(true);
GraphParser graphParser = new GraphParser(file);
graphParser.addObserver(this);
graphParser.getProgressCounter().addObserver(this);
if (this.parseThread != null) {
this.parseThread.interrupt();
}
this.parseThread = new Thread(graphParser);
this.parseThread.start();
}
}
@Override
public void update(Observable o, Object arg) {
if (o instanceof GraphParser) {
if (arg instanceof GenomeGraph) {
GenomeGraph graph = (GenomeGraph) arg;
System.out.printf("[%s] File Parsed.%n", Thread.currentThread().getName());
this.setGraph(graph);
} else if (arg instanceof Exception) {
Exception e = (Exception) arg;
// TODO find out a smart way to catch Exceptions across threads
throw new RuntimeException(e);
}
} else if (o instanceof FileProgressCounter) {
progressBar.setVisible(true);
FileProgressCounter progress = (FileProgressCounter) o;
this.getProgressBar().setProgress(progress.percentage());
if (progressBar.getProgress() == 1.0d) {
progressBar.setVisible(false);
}
}
}
/**
* Set the graph for this GUIController.
* @param graph Graph to use.
*/
public void setGraph(GenomeGraph graph) {
this.graphController.setGraph(graph);
disableGraphUIElements(graph == null);
if (graph != null) {
System.out.printf("[%s] Graph was set to %s.%n", Thread.currentThread().getName(), graph.getID());
System.out.printf("[%s] The graph has %d nodes%n", Thread.currentThread().getName(), graph.size());
} else {
System.out.printf("[%s] graph was set to null.%n", Thread.currentThread().getName());
}
}
/**
* Read out the file which contains all the recently opened files.
*/
private void initRecent() {
try {
Files.createFile(new File("Recent.txt").toPath());
} catch (FileAlreadyExistsException e) {
//This will always happen if a user has used the program before.
//Therefore it is unnecessary to handle further.
} catch (IOException e) {
Alerts.error("This file can't be opened").show();
return;
}
if (recentFile != null) {
try (Scanner sc = new Scanner(recentFile)) {
while (sc.hasNextLine()) {
String next = sc.nextLine();
MenuItem mi = new MenuItem(next);
mi.setOnAction(event -> {
try {
file = new File(mi.getText());
openFile(file);
} catch (UnknownTypeException e) {
Alerts.error("This file is malformed and cannot be parsed").show();
} catch (IOException e) {
Alerts.error("This file can't be opened").show();
}
});
menuRecent.getItems().add(mi);
recentItems = recentItems.concat(next + System.getProperty("line.separator"));
}
} catch (FileNotFoundException e) {
Alerts.error("This file can't be found").show();
}
}
}
/**
* Initializes the open button so that the user can decide which file to open.
* Sets the action for the open MenuItem.
* Sets the event for the quit MenuItem.
*/
private void initMenubar() {
btnOpen.setOnAction((ActionEvent event) -> {
FileChooser fileChooser = new FileChooser();
final ExtensionFilter extFilterGFA = new ExtensionFilter("GFA files (*.gfa)", "*.GFA");
fileChooser.getExtensionFilters().add(extFilterGFA);
if (file != null) {
File existDirectory = file.getParentFile();
fileChooser.setInitialDirectory(existDirectory);
}
try {
file = fileChooser.showOpenDialog(ProgrammingLife.getStage());
if (file != null) {
this.openFile(file);
updateRecent();
}
} catch (FileNotFoundException e) {
Alerts.error("This file can't be found").show();
} catch (IOException e) {
Alerts.error("This file can't be opened").show();
} catch (UnknownTypeException e) {
Alerts.error("This file is malformed and cannot be parsed").show();
}
});
btnQuit.setOnAction(event -> Alerts.quitAlert());
btnAbout.setOnAction(event -> Alerts.infoAboutAlert());
btnInstructions.setOnAction(event -> Alerts.infoInstructionAlert());
}
/**
* Updates the recent files file after opening a file.
*/
private void updateRecent() {
try (BufferedWriter recentsWriter = new BufferedWriter(new FileWriter(recentFile, true))) {
if (!recentItems.contains(file.getAbsolutePath())) {
recentsWriter.write(file.getAbsolutePath() + System.getProperty("line.separator"));
recentsWriter.flush();
recentsWriter.close();
initRecent();
}
} catch (IOException e) {
Alerts.error("This file can't be updated").show();
}
}
/**
* Initializes the bookmark buttons in the menu.
*/
private void initBookmarkMenu() {
btnBookmarks.setOnAction(event -> {
try {
FXMLLoader loader = new FXMLLoader(ProgrammingLife.class.getResource("/LoadBookmarkWindow.fxml"));
AnchorPane page = loader.load();
GuiLoadBookmarkController gc = loader.getController();
gc.setGuiController(this);
gc.initBookmarks();
if (this.graphController.getGraph() != null) {
gc.setBtnCreateBookmarkActive(true);
}
Scene scene = new Scene(page);
Stage bookmarkDialogStage = new Stage();
bookmarkDialogStage.setResizable(false);
bookmarkDialogStage.setScene(scene);
bookmarkDialogStage.setTitle("Load Bookmark");
bookmarkDialogStage.initOwner(ProgrammingLife.getStage());
bookmarkDialogStage.showAndWait();
} catch (IOException e) {
Alerts.error("The bookmarks file can't be opened").show();
}
});
}
/**
* Method to disable the UI Elements on the left of the GUI.
* @param isDisabled boolean, true disables the left anchor panel.
*/
private void disableGraphUIElements(boolean isDisabled) {
anchorLeftControlPanel.setDisable(isDisabled);
}
/**
* Initializes the buttons on the panel on the left side which do translation/zoom.
*/
private void initLeftControlpanelScreenModifiers() {
disableGraphUIElements(true);
btnTranslate.setOnAction(event -> {
GridPane root = new GridPane();
TextField f1 = new TextField();
TextField f2 = new TextField();
Button translate = new Button("Translate");
root.add(new Label("X value"), 0, 0);
root.add(f1, 1, 0);
root.add(new Label("Y value"), 0, 1);
root.add(f2, 1, 1);
root.add(translate, 1, 2);
Stage s = new Stage();
s.setScene(new Scene(root, 300, 200));
s.show();
translate.setOnAction(event2 -> {
this.translateX = Integer.valueOf(f1.getText());
this.translateY = Integer.valueOf(f2.getText());
grpDrawArea.setTranslateX(grpDrawArea.getTranslateX() + this.translateX);
grpDrawArea.setTranslateY(grpDrawArea.getTranslateY() + this.translateY);
s.close();
});
});
btnTranslateReset.setOnAction(event -> {
grpDrawArea.setTranslateX(0);
grpDrawArea.setTranslateY(0);
});
btnZoomIn.setOnAction(event -> {
grpDrawArea.setScaleX(grpDrawArea.getScaleX() + 0.05);
grpDrawArea.setScaleY(grpDrawArea.getScaleY() + 0.05);
});
btnZoomOut.setOnAction(event -> {
grpDrawArea.setScaleX(grpDrawArea.getScaleX() - 0.05);
grpDrawArea.setScaleY(grpDrawArea.getScaleY() - 0.05);
});
btnZoomReset.setOnAction(event -> {
grpDrawArea.setScaleX(1);
grpDrawArea.setScaleY(1);
});
}
/**
* Initializes the button on the left side that are used to draw the graph.
*/
private void initLeftControlpanelDraw() {
disableGraphUIElements(true);
btnDraw.setOnAction(event -> {
System.out.printf("[%s] Drawing graph...%n", Thread.currentThread().getName());
int centerNode = 0;
int maxDepth = 0;
try {
centerNode = Integer.parseInt(txtCenterNode.getText());
maxDepth = Integer.parseInt(txtMaxDrawDepth.getText());
} catch (NumberFormatException e) {
Alerts.warning("Input is not a number, try again with a number as input.").show();
}
if (graphController.getGraph().contains(centerNode)) {
this.graphController.clear();
this.graphController.draw(centerNode, maxDepth);
System.out.printf("[%s] Graph drawn.%n", Thread.currentThread().getName());
} else {
Alerts.warning("The centernode is not a existing node, "
+ "try again with a number that exists as a node.").show();
}
});
btnDrawRandom.setOnAction(event -> {
int randomNodeID = (int) Math.ceil(Math.random() * this.graphController.getGraph().size());
txtCenterNode.setText(Integer.toString(randomNodeID));
btnDraw.fire();
});
btnBookmark.setOnAction(event -> buttonBookmark());
txtMaxDrawDepth.textProperty().addListener(new NumbersOnlyListener(txtMaxDrawDepth));
txtMaxDrawDepth.setText(INITIAL_MAX_DRAW_DEPTH);
txtCenterNode.textProperty().addListener(new NumbersOnlyListener(txtCenterNode));
txtCenterNode.setText(INITIAL_CENTER_NODE);
}
/**
* {@link ChangeListener} to make a {@link TextField} only accept numbers.
*/
private class NumbersOnlyListener implements ChangeListener<String> {
private final TextField tf;
/**
* Constructor for the Listener.
* @param tf {@link TextField} is the text field on which the listener listens
*/
NumbersOnlyListener(TextField tf) {
this.tf = tf;
}
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (!newValue.matches("\\d")) {
tf.setText(newValue.replaceAll("[^\\d]", ""));
}
}
}
/**
* Handles the events of the bookmark button.
*/
private void buttonBookmark() {
try {
FXMLLoader loader = new FXMLLoader(ProgrammingLife.class.getResource("/CreateBookmarkWindow.fxml"));
AnchorPane page = loader.load();
GuiCreateBookmarkController gc = loader.getController();
gc.setGuiController(this);
gc.setText(txtCenterNode.getText(), txtMaxDrawDepth.getText());
Scene scene = new Scene(page);
Stage bookmarkDialogStage = new Stage();
bookmarkDialogStage.setResizable(false);
bookmarkDialogStage.setScene(scene);
bookmarkDialogStage.setTitle("Create Bookmark");
bookmarkDialogStage.initOwner(ProgrammingLife.getStage());
bookmarkDialogStage.showAndWait();
} catch (IOException e) {
Alerts.error("This bookmark cannot be created.").show();
}
}
/**
* Initialises the mouse events.
*/
private void initMouse() {
grpDrawArea.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> {
orgSceneX = event.getSceneX();
orgSceneY = event.getSceneY();
orgTranslateX = ((Group) (event.getSource())).getTranslateX();
orgTranslateY = ((Group) (event.getSource())).getTranslateY();
});
grpDrawArea.addEventHandler(MouseEvent.MOUSE_DRAGGED, event -> {
if (event.isAltDown()) {
((Group) (event.getSource())).setTranslateX(orgTranslateX + event.getSceneX() - orgSceneX);
((Group) (event.getSource())).setTranslateY(orgTranslateY + event.getSceneY() - orgSceneY);
}
});
grpDrawArea.addEventHandler(ScrollEvent.SCROLL, event -> {
if (event.isAltDown()) {
grpDrawArea.setScaleX(grpDrawArea.getScaleX() + event.getDeltaY() / 250);
grpDrawArea.setScaleY(grpDrawArea.getScaleY() + event.getDeltaY() / 250);
}
});
}
/**
* Initialises the Console.
* @return the ConsoleView to print to.
*/
private ConsoleView initConsole() {
final ConsoleView console = new ConsoleView(Charset.forName("UTF-8"));
AnchorPane root = new AnchorPane(console);
Stage st = new Stage();
st.setScene(new Scene(root, 500, 500, Color.GRAY));
st.setMinWidth(500);
st.setMinHeight(250);
AnchorPane.setBottomAnchor(console, 0.d);
AnchorPane.setTopAnchor(console, 0.d);
AnchorPane.setRightAnchor(console, 0.d);
AnchorPane.setLeftAnchor(console, 0.d);
btnToggle.setOnAction(event -> {
if (btnToggle.isSelected()) {
st.show();
} else {
st.close();
}
});
st.show();
btnToggle.setSelected(true);
root.visibleProperty().bind(btnToggle.selectedProperty());
System.setOut(console.getOut());
return console;
}
private ProgressBar getProgressBar() {
return this.progressBar;
}
/**
* Sets the text field for drawing the graph.
* @param center The center node
* @param radius The radius of the subgraph
*/
void setText(int center, int radius) {
txtCenterNode.setText(String.valueOf(center));
txtMaxDrawDepth.setText(String.valueOf(radius));
}
public File getFile() {
return this.file;
}
public void setFile(File file) {
this.file = file;
}
GraphController getGraphController() {
return this.graphController;
}
}
|
package redis.clients.jedis;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.util.Hashing;
import redis.clients.util.Pool;
/**
* "sentinel" ,
*
*
* @author hailin0@yeah.net
* @createDate 2016715
*
*/
public class ShardedJedisSentinelPool extends Pool<ShardedJedis> {
private final Logger log = Logger.getLogger(getClass().getName());
private GenericObjectPoolConfig poolConfig;
/**
* sentinel sentinelmaster
*/
private Set<MasterListener> masterListeners;
/**
* master
*
*/
private volatile Map<String, HostAndPort> localMasterRoute = new ConcurrentHashMap<String, HostAndPort>();
/**
* sentinelmaster
*/
private int retrySentinel = 5;
private int connectionTimeout;
private int soTimeout;
private int database;
private String password;
/**
*
* @param masters
* @param sentinels
*/
public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels) {
this(masters, sentinels, new GenericObjectPoolConfig());
}
public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig) {
this(masters, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT);
}
public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, int soTimeout) {
this(masters, sentinels, poolConfig, soTimeout, 5);
}
public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
GenericObjectPoolConfig poolConfig, int soTimeout, int retrySentinel) {
this(masters, sentinels, poolConfig, soTimeout, retrySentinel, Protocol.DEFAULT_TIMEOUT,
null, Protocol.DEFAULT_DATABASE);
}
public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, int soTimeout, int retrySentinel,
int connectionTimeout, final String password, final int database) {
this.poolConfig = poolConfig;
this.soTimeout = soTimeout;
this.retrySentinel = retrySentinel;
this.connectionTimeout = connectionTimeout;
this.password = password;
this.database = database;
this.masterListeners = new HashSet<MasterListener>(sentinels.size());
Map<String, HostAndPort> newMasterRoute = initSentinels(sentinels, masters);
initPool(newMasterRoute);
}
/**
* newMasterRoute
*
* @param newMasterRoute
*/
private void initPool(Map<String, HostAndPort> newMasterRoute) {
if (!equals(localMasterRoute, newMasterRoute)) {
List<JedisShardInfo> shardMasters = makeShardInfoList(newMasterRoute);
initPool(poolConfig, new ShardedJedisFactory(shardMasters, Hashing.MURMUR_HASH, null));
localMasterRoute.putAll(newMasterRoute);
}
}
/**
* ShardedJedis
*
*/
@Override
public ShardedJedis getResource() {
ShardedJedis jedis = null;
try{
jedis = super.getResource();
}catch(Exception e){
e.printStackTrace();
}
if(jedis!=null)
jedis.setDataSource(this);
return jedis;
}
/**
* ShardedJedisPool
*
* @deprecated starting from Jedis 3.0 this method will not be exposed. Resource cleanup should be done using @see
* {@link redis.clients.jedis.Jedis#close()}
*/
@Override
@Deprecated
public void returnBrokenResource(final ShardedJedis resource) {
if (resource != null) {
returnBrokenResourceObject(resource);
}
}
/**
* ShardedJedisPool
*
* @deprecated starting from Jedis 3.0 this method will not be exposed. Resource cleanup should be done using @see
* {@link redis.clients.jedis.Jedis#close()}
*/
@Override
@Deprecated
public void returnResource(final ShardedJedis resource) {
if (resource != null) {
resource.resetState();
returnResourceObject(resource);
}
}
/**
* close
*/
public void destroy() {
for (MasterListener m : masterListeners) {
m.shutdown();
}
super.destroy();
}
/**
*
*
* @param localMasterRoute
* @param MasterRoute
* @return
*/
private boolean equals(Map<String, HostAndPort> localMasterRoute,
Map<String, HostAndPort> newMasterRoute) {
if (localMasterRoute != null && newMasterRoute != null) {
if (localMasterRoute.size() == newMasterRoute.size()) {
Set<String> keySet = newMasterRoute.keySet();
for (String key : keySet) {
if (!localMasterRoute.get(key).equals(newMasterRoute.get(key))) {
return false;
}
}
return true;
}
}
return false;
}
/**
*
*
* @return
*/
private List<HostAndPort> getCurrentHostMaster() {
return toHostAndPort(localMasterRoute);
}
/**
*
* @param routingTable
* @return
*/
private List<HostAndPort> toHostAndPort(Map<String, HostAndPort> routingTable) {
return new ArrayList<HostAndPort>(routingTable.values());
}
/**
*
* @param masterAddr
* @return
*/
private HostAndPort toHostAndPort(List<String> masterAddr) {
String host = masterAddr.get(0);
int port = Integer.parseInt(masterAddr.get(1));
return new HostAndPort(host, port);
}
/**
* JedisShardInfo
*
* @param newMasterRoute
* @return
*/
private List<JedisShardInfo> makeShardInfoList(Map<String, HostAndPort> newMasterRoute) {
List<JedisShardInfo> shardMasters = new ArrayList<JedisShardInfo>();
Set<Entry<String, HostAndPort>> entrySet = newMasterRoute.entrySet();
StringBuilder info = new StringBuilder();
for (Entry<String, HostAndPort> entry : entrySet) {
/**
* master-name(entry.getKey())JedisShardInfoname
* <p>
* masterhash,redis.clients.util.Sharded.getShard(String key)
*/
JedisShardInfo jedisShardInfo = new JedisShardInfo(entry.getValue().getHost(), entry
.getValue().getPort(), soTimeout, entry.getKey());
jedisShardInfo.setPassword(password);
shardMasters.add(jedisShardInfo);
info.append(entry.getKey());
info.append(":");
info.append(entry.getValue().toString());
info.append(" ");
}
log.info("Created ShardedJedisPool to master at [" + info.toString() + "]");
return shardMasters;
}
/**
* Sentinelsmaster
*
* @param sentinels
* @param masters
* @return
*/
private Map<String, HostAndPort> initSentinels(Set<String> sentinels, final List<String> masters) {
log.info("Trying to find all master from available Sentinels...");
Map<String, HostAndPort> MasterRoute = new LinkedHashMap<String, HostAndPort>();
for (String masterName : masters) {
HostAndPort master = MasterRoute.get(masterName);
// master
if (null != master) {
continue;
}
boolean fetched = false;
boolean sentinelAvailable = false;
int sentinelRetryCount = 0;
while (!fetched && sentinelRetryCount < retrySentinel) {
for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel.split(":")));
log.fine("Connecting to Sentinel " + hap);
Jedis jedis = null;
try {
jedis = new Jedis(hap.getHost(), hap.getPort());
// sentinelmasterNamemaster-host
List<String> masterAddr = jedis.sentinelGetMasterAddrByName(masterName);
// connected to sentinel...
sentinelAvailable = true;
if (masterAddr == null || masterAddr.size() != 2) {
log.warning("Can not get master addr, master name: " + masterName
+ ". Sentinel: " + hap + ".");
continue;
}
// masterName-master
master = toHostAndPort(masterAddr);
log.fine("Found Redis master at " + master);
MasterRoute.put(masterName, master);
fetched = true;
jedis.disconnect();
break;
} catch (JedisConnectionException e) {
log.warning("Cannot connect to sentinel running @ " + hap
+ ". Trying next one.");
}finally{
try{
if(jedis != null){
jedis.disconnect();
}
}catch(Exception e1){
e1.printStackTrace();
}
}
}
if (null == master) {
try {
if (sentinelAvailable) {
// can connect to sentinel, but master name seems to not
// monitored
throw new JedisException("Can connect to sentinel, but " + masterName
+ " seems to be not monitored...");
} else {
log.severe("All sentinels down, cannot determine where is "
+ masterName
+ " master is running... sleeping 1000ms, Will try again.");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
fetched = false;
sentinelRetryCount++;
}
}
// Try sentinelRetry times.
if (!fetched && sentinelRetryCount >= retrySentinel) {
log.severe("All sentinels down and try " + sentinelRetryCount + " times, Abort.");
throw new JedisConnectionException("Cannot connect all sentinels, Abort.");
}
}
log.info("Redis master running at " + MasterRoute.size()
+ ", starting Sentinel listeners...");
for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel.split(":")));
MasterListener masterListener = new MasterListener(masters, hap.getHost(),
hap.getPort());
// whether MasterListener threads are alive or not, process can be stopped
masterListener.setDaemon(true);
masterListeners.add(masterListener);
masterListener.start();
}
return MasterRoute;
}
/**
*
* mastersentinelmaster
*
* @author hailin0@yeah.net
* @createDate 2016715
*
*/
protected class MasterListener extends Thread {
protected List<String> masters;
protected String host;
protected int port;
protected long subscribeRetryWaitTimeMillis = 5000;
protected volatile Jedis j;
protected AtomicBoolean running = new AtomicBoolean(false);
protected MasterListener() {
}
public MasterListener(List<String> masters, String host, int port) {
super(String.format("MasterListener-%s-[%s:%d]", masters, host, port));
this.masters = masters;
this.host = host;
this.port = port;
}
public MasterListener(List<String> masters, String host, int port,
long subscribeRetryWaitTimeMillis) {
this(masters, host, port);
this.subscribeRetryWaitTimeMillis = subscribeRetryWaitTimeMillis;
}
public void run() {
running.set(true);
while (running.get()) {
// Sentineltry-catch.
try {
j = new Jedis(host, port);
// master
j.subscribe(new MasterChengeProcessor(this.masters, this.host, this.port),
"+switch-master");
} catch (JedisConnectionException e) {
if (running.get()) {
log.severe("Lost connection to Sentinel at " + host + ":" + port
+ ". Sleeping 5000ms and retrying.");
try {
Thread.sleep(subscribeRetryWaitTimeMillis);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
log.fine("Unsubscribing from Sentinel at " + host + ":" + port);
}
}
}
}
public void shutdown() {
try {
log.fine("Shutting down listener on " + host + ":" + port);
running.set(false);
// This isn't good, the Jedis object is not thread safe
if (j != null) {
j.disconnect();
}
} catch (Exception e) {
log.log(Level.SEVERE, "Caught exception while shutting down: ", e);
}
}
}
/**
* master
*/
private ConcurrentHashMap<String, HostAndPort> updatePoolLock = new ConcurrentHashMap<String, HostAndPort>();
/**
*
* master
*
* @author hailin0@yeah.net
* @createDate 2016715
*
*/
protected class MasterChengeProcessor extends JedisPubSub {
protected List<String> masters;
protected String host;
protected int port;
/**
* @param masters
* @param host
* @param port
*/
public MasterChengeProcessor(List<String> masters, String host, int port) {
super();
this.masters = masters;
this.host = host;
this.port = port;
}
/*
* (non-Javadoc)
*
* @see redis.clients.jedis.JedisPubSub#onMessage(java.lang.String, java.lang.String)
*/
@Override
public void onMessage(String channel, String message) {
masterChengeProcessor(channel, message);
}
/**
* master
*/
private void masterChengeProcessor(String channel, String message) {
/**
* messagemaster-name old-master-host old-master-port new-master-host new-master-port
* <p>
* master1 192.168.1.112 6380 192.168.1.111 6379
*/
log.fine("Sentinel " + host + ":" + port + " published: " + message + ".");
String[] switchMasterMsg = message.split(" ");
if (switchMasterMsg.length > 3) {
String chengeMasterName = switchMasterMsg[0];
HostAndPort newHostMaster = toHostAndPort(Arrays.asList(switchMasterMsg[3],
switchMasterMsg[4]));
boolean lock = lock(chengeMasterName, newHostMaster);
try {
if (lock) {
Map<String, HostAndPort> newMasterRoute = new LinkedHashMap<String, HostAndPort>(
localMasterRoute);
newMasterRoute.put(chengeMasterName, newHostMaster);
log.info("Sentinel " + host + ":" + port + " start update...");
synchronized (MasterChengeProcessor.class) {
// pool
initPool(newMasterRoute);
}
} else {
StringBuilder info = new StringBuilder();
for (String masterName : masters) {
info.append(masterName);
info.append(",");
}
log.fine("Ignoring message on +switch-master for master name "
+ switchMasterMsg[0] + ", our monitor master name are [" + info
+ "]");
}
} finally {
if (lock) {
unLock(chengeMasterName, newHostMaster);
}
}
} else {
log.severe("Invalid message received on Sentinel " + host + ":" + port
+ " on channel +switch-master: " + message);
}
}
/**
* 1.sentinelmaster-slave,master
* <p>
* 2.masterip
* <p>
* 3.mastermasterlock
* <p>
*
* @param chengeMasterName master-name
* @param newHostMaster master
* @return
*/
private boolean lock(String chengeMasterName, HostAndPort newHostMaster) {
int index = masters.indexOf(chengeMasterName);
if (index == -1) {
return false;
}
HostAndPort currentHostAndPort = localMasterRoute.get(chengeMasterName);
if (newHostMaster.equals(currentHostAndPort)) {
log.info("Sentinel " + host + ":" + port + " update " + chengeMasterName
+ " failure! because Has been updated.");
return false;
}
String key = String.format("%s-%s", chengeMasterName, newHostMaster);
HostAndPort putIfAbsent = updatePoolLock.putIfAbsent(key, newHostMaster);
if (null != putIfAbsent && newHostMaster.equals(putIfAbsent)) {
log.info("Sentinel " + host + ":" + port + " lock " + chengeMasterName
+ " failure! because Has been lock.");
return false;
}
log.info("Sentinel " + host + ":" + port + " lock " + chengeMasterName
+ " success! key:" + key);
return true;
}
/**
*
*
* @param chengeMasterName
* @param newHostMaster
*/
private void unLock(String chengeMasterName, HostAndPort newHostMaster) {
String key = String.format("%s-%s", chengeMasterName, newHostMaster);
updatePoolLock.remove(key);
log.info("Sentinel " + host + ":" + port + " unlock " + chengeMasterName + " success.");
}
}
/**
*
* ShardedJedis
*
* @author hailin0@yeah.net
* @createDate 2016715
*
*/
protected class ShardedJedisFactory implements PooledObjectFactory<ShardedJedis> {
private List<JedisShardInfo> shards;
private Hashing algo;
private Pattern keyTagPattern;
public ShardedJedisFactory(List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {
this.shards = shards;
this.algo = algo;
this.keyTagPattern = keyTagPattern;
}
public PooledObject<ShardedJedis> makeObject() throws Exception {
ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern);
return new DefaultPooledObject<ShardedJedis>(jedis);
}
public void destroyObject(PooledObject<ShardedJedis> pooledShardedJedis) throws Exception {
final ShardedJedis shardedJedis = pooledShardedJedis.getObject();
for (Jedis jedis : shardedJedis.getAllShards()) {
try {
try {
jedis.quit();
} catch (Exception e) {
}
jedis.disconnect();
} catch (Exception e) {
}
}
}
public boolean validateObject(PooledObject<ShardedJedis> pooledShardedJedis) {
try {
ShardedJedis jedis = pooledShardedJedis.getObject();
for (Jedis shard : jedis.getAllShards()) {
if (!shard.ping().equals("PONG")) {
return false;
}
}
return true;
} catch (Exception ex) {
return false;
}
}
public void activateObject(PooledObject<ShardedJedis> p) throws Exception {
}
public void passivateObject(PooledObject<ShardedJedis> p) throws Exception {
}
}
}
|
package techreborn.init.recipes;
import com.google.common.base.CaseFormat;
import net.minecraft.init.Blocks;
import net.minecraft.init.Enchantments;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import reborncore.common.registration.RebornRegistry;
import reborncore.common.registration.impl.ConfigRegistry;
import reborncore.common.util.OreUtil;
import reborncore.common.util.RebornCraftingHelper;
import reborncore.common.util.StringUtils;
import techreborn.Core;
import techreborn.blocks.BlockStorage;
import techreborn.blocks.BlockStorage2;
import techreborn.compat.CompatManager;
import techreborn.config.ConfigTechReborn;
import techreborn.init.IC2Duplicates;
import techreborn.init.ModBlocks;
import techreborn.init.ModItems;
import techreborn.items.DynamicCell;
import techreborn.items.ItemUpgrades;
import techreborn.items.ingredients.ItemDustsSmall;
import techreborn.items.ingredients.ItemNuggets;
import techreborn.items.ingredients.ItemParts;
import techreborn.lib.ModInfo;
@RebornRegistry(modID = ModInfo.MOD_ID)
public class CraftingTableRecipes extends RecipeMethods {
@ConfigRegistry(config = "recipes", category = "crafting", key = "cellRecipe", comment = "Enables the new thermal expansion compatible cell recipe")
public static boolean newCellRecipe = true;
public static void init() {
registerCompressionRecipes();
registerMixedMetalIngotRecipes();
registerShapeless(BlockStorage2.getStorageBlockByName("iridium_reinforced_stone", 1), "stone", "plateIridiumAlloy");
registerShapeless(BlockStorage2.getStorageBlockByName("iridium_reinforced_tungstensteel", 1), BlockStorage2.getStorageBlockByName("tungstensteel", 1), "plateIridium");
registerShapeless(BlockStorage2.getStorageBlockByName("iridium_reinforced_tungstensteel", 1), BlockStorage2.getStorageBlockByName("iridium_reinforced_stone", 1), getMaterialObject("tungstensteel", Type.INGOT));
registerShapeless(getStack(ModBlocks.RUBBER_PLANKS, 4), getStack(ModBlocks.RUBBER_LOG));
if(newCellRecipe){
registerShaped(DynamicCell.getEmptyCell(16), " T ", "TGT", " T ", 'T', "ingotTin", 'G', "paneGlass"); // Blame thermal expansion for making gears have the same recipe
} else {
registerShaped(DynamicCell.getEmptyCell(16), " T ", "T T", " T ", 'T', "ingotTin");
}
registerShaped(getStack(ModBlocks.REFINED_IRON_FENCE), "RRR", "RRR", 'R', "ingotRefinedIron");
registerShaped(getStack(ModBlocks.REINFORCED_GLASS, 7), "GAG", "GGG", "GAG", 'A', "plateAdvancedAlloy", 'G', "blockGlass");
registerShaped(getStack(ModBlocks.REINFORCED_GLASS, 7), "GGG", "AGA", "GGG", 'A', "plateAdvancedAlloy", 'G', "blockGlass");
// Tools and devices
registerShaped(getStack(ModItems.WRENCH), "BNB", "NBN", " B ", 'B', "ingotBronze", 'N', "nuggetBronze");
registerShaped(getStack(ModItems.TREE_TAP), " S ", "PPP", "P ", 'S', "stickWood", 'P', "plankWood");
registerShaped(getStack(ModItems.ELECTRIC_TREE_TAP), "TB", " ", 'T', getStack(ModItems.TREE_TAP), 'B', "reBattery");
registerShaped(getStack(ModItems.NANOSABER), "DC ", "DC ", "GLG", 'L', "lapotronCrystal", 'C', "plateCarbon", 'D', "plateDiamond", 'G', getMaterialObject("glowstone", Type.SMALL_DUST));
ItemStack rockCutter = getStack(ModItems.ROCK_CUTTER);
rockCutter.addEnchantment(Enchantments.SILK_TOUCH, 1);
registerShaped(rockCutter, "DT ", "DT ", "DCB", 'D', "dustDiamond", 'T', "ingotTitanium", 'C', "circuitBasic", 'B', "reBattery");
registerShaped(getStack(ModItems.STEEL_DRILL), " S ", "SCS", "SBS", 'S', "ingotSteel", 'C', "circuitBasic", 'B', "reBattery");
registerShaped(getStack(ModItems.DIAMOND_DRILL), " D ", "DCD", "TST", 'D', "gemDiamond", 'C', "circuitAdvanced", 'S', getStack(ModItems.STEEL_DRILL, 1, OreDictionary.WILDCARD_VALUE), 'T', "ingotTitanium");
registerShaped(getStack(ModItems.ADVANCED_DRILL), " I ", "NCN", "OAO", 'I', "plateIridiumAlloy", 'N', "nuggetIridium", 'A', getStack(ModItems.DIAMOND_DRILL, 1, OreDictionary.WILDCARD_VALUE), 'C', "circuitMaster", 'O', getMaterial("overclock", Type.UPGRADE));
registerShaped(getStack(ModItems.STEEL_CHAINSAW), " SS", "SCS", "BS ", 'S', "ingotSteel", 'C', "circuitBasic", 'B', "reBattery");
registerShaped(getStack(ModItems.DIAMOND_CHAINSAW), " DD", "TCD", "ST ", 'D', "gemDiamond", 'C', "circuitAdvanced", 'S', getStack(ModItems.STEEL_CHAINSAW, 1, OreDictionary.WILDCARD_VALUE), 'T', "ingotTitanium");
registerShaped(getStack(ModItems.ADVANCED_CHAINSAW), " NI", "OCN", "DO ", 'I', "plateIridiumAlloy", 'N', "nuggetIridium", 'D', getStack(ModItems.DIAMOND_CHAINSAW, 1, OreDictionary.WILDCARD_VALUE), 'C', "circuitMaster", 'O', getMaterial("overclock", Type.UPGRADE));
registerShaped(getStack(ModItems.STEEL_JACKHAMMER), "SBS", "SCS", " S ", 'S', "ingotSteel", 'C', "circuitBasic", 'B', "reBattery");
registerShaped(getStack(ModItems.DIAMOND_JACKHAMMER), "DSD", "TCT", " D ", 'D', "gemDiamond", 'C', "circuitAdvanced", 'S', getStack(ModItems.STEEL_JACKHAMMER, 1, OreDictionary.WILDCARD_VALUE), 'T', "ingotTitanium");
registerShaped(getStack(ModItems.ADVANCED_JACKHAMMER), "NDN", "OCO", " I ", 'I', "plateIridiumAlloy", 'N', "nuggetIridium", 'D', getStack(ModItems.DIAMOND_JACKHAMMER, 1, OreDictionary.WILDCARD_VALUE), 'C', "circuitMaster", 'O', getMaterial("overclock", Type.UPGRADE));
registerShaped(getStack(ModItems.CLOAKING_DEVICE), "CIC", "IOI", "CIC", 'C', "ingotChrome", 'I', "plateIridiumAlloy", 'O', getStack(ModItems.LAPOTRONIC_ORB));
registerShaped(getStack(ModItems.LAPOTRONIC_ORB_PACK), "FOF", "SPS", "FIF", 'F', "circuitMaster", 'O', getStack(ModItems.LAPOTRONIC_ORB), 'S', "craftingSuperconductor", 'I', "ingotIridium", 'P', getStack(ModItems.LITHIUM_BATTERY_PACK));
if (ConfigTechReborn.enableGemArmorAndTools) {
addToolAndArmourRecipes(getStack(ModItems.RUBY_SWORD), getStack(ModItems.RUBY_PICKAXE), getStack(ModItems.RUBY_AXE), getStack(ModItems.RUBY_HOE), getStack(ModItems.RUBY_SPADE), getStack(ModItems.RUBY_HELMET), getStack(ModItems.RUBY_CHESTPLATE), getStack(ModItems.RUBY_LEGGINGS), getStack(ModItems.RUBY_BOOTS), "gemRuby");
addToolAndArmourRecipes(getStack(ModItems.SAPPHIRE_SWORD), getStack(ModItems.SAPPHIRE_PICKAXE), getStack(ModItems.SAPPHIRE_AXE), getStack(ModItems.SAPPHIRE_HOE), getStack(ModItems.SAPPHIRE_SPADE), getStack(ModItems.SAPPHIRE_HELMET), getStack(ModItems.SAPPHIRE_CHSTPLATE), getStack(ModItems.SAPPHIRE_LEGGINGS), getStack(ModItems.SAPPHIRE_BOOTS), "gemSapphire");
addToolAndArmourRecipes(getStack(ModItems.PERIDOT_SWORD), getStack(ModItems.PERIDOT_PICKAXE), getStack(ModItems.PERIDOT_AXE), getStack(ModItems.PERIDOT_HOE), getStack(ModItems.PERIDOT_SAPPHIRE), getStack(ModItems.PERIDOT_HELMET), getStack(ModItems.PERIDOT_CHESTPLATE), getStack(ModItems.PERIDOT_LEGGINGS), getStack(ModItems.PERIDOT_BOOTS), "gemPeridot");
addToolAndArmourRecipes(getStack(ModItems.BRONZE_SWORD), getStack(ModItems.BRONZE_PICKAXE), getStack(ModItems.BRONZE_AXE), getStack(ModItems.BRONZE_HOE), getStack(ModItems.BRONZE_SPADE), getStack(ModItems.BRONZE_HELMET), getStack(ModItems.BRONZE_CHESTPLATE), getStack(ModItems.BRONZE_LEGGINGS), getStack(ModItems.BRONZE_BOOTS), "ingotBronze");
}
//Upgrades
registerShaped(ItemUpgrades.getUpgradeByName("energy_storage"), "PPP", "WBW", "PCP", 'P', "plankWood", 'W', getStack(IC2Duplicates.CABLE_ICOPPER), 'C', "circuitBasic", 'B', "reBattery");
registerShaped(ItemUpgrades.getUpgradeByName("overclock"), "TTT", "WCW", 'T', getMaterial("coolant_simple", Type.PART), 'W', getStack(IC2Duplicates.CABLE_ICOPPER), 'C', "circuitBasic");
registerShaped(ItemUpgrades.getUpgradeByName("overclock", 2), " T ", "WCW", 'T', getMaterial("helium_coolant_triple", Type.PART), 'W', getStack(IC2Duplicates.CABLE_ICOPPER), 'C', "circuitBasic");
registerShaped(ItemUpgrades.getUpgradeByName("overclock", 2), " T ", "WCW", 'T', getMaterial("nak_coolant_simple", Type.PART), 'W', getStack(IC2Duplicates.CABLE_ICOPPER), 'C', "circuitBasic");
registerShaped(ItemUpgrades.getUpgradeByName("transformer"), "GGG", "WTW", "GCG", 'G', "blockGlass", 'W', getStack(IC2Duplicates.CABLE_IGOLD), 'C', "circuitBasic", 'T', getStack(IC2Duplicates.MVT));
//Machines
registerShaped(getMaterial("standard", 4, Type.MACHINE_CASING), "RRR", "CAC", "RRR", 'R', "ingotRefinedIron", 'C', "circuitBasic", 'A', "machineBlockBasic");
registerShaped(getMaterial("standard", 4, Type.MACHINE_CASING), "RRR", "CAC", "RRR", 'R', "plateIron", 'C', "circuitBasic", 'A', "machineBlockBasic");
registerShaped(getMaterial("standard", 4, Type.MACHINE_CASING), "RRR", "CAC", "RRR", 'R', "plateAluminum", 'C', "circuitBasic", 'A', "machineBlockBasic");
registerShaped(getMaterial("reinforced", 4, Type.MACHINE_CASING), "RRR", "CAC", "RRR", 'R', "plateSteel", 'C', "circuitAdvanced", 'A', "machineBlockAdvanced");
registerShaped(getMaterial("reinforced", 1, Type.MACHINE_CASING), "RRR", "CAC", "RRR", 'R', "plateSteel", 'C', "circuitAdvanced", 'A', getMaterial("standard", Type.MACHINE_CASING));
registerShaped(getMaterial("advanced", 4, Type.MACHINE_CASING), "RRR", "CAC", "RRR", 'R', "plateChrome", 'C', "circuitElite", 'A', "machineBlockElite");
registerShaped(getMaterial("advanced", 1, Type.MACHINE_CASING), "RRR", "CAC", "RRR", 'R', "plateChrome", 'C', "circuitElite", 'A', getMaterial("reinforced", Type.MACHINE_CASING));
registerShaped(getStack(ModBlocks.SEMI_FLUID_GENERATOR), "III", "IHI", "CGC", 'I', "plateIron", 'H', "glassReinforced", 'C', "circuitBasic", 'G', getStack(IC2Duplicates.GENERATOR));
registerShaped(getStack(ModBlocks.SEMI_FLUID_GENERATOR), "III", "IHI", "CGC", 'I', "plateAluminum", 'H', "glassReinforced", 'C', "circuitBasic", 'G', getStack(IC2Duplicates.GENERATOR));
registerShaped(getStack(ModBlocks.DIESEL_GENERATOR), "III", "I I", "CGC", 'I', "ingotRefinedIron", 'C', "circuitBasic", 'G', getStack(IC2Duplicates.GENERATOR));
registerShaped(getStack(ModBlocks.DIESEL_GENERATOR), "III", "I I", "CGC", 'I', "plateAluminum", 'C', "circuitBasic", 'G', getStack(IC2Duplicates.GENERATOR));
registerShaped(getStack(ModBlocks.GAS_TURBINE), "IAI", "WGW", "IAI", 'I', "plateInvar", 'A', "circuitAdvanced", 'W', getStack(ModBlocks.WIND_MILL), 'G', "glassReinforced");
registerShaped(getStack(ModBlocks.GAS_TURBINE), "IAI", "WGW", "IAI", 'I', "plateAluminum", 'A', "circuitAdvanced", 'W', getStack(ModBlocks.WIND_MILL), 'G', "glassReinforced");
registerShaped(getStack(ModBlocks.THERMAL_GENERATOR), "III", "IRI", "CGC", 'I', "plateInvar", 'R', "glassReinforced", 'G', getStack(IC2Duplicates.GENERATOR), 'C', "circuitBasic");
registerShaped(getStack(ModBlocks.WIND_MILL), " I ", " G ", " I ", 'I', "plateMagnalium", 'G', getStack(IC2Duplicates.GENERATOR));
registerShaped(getStack(ModBlocks.WIND_MILL), "IGI", 'I', "plateMagnalium", 'G', getStack(IC2Duplicates.GENERATOR));
registerShaped(getStack(ModBlocks.LIGHTNING_ROD), "CAC", "ACA", "CAC", 'A', getStack(ModBlocks.MACHINE_CASINGS, 1, 2), 'C', "circuitMaster");
registerShaped(getStack(ModBlocks.IRON_ALLOY_FURNACE), "III", "F F", "III", 'I', "ingotRefinedIron", 'F', getStack(IC2Duplicates.IRON_FURNACE));
registerShaped(getStack(ModBlocks.INDUSTRIAL_ELECTROLYZER), "RER", "CFC", "RER", 'R', "plateIron", 'E', getStack(IC2Duplicates.EXTRACTOR), 'C', "circuitAdvanced", 'F', "machineBlockAdvanced");
registerShaped(getStack(ModBlocks.INDUSTRIAL_CENTRIFUGE), "RCR", "AEA", "RCR", 'R', "ingotRefinedIron", 'E', getStack(IC2Duplicates.EXTRACTOR), 'A', "machineBlockAdvanced", 'C', "circuitAdvanced");
registerShaped(getStack(ModBlocks.INDUSTRIAL_CENTRIFUGE), "RCR", "AEA", "RCR", 'R', "plateAluminum", 'E', getStack(IC2Duplicates.EXTRACTOR), 'A', "machineBlockAdvanced", 'C', "circuitAdvanced");
registerShaped(getStack(ModBlocks.INDUSTRIAL_SAWMILL), "PAP", "SSS", "ACA", 'P', "ingotRefinedIron", 'A', "circuitAdvanced", 'S', getMaterial("diamond_saw_blade", Type.PART), 'C', "machineBlockAdvanced");
registerShaped(getStack(ModBlocks.INDUSTRIAL_BLAST_FURNACE), "CHC", "HBH", "FHF", 'H', getMaterial("cupronickelHeatingCoil", Type.PART), 'C', "circuitAdvanced", 'B', "machineBlockAdvanced", 'F', getStack(IC2Duplicates.ELECTRICAL_FURNACE));
registerShaped(getStack(ModBlocks.INDUSTRIAL_GRINDER), "ECG", "HHH", "CBC", 'E', getStack(ModBlocks.INDUSTRIAL_ELECTROLYZER), 'H', "craftingDiamondGrinder", 'C', "circuitAdvanced", 'B', "machineBlockAdvanced", 'G', getStack(IC2Duplicates.GRINDER));
registerShaped(getStack(ModBlocks.IMPLOSION_COMPRESSOR), "ABA", "CPC", "ABA", 'A', getMaterialObject("advancedAlloy", Type.INGOT), 'C', "circuitAdvanced", 'B', "machineBlockAdvanced", 'P', getStack(IC2Duplicates.COMPRESSOR));
registerShaped(getStack(ModBlocks.VACUUM_FREEZER), "SPS", "CGC", "SPS", 'S', "plateSteel", 'C', "circuitAdvanced", 'G', "glassReinforced", 'P', getStack(IC2Duplicates.EXTRACTOR));
registerShaped(getStack(ModBlocks.DISTILLATION_TOWER), "CMC", "PBP", "EME", 'E', getStack(ModBlocks.INDUSTRIAL_ELECTROLYZER), 'M', "circuitMaster", 'B', "machineBlockElite", 'C', getStack(ModBlocks.INDUSTRIAL_CENTRIFUGE), 'P', getStack(IC2Duplicates.EXTRACTOR));
registerShaped(getStack(ModBlocks.CHEMICAL_REACTOR), "IMI", "CPC", "IEI", 'I', "plateInvar", 'C', "circuitAdvanced", 'M', getStack(IC2Duplicates.EXTRACTOR), 'P', getStack(IC2Duplicates.COMPRESSOR), 'E', getStack(IC2Duplicates.EXTRACTOR));
registerShaped(getStack(ModBlocks.ROLLING_MACHINE), "PCP", "MBM", "PCP", 'P', getStack(Blocks.PISTON), 'C', "circuitAdvanced", 'M', getStack(IC2Duplicates.COMPRESSOR), 'B', "machineBlockBasic");
registerShaped(getStack(ModBlocks.AUTO_CRAFTING_TABLE), "MPM", "PCP", "MPM", 'M', "circuitAdvanced", 'C', "workbench", 'P', "plateIron");
registerShaped(getStack(ModBlocks.CHARGE_O_MAT), "ETE", "COC", "EAE", 'E', "circuitMaster", 'T', "energyCrystal", 'C', "chest", 'O', getStack(ModItems.LAPOTRONIC_ORB), 'A', "machineBlockAdvanced");
registerShaped(getStack(ModBlocks.ALLOY_SMELTER), " C ", "FMF", " ", 'C', "circuitBasic", 'F', getStack(IC2Duplicates.ELECTRICAL_FURNACE), 'M', "machineBlockBasic");
registerShaped(getStack(ModBlocks.INTERDIMENSIONAL_SU), "PAP", "ACA", "PAP", 'P', "plateIridiumAlloy", 'C', "chestEnder", 'A', getStack(ModBlocks.ADJUSTABLE_SU));
registerShaped(getStack(ModBlocks.ADJUSTABLE_SU), "LLL", "LCL", "LLL", 'L', getStack(ModItems.LAPOTRONIC_ORB), 'C', "energyCrystal");
registerShaped(getStack(ModBlocks.LAPOTRONIC_SU), " L ", "CBC", " M ", 'L', getStack(IC2Duplicates.LVT), 'C', "circuitAdvanced", 'M', getStack(IC2Duplicates.MVT), 'B', getStack(ModBlocks.LSU_STORAGE));
registerShaped(getStack(ModBlocks.LSU_STORAGE), "LLL", "LCL", "LLL", 'L', "blockLapis", 'C', "circuitBasic");
registerShaped(getStack(ModBlocks.SCRAPBOXINATOR), "ICI", "DSD", "ICI", 'S', getStack(ModItems.SCRAP_BOX), 'C', "circuitBasic", 'I', "plateIron", 'D', "dirt");
registerShaped(getStack(ModBlocks.FUSION_CONTROL_COMPUTER), "CCC", "PTP", "CCC", 'P', "energyCrystal", 'T', getStack(ModBlocks.FUSION_COIL), 'C', "circuitMaster");
registerShaped(getStack(ModBlocks.FUSION_COIL), "CSC", "NAN", "CRC", 'A', getStack(ModBlocks.MACHINE_CASINGS, 1, 2), 'N', getMaterial("nichromeHeatingCoil", Type.PART), 'C', "circuitMaster", 'S', "craftingSuperconductor", 'R', IC2Duplicates.IRIDIUM_NEUTRON_REFLECTOR.getStackBasedOnConfig());
registerShaped(getStack(ModBlocks.DIGITAL_CHEST), "PPP", "PDP", "PCP", 'P', "plateAluminum", 'D', getMaterial("data_orb", Type.PART), 'C', getMaterial("computer_monitor", Type.PART));
registerShaped(getStack(ModBlocks.DIGITAL_CHEST), "PPP", "PDP", "PCP", 'P', "plateSteel", 'D', getMaterial("data_orb", Type.PART), 'C', getMaterial("computer_monitor", Type.PART));
registerShaped(getStack(ModBlocks.MATTER_FABRICATOR), "ETE", "AOA", "ETE", 'E', "circuitMaster", 'T', getStack(IC2Duplicates.EXTRACTOR), 'A', "machineBlockElite", 'O', getStack(ModItems.LAPOTRONIC_ORB));
registerShaped(getStack(ModBlocks.COMPUTER_CUBE), "OMC", "MFM", "CMO", 'O', getMaterial("data_orb", Type.PART), 'M', getMaterial("computer_monitor", Type.PART), 'C', "circuitMaster", 'F', "machineBlockAdvanced");
registerShaped(getStack(ModBlocks.PLAYER_DETECTOR, true), " D ", "CFC", " D ", 'D', "circuitStorage", 'C', "circuitAdvanced", 'F', getStack(ModBlocks.COMPUTER_CUBE));
registerShaped(getStack(ModBlocks.DRAGON_EGG_SYPHON), "CTC", "PSP", "CBC", 'C', "circuitMaster", 'T', getStack(IC2Duplicates.MFE), 'P', "plateIridiumAlloy", 'S', "craftingSuperconductor", 'B', getStack(ModItems.LAPOTRONIC_ORB));
registerShaped(getStack(ModBlocks.PLASMA_GENERATOR), "PPP", "PTP", "CGC", 'P', "plateTungstensteel", 'T', getStack(IC2Duplicates.HVT), 'C', "circuitMaster", 'G', getStack(IC2Duplicates.GENERATOR));
registerShaped(getStack(ModBlocks.SOLAR_PANEL, 1, 0), "DLD", "LDL", "CGC", 'D', "dustCoal", 'L', "paneGlass", 'G', getStack(IC2Duplicates.GENERATOR), 'C', "circuitBasic");
registerShaped(getStack(ModBlocks.SOLAR_PANEL, 1, 1), "DLD", "LDL", "CPC", 'D', "dustCoal", 'L', "blockGlass", 'C', "circuitAdvanced", 'P', getStack(ModBlocks.SOLAR_PANEL, 1, 0));
registerShaped(getStack(ModBlocks.SOLAR_PANEL, 1, 1), "DLD", "LDL", "CPC", 'D', "dustCoal", 'L', "blockGlass", 'C', "circuitAdvanced", 'P', "machineBlockBasic");
registerShaped(getStack(ModBlocks.SOLAR_PANEL, 1, 2), "DLD", "LDL", "CPC", 'D', "dustDiamond", 'L', "blockGlass", 'C', "circuitAdvanced", 'P', getStack(ModBlocks.SOLAR_PANEL, 1, 1));
registerShaped(getStack(ModBlocks.SOLAR_PANEL, 1, 2), "DLD", "LDL", "CPC", 'D', "dustDiamond", 'L', "blockGlass", 'C', "circuitAdvanced", 'P', "machineBlockBasic");
registerShaped(getStack(ModBlocks.SOLAR_PANEL, 1, 3), "DLD", "LDL", "CPC", 'D', "dustDiamond", 'L', "glassReinforced", 'C', "circuitAdvanced", 'P', getStack(ModBlocks.SOLAR_PANEL, 1, 2));
registerShaped(getStack(ModBlocks.SOLAR_PANEL, 1, 3), "DLD", "LDL", "CPC", 'D', "dustDiamond", 'L', "glassReinforced", 'C', "circuitAdvanced", 'P', "machineBlockAdvanced");
registerShaped(getStack(ModBlocks.SOLAR_PANEL, 1, 4), "DLD", "LDL", "CPC", 'D', "dustDiamond", 'L', "glassReinforced", 'C', "circuitMaster", 'P', getStack(ModBlocks.SOLAR_PANEL, 1, 3));
registerShaped(getStack(ModBlocks.SOLAR_PANEL, 1, 4), "DLD", "LDL", "CPC", 'D', "dustDiamond", 'L', "glassReinforced", 'C', "circuitMaster", 'P', "machineBlockElite");
registerShaped(getStack(ModBlocks.ALARM, 1, 0), "ICI", "SRS", "ICI", 'I', "ingotIron", 'C', getMaterial("copper", Type.CABLE), 'S', getMaterial("insulatedcopper", Type.CABLE), 'R', "blockRedstone" );
registerShaped(getStack(ModBlocks.FLUID_REPLICATOR), "PCP", "CFC", "ESR", 'P', "plateTungstensteel", 'F', "machineBlockElite", 'C', "circuitMaster", 'E', getStack(ModBlocks.INDUSTRIAL_ELECTROLYZER), 'S', "craftingSuperconductor",'R', getStack(ModBlocks.CHEMICAL_REACTOR));
if (!IC2Duplicates.deduplicate()) {
registerShaped(getStack(IC2Duplicates.HVT), " H ", " M ", " H ", 'M', getStack(IC2Duplicates.MVT), 'H', getStack(IC2Duplicates.CABLE_IHV));
registerShaped(getStack(IC2Duplicates.MVT), " G ", " M ", " G ", 'M', "machineBlockBasic", 'G', getStack(IC2Duplicates.CABLE_IGOLD));
registerShaped(getStack(IC2Duplicates.LVT), "PWP", "CCC", "PPP", 'P', "plankWood", 'C', "ingotCopper", 'W', getStack(IC2Duplicates.CABLE_ICOPPER));
registerShaped(getStack(IC2Duplicates.BAT_BOX), "WCW", "BBB", "WWW", 'W', "plankWood", 'B', "reBattery", 'C', getStack(IC2Duplicates.CABLE_ICOPPER));
registerShaped(getStack(IC2Duplicates.MFE), "GEG", "EME", "GEG", 'M', "machineBlockBasic", 'E', "energyCrystal", 'G', getStack(IC2Duplicates.CABLE_IGOLD));
registerShaped(getStack(IC2Duplicates.MFSU), "LAL", "LML", "LOL", 'A', "circuitAdvanced", 'L', "lapotronCrystal", 'M', getStack(IC2Duplicates.MFE), 'O', "machineBlockAdvanced");
registerShaped(getStack(IC2Duplicates.COMPRESSOR), "S S", "SCS", "SMS", 'C', "circuitBasic", 'M', "machineBlockBasic", 'S', "stone");
registerShaped(getStack(IC2Duplicates.ELECTRICAL_FURNACE), " C ", "RFR", " ", 'C', "circuitBasic", 'F', getStack(IC2Duplicates.IRON_FURNACE), 'R', "dustRedstone");
registerShaped(getStack(IC2Duplicates.RECYCLER), " E ", "DCD", "GDG", 'D', "dirt", 'C', getStack(IC2Duplicates.COMPRESSOR), 'G', "dustGlowstone", 'E', "circuitBasic");
registerShaped(getStack(IC2Duplicates.IRON_FURNACE), "III", "I I", "III", 'I', "ingotIron");
registerShaped(getStack(IC2Duplicates.IRON_FURNACE), " I ", "I I", "IFI", 'I', "ingotIron", 'F', getStack(Blocks.FURNACE));
registerShaped(getStack(IC2Duplicates.EXTRACTOR), "TMT", "TCT", " ", 'T', getStack(ModItems.TREE_TAP, true), 'M', "machineBlockBasic", 'C', "circuitBasic");
registerShaped(getStack(IC2Duplicates.GRINDER), "FFF", "SMS", " C ", 'F', Items.FLINT, 'S', getStack(Blocks.COBBLESTONE), 'M', getMaterial("machine", Type.MACHINE_FRAME), 'C', "circuitBasic");
registerShapeless(getStack(IC2Duplicates.FREQ_TRANSMITTER), getStack(IC2Duplicates.CABLE_ICOPPER), "circuitBasic");
registerShapeless(getStack(IC2Duplicates.GENERATOR), "reBattery", "machineBlockBasic", getStack(Blocks.FURNACE));
registerShaped(getStack(IC2Duplicates.WATER_MILL), "SWS", "WGW", "SWS", 'S', "stickWood", 'W', "plankWood", 'G', getStack(IC2Duplicates.GENERATOR));
}
if (!CompatManager.isQuantumStorageLoaded) {
registerShaped(getStack(ModBlocks.QUANTUM_CHEST), "DCD", "ATA", "DQD", 'D', getMaterial("dataOrb", Type.PART), 'C', getMaterial("computerMonitor", Type.PART), 'A', "machineBlockElite", 'Q', getStack(ModBlocks.DIGITAL_CHEST), 'T', getStack(IC2Duplicates.COMPRESSOR));
registerShaped(getStack(ModBlocks.QUANTUM_TANK), "EPE", "PCP", "EPE", 'P', "platePlatinum", 'E', "circuitAdvanced", 'C', getStack(ModBlocks.QUANTUM_CHEST));
}
//Lighting
registerShaped(getStack(ModBlocks.LAMP_INCANDESCENT), "GGG", "TCT", "GGG", 'G', "paneGlass", 'T', getMaterial("copper", Type.CABLE), 'C', getMaterial("carbon_fiber", Type.PART));
registerShaped(getStack(ModBlocks.LAMP_LED), "GGG", "TLT", "GGG", 'G', "paneGlass", 'T', getMaterial("tin", Type.CABLE), 'L', "dustGlowstone");
//Parts
registerShaped(getMaterial("iridium_alloy", Type.INGOT), "IAI", "ADA", "IAI", 'I', "ingotIridium", 'D', "dustDiamond", 'A', "plateAdvancedAlloy");
registerShaped(getStack(ModItems.RE_BATTERY), " W ", "TRT", "TRT", 'T', "ingotTin", 'R', "dustRedstone", 'W', getStack(IC2Duplicates.CABLE_ICOPPER));
registerShaped(getStack(ModItems.LITHIUM_BATTERY), " C ", "PFP", "PFP", 'F', getCell("lithium"), 'P', "plateAluminum", 'C', getStack(IC2Duplicates.CABLE_IGOLD));
registerShaped(getStack(ModItems.LITHIUM_BATTERY_PACK), "BCB", "BPB", "B B", 'B', getStack(ModItems.LITHIUM_BATTERY), 'P', "plateAluminum", 'C', "circuitAdvanced");
registerShaped(getStack(ModItems.ENERGY_CRYSTAL), "RRR", "RDR", "RRR", 'R', "dustRedstone", 'D', "gemDiamond");
registerShaped(getStack(ModItems.LAPOTRONIC_CRYSTAL), "LCL", "LEL", "LCL", 'L', "dyeBlue", 'E', "energyCrystal", 'C', "circuitBasic");
registerShaped(getStack(ModItems.LAPOTRONIC_ORB), "LLL", "LPL", "LLL", 'L', "lapotronCrystal", 'P', "plateIridiumAlloy");
registerShaped(getStack(ModItems.SCRAP_BOX), "SSS", "SSS", "SSS", 'S', getMaterial("scrap", Type.PART));
registerShaped(getMaterial("machine", Type.MACHINE_FRAME), "AAA", "A A", "AAA", 'A', "ingotRefinedIron");
registerShaped(getMaterial("advanced_machine", Type.MACHINE_FRAME), " C ", "AMA", " C ", 'A', "plateAdvancedAlloy", 'C', "plateCarbon", 'M', "machineBlockBasic");
registerShaped(getMaterial("highly_advanced_machine", Type.MACHINE_FRAME), "CTC", "TBT", "CTC", 'C', "plateChrome", 'T', "plateTitanium", 'B', "machineBlockAdvanced");
registerShaped(getMaterial("data_storage_circuit", Type.PART), "RGR", "LCL", "EEE", 'R', "dustRedstone", 'G', "dustGlowstone", 'L', "gemLapis", 'C', "circuitBasic", 'E', "plateEmerald");
registerShaped(getMaterial("data_control_circuit", Type.PART), "ADA", "DID", "ADA", 'I', "ingotIridium", 'A', "circuitAdvanced", 'D', "circuitStorage");
registerShaped(getMaterial("energy_flow_circuit", 4, Type.PART), "ATA", "LIL", "ATA", 'T', "ingotTungsten", 'I', "plateIridiumAlloy", 'A', "circuitAdvanced", 'L', "lapotronCrystal");
registerShaped(getMaterial("data_orb", Type.PART), "DDD", "DSD", "DDD", 'D', "circuitStorage", 'S', "circuitElite");
registerShaped(getMaterial("diamond_saw_blade", 4, Type.PART), "DSD", "S S", "DSD", 'D', "dustDiamond", 'S', "ingotSteel");
registerShaped(getMaterial("diamond_grinding_head", 2, Type.PART), "DSD", "SGS", "DSD", 'S', "ingotSteel", 'D', "dustDiamond", 'G', "gemDiamond");
registerShaped(getMaterial("tungsten_grinding_head", 2, Type.PART), "TST", "SBS", "TST", 'S', "ingotSteel", 'T', "ingotTungsten", 'B', "blockSteel");
registerShaped(getMaterial("computer_monitor", Type.PART), "ADA", "DGD", "ADA", 'D', "dye", 'A', "ingotAluminum", 'G', "paneGlass");
registerShaped(getMaterial("coolant_simple", 2, Type.PART), " T ", "TWT", " T ", 'T', "ingotTin", 'W', getStack(Items.WATER_BUCKET));
registerShaped(getMaterial("coolant_simple", 2, Type.PART), " T ", "TWT", " T ", 'T', "ingotTin", 'W', getCell("water"));
registerShaped(getMaterial("coolant_triple", Type.PART), "TTT", "CCC", "TTT", 'T', "ingotTin", 'C', getMaterial("coolant_simple", Type.PART));
registerShaped(getMaterial("coolant_six", Type.PART), "TCT", "TPT", "TCT", 'T', "ingotTin", 'C', getMaterial("coolant_triple", Type.PART), 'P', "plateCopper");
registerShaped(getMaterial("helium_coolant_simple", Type.PART), " T ", "TCT", " T ", 'T', "ingotTin", 'C', getCell("helium"));
registerShaped(getMaterial("helium_coolant_triple", Type.PART), "TTT", "CCC", "TTT", 'T', "ingotTin", 'C', getMaterial("helium_coolant_simple", Type.PART));
registerShaped(getMaterial("helium_coolant_six", Type.PART), "THT", "TCT", "THT", 'T', "ingotTin", 'C', "ingotCopper", 'H', getMaterial("helium_coolant_triple", Type.PART));
registerShaped(getMaterial("nak_coolant_simple", Type.PART), "TST", "PCP", "TST", 'T', "ingotTin", 'C', getMaterial("coolant_simple", Type.PART), 'S', getCell("sodium"), 'P', getCell("potassium"));
registerShaped(getMaterial("nak_coolant_simple", Type.PART), "TPT", "SCS", "TPT", 'T', "ingotTin", 'C', getMaterial("coolant_simple", Type.PART), 'S', getCell("sodium"), 'P', getCell("potassium"));
registerShaped(getMaterial("nak_coolant_triple", Type.PART), "TTT", "CCC", "TTT", 'T', "ingotTin", 'C', getMaterial("nak_coolant_simple", Type.PART));
registerShaped(getMaterial("nak_coolant_six", Type.PART), "THT", "TCT", "THT", 'T', "ingotTin", 'C', "ingotCopper", 'H', getMaterial("nak_coolant_triple", Type.PART));
registerShaped(getMaterial("super_conductor", 4, Type.PART), "CCC", "TIT", "EEE", 'E', "circuitMaster", 'C', getMaterial("heliumCoolantSimple", Type.PART), 'T', "ingotTungsten", 'I', "plateIridiumAlloy");
if (!IC2Duplicates.deduplicate()) {
registerShaped(getMaterial("copper", 6, Type.CABLE), "CCC", 'C', "ingotCopper");
registerShaped(getMaterial("tin", 9, Type.CABLE), "TTT", 'T', "ingotTin");
registerShaped(getMaterial("gold", 12, Type.CABLE), "GGG", 'G', "ingotGold");
registerShaped(getMaterial("hv", 12, Type.CABLE), "RRR", 'R', "ingotRefinedIron");
registerShaped(getMaterial("insulatedcopper", 6, Type.CABLE), "RRR", "CCC", "RRR", 'R', "itemRubber", 'C', "ingotCopper");
registerShaped(getMaterial("insulatedcopper", 6, Type.CABLE), "RCR", "RCR", "RCR", 'R', "itemRubber", 'C', "ingotCopper");
registerShapeless(getMaterial("insulatedcopper", Type.CABLE), "itemRubber", getMaterial("copper", Type.CABLE));
registerShaped(getMaterial("insulatedgold", 4, Type.CABLE), "RRR", "RGR", "RRR", 'R', "itemRubber", 'G', "ingotGold");
registerShapeless(getMaterial("insulatedgold", Type.CABLE), "itemRubber", "itemRubber", getMaterial("gold", Type.CABLE));
registerShaped(getMaterial("insulatedhv", 4, Type.CABLE), "RRR", "RIR", "RRR", 'R', "itemRubber", 'I', "ingotRefinedIron");
registerShapeless(getMaterial("insulatedhv", Type.CABLE), "itemRubber", "itemRubber", getMaterial("hv", Type.CABLE));
registerShaped(getMaterial("glassfiber", 4, Type.CABLE), "GGG", "RDR", "GGG", 'R', "dustRedstone", 'D', "gemDiamond", 'G', "blockGlass");
registerShaped(getMaterial("glassfiber", 4, Type.CABLE), "GGG", "RDR", "GGG", 'R', "dustRedstone", 'D', "dustDiamond", 'G', "blockGlass");
registerShaped(getMaterial("glassfiber", 3, Type.CABLE), "GGG", "RDR", "GGG", 'R', "dustRedstone", 'D', "gemRuby", 'G', "blockGlass");
registerShaped(getMaterial("glassfiber", 3, Type.CABLE), "GGG", "RDR", "GGG", 'R', "dustRedstone", 'D', "dustRuby", 'G', "blockGlass");
registerShaped(getMaterial("glassfiber", 6, Type.CABLE), "GGG", "RDR", "GGG", 'R', "ingotSilver", 'D', "gemDiamond", 'G', "blockGlass");
registerShaped(getMaterial("glassfiber", 6, Type.CABLE), "GGG", "RDR", "GGG", 'R', "ingotSilver", 'D', "dustDiamond", 'G', "blockGlass");
registerShaped(getMaterial("glassfiber", 8, Type.CABLE), "GGG", "RDR", "GGG", 'R', "ingotElectrum", 'D', "gemDiamond", 'G', "blockGlass");
registerShaped(getMaterial("glassfiber", 8, Type.CABLE), "GGG", "RDR", "GGG", 'R', "ingotElectrum", 'D', "dustDiamond", 'G', "blockGlass");
registerShaped(getMaterial("carbon_fiber", Type.PART), " C ", "C C", " C ", 'C', "dustCoal");
registerShaped(getMaterial("carbon_fiber", Type.PART), "CCC", "C C", "CCC", 'C', getCell("carbon"));
registerShapeless(getMaterial("carbon_mesh", Type.PART), getMaterial("carbon_fiber", Type.PART), getMaterial("carbon_fiber", Type.PART));
registerShaped(getMaterial("electronic_circuit", Type.PART), "WWW", "SRS", "WWW", 'R', "ingotRefinedIron", 'S', Items.REDSTONE, 'W', getStack(IC2Duplicates.CABLE_ICOPPER));
registerShaped(getMaterial("advanced_circuit", Type.PART), "RGR", "LCL", "RGR", 'R', "dustRedstone", 'G', "dustGlowstone", 'L', "gemLapis", 'C', "circuitBasic");
registerShaped(getMaterial("iridium_neutron_reflector", Type.PART), "PPP", "PIP", "PPP", 'P', "reflectorThick", 'I', "ingotIridium");
registerShaped(getMaterial("thick_neutron_reflector", Type.PART), " P ", "PCP", " P ", 'P', "reflectorBasic", 'C', getCell("Berylium"));
registerShaped(getMaterial("neutron_reflector", Type.PART), "TCT", "CPC", "TCT", 'T', "dustTin", 'C', "dustCoal", 'P', "plateCopper");
}
//UU-Matter
ItemStack uuStack = new ItemStack(ModItems.UU_MATTER);
registerShaped(getStack(Blocks.LOG, 8), " U ", " ", " ", 'U', uuStack);
registerShaped(getStack(Blocks.STONE, 16), " ", " U ", " ", 'U', uuStack);
registerShaped(getStack(Blocks.SNOW, 16), "U U", " ", " ", 'U', uuStack);
registerShaped(getStack(Blocks.GRASS, 16), " ", "U ", "U ", 'U', uuStack);
registerShaped(getStack(Blocks.OBSIDIAN, 12), "U U", "U U", " ", 'U', uuStack);
registerShaped(getStack(Blocks.GLASS, 32), " U ", "U U", " U ", 'U', uuStack);
registerShaped(getStack(Items.DYE, 32, 3), "UU ", " U", "UU ", 'U', uuStack);
registerShaped(getStack(Blocks.GLOWSTONE, 8), " U ", "U U", "UUU", 'U', uuStack);
registerShaped(getStack(Blocks.CACTUS, 48), " U ", "UUU", "U U", 'U', uuStack);
registerShaped(getStack(Items.REEDS, 48), "U U", "U U", "U U", 'U', uuStack);
registerShaped(getStack(Blocks.VINE, 24), "U ", "U ", "U ", 'U', uuStack);
registerShaped(getStack(Items.SNOWBALL, 16), " ", " ", "UUU", 'U', uuStack);
registerShaped(getStack(Items.CLAY_BALL, 48), "UU ", "U ", "UU ", 'U', uuStack);
registerShaped(getStack(Blocks.WATERLILY, 64), "U U", " U ", " U ", 'U', uuStack);
registerShaped(getStack(Items.GUNPOWDER, 15), "UUU", "U ", "UUU", 'U', uuStack);
registerShaped(getStack(Items.BONE, 32), "U ", "UU ", "U ", 'U', uuStack);
registerShaped(getStack(Items.FEATHER, 32), " U ", " U ", "U U", 'U', uuStack);
registerShaped(getStack(Items.DYE, 48), " UU", " UU", " U ", 'U', uuStack);
registerShaped(getStack(Items.ENDER_PEARL, 1), "UUU", "U U", " U ", 'U', uuStack);
registerShaped(getStack(Items.COAL, 5), " U", "U ", " U", 'U', uuStack);
registerShaped(getStack(Blocks.IRON_ORE, 2), "U U", " U ", "U U", 'U', uuStack);
registerShaped(getStack(Blocks.GOLD_ORE, 2), " U ", "UUU", " U ", 'U', uuStack);
registerShaped(getStack(Items.REDSTONE, 24), " ", " U ", "UUU", 'U', uuStack);
registerShaped(getStack(Items.DYE, 9, 4), " U ", " U ", " UU", 'U', uuStack);
registerShaped(getStack(Blocks.EMERALD_ORE, 1), "UU ", "U U", " UU", 'U', uuStack);
registerShaped(getStack(Items.EMERALD, 2), "UUU", "UUU", " U ", 'U', uuStack);
registerShaped(getStack(Items.DIAMOND, 1), "UUU", "UUU", "UUU", 'U', uuStack);
registerShaped(getMaterial("tin", 10, Type.DUST), " ", "U U", " U", 'U', uuStack);
registerShaped(getMaterial("copper", 10, Type.DUST), " U", "U U", " ", 'U', uuStack);
registerShaped(getMaterial("lead", 14, Type.DUST), "UUU", "UUU", "U ", 'U', uuStack);
registerShaped(getMaterial("platinum", Type.DUST), " U", "UUU", "UUU", 'U', uuStack);
registerShaped(getMaterial("tungsten", Type.DUST), "U ", "UUU", "UUU", 'U', uuStack);
registerShaped(getMaterial("titanium", 2, Type.DUST), "UUU", " U ", " U ", 'U', uuStack);
registerShaped(getMaterial("aluminum", 16, Type.DUST), " U ", " U ", "UUU", 'U', uuStack);
registerShaped(getMaterial("iridium", 1, Type.ORE), "UUU", " U ", "UUU", 'U', uuStack);
for (String part : ItemParts.types) {
if (part.endsWith("Gear")) {
registerShaped(getMaterial(part, Type.PART), " O ", "OIO", " O ", 'I', getStack(Items.IRON_INGOT), 'O', "ingot" + StringUtils.toFirstCapital(part.replace("Gear", "")));
}
}
registerShaped(new ItemStack(ModBlocks.RUBBER_LOG_SLAB_HALF, 6), "WWW", 'W', new ItemStack(ModBlocks.RUBBER_PLANKS));
registerShaped(new ItemStack(ModBlocks.RUBBER_LOG_STAIR, 4), "W ", "WW ", "WWW", 'W', new ItemStack(ModBlocks.RUBBER_PLANKS));
Core.logHelper.info("Crafting Table Recipes Added");
}
static void registerCompressionRecipes() {
for (String name : BlockStorage.types) {
if (OreUtil.hasIngot(name)) {
registerShaped(BlockStorage.getStorageBlockByName(name), "AAA", "AAA", "AAA", 'A', "ingot" + StringUtils.toFirstCapital(name));
registerShapeless(getMaterial(name, 9, Type.INGOT), BlockStorage.getStorageBlockByName(name));
} else if (OreUtil.hasGem(name)) {
registerShaped(BlockStorage.getStorageBlockByName(name), "AAA", "AAA", "AAA", 'A', "gem" + StringUtils.toFirstCapital(name));
registerShapeless(getMaterial(name, 9, Type.GEM), BlockStorage.getStorageBlockByName(name));
}
}
for (String block : BlockStorage2.types){
block = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, block);
if (OreUtil.hasIngot(block)) {
registerShaped(BlockStorage2.getStorageBlockByName(block), "AAA", "AAA", "AAA", 'A', "ingot" + StringUtils.toFirstCapital(block));
registerShapeless(getMaterial(block, 9, Type.INGOT), BlockStorage2.getStorageBlockByName(block));
} else if (OreUtil.hasGem(block)) {
registerShaped(BlockStorage2.getStorageBlockByName(block), "AAA", "AAA", "AAA", 'A', "gem" + StringUtils.toFirstCapital(block));
registerShapeless(getMaterial(block, 9, Type.GEM), BlockStorage2.getStorageBlockByName(block));
}
}
for (String name : ItemDustsSmall.types) {
if (name.equals(ModItems.META_PLACEHOLDER)) {
continue;
}
registerShapeless(getMaterial(name, 4, Type.SMALL_DUST), getMaterialObject(name, Type.DUST));
registerShapeless(getMaterial(name, Type.DUST), getMaterialObject(name, Type.SMALL_DUST), getMaterialObject(name, Type.SMALL_DUST), getMaterialObject(name, Type.SMALL_DUST), getMaterialObject(name, Type.SMALL_DUST));
}
for (String nuggets : ItemNuggets.types) {
if (nuggets.equals(ModItems.META_PLACEHOLDER) || nuggets.equalsIgnoreCase("diamond"))
continue;
registerShapeless(getMaterial(nuggets, 9, Type.NUGGET), CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "ingot_" + nuggets));
registerShaped(getMaterial(nuggets, Type.INGOT), "NNN", "NNN", "NNN", 'N', CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "nugget_" + nuggets));
}
registerShapeless(getMaterial("diamond", 9, Type.NUGGET), "gemDiamond");
registerShaped(getStack(Items.DIAMOND), "NNN", "NNN", "NNN", 'N', "nuggetDiamond");
}
static void registerMixedMetalIngotRecipes() {
if (!IC2Duplicates.deduplicate()) {
registerMixedMetal("ingotRefinedIron", "ingotBronze", "ingotTin", 2);
registerMixedMetal("ingotRefinedIron", "ingotBronze", "ingotZinc", 2);
registerMixedMetal("ingotNickel", "ingotBronze", "ingotTin", 3);
registerMixedMetal("ingotNickel", "ingotBronze", "ingotZinc", 3);
registerMixedMetal("ingotNickel", "ingotBronze", "ingotAluminum", 4);
registerMixedMetal("ingotInvar", "ingotBronze", "ingotTin", 4);
registerMixedMetal("ingotInvar", "ingotBronze", "ingotZinc", 4);
registerMixedMetal("ingotInvar", "ingotBronze", "ingotAluminum", 5);
registerMixedMetal("ingotTitanium", "ingotBronze", "ingotTin", 5);
registerMixedMetal("ingotTitanium", "ingotBronze", "ingotZinc", 5);
registerMixedMetal("ingotTungsten", "ingotBronze", "ingotTin", 5);
registerMixedMetal("ingotTungsten", "ingotBronze", "ingotZinc", 5);
registerMixedMetal("ingotTitanium", "ingotBronze", "ingotAluminum", 6);
registerMixedMetal("ingotTungsten", "ingotBronze", "ingotAluminum", 6);
registerMixedMetal("ingotTungstensteel", "ingotBronze", "ingotTin", 8);
registerMixedMetal("ingotTungstensteel", "ingotBronze", "ingotZinc", 8);
registerMixedMetal("ingotTungstensteel", "ingotBronze", "ingotAluminum", 9);
}
}
static void registerMixedMetal(String top, String middle, String bottom, int amount) {
if (!OreDictionary.doesOreNameExist(top)) {
return;
}
if (!OreDictionary.doesOreNameExist(middle)) {
return;
}
if (!OreDictionary.doesOreNameExist(bottom)) {
return;
}
if (top.equals("ingotRefinedIron") && IC2Duplicates.deduplicate()) {
registerShaped(getMaterial("mixed_metal", amount, Type.INGOT), "TTT", "MMM", "BBB", 'T', "ingotRefinedIron", 'M', middle, 'B', bottom);
} else {
registerShaped(getMaterial("mixed_metal", amount, Type.INGOT), "TTT", "MMM", "BBB", 'T', top, 'M', middle, 'B', bottom);
}
if (middle.equals("ingotBronze")) {
registerMixedMetal(top, "ingotBrass", bottom, amount);
}
if (bottom.equals("ingotAluminum")) {
registerMixedMetal(top, middle, "ingotAluminium", amount);
}
}
static void registerShaped(ItemStack output, Object... inputs) {
RebornCraftingHelper.addShapedOreRecipe(output, inputs);
}
static void registerShapeless(ItemStack output, Object... inputs) {
RebornCraftingHelper.addShapelessOreRecipe(output, inputs);
}
static void addToolAndArmourRecipes(ItemStack sword,
ItemStack pickaxe,
ItemStack axe,
ItemStack hoe,
ItemStack spade,
ItemStack helmet,
ItemStack chestplate,
ItemStack leggings,
ItemStack boots,
String material) {
registerShaped(sword, "G", "G", "S", 'S', Items.STICK, 'G', material);
registerShaped(pickaxe, "GGG", " S ", " S ", 'S', Items.STICK, 'G', material);
registerShaped(axe, "GG", "GS", " S", 'S', Items.STICK, 'G', material);
registerShaped(hoe, "GG", " S", " S", 'S', Items.STICK, 'G', material);
registerShaped(spade, "G", "S", "S", 'S', Items.STICK, 'G', material);
registerShaped(helmet, "GGG", "G G", 'G', material);
registerShaped(chestplate, "G G", "GGG", "GGG", 'G', material);
registerShaped(leggings, "GGG", "G G", "G G", 'G', material);
registerShaped(boots, "G G", "G G", 'G', material);
}
}
|
package website.automate.waml.io.model.main;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonValue;
import website.automate.waml.io.model.main.action.Action;
import java.util.List;
import java.util.Objects;
@JsonPropertyOrder({"name", "precedence", "description", "fragment", "timeout", "when", "unless",
"report", "steps"})
public class Scenario {
private static final String FRAGMENT_PREFIX = "_";
private String name;
private String path;
private List<Action> steps;
@JsonIgnore
public String getName() {
return name;
}
@JsonValue
public List<Action> getSteps() {
return steps;
}
public void setSteps(List<Action> steps) {
this.steps = steps;
}
public void setName(String name) {
this.name = name;
}
@JsonIgnore
public boolean isFragment() {
return getName().startsWith(FRAGMENT_PREFIX);
}
@JsonIgnore
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Scenario scenario = (Scenario) o;
return Objects.equals(getName(), scenario.getName()) &&
Objects.equals(getPath(), scenario.getPath());
}
@Override
public int hashCode() {
return Objects.hash(getName(), getPath());
}
}
|
package zmaster587.advancedRocketry;
import net.minecraft.block.Block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.material.MaterialLiquid;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.StateMapperBase;
import net.minecraft.client.renderer.color.IBlockColor;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Biomes;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemBucket;
import net.minecraft.item.ItemDoor;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.stats.Achievement;
import net.minecraft.world.WorldType;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.common.AchievementPage;
import net.minecraftforge.common.ForgeChunkManager;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartedEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.event.FMLServerStoppedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.OreDictionary.OreRegisterEvent;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import zmaster587.advancedRocketry.achievements.ARAchivements;
import zmaster587.advancedRocketry.api.*;
import zmaster587.advancedRocketry.api.atmosphere.AtmosphereRegister;
import zmaster587.advancedRocketry.api.fuel.FuelRegistry;
import zmaster587.advancedRocketry.api.fuel.FuelRegistry.FuelType;
import zmaster587.advancedRocketry.api.satellite.SatelliteProperties;
import zmaster587.advancedRocketry.armor.ItemSpaceArmor;
import zmaster587.advancedRocketry.atmosphere.AtmosphereVacuum;
import zmaster587.advancedRocketry.block.BlockCharcoalLog;
import zmaster587.advancedRocketry.block.BlockCrystal;
import zmaster587.advancedRocketry.block.BlockDoor2;
import zmaster587.advancedRocketry.block.BlockElectricMushroom;
import zmaster587.advancedRocketry.block.BlockFluid;
import zmaster587.advancedRocketry.block.BlockHalfTile;
import zmaster587.advancedRocketry.block.BlockIntake;
import zmaster587.advancedRocketry.block.BlockLandingPad;
import zmaster587.advancedRocketry.block.BlockLaser;
import zmaster587.advancedRocketry.block.BlockLightSource;
import zmaster587.advancedRocketry.block.BlockLinkedHorizontalTexture;
import zmaster587.advancedRocketry.block.BlockMiningDrill;
import zmaster587.advancedRocketry.block.BlockPlanetSoil;
import zmaster587.advancedRocketry.block.BlockPress;
import zmaster587.advancedRocketry.block.BlockPressurizedFluidTank;
import zmaster587.advancedRocketry.block.BlockQuartzCrucible;
import zmaster587.advancedRocketry.block.BlockRedstoneEmitter;
import zmaster587.advancedRocketry.block.BlockRocketMotor;
import zmaster587.advancedRocketry.block.BlockRotatableModel;
import zmaster587.advancedRocketry.block.BlockSeat;
import zmaster587.advancedRocketry.block.BlockFuelTank;
import zmaster587.advancedRocketry.block.BlockStationModuleDockingPort;
import zmaster587.advancedRocketry.block.BlockTileNeighborUpdate;
import zmaster587.advancedRocketry.block.BlockTileRedstoneEmitter;
import zmaster587.advancedRocketry.block.BlockWarpCore;
import zmaster587.advancedRocketry.block.BlockWarpShipMonitor;
import zmaster587.advancedRocketry.block.cable.BlockDataCable;
import zmaster587.advancedRocketry.block.cable.BlockEnergyCable;
import zmaster587.advancedRocketry.block.cable.BlockLiquidPipe;
import zmaster587.advancedRocketry.block.multiblock.BlockARHatch;
import zmaster587.advancedRocketry.block.plant.BlockAlienLeaves;
import zmaster587.advancedRocketry.block.plant.BlockAlienSapling;
import zmaster587.advancedRocketry.block.plant.BlockAlienWood;
import zmaster587.advancedRocketry.block.BlockTorchUnlit;
import zmaster587.advancedRocketry.command.WorldCommand;
import zmaster587.advancedRocketry.common.CommonProxy;
import zmaster587.advancedRocketry.dimension.DimensionManager;
import zmaster587.advancedRocketry.dimension.DimensionProperties;
import zmaster587.advancedRocketry.entity.EntityDummy;
import zmaster587.advancedRocketry.entity.EntityLaserNode;
import zmaster587.advancedRocketry.entity.EntityRocket;
import zmaster587.advancedRocketry.entity.EntityStationDeployedRocket;
import zmaster587.advancedRocketry.event.BucketHandler;
import zmaster587.advancedRocketry.event.CableTickHandler;
import zmaster587.advancedRocketry.event.PlanetEventHandler;
import zmaster587.advancedRocketry.event.WorldEvents;
import zmaster587.advancedRocketry.integration.CompatibilityMgr;
import zmaster587.libVulpes.inventory.GuiHandler;
import zmaster587.libVulpes.items.ItemBlockMeta;
import zmaster587.libVulpes.items.ItemIngredient;
import zmaster587.libVulpes.items.ItemProjector;
import zmaster587.advancedRocketry.item.*;
import zmaster587.advancedRocketry.item.components.ItemJetpack;
import zmaster587.advancedRocketry.item.components.ItemPressureTank;
import zmaster587.advancedRocketry.item.components.ItemUpgrade;
import zmaster587.advancedRocketry.mission.MissionGasCollection;
import zmaster587.advancedRocketry.mission.MissionOreMining;
import zmaster587.advancedRocketry.network.PacketAtmSync;
import zmaster587.advancedRocketry.network.PacketBiomeIDChange;
import zmaster587.advancedRocketry.network.PacketDimInfo;
import zmaster587.advancedRocketry.network.PacketOxygenState;
import zmaster587.advancedRocketry.network.PacketSatellite;
import zmaster587.advancedRocketry.network.PacketSpaceStationInfo;
import zmaster587.advancedRocketry.network.PacketStationUpdate;
import zmaster587.advancedRocketry.network.PacketStellarInfo;
import zmaster587.advancedRocketry.network.PacketStorageTileUpdate;
import zmaster587.advancedRocketry.satellite.SatelliteBiomeChanger;
import zmaster587.advancedRocketry.satellite.SatelliteComposition;
import zmaster587.advancedRocketry.satellite.SatelliteDensity;
import zmaster587.advancedRocketry.satellite.SatelliteEnergy;
import zmaster587.advancedRocketry.satellite.SatelliteMassScanner;
import zmaster587.advancedRocketry.satellite.SatelliteOptical;
import zmaster587.advancedRocketry.satellite.SatelliteOreMapping;
import zmaster587.advancedRocketry.stations.SpaceObject;
import zmaster587.advancedRocketry.stations.SpaceObjectManager;
import zmaster587.advancedRocketry.tile.Satellite.TileEntitySatelliteControlCenter;
import zmaster587.advancedRocketry.tile.Satellite.TileSatelliteBuilder;
import zmaster587.advancedRocketry.tile.*;
import zmaster587.advancedRocketry.tile.cables.TileDataPipe;
import zmaster587.advancedRocketry.tile.cables.TileEnergyPipe;
import zmaster587.advancedRocketry.tile.cables.TileLiquidPipe;
import zmaster587.advancedRocketry.tile.hatch.TileDataBus;
import zmaster587.advancedRocketry.tile.hatch.TileSatelliteHatch;
import zmaster587.advancedRocketry.tile.infrastructure.TileEntityFuelingStation;
import zmaster587.advancedRocketry.tile.infrastructure.TileEntityMoniteringStation;
import zmaster587.advancedRocketry.tile.infrastructure.TileRocketFluidLoader;
import zmaster587.advancedRocketry.tile.infrastructure.TileRocketFluidUnloader;
import zmaster587.advancedRocketry.tile.infrastructure.TileRocketLoader;
import zmaster587.advancedRocketry.tile.infrastructure.TileRocketUnloader;
import zmaster587.advancedRocketry.tile.multiblock.*;
import zmaster587.advancedRocketry.tile.multiblock.energy.TileMicrowaveReciever;
import zmaster587.advancedRocketry.tile.multiblock.machine.TileChemicalReactor;
import zmaster587.advancedRocketry.tile.multiblock.machine.TileCrystallizer;
import zmaster587.advancedRocketry.tile.multiblock.machine.TileCuttingMachine;
import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectricArcFurnace;
import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectrolyser;
import zmaster587.advancedRocketry.tile.multiblock.machine.TileLathe;
import zmaster587.advancedRocketry.tile.multiblock.machine.TilePrecisionAssembler;
import zmaster587.advancedRocketry.tile.multiblock.machine.TileRollingMachine;
import zmaster587.advancedRocketry.tile.oxygen.TileCO2Scrubber;
import zmaster587.advancedRocketry.tile.oxygen.TileOxygenCharger;
import zmaster587.advancedRocketry.tile.oxygen.TileOxygenVent;
import zmaster587.advancedRocketry.tile.station.TileStationAltitudeController;
import zmaster587.advancedRocketry.tile.station.TileDockingPort;
import zmaster587.advancedRocketry.tile.station.TileLandingPad;
import zmaster587.advancedRocketry.tile.station.TileStationGravityController;
import zmaster587.advancedRocketry.tile.station.TileStationOrientationControl;
import zmaster587.advancedRocketry.tile.station.TileWarpShipMonitor;
import zmaster587.advancedRocketry.util.FluidColored;
import zmaster587.advancedRocketry.util.SealableBlockHandler;
import zmaster587.advancedRocketry.util.XMLPlanetLoader;
import zmaster587.advancedRocketry.world.biome.BiomeGenAlienForest;
import zmaster587.advancedRocketry.world.biome.BiomeGenCrystal;
import zmaster587.advancedRocketry.world.biome.BiomeGenDeepSwamp;
import zmaster587.advancedRocketry.world.biome.BiomeGenHotDryRock;
import zmaster587.advancedRocketry.world.biome.BiomeGenMoon;
import zmaster587.advancedRocketry.world.biome.BiomeGenMarsh;
import zmaster587.advancedRocketry.world.biome.BiomeGenOceanSpires;
import zmaster587.advancedRocketry.world.biome.BiomeGenSpace;
import zmaster587.advancedRocketry.world.biome.BiomeGenStormland;
import zmaster587.advancedRocketry.world.decoration.MapGenLander;
import zmaster587.advancedRocketry.world.ore.OreGenerator;
import zmaster587.advancedRocketry.world.provider.WorldProviderPlanet;
import zmaster587.advancedRocketry.world.provider.WorldProviderSpace;
import zmaster587.advancedRocketry.world.type.WorldTypePlanetGen;
import zmaster587.advancedRocketry.world.type.WorldTypeSpace;
import zmaster587.libVulpes.LibVulpes;
import zmaster587.libVulpes.api.LibVulpesBlocks;
import zmaster587.libVulpes.api.LibVulpesItems;
import zmaster587.libVulpes.api.material.AllowedProducts;
import zmaster587.libVulpes.api.material.MaterialRegistry;
import zmaster587.libVulpes.api.material.MixedMaterial;
import zmaster587.libVulpes.block.BlockAlphaTexture;
import zmaster587.libVulpes.block.BlockMeta;
import zmaster587.libVulpes.block.BlockTile;
import zmaster587.libVulpes.block.RotatableBlock;
import zmaster587.libVulpes.block.multiblock.BlockMultiBlockComponentVisible;
import zmaster587.libVulpes.block.multiblock.BlockMultiblockMachine;
import zmaster587.libVulpes.network.PacketHandler;
import zmaster587.libVulpes.network.PacketItemModifcation;
import zmaster587.libVulpes.recipe.NumberedOreDictStack;
import zmaster587.libVulpes.recipe.RecipesMachine;
import zmaster587.libVulpes.tile.TileMaterial;
import zmaster587.libVulpes.tile.multiblock.TileMultiBlock;
import zmaster587.libVulpes.util.InputSyncHandler;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.Logger;
import scala.Int;
@Mod(modid="advancedRocketry", name="Advanced Rocketry", version="%VERSION%", dependencies="required-after:libVulpes@[%LIBVULPESVERSION%,)")
public class AdvancedRocketry {
@SidedProxy(clientSide="zmaster587.advancedRocketry.client.ClientProxy", serverSide="zmaster587.advancedRocketry.common.CommonProxy")
public static CommonProxy proxy;
@Instance(value = Constants.modId)
public static AdvancedRocketry instance;
public static WorldType planetWorldType;
public static WorldType spaceWorldType;
public static CompatibilityMgr compat = new CompatibilityMgr();
public static Logger logger = Logger.getLogger(Constants.modId);
private static Configuration config;
private static final String BIOMECATETORY = "Biomes";
String[] sealableBlockWhileList;
//static {
// FluidRegistry.enableUniversalBucket(); // Must be called before preInit
public static MaterialRegistry materialRegistry = new MaterialRegistry();
private HashMap<AllowedProducts, HashSet<String>> modProducts = new HashMap<AllowedProducts, HashSet<String>>();
private static CreativeTabs tabAdvRocketry = new CreativeTabs("advancedRocketry") {
@Override
public Item getTabIconItem() {
return AdvancedRocketryItems.itemSatelliteIdChip;
}
};
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
//Init API
DimensionManager.planetWorldProvider = WorldProviderPlanet.class;
AdvancedRocketryAPI.atomsphereSealHandler = SealableBlockHandler.INSTANCE;
((SealableBlockHandler)AdvancedRocketryAPI.atomsphereSealHandler).loadDefaultData();
config = new Configuration(new File(event.getModConfigurationDirectory(), "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/advancedRocketry.cfg"));
config.load();
final String oreGen = "Ore Generation";
final String ROCKET = "Rockets";
final String MOD_INTERACTION = "Mod Interaction";
final String PLANET = "Planet";
final String ASTEROID = "Asteroid";
final String GAS_MINING = "GasMining";
final String PERFORMANCE = "Performance";
AtmosphereVacuum.damageValue = (int) config.get(Configuration.CATEGORY_GENERAL, "vacuumDamage", 1, "Amount of damage taken every second in a vacuum").getInt();
zmaster587.advancedRocketry.api.Configuration.buildSpeedMultiplier = (float) config.get(Configuration.CATEGORY_GENERAL, "buildSpeedMultiplier", 1f, "Multiplier for the build speed of the Rocket Builder (0.5 is twice as fast 2 is half as fast").getDouble();
zmaster587.advancedRocketry.api.Configuration.spaceDimId = config.get(Configuration.CATEGORY_GENERAL,"spaceStationId" , -2,"Dimension ID to use for space stations").getInt();
zmaster587.advancedRocketry.api.Configuration.enableOxygen = config.get(Configuration.CATEGORY_GENERAL, "EnableAtmosphericEffects", true, "If true, allows players being hurt due to lack of oxygen and allows effects from non-standard atmosphere types").getBoolean();
zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods = config.get(Configuration.CATEGORY_GENERAL, "makeMaterialsForOtherMods", true, "If true the machines from AdvancedRocketry will produce things like plates/rods for other mods even if Advanced Rocketry itself does not use the material (This can increase load time)").getBoolean();
zmaster587.advancedRocketry.api.Configuration.scrubberRequiresCartrige = config.get(Configuration.CATEGORY_GENERAL, "scrubberRequiresCartrige", true, "If true the Oxygen scrubbers require a consumable carbon collection cartridge").getBoolean();
zmaster587.advancedRocketry.api.Configuration.enableLaserDrill = config.get(Configuration.CATEGORY_GENERAL, "EnableLaserDrill", true, "Enables the laser drill machine").getBoolean();
zmaster587.advancedRocketry.api.Configuration.spaceLaserPowerMult = (float)config.get(Configuration.CATEGORY_GENERAL, "LaserDrillPowerMultiplier", 1d, "Power multiplier for the laser drill machine").getDouble();
zmaster587.advancedRocketry.api.Configuration.enableTerraforming = config.get(Configuration.CATEGORY_GENERAL, "EnableTerraforming", true,"Enables terraforming items and blocks").getBoolean();
zmaster587.advancedRocketry.api.Configuration.spaceSuitOxygenTime = config.get(Configuration.CATEGORY_GENERAL, "spaceSuitO2Buffer", 30, "Maximum time in minutes that the spacesuit's internal buffer can store O2 for").getInt();
zmaster587.advancedRocketry.api.Configuration.travelTimeMultiplier = (float)config.get(Configuration.CATEGORY_GENERAL, "warpTravelTime", 1f, "Multiplier for warp travel time").getDouble();
zmaster587.advancedRocketry.api.Configuration.maxBiomesPerPlanet = config.get(Configuration.CATEGORY_GENERAL, "maxBiomesPerPlanet", 5, "Maximum unique biomes per planet, -1 to disable").getInt();
zmaster587.advancedRocketry.api.Configuration.allowTerraforming = config.get(Configuration.CATEGORY_GENERAL, "allowTerraforming", false, "EXPERIMENTAL: If set to true allows contruction and usage of the terraformer. This is known to cause strange world generation after successful terraform").getBoolean();
zmaster587.advancedRocketry.api.Configuration.terraformingBlockSpeed = config.get(Configuration.CATEGORY_GENERAL, "biomeUpdateSpeed", 1, "How many blocks have the biome changed per tick. Large numbers can slow the server down", Integer.MAX_VALUE, 1).getInt();
zmaster587.advancedRocketry.api.Configuration.terraformSpeed = config.get(Configuration.CATEGORY_GENERAL, "terraformMult", 1f, "Multplier for terraforming speed").getDouble();
zmaster587.advancedRocketry.api.Configuration.terraformRequiresFluid = config.get(Configuration.CATEGORY_GENERAL, "TerraformerRequiresFluids", true).getBoolean();
zmaster587.advancedRocketry.api.Configuration.canPlayerRespawnInSpace = config.get(Configuration.CATEGORY_GENERAL, "allowPlanetRespawn", false, "If true players will respawn near beds on planets IF the spawn location is in a breathable atmosphere").getBoolean();
DimensionManager.dimOffset = config.getInt("minDimension", PLANET, 2, -127, 127, "Dimensions including and after this number are allowed to be made into planets");
zmaster587.advancedRocketry.api.Configuration.blackListAllVanillaBiomes = config.getBoolean("blackListVanillaBiomes", PLANET, false, "Prevents any vanilla biomes from spawning on planets");
zmaster587.advancedRocketry.api.Configuration.overrideGCAir = config.get(MOD_INTERACTION, "OverrideGCAir", true, "If true Galaciticcraft's air will be disabled entirely requiring use of Advanced Rocketry's Oxygen system on GC planets").getBoolean();
zmaster587.advancedRocketry.api.Configuration.fuelPointsPerDilithium = config.get(Configuration.CATEGORY_GENERAL, "pointsPerDilithium", 500, "How many units of fuel should each Dilithium Crystal give to warp ships", 1, 1000).getInt();
zmaster587.advancedRocketry.api.Configuration.electricPlantsSpawnLightning = config.get(Configuration.CATEGORY_GENERAL, "electricPlantsSpawnLightning", true, "Should Electric Mushrooms be able to spawn lightning").getBoolean();
zmaster587.advancedRocketry.api.Configuration.allowSawmillVanillaWood = config.get(Configuration.CATEGORY_GENERAL, "sawMillCutVanillaWood", true, "Should the cutting machine be able to cut vanilla wood into planks").getBoolean();
zmaster587.advancedRocketry.api.Configuration.automaticRetroRockets = config.get(ROCKET, "autoRetroRockets", true, "Setting to false will disable the retrorockets that fire automatically on reentry on both player and automated rockets").getBoolean();
zmaster587.advancedRocketry.api.Configuration.atmosphereHandleBitMask = config.get(PERFORMANCE, "atmosphereCalculationMethod", 0, "BitMask: 0: no threading, radius based; 1: threading, radius based (EXP); 2: no threading volume based; 3: threading volume based (EXP)").getInt();
zmaster587.advancedRocketry.api.Configuration.advancedVFX = config.get(PERFORMANCE, "advancedVFX", true, "Advanced visual effects").getBoolean();
zmaster587.advancedRocketry.api.Configuration.gasCollectionMult = config.get(GAS_MINING, "gasMissionMultiplier", 1.0, "Multiplier for the amount of time gas collection missions take").getDouble();
zmaster587.advancedRocketry.api.Configuration.asteroidMiningMult = config.get(ASTEROID, "miningMissionMultiplier", 1.0, "Multiplier changing how much total material is brought back from a mining mission").getDouble();
zmaster587.advancedRocketry.api.Configuration.standardAsteroidOres = config.get(ASTEROID, "standardOres", new String[] {"oreIron", "oreGold", "oreCopper", "oreTin", "oreRedstone"}, "List of oredictionary names of ores allowed to spawn in asteriods").getStringList();
//Client
zmaster587.advancedRocketry.api.Configuration.rocketRequireFuel = config.get(ROCKET, "rocketsRequireFuel", true, "Set to false if rockets should not require fuel to fly").getBoolean();
zmaster587.advancedRocketry.api.Configuration.rocketThrustMultiplier = config.get(ROCKET, "thrustMultiplier", 1f, "Multiplier for per-engine thrust").getDouble();
zmaster587.advancedRocketry.api.Configuration.fuelCapacityMultiplier = config.get(ROCKET, "fuelCapacityMultiplier", 1f, "Multiplier for per-tank capacity").getDouble();
//Copper Config
zmaster587.advancedRocketry.api.Configuration.generateCopper = config.get(oreGen, "GenerateCopper", true).getBoolean();
zmaster587.advancedRocketry.api.Configuration.copperClumpSize = config.get(oreGen, "CopperPerClump", 6).getInt();
zmaster587.advancedRocketry.api.Configuration.copperPerChunk = config.get(oreGen, "CopperPerChunk", 10).getInt();
//Tin Config
zmaster587.advancedRocketry.api.Configuration.generateTin = config.get(oreGen, "GenerateTin", true).getBoolean();
zmaster587.advancedRocketry.api.Configuration.tinClumpSize = config.get(oreGen, "TinPerClump", 6).getInt();
zmaster587.advancedRocketry.api.Configuration.tinPerChunk = config.get(oreGen, "TinPerChunk", 10).getInt();
zmaster587.advancedRocketry.api.Configuration.generateDilithium = config.get(oreGen, "generateDilithium", true).getBoolean();
zmaster587.advancedRocketry.api.Configuration.dilithiumClumpSize = config.get(oreGen, "DilithiumPerClump", 16).getInt();
zmaster587.advancedRocketry.api.Configuration.dilithiumPerChunk = config.get(oreGen, "DilithiumPerChunk", 1).getInt();
zmaster587.advancedRocketry.api.Configuration.dilithiumPerChunkMoon = config.get(oreGen, "DilithiumPerChunkLuna", 10).getInt();
zmaster587.advancedRocketry.api.Configuration.generateAluminum = config.get(oreGen, "generateAluminum", true).getBoolean();
zmaster587.advancedRocketry.api.Configuration.aluminumClumpSize = config.get(oreGen, "AluminumPerClump", 16).getInt();
zmaster587.advancedRocketry.api.Configuration.aluminumPerChunk = config.get(oreGen, "AluminumPerChunk", 1).getInt();
zmaster587.advancedRocketry.api.Configuration.generateRutile = config.get(oreGen, "GenerateRutile", true).getBoolean();
zmaster587.advancedRocketry.api.Configuration.rutileClumpSize = config.get(oreGen, "RutilePerClump", 3).getInt();
zmaster587.advancedRocketry.api.Configuration.rutilePerChunk = config.get(oreGen, "RutilePerChunk", 6).getInt();
sealableBlockWhileList = config.getStringList(Configuration.CATEGORY_GENERAL, "sealableBlockWhiteList", new String[] {}, "Mod:Blockname for example \"minecraft:chest\"");
//Satellite config
zmaster587.advancedRocketry.api.Configuration.microwaveRecieverMulitplier = 10*(float)config.get(Configuration.CATEGORY_GENERAL, "MicrowaveRecieverMulitplier", 1f, "Multiplier for the amount of energy produced by the microwave reciever").getDouble();
String str[] = config.getStringList("spaceLaserDimIdBlackList", Configuration.CATEGORY_GENERAL, new String[] {}, "Laser drill will not mine these dimension");
//Load laser dimid blacklists
for(String s : str) {
try {
zmaster587.advancedRocketry.api.Configuration.laserBlackListDims.add(Integer.parseInt(s));
} catch (NumberFormatException e) {
logger.warning("Invalid number \"" + s + "\" for laser dimid blacklist");
}
}
config.save();
//Register Packets
PacketHandler.INSTANCE.addDiscriminator(PacketDimInfo.class);
PacketHandler.INSTANCE.addDiscriminator(PacketSatellite.class);
PacketHandler.INSTANCE.addDiscriminator(PacketStellarInfo.class);
PacketHandler.INSTANCE.addDiscriminator(PacketItemModifcation.class);
PacketHandler.INSTANCE.addDiscriminator(PacketOxygenState.class);
PacketHandler.INSTANCE.addDiscriminator(PacketStationUpdate.class);
PacketHandler.INSTANCE.addDiscriminator(PacketSpaceStationInfo.class);
PacketHandler.INSTANCE.addDiscriminator(PacketAtmSync.class);
PacketHandler.INSTANCE.addDiscriminator(PacketBiomeIDChange.class);
PacketHandler.INSTANCE.addDiscriminator(PacketStorageTileUpdate.class);
//if(zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods)
MinecraftForge.EVENT_BUS.register(this);
SatelliteRegistry.registerSatellite("optical", SatelliteOptical.class);
SatelliteRegistry.registerSatellite("solar", SatelliteEnergy.class);
SatelliteRegistry.registerSatellite("density", SatelliteDensity.class);
SatelliteRegistry.registerSatellite("composition", SatelliteComposition.class);
SatelliteRegistry.registerSatellite("mass", SatelliteMassScanner.class);
SatelliteRegistry.registerSatellite("asteroidMiner", MissionOreMining.class);
SatelliteRegistry.registerSatellite("gasMining", MissionGasCollection.class);
SatelliteRegistry.registerSatellite("solarEnergy", SatelliteEnergy.class);
SatelliteRegistry.registerSatellite("oreScanner", SatelliteOreMapping.class);
SatelliteRegistry.registerSatellite("biomeChanger", SatelliteBiomeChanger.class);
AdvancedRocketryBlocks.blocksGeode = new Block(MaterialGeode.geode).setUnlocalizedName("geode").setCreativeTab(LibVulpes.tabLibVulpesOres).setHardness(6f).setResistance(2000F);
AdvancedRocketryBlocks.blocksGeode.setHarvestLevel("jackhammer", 2);
AdvancedRocketryBlocks.blockLaunchpad = new BlockLinkedHorizontalTexture(Material.ROCK).setUnlocalizedName("pad").setCreativeTab(tabAdvRocketry).setHardness(2f).setResistance(10f);
AdvancedRocketryBlocks.blockStructureTower = new BlockAlphaTexture(Material.ROCK).setUnlocalizedName("structuretower").setCreativeTab(tabAdvRocketry).setHardness(2f);
AdvancedRocketryBlocks.blockGenericSeat = new BlockSeat(Material.CLOTH).setUnlocalizedName("seat").setCreativeTab(tabAdvRocketry).setHardness(0.5f);
AdvancedRocketryBlocks.blockEngine = new BlockRocketMotor(Material.ROCK).setUnlocalizedName("rocket").setCreativeTab(tabAdvRocketry).setHardness(2f);
AdvancedRocketryBlocks.blockFuelTank = new BlockFuelTank(Material.ROCK).setUnlocalizedName("fuelTank").setCreativeTab(tabAdvRocketry).setHardness(2f);
AdvancedRocketryBlocks.blockSawBlade = new BlockRotatableModel(Material.ROCK).setCreativeTab(tabAdvRocketry).setUnlocalizedName("sawBlade").setHardness(2f);
AdvancedRocketryBlocks.blockMotor = new BlockRotatableModel(Material.ROCK).setCreativeTab(tabAdvRocketry).setUnlocalizedName("motor").setHardness(2f);
AdvancedRocketryBlocks.blockConcrete = new Block(Material.ROCK).setUnlocalizedName("concrete").setCreativeTab(tabAdvRocketry).setHardness(3f).setResistance(16f);
AdvancedRocketryBlocks.blockPlatePress = new BlockPress().setUnlocalizedName("blockHandPress").setCreativeTab(tabAdvRocketry).setHardness(2f);
AdvancedRocketryBlocks.blockAirLock = new BlockDoor2(Material.ROCK).setUnlocalizedName("smallAirlockDoor").setHardness(3f).setResistance(8f);
AdvancedRocketryBlocks.blockLandingPad = new BlockLandingPad(Material.ROCK).setUnlocalizedName("dockingPad").setHardness(3f).setCreativeTab(tabAdvRocketry);
AdvancedRocketryBlocks.blockOxygenDetection = new BlockRedstoneEmitter(Material.ROCK,"advancedrocketry:atmosphereDetector_active").setUnlocalizedName("atmosphereDetector").setHardness(3f).setCreativeTab(tabAdvRocketry);
AdvancedRocketryBlocks.blockOxygenScrubber = new BlockTile(TileCO2Scrubber.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("scrubber").setHardness(3f);
AdvancedRocketryBlocks.blockUnlitTorch = new BlockTorchUnlit().setHardness(0.0F).setUnlocalizedName("unlittorch");
AdvancedRocketryBlocks.blockVitrifiedSand = new Block(Material.SAND).setUnlocalizedName("vitrifiedSand").setCreativeTab(CreativeTabs.BUILDING_BLOCKS).setHardness(0.5F);
AdvancedRocketryBlocks.blockCharcoalLog = new BlockCharcoalLog().setUnlocalizedName("charcoallog").setCreativeTab(CreativeTabs.BUILDING_BLOCKS);
AdvancedRocketryBlocks.blockElectricMushroom = new BlockElectricMushroom().setUnlocalizedName("electricMushroom").setCreativeTab(tabAdvRocketry).setHardness(0.0F);
AdvancedRocketryBlocks.blockCrystal = new BlockCrystal().setUnlocalizedName("crystal").setCreativeTab(LibVulpes.tabLibVulpesOres).setHardness(2f);
AdvancedRocketryBlocks.blockOrientationController = new BlockTile(TileStationOrientationControl.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("orientationControl").setHardness(3f);
AdvancedRocketryBlocks.blockGravityController = new BlockTile(TileStationGravityController.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("gravityControl").setHardness(3f);
AdvancedRocketryBlocks.blockAltitudeController = new BlockTile(TileStationAltitudeController.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("altitudeController").setHardness(3f);
AdvancedRocketryBlocks.blockOxygenCharger = new BlockHalfTile(TileOxygenCharger.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("oxygenCharger").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockOxygenVent = new BlockTile(TileOxygenVent.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("oxygenVent").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockCircleLight = new Block(Material.IRON).setUnlocalizedName("circleLight").setCreativeTab(tabAdvRocketry).setHardness(2f).setLightLevel(1f);
AdvancedRocketryBlocks.blockRocketBuilder = new BlockTile(TileRocketBuilder.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("rocketAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockDeployableRocketBuilder = new BlockTile(TileStationDeployedAssembler.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("deployableRocketAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockStationBuilder = new BlockTile(TileStationBuilder.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("stationAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockFuelingStation = new BlockTileRedstoneEmitter(TileEntityFuelingStation.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("fuelStation").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockMonitoringStation = new BlockTileNeighborUpdate(TileEntityMoniteringStation.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockMonitoringStation.setUnlocalizedName("monitoringstation");
AdvancedRocketryBlocks.blockWarpShipMonitor = new BlockWarpShipMonitor(TileWarpShipMonitor.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockWarpShipMonitor.setUnlocalizedName("stationmonitor");
AdvancedRocketryBlocks.blockSatelliteBuilder = new BlockMultiblockMachine(TileSatelliteBuilder.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockSatelliteBuilder.setUnlocalizedName("satelliteBuilder");
AdvancedRocketryBlocks.blockSatelliteControlCenter = new BlockTile(TileEntitySatelliteControlCenter.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockSatelliteControlCenter.setUnlocalizedName("satelliteMonitor");
AdvancedRocketryBlocks.blockMicrowaveReciever = new BlockMultiblockMachine(TileMicrowaveReciever.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockMicrowaveReciever.setUnlocalizedName("microwaveReciever");
//Arcfurnace
AdvancedRocketryBlocks.blockArcFurnace = new BlockMultiblockMachine(TileElectricArcFurnace.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("electricArcFurnace").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockMoonTurf = new BlockPlanetSoil().setMapColor(MapColor.SNOW).setHardness(0.5F).setUnlocalizedName("turf").setCreativeTab(tabAdvRocketry);
AdvancedRocketryBlocks.blockHotTurf = new BlockPlanetSoil().setMapColor(MapColor.NETHERRACK).setHardness(0.5F).setUnlocalizedName("hotDryturf").setCreativeTab(tabAdvRocketry);
AdvancedRocketryBlocks.blockLoader = new BlockARHatch(Material.ROCK).setUnlocalizedName("loader").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockAlienWood = new BlockAlienWood().setUnlocalizedName("log").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockAlienLeaves = new BlockAlienLeaves().setUnlocalizedName("leaves2").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockAlienSapling = new BlockAlienSapling().setUnlocalizedName("sapling").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockLightSource = new BlockLightSource();
AdvancedRocketryBlocks.blockBlastBrick = new BlockMultiBlockComponentVisible(Material.ROCK).setCreativeTab(tabAdvRocketry).setUnlocalizedName("blastBrick").setHardness(3F).setResistance(15F);
AdvancedRocketryBlocks.blockQuartzCrucible = new BlockQuartzCrucible().setUnlocalizedName("qcrucible");
AdvancedRocketryBlocks.blockPrecisionAssembler = new BlockMultiblockMachine(TilePrecisionAssembler.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("precisionAssemblingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockCuttingMachine = new BlockMultiblockMachine(TileCuttingMachine.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("cuttingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockCrystallizer = new BlockMultiblockMachine(TileCrystallizer.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("Crystallizer").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockWarpCore = new BlockWarpCore(TileWarpCore.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("warpCore").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockChemicalReactor = new BlockMultiblockMachine(TileChemicalReactor.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("chemreactor").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockLathe = new BlockMultiblockMachine(TileLathe.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("lathe").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockRollingMachine = new BlockMultiblockMachine(TileRollingMachine.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("rollingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockElectrolyser = new BlockMultiblockMachine(TileElectrolyser.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("electrolyser").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockAtmosphereTerraformer = new BlockMultiblockMachine(TileAtmosphereTerraformer.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("atmosphereTerraformer").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockPlanetAnalyser = new BlockMultiblockMachine(TilePlanetAnalyser.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("planetanalyser").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockObservatory = (BlockMultiblockMachine) new BlockMultiblockMachine(TileObservatory.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("observatory").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockGuidanceComputer = new BlockTile(TileGuidanceComputer.class,GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("guidanceComputer").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockPlanetSelector = new BlockTile(TilePlanetSelector.class,GuiHandler.guiId.MODULARFULLSCREEN.ordinal()).setUnlocalizedName("planetSelector").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockBiomeScanner = new BlockMultiblockMachine(TileBiomeScanner.class,GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("biomeScanner").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockDrill = new BlockMiningDrill().setUnlocalizedName("drill").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockSuitWorkStation = new BlockTile(TileSuitWorkStation.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("suitWorkStation").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockIntake = new BlockIntake(Material.IRON).setUnlocalizedName("gasIntake").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockPressureTank = new BlockPressurizedFluidTank(Material.IRON).setUnlocalizedName("pressurizedTank").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockSolarPanel = new Block(Material.IRON).setUnlocalizedName("solarPanel").setCreativeTab(tabAdvRocketry).setHardness(3f);
AdvancedRocketryBlocks.blockSolarGenerator = new BlockTile(TileSolarPanel.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f).setUnlocalizedName("solarGenerator");
AdvancedRocketryBlocks.blockDockingPort = new BlockStationModuleDockingPort(Material.IRON).setUnlocalizedName("stationMarker").setCreativeTab(tabAdvRocketry).setHardness(3f);
if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) {
AdvancedRocketryBlocks.blockSpaceLaser = new BlockLaser();
AdvancedRocketryBlocks.blockSpaceLaser.setCreativeTab(tabAdvRocketry);
}
//Fluid Registration
AdvancedRocketryFluids.fluidOxygen = new FluidColored("oxygen",0x8f94b9).setUnlocalizedName("oxygen").setGaseous(true);
if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidOxygen))
{
AdvancedRocketryFluids.fluidOxygen = FluidRegistry.getFluid("oxygen");
}
AdvancedRocketryFluids.fluidHydrogen = new FluidColored("hydrogen",0xdbc1c1).setUnlocalizedName("hydrogen").setGaseous(true);
if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidHydrogen))
{
AdvancedRocketryFluids.fluidHydrogen = FluidRegistry.getFluid("hydrogen");
}
AdvancedRocketryFluids.fluidRocketFuel = new FluidColored("rocketFuel", 0xe5d884).setUnlocalizedName("rocketFuel").setGaseous(true);
if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidRocketFuel))
{
AdvancedRocketryFluids.fluidRocketFuel = FluidRegistry.getFluid("rocketFuel");
}
AdvancedRocketryFluids.fluidNitrogen = new FluidColored("nitrogen", 0x97a7e7);
if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidNitrogen))
{
AdvancedRocketryFluids.fluidNitrogen = FluidRegistry.getFluid("nitrogen");
}
AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidNitrogen);
AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidHydrogen);
AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidOxygen);
//AdvancedRocketryBlocks.blockOxygenFluid = new BlockFluid(AdvancedRocketryFluids.fluidOxygen, Material.WATER).setUnlocalizedName("oxygenFluidBlock").setCreativeTab(CreativeTabs.MISC);
//AdvancedRocketryBlocks.blockHydrogenFluid = new BlockFluid(AdvancedRocketryFluids.fluidHydrogen, Material.WATER).setUnlocalizedName("hydrogenFluidBlock").setCreativeTab(CreativeTabs.MISC);
//AdvancedRocketryBlocks.blockFuelFluid = new BlockFluid(AdvancedRocketryFluids.fluidRocketFuel, new MaterialLiquid(MapColor.YELLOW)).setUnlocalizedName("rocketFuelBlock").setCreativeTab(CreativeTabs.MISC);
//AdvancedRocketryBlocks.blockNitrogenFluid = new BlockFluid(AdvancedRocketryFluids.fluidNitrogen, Material.WATER).setUnlocalizedName("nitrogenFluidBlock").setCreativeTab(CreativeTabs.MISC);
//Cables
AdvancedRocketryBlocks.blockFluidPipe = new BlockLiquidPipe(Material.IRON).setUnlocalizedName("liquidPipe").setCreativeTab(tabAdvRocketry);
AdvancedRocketryBlocks.blockDataPipe = new BlockDataCable(Material.IRON).setUnlocalizedName("dataPipe").setCreativeTab(tabAdvRocketry);
AdvancedRocketryBlocks.blockEnergyPipe = new BlockEnergyCable(Material.IRON).setUnlocalizedName("energyPipe").setCreativeTab(tabAdvRocketry);
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockDataPipe.setRegistryName("dataPipe"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockEnergyPipe.setRegistryName("energyPipe"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockFluidPipe.setRegistryName("liquidPipe"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLaunchpad.setRegistryName("launchpad"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockRocketBuilder.setRegistryName("rocketBuilder"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockStructureTower.setRegistryName("structureTower"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockGenericSeat.setRegistryName("seat"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockEngine.setRegistryName("rocketmotor"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockFuelTank.setRegistryName("fuelTank"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockFuelingStation.setRegistryName("fuelingStation"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockMonitoringStation.setRegistryName("monitoringStation"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSatelliteBuilder.setRegistryName("satelliteBuilder"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockMoonTurf.setRegistryName("moonTurf"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockHotTurf.setRegistryName("hotTurf"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLoader.setRegistryName("loader"), ItemBlockMeta.class, false);
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPrecisionAssembler.setRegistryName("precisionassemblingmachine"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockBlastBrick.setRegistryName("blastBrick"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockQuartzCrucible.setRegistryName("quartzcrucible"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCrystallizer.setRegistryName("crystallizer"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCuttingMachine.setRegistryName("cuttingMachine"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAlienWood.setRegistryName("alienWood"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAlienLeaves.setRegistryName("alienLeaves"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAlienSapling.setRegistryName("alienSapling"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockObservatory.setRegistryName("observatory"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockConcrete.setRegistryName("concrete"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPlanetSelector.setRegistryName("planetSelector"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSatelliteControlCenter.setRegistryName("satelliteControlCenter"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPlanetAnalyser.setRegistryName("planetAnalyser"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockGuidanceComputer.setRegistryName("guidanceComputer"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockArcFurnace.setRegistryName("arcFurnace"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSawBlade.setRegistryName("sawBlade"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockMotor.setRegistryName("motor"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLathe.setRegistryName("lathe"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockRollingMachine.setRegistryName("rollingMachine"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPlatePress.setRegistryName("platePress"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockStationBuilder.setRegistryName("stationBuilder"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockElectrolyser.setRegistryName("electrolyser"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockChemicalReactor.setRegistryName("chemicalReactor"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenScrubber.setRegistryName("oxygenScrubber"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenVent.setRegistryName("oxygenVent"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenCharger.setRegistryName("oxygenCharger"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAirLock.setRegistryName("airlock_door"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLandingPad.setRegistryName("landingPad"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockWarpCore.setRegistryName("warpCore"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockWarpShipMonitor.setRegistryName("warpMonitor"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenDetection.setRegistryName("oxygenDetection"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockUnlitTorch.setRegistryName("unlitTorch"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blocksGeode.setRegistryName("geode"));
//LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenFluid.setRegistryName("oxygenFluid"));
//LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockHydrogenFluid.setRegistryName("hydrogenFluid"));
//LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockFuelFluid.setRegistryName("rocketFuel"));
//LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockNitrogenFluid.setRegistryName("nitrogenFluid"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockVitrifiedSand.setRegistryName("vitrifiedSand"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCharcoalLog.setRegistryName("charcoalLog"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockElectricMushroom.setRegistryName("electricMushroom"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCrystal.setRegistryName("crystal"), ItemBlockCrystal.class, true );
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOrientationController.setRegistryName("orientationController"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockGravityController.setRegistryName("gravityController"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockDrill.setRegistryName("drill"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockMicrowaveReciever.setRegistryName("microwaveReciever"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLightSource.setRegistryName("lightSource"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSolarPanel.setRegistryName("solarPanel"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSuitWorkStation.setRegistryName("suitWorkStation"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockBiomeScanner.setRegistryName("biomeScanner"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAtmosphereTerraformer.setRegistryName("terraformer"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockDeployableRocketBuilder.setRegistryName("deployableRocketBuilder"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPressureTank.setRegistryName("liquidTank"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockIntake.setRegistryName("intake"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCircleLight.setRegistryName("circleLight"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSolarGenerator.setRegistryName("solarGenerator"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockDockingPort.setRegistryName("stationMarker"));
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAltitudeController.setRegistryName("altitudeController"));
//TODO, use different mechanism to enable/disable drill
if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill)
LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSpaceLaser.setRegistryName("spaceLaser"));
AdvancedRocketryItems.itemWafer = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:wafer").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemCircuitPlate = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:circuitplate").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemIC = new ItemIngredient(6).setUnlocalizedName("advancedrocketry:circuitIC").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemMisc = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:miscpart").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemSawBlade = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:sawBlade").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemSpaceStationChip = new ItemStationChip().setUnlocalizedName("stationChip").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemAsteroidChip = new ItemAsteroidChip().setUnlocalizedName("asteroidChip").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemSpaceStation = new ItemPackedStructure().setUnlocalizedName("station");
AdvancedRocketryItems.itemSmallAirlockDoor = new ItemDoor(AdvancedRocketryBlocks.blockAirLock).setUnlocalizedName("smallAirlock").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemCarbonScrubberCartridge = new Item().setMaxDamage(172800).setUnlocalizedName("carbonScrubberCartridge").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemLens = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:lens").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemSatellitePowerSource = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:satellitePowerSource").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemSatellitePrimaryFunction = new ItemIngredient(6).setUnlocalizedName("advancedrocketry:satellitePrimaryFunction").setCreativeTab(tabAdvRocketry);
//TODO: move registration in the case we have more than one chip type
AdvancedRocketryItems.itemDataUnit = new ItemData().setUnlocalizedName("advancedrocketry:dataUnit").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemOreScanner = new ItemOreScanner().setUnlocalizedName("OreScanner").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemQuartzCrucible = new ItemBlock(AdvancedRocketryBlocks.blockQuartzCrucible).setUnlocalizedName("qcrucible").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemSatellite = new ItemSatellite().setUnlocalizedName("satellite");
AdvancedRocketryItems.itemSatelliteIdChip = new ItemSatelliteIdentificationChip().setUnlocalizedName("satelliteIdChip").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemPlanetIdChip = new ItemPlanetIdentificationChip().setUnlocalizedName("planetIdChip").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemBiomeChanger = new ItemBiomeChanger().setUnlocalizedName("biomeChanger").setCreativeTab(tabAdvRocketry);
//Fluids
AdvancedRocketryItems.itemBucketRocketFuel = new Item().setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketRocketFuel").setContainerItem(Items.BUCKET);
AdvancedRocketryItems.itemBucketNitrogen = new Item().setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketNitrogen").setContainerItem(Items.BUCKET);
AdvancedRocketryItems.itemBucketHydrogen = new Item().setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketHydrogen").setContainerItem(Items.BUCKET);
AdvancedRocketryItems.itemBucketOxygen = new Item().setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketOxygen").setContainerItem(Items.BUCKET);
//FluidRegistry.addBucketForFluid(AdvancedRocketryFluids.fluidHydrogen);
//FluidRegistry.addBucketForFluid(AdvancedRocketryFluids.fluidNitrogen);
//FluidRegistry.addBucketForFluid(AdvancedRocketryFluids.fluidOxygen);
//FluidRegistry.addBucketForFluid(AdvancedRocketryFluids.fluidRocketFuel);
//Suit Component Registration
AdvancedRocketryItems.itemJetpack = new ItemJetpack().setCreativeTab(tabAdvRocketry).setUnlocalizedName("jetPack");
AdvancedRocketryItems.itemPressureTank = new ItemPressureTank(4, 1000).setCreativeTab(tabAdvRocketry).setUnlocalizedName("advancedrocketry:pressureTank");
AdvancedRocketryItems.itemUpgrade = new ItemUpgrade(5).setCreativeTab(tabAdvRocketry).setUnlocalizedName("advancedrocketry:itemUpgrade");
AdvancedRocketryItems.itemAtmAnalyser = new ItemAtmosphereAnalzer().setCreativeTab(tabAdvRocketry).setUnlocalizedName("atmAnalyser");
//Armor registration
AdvancedRocketryItems.itemSpaceSuit_Helmet = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, EntityEquipmentSlot.HEAD).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceHelmet");
AdvancedRocketryItems.itemSpaceSuit_Chest = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, EntityEquipmentSlot.CHEST).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceChest");
AdvancedRocketryItems.itemSpaceSuit_Leggings = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, EntityEquipmentSlot.LEGS).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceLeggings");
AdvancedRocketryItems.itemSpaceSuit_Boots = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, EntityEquipmentSlot.FEET).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceBoots");
AdvancedRocketryItems.itemSealDetector = new ItemSealDetector().setMaxStackSize(1).setCreativeTab(tabAdvRocketry).setUnlocalizedName("sealDetector");
//Tools
AdvancedRocketryItems.itemJackhammer = new ItemJackHammer(ToolMaterial.DIAMOND).setUnlocalizedName("jackhammer").setCreativeTab(tabAdvRocketry);
AdvancedRocketryItems.itemJackhammer.setHarvestLevel("jackhammer", 3);
AdvancedRocketryItems.itemJackhammer.setHarvestLevel("pickaxe", 3);
//Register Satellite Properties
SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteOptical.class)));
SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 1), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteComposition.class)));
SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 2), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteMassScanner.class)));
SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 3), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteEnergy.class)));
SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 4), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteOreMapping.class)));
SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 5), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteBiomeChanger.class)));
SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0), new SatelliteProperties().setPowerGeneration(1));
SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,1), new SatelliteProperties().setPowerGeneration(10));
SatelliteRegistry.registerSatelliteProperty(new ItemStack(LibVulpesItems.itemBattery, 1, 0), new SatelliteProperties().setPowerStorage(100));
SatelliteRegistry.registerSatelliteProperty(new ItemStack(LibVulpesItems.itemBattery, 1, 1), new SatelliteProperties().setPowerStorage(400));
SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemDataUnit, 1, 0), new SatelliteProperties().setMaxData(1000));
//Item Registration
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemQuartzCrucible.setRegistryName("iquartzcrucible"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemOreScanner.setRegistryName("oreScanner"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSatellitePowerSource.setRegistryName("satellitePowerSource"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSatellitePrimaryFunction.setRegistryName("satellitePrimaryFunction"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemCircuitPlate.setRegistryName("itemCircuitPlate"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemIC.setRegistryName("ic"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemWafer.setRegistryName("wafer"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemDataUnit.setRegistryName("dataUnit"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSatellite.setRegistryName("satellite"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSatelliteIdChip.setRegistryName("satelliteIdChip"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemPlanetIdChip.setRegistryName("planetIdChip"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemMisc.setRegistryName("misc"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSawBlade.setRegistryName("sawBladeIron"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceStationChip.setRegistryName("spaceStationChip"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceStation.setRegistryName("spaceStation"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceSuit_Helmet.setRegistryName("spaceHelmet"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceSuit_Boots.setRegistryName("spaceBoots"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceSuit_Chest.setRegistryName("spaceChestplate"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceSuit_Leggings.setRegistryName("spaceLeggings"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBucketRocketFuel.setRegistryName("bucketRocketFuel"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBucketNitrogen.setRegistryName("bucketNitrogen"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBucketHydrogen.setRegistryName("bucketHydrogen"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBucketOxygen.setRegistryName("bucketOxygen"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSmallAirlockDoor.setRegistryName("smallAirlockDoor"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemCarbonScrubberCartridge.setRegistryName("carbonScrubberCartridge"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSealDetector.setRegistryName("sealDetector"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemJackhammer.setRegistryName("jackHammer"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemAsteroidChip.setRegistryName("asteroidChip"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemLens.setRegistryName("lens"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemJetpack.setRegistryName("jetPack"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemPressureTank.setRegistryName("pressureTank"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemUpgrade.setRegistryName("itemUpgrade"));
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemAtmAnalyser.setRegistryName("atmAnalyser"));
if(zmaster587.advancedRocketry.api.Configuration.enableTerraforming)
LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBiomeChanger.setRegistryName("biomeChanger"));
//Register multiblock items with the projector
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileCuttingMachine(), (BlockTile)AdvancedRocketryBlocks.blockCuttingMachine);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileLathe(), (BlockTile)AdvancedRocketryBlocks.blockLathe);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileCrystallizer(), (BlockTile)AdvancedRocketryBlocks.blockCrystallizer);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TilePrecisionAssembler(), (BlockTile)AdvancedRocketryBlocks.blockPrecisionAssembler);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileObservatory(), (BlockTile)AdvancedRocketryBlocks.blockObservatory);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TilePlanetAnalyser(), (BlockTile)AdvancedRocketryBlocks.blockPlanetAnalyser);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileRollingMachine(), (BlockTile)AdvancedRocketryBlocks.blockRollingMachine);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileElectricArcFurnace(), (BlockTile)AdvancedRocketryBlocks.blockArcFurnace);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileElectrolyser(), (BlockTile)AdvancedRocketryBlocks.blockElectrolyser);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileChemicalReactor(), (BlockTile)AdvancedRocketryBlocks.blockChemicalReactor);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileWarpCore(), (BlockTile)AdvancedRocketryBlocks.blockWarpCore);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileMicrowaveReciever(), (BlockTile)AdvancedRocketryBlocks.blockMicrowaveReciever);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileBiomeScanner(), (BlockTile)AdvancedRocketryBlocks.blockBiomeScanner);
((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileAtmosphereTerraformer(), (BlockTile)AdvancedRocketryBlocks.blockAtmosphereTerraformer);
//End Items
EntityRegistry.registerModEntity(EntityDummy.class, "mountDummy", 0, this, 16, 20, false);
EntityRegistry.registerModEntity(EntityRocket.class, "rocket", 1, this, 64, 3, true);
EntityRegistry.registerModEntity(EntityLaserNode.class, "laserNode", 2, instance, 256, 20, false);
EntityRegistry.registerModEntity(EntityStationDeployedRocket.class, "deployedRocket", 3, this, 256, 600, true);
GameRegistry.registerTileEntity(TileRocketBuilder.class, "ARrocketBuilder");
GameRegistry.registerTileEntity(TileWarpCore.class, "ARwarpCore");
//GameRegistry.registerTileEntity(TileModelRender.class, "ARmodelRenderer");
GameRegistry.registerTileEntity(TileEntityFuelingStation.class, "ARfuelingStation");
GameRegistry.registerTileEntity(TileEntityMoniteringStation.class, "ARmonitoringStation");
//GameRegistry.registerTileEntity(TileMissionController.class, "ARmissionControlComp");
GameRegistry.registerTileEntity(TileSpaceLaser.class, "ARspaceLaser");
GameRegistry.registerTileEntity(TilePrecisionAssembler.class, "ARprecisionAssembler");
GameRegistry.registerTileEntity(TileObservatory.class, "ARobservatory");
GameRegistry.registerTileEntity(TileCrystallizer.class, "ARcrystallizer");
GameRegistry.registerTileEntity(TileCuttingMachine.class, "ARcuttingmachine");
GameRegistry.registerTileEntity(TileDataBus.class, "ARdataBus");
GameRegistry.registerTileEntity(TileSatelliteHatch.class, "ARsatelliteHatch");
GameRegistry.registerTileEntity(TileSatelliteBuilder.class, "ARsatelliteBuilder");
GameRegistry.registerTileEntity(TileEntitySatelliteControlCenter.class, "ARTileEntitySatelliteControlCenter");
GameRegistry.registerTileEntity(TilePlanetAnalyser.class, "ARplanetAnalyser");
GameRegistry.registerTileEntity(TileGuidanceComputer.class, "ARguidanceComputer");
GameRegistry.registerTileEntity(TileElectricArcFurnace.class, "ARelectricArcFurnace");
GameRegistry.registerTileEntity(TilePlanetSelector.class, "ARTilePlanetSelector");
//GameRegistry.registerTileEntity(TileModelRenderRotatable.class, "ARTileModelRenderRotatable");
GameRegistry.registerTileEntity(TileMaterial.class, "ARTileMaterial");
GameRegistry.registerTileEntity(TileLathe.class, "ARTileLathe");
GameRegistry.registerTileEntity(TileRollingMachine.class, "ARTileMetalBender");
GameRegistry.registerTileEntity(TileStationBuilder.class, "ARStationBuilder");
GameRegistry.registerTileEntity(TileElectrolyser.class, "ARElectrolyser");
GameRegistry.registerTileEntity(TileChemicalReactor.class, "ARChemicalReactor");
GameRegistry.registerTileEntity(TileOxygenVent.class, "AROxygenVent");
GameRegistry.registerTileEntity(TileOxygenCharger.class, "AROxygenCharger");
GameRegistry.registerTileEntity(TileCO2Scrubber.class, "ARCO2Scrubber");
GameRegistry.registerTileEntity(TileWarpShipMonitor.class, "ARStationMonitor");
GameRegistry.registerTileEntity(TileAtmosphereDetector.class, "AROxygenDetector");
GameRegistry.registerTileEntity(TileStationOrientationControl.class, "AROrientationControl");
GameRegistry.registerTileEntity(TileStationGravityController.class, "ARGravityControl");
GameRegistry.registerTileEntity(TileLiquidPipe.class, "ARLiquidPipe");
GameRegistry.registerTileEntity(TileDataPipe.class, "ARDataPipe");
GameRegistry.registerTileEntity(TileEnergyPipe.class, "AREnergyPipe");
GameRegistry.registerTileEntity(TileDrill.class, "ARDrill");
GameRegistry.registerTileEntity(TileMicrowaveReciever.class, "ARMicrowaveReciever");
GameRegistry.registerTileEntity(TileSuitWorkStation.class, "ARSuitWorkStation");
GameRegistry.registerTileEntity(TileRocketLoader.class, "ARRocketLoader");
GameRegistry.registerTileEntity(TileRocketUnloader.class, "ARRocketUnloader");
GameRegistry.registerTileEntity(TileBiomeScanner.class, "ARBiomeScanner");
GameRegistry.registerTileEntity(TileAtmosphereTerraformer.class, "ARAttTerraformer");
GameRegistry.registerTileEntity(TileLandingPad.class, "ARLandingPad");
GameRegistry.registerTileEntity(TileStationDeployedAssembler.class, "ARStationDeployableRocketAssembler");
GameRegistry.registerTileEntity(TileFluidTank.class, "ARFluidTank");
GameRegistry.registerTileEntity(TileRocketFluidUnloader.class, "ARFluidUnloader");
GameRegistry.registerTileEntity(TileRocketFluidLoader.class, "ARFluidLoader");
GameRegistry.registerTileEntity(TileSolarPanel.class, "ARSolarGenerator");
GameRegistry.registerTileEntity(TileDockingPort.class, "ARDockingPort");
GameRegistry.registerTileEntity(TileStationAltitudeController.class, "ARStationAltitudeController");
//OreDict stuff
OreDictionary.registerOre("waferSilicon", new ItemStack(AdvancedRocketryItems.itemWafer,1,0));
OreDictionary.registerOre("ingotCarbon", new ItemStack(AdvancedRocketryItems.itemMisc, 1, 1));
OreDictionary.registerOre("concrete", new ItemStack(AdvancedRocketryBlocks.blockConcrete));
//AUDIO
//Register Space Objects
SpaceObjectManager.getSpaceManager().registerSpaceObjectType("genericObject", SpaceObject.class);
//Register Allowed Products
materialRegistry.registerMaterial(new zmaster587.libVulpes.api.material.Material("TitaniumAluminide", "pickaxe", 1, 0xaec2de, AllowedProducts.getProductByName("PLATE").getFlagValue() | AllowedProducts.getProductByName("INGOT").getFlagValue() | AllowedProducts.getProductByName("NUGGET").getFlagValue() | AllowedProducts.getProductByName("DUST").getFlagValue() | AllowedProducts.getProductByName("STICK").getFlagValue() | AllowedProducts.getProductByName("BLOCK").getFlagValue() | AllowedProducts.getProductByName("GEAR").getFlagValue() | AllowedProducts.getProductByName("SHEET").getFlagValue(), false));
materialRegistry.registerOres(LibVulpes.tabLibVulpesOres);
//Regiser item/block crap
proxy.preinit();
}
@EventHandler
public void load(FMLInitializationEvent event)
{
//TODO: move to proxy
//Minecraft.getMinecraft().getBlockColors().registerBlockColorHandler((IBlockColor) AdvancedRocketryBlocks.blockFuelFluid, new Block[] {AdvancedRocketryBlocks.blockFuelFluid});
proxy.init();
zmaster587.advancedRocketry.cable.NetworkRegistry.registerFluidNetwork();
ItemStack userInterface = new ItemStack(AdvancedRocketryItems.itemMisc, 1,0);
ItemStack basicCircuit = new ItemStack(AdvancedRocketryItems.itemIC, 1,0);
ItemStack advancedCircuit = new ItemStack(AdvancedRocketryItems.itemIC, 1,2);
ItemStack controlCircuitBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,3);
ItemStack itemIOBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,4);
ItemStack liquidIOBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,5);
ItemStack trackingCircuit = new ItemStack(AdvancedRocketryItems.itemIC,1,1);
ItemStack opticalSensor = new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0);
ItemStack biomeChanger = new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 5);
ItemStack smallSolarPanel = new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0);
ItemStack largeSolarPanel = new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,1);
ItemStack smallBattery = new ItemStack(LibVulpesItems.itemBattery,1,0);
ItemStack battery2x = new ItemStack(LibVulpesItems.itemBattery,1,1);
ItemStack superHighPressureTime = new ItemStack(AdvancedRocketryItems.itemPressureTank,1,3);
//Register Alloys
MaterialRegistry.registerMixedMaterial(new MixedMaterial(TileElectricArcFurnace.class, "oreRutile", new ItemStack[] {MaterialRegistry.getMaterialFromName("Titanium").getProduct(AllowedProducts.getProductByName("INGOT"))}));
NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockBlastBrick,16), new ItemStack(Items.MAGMA_CREAM,1), new ItemStack(Items.MAGMA_CREAM,1), Blocks.BRICK_BLOCK, Blocks.BRICK_BLOCK, Blocks.BRICK_BLOCK, Blocks.BRICK_BLOCK);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockArcFurnace), "aga","ice", "aba", 'a', Items.NETHERBRICK, 'g', userInterface, 'i', itemIOBoard, 'e',controlCircuitBoard, 'c', AdvancedRocketryBlocks.blockBlastBrick, 'b', "ingotCopper"));
GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemQuartzCrucible), " a ", "aba", " a ", Character.valueOf('a'), Items.QUARTZ, Character.valueOf('b'), Items.CAULDRON);
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockPlatePress, " ", " a ", "iii", 'a', Blocks.PISTON, 'i', "ingotIron"));
GameRegistry.addRecipe(new ShapedOreRecipe(MaterialRegistry.getItemStackFromMaterialAndType("Iron", AllowedProducts.getProductByName("STICK")), "x ", " x ", " x", 'x', "ingotIron"));
GameRegistry.addRecipe(new ShapedOreRecipe(MaterialRegistry.getItemStackFromMaterialAndType("Steel", AllowedProducts.getProductByName("STICK")), "x ", " x ", " x", 'x', "ingotSteel"));
GameRegistry.addSmelting(MaterialRegistry.getMaterialFromName("Dilithium").getProduct(AllowedProducts.getProductByName("ORE")), MaterialRegistry.getMaterialFromName("Dilithium").getProduct(AllowedProducts.getProductByName("DUST")), 0);
//Supporting Materials
GameRegistry.addRecipe(new ShapedOreRecipe(userInterface, "lrl", "fgf", 'l', "dyeLime", 'r', Items.REDSTONE, 'g', Blocks.GLASS_PANE, 'f', Items.GLOWSTONE_DUST));
GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockGenericSeat), "xxx", 'x', Blocks.WOOL);
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockConcrete), Blocks.SAND, Blocks.GRAVEL, Items.WATER_BUCKET);
GameRegistry.addRecipe(new ShapelessOreRecipe(AdvancedRocketryBlocks.blockLaunchpad, "concrete", "dyeBlack", "dyeYellow"));
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockStructureTower, "ooo", " o ", "ooo", 'o', "stickSteel"));
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockEngine, "sss", " t ","t t", 's', "ingotSteel", 't', "plateTitanium"));
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockFuelTank, "s s", "p p", "s s", 'p', "plateSteel", 's', "stickSteel"));
GameRegistry.addRecipe(new ShapedOreRecipe(smallBattery, " c ","prp", "prp", 'c', "stickIron", 'r', Items.REDSTONE, 'p', "plateTin"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(LibVulpesItems.itemBattery,1,1), "bpb", "bpb", 'b', smallBattery, 'p', "plateCopper"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), "ppp", " g ", " l ", 'p', Blocks.GLASS_PANE, 'g', Items.GLOWSTONE_DUST, 'l', "plateGold"));
GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockObservatory), "gug", "pbp", "rrr", 'g', Blocks.GLASS_PANE, 'u', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'r', MaterialRegistry.getItemStackFromMaterialAndType("Iron", AllowedProducts.getProductByName("STICK")));
//Hatches
GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,0), "c", "m"," ", 'c', Blocks.CHEST, 'm', LibVulpesBlocks.blockStructureBlock);
GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,1), "m", "c"," ", 'c', Blocks.CHEST, 'm', LibVulpesBlocks.blockStructureBlock);
GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,2), "c", "m", " ", 'c', AdvancedRocketryBlocks.blockFuelTank, 'm', LibVulpesBlocks.blockStructureBlock);
GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,3), "m", "c", " ", 'c', AdvancedRocketryBlocks.blockFuelTank, 'm', LibVulpesBlocks.blockStructureBlock);
GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,0), "m", "c"," ", 'c', AdvancedRocketryItems.itemDataUnit, 'm', LibVulpesBlocks.blockStructureBlock);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,1), " x ", "xmx"," x ", 'x', "stickTitanium", 'm', LibVulpesBlocks.blockStructureBlock));
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,2), new ItemStack(LibVulpesBlocks.blockHatch,1,1), trackingCircuit);
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,3), new ItemStack(LibVulpesBlocks.blockHatch,1,0), trackingCircuit);
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,4), new ItemStack(LibVulpesBlocks.blockHatch,1,3), trackingCircuit);
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,5), new ItemStack(LibVulpesBlocks.blockHatch,1,2), trackingCircuit);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockMotor), " cp", "rrp"," cp", 'c', "coilCopper", 'p', "plateSteel", 'r', "stickSteel"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0), "rrr", "ggg","ppp", 'r', Items.REDSTONE, 'g', Items.GLOWSTONE_DUST, 'p', "plateGold"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(LibVulpesItems.itemHoloProjector), "oro", "rpr", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'r', Items.REDSTONE, 'p', "plateIron"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 2), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', "crystalDilithium"));
GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 1), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', trackingCircuit);
GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 3), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemLens, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', trackingCircuit);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSawBlade,1,0), " x ","xox", " x ", 'x', "plateIron", 'o', "stickIron"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockSawBlade,1,0), "r r","xox", "x x", 'r', "stickIron", 'x', "plateIron", 'o', new ItemStack(AdvancedRocketryItems.itemSawBlade,1,0)));
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemSpaceStationChip), LibVulpesItems.itemLinker , basicCircuit);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge), "xix", "xix", "xix", 'x', "sheetIron", 'i', Blocks.IRON_BARS));
//O2 Support
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenVent), "bfb", "bmb", "btb", 'b', Blocks.IRON_BARS, 'f', "fanSteel", 'm', AdvancedRocketryBlocks.blockMotor, 't', AdvancedRocketryBlocks.blockFuelTank));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenScrubber), "bfb", "bmb", "btb", 'b', Blocks.IRON_BARS, 'f', "fanSteel", 'm', AdvancedRocketryBlocks.blockMotor, 't', "ingotCarbon"));
//MACHINES
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPrecisionAssembler), "abc", "def", "ghi", 'a', Items.REPEATER, 'b', userInterface, 'c', Items.DIAMOND, 'd', itemIOBoard, 'e', LibVulpesBlocks.blockStructureBlock, 'f', controlCircuitBoard, 'g', Blocks.FURNACE, 'h', "gearSteel", 'i', Blocks.DROPPER));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockCrystallizer), "ada", "ecf","bgb", 'a', Items.QUARTZ, 'b', Items.REPEATER, 'c', LibVulpesBlocks.blockStructureBlock, 'd', userInterface, 'e', itemIOBoard, 'f', controlCircuitBoard, 'g', "plateSteel"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockCuttingMachine), "aba", "cde", "opo", 'a', "gearSteel", 'b', userInterface, 'c', itemIOBoard, 'e', controlCircuitBoard, 'p', "plateSteel", 'o', Blocks.OBSIDIAN, 'd', LibVulpesBlocks.blockStructureBlock));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockLathe), "rsr", "abc", "pgp", 'r', "stickIron",'a', itemIOBoard, 'c', controlCircuitBoard, 'g', "gearSteel", 'p', "plateSteel", 'b', LibVulpesBlocks.blockStructureBlock, 's', userInterface));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockRollingMachine), "psp", "abc", "iti", 'a', itemIOBoard, 'c', controlCircuitBoard, 'p', "gearSteel", 's', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'i', "blockIron",'t', liquidIOBoard));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockMonitoringStation), "coc", "cbc", "cpc", 'c', "stickCopper", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'b', LibVulpesBlocks.blockStructureBlock, 'p', LibVulpesItems.itemBattery));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockFuelingStation), "bgb", "lbf", "ppp", 'p', "plateTin", 'f', "fanSteel", 'l', liquidIOBoard, 'g', AdvancedRocketryItems.itemMisc, 'x', AdvancedRocketryBlocks.blockFuelTank, 'b', LibVulpesBlocks.blockStructureBlock));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockSatelliteControlCenter), "oso", "cbc", "rtr", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 's', userInterface, 'c', "stickCopper", 'b', LibVulpesBlocks.blockStructureBlock, 'r', Items.REPEATER, 't', LibVulpesItems.itemBattery));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockSatelliteBuilder), "dht", "cbc", "mas", 'd', AdvancedRocketryItems.itemDataUnit, 'h', Blocks.HOPPER, 'c', basicCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'm', AdvancedRocketryBlocks.blockMotor, 'a', Blocks.ANVIL, 's', AdvancedRocketryBlocks.blockSawBlade, 't', "plateTitanium"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPlanetAnalyser), "tst", "pbp", "cpc", 't', trackingCircuit, 's', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'p', "plateTin", 'c', AdvancedRocketryItems.itemPlanetIdChip));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockGuidanceComputer), "ctc", "rbr", "crc", 'c', trackingCircuit, 't', "plateTitanium", 'r', Items.REDSTONE, 'b', LibVulpesBlocks.blockStructureBlock));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPlanetSelector), "cpc", "lbl", "coc", 'c', trackingCircuit, 'o',new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'l', Blocks.LEVER, 'b', AdvancedRocketryBlocks.blockGuidanceComputer, 'p', Blocks.STONE_BUTTON));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockRocketBuilder), "sgs", "cbc", "tdt", 's', "stickTitanium", 'g', AdvancedRocketryItems.itemMisc, 'c', controlCircuitBoard, 'b', LibVulpesBlocks.blockStructureBlock, 't', "gearTitanium", 'd', AdvancedRocketryBlocks.blockConcrete));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockStationBuilder), "gdg", "dsd", "ada", 'g', "gearTitanium", 'a', advancedCircuit, 'd', "dustDilithium", 's', new ItemStack(AdvancedRocketryBlocks.blockRocketBuilder)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockElectrolyser), "pip", "abc", "ded", 'd', basicCircuit, 'p', "plateSteel", 'i', userInterface, 'a', liquidIOBoard, 'c', controlCircuitBoard, 'b', LibVulpesBlocks.blockStructureBlock, 'e', Blocks.REDSTONE_TORCH));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenCharger), "fif", "tbt", "pcp", 'p', "plateSteel", 'f', "fanSteel", 'c', Blocks.HEAVY_WEIGHTED_PRESSURE_PLATE, 'i', AdvancedRocketryItems.itemMisc, 'b', LibVulpesBlocks.blockStructureBlock, 't', AdvancedRocketryBlocks.blockFuelTank));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockChemicalReactor), "pip", "abd", "rcr", 'a', itemIOBoard, 'd', controlCircuitBoard, 'r', basicCircuit, 'p', "plateGold", 'i', userInterface, 'c', liquidIOBoard, 'b', LibVulpesBlocks.blockStructureBlock, 'g', "plateGold"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockWarpCore), "gcg", "pbp", "gcg", 'p', "plateSteel", 'c', advancedCircuit, 'b', "coilCopper", 'g', "plateTitanium"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenDetection), "pip", "gbf", "pcp", 'p', "plateSteel",'f', "fanSteel", 'i', userInterface, 'c', basicCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'g', Blocks.IRON_BARS));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockWarpShipMonitor), "pip", "obo", "pcp", 'o', controlCircuitBoard, 'p', "plateSteel", 'i', userInterface, 'c', advancedCircuit, 'b', LibVulpesBlocks.blockStructureBlock));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockBiomeScanner), "plp", "bsb","ppp", 'p', "plateTin", 'l', biomeChanger, 'b', smallBattery, 's', LibVulpesBlocks.blockStructureBlock));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockDeployableRocketBuilder), "gdg", "dad", "rdr", 'g', "gearTitaniumAluminide", 'd', "dustDilithium", 'r', "stickTitaniumAluminide", 'a', AdvancedRocketryBlocks.blockRocketBuilder));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPressureTank), "tgt","tgt","tgt", 't', superHighPressureTime, 'g', Blocks.GLASS_PANE));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockIntake), "rhr", "hbh", "rhr", 'r', "stickTitanium", 'h', Blocks.HOPPER, 'b', LibVulpesBlocks.blockStructureBlock));
//Armor recipes
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Boots, " r ", "w w", "p p", 'r', "stickIron", 'w', Blocks.WOOL, 'p', "plateIron"));
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Leggings, "wrw", "w w", "w w", 'w', Blocks.WOOL, 'r', "stickIron"));
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Chest, "wrw", "wtw", "wfw", 'w', Blocks.WOOL, 'r', "stickIron", 't', AdvancedRocketryBlocks.blockFuelTank, 'f', "fanSteel"));
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Helmet, "prp", "rgr", "www", 'w', Blocks.WOOL, 'r', "stickIron", 'p', "plateIron", 'g', Blocks.GLASS_PANE));
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemJetpack, "cpc", "lsl", "f f", 'c', AdvancedRocketryItems.itemPressureTank, 'f', Items.FIRE_CHARGE, 's', Items.STRING, 'l', Blocks.LEVER, 'p', "plateSteel"));
//Tool Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemJackhammer, " pt","imp","di ",'d', Items.DIAMOND, 'm', AdvancedRocketryBlocks.blockMotor, 'p', "plateAluminum", 't', "stickTitanium", 'i', "stickIron"));
//Other blocks
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSmallAirlockDoor, "pp", "pp","pp", 'p', "plateSteel"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockCircleLight), "p ", " l ", " ", 'p', "sheetIron", 'l', Blocks.GLOWSTONE));
//TEMP RECIPES
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemSatelliteIdChip), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0));
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemPlanetIdChip), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0), new ItemStack(AdvancedRocketryItems.itemSatelliteIdChip));
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemMisc,1,1), new ItemStack(Items.COAL,1,1), new ItemStack(Items.COAL,1,1), new ItemStack(Items.COAL,1,1), new ItemStack(Items.COAL,1,1) ,new ItemStack(Items.COAL,1,1) ,new ItemStack(Items.COAL,1,1));
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLandingPad), new ItemStack(AdvancedRocketryBlocks.blockConcrete), trackingCircuit);
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemAsteroidChip), trackingCircuit.copy(), AdvancedRocketryItems.itemDataUnit);
GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockDataPipe, 8), "ggg", " d ", "ggg", 'g', Blocks.GLASS_PANE, 'd', AdvancedRocketryItems.itemDataUnit);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockEnergyPipe, 32), "ggg", " d ", "ggg", 'g', Items.CLAY_BALL, 'd', "stickCopper"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockFluidPipe, 32), "ggg", " d ", "ggg", 'g', Items.CLAY_BALL, 'd', "sheetCopper"));
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockDrill), LibVulpesBlocks.blockStructureBlock, Items.IRON_PICKAXE);
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockOrientationController), LibVulpesBlocks.blockStructureBlock, Items.COMPASS, userInterface);
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockGravityController), LibVulpesBlocks.blockStructureBlock, Blocks.PISTON, Blocks.REDSTONE_BLOCK);
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockAltitudeController), LibVulpesBlocks.blockStructureBlock, userInterface, basicCircuit);
GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemLens), " g ", "g g", 'g', Blocks.GLASS_PANE);
GameRegistry.addShapelessRecipe(largeSolarPanel.copy(), smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockMicrowaveReciever), "ggg", "tbc", "aoa", 'g', "plateGold", 't', trackingCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'c', controlCircuitBoard, 'a', advancedCircuit, 'o', opticalSensor));
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockSolarPanel, "rrr", "gbg", "ppp", 'r' , Items.REDSTONE, 'g', Items.GLOWSTONE_DUST, 'b', LibVulpesBlocks.blockStructureBlock, 'p', "plateGold"));
GameRegistry.addRecipe(new ShapelessOreRecipe(AdvancedRocketryBlocks.blockSolarGenerator, "itemBattery", LibVulpesBlocks.blockForgeOutputPlug, AdvancedRocketryBlocks.blockSolarPanel));
GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockDockingPort), trackingCircuit, new ItemStack(AdvancedRocketryBlocks.blockLoader, 1,1));
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemOreScanner, "lwl", "bgb", " ", 'l', Blocks.LEVER, 'g', userInterface, 'b', "itemBattery", 'w', advancedCircuit));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 4), " c ","sss", "tot", 'c', "stickCopper", 's', "sheetIron", 'o', AdvancedRocketryItems.itemOreScanner, 't', trackingCircuit));
GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockSuitWorkStation), "c","b", 'c', Blocks.CRAFTING_TABLE, 'b', LibVulpesBlocks.blockStructureBlock);
RecipesMachine.getInstance().addRecipe(TileElectrolyser.class, new Object[] {new FluidStack(AdvancedRocketryFluids.fluidOxygen, 100), new FluidStack(AdvancedRocketryFluids.fluidHydrogen, 100)}, 100, 20, new FluidStack(FluidRegistry.WATER, 10));
RecipesMachine.getInstance().addRecipe(TileChemicalReactor.class, new FluidStack(AdvancedRocketryFluids.fluidRocketFuel, 20), 100, 10, new FluidStack(AdvancedRocketryFluids.fluidOxygen, 10), new FluidStack(AdvancedRocketryFluids.fluidHydrogen, 10));
if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) {
GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockSpaceLaser, "ata", "bec", "gpg", 'a', advancedCircuit, 't', trackingCircuit, 'b', LibVulpesItems.itemBattery, 'e', Items.EMERALD, 'c', controlCircuitBoard, 'g', "gearTitanium", 'p', LibVulpesBlocks.blockStructureBlock));
}
if(zmaster587.advancedRocketry.api.Configuration.allowTerraforming) {
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockAtmosphereTerraformer), "gdg", "lac", "gbg", 'g', "gearTitaniumAluminide", 'd', "crystalDilithium", 'l', liquidIOBoard, 'a', LibVulpesBlocks.blockAdvStructureBlock, 'c', controlCircuitBoard, 'b', battery2x));
}
//Control boards
GameRegistry.addRecipe(new ShapedOreRecipe(itemIOBoard, "rvr", "dwd", "dpd", 'r', Items.REDSTONE, 'v', Items.DIAMOND, 'd', "dustGold", 'w', Blocks.WOODEN_SLAB, 'p', "plateIron"));
GameRegistry.addRecipe(new ShapedOreRecipe(controlCircuitBoard, "rvr", "dwd", "dpd", 'r', Items.REDSTONE, 'v', Items.DIAMOND, 'd', "dustCopper", 'w', Blocks.WOODEN_SLAB, 'p', "plateIron"));
GameRegistry.addRecipe(new ShapedOreRecipe(liquidIOBoard, "rvr", "dwd", "dpd", 'r', Items.REDSTONE, 'v', Items.DIAMOND, 'd', new ItemStack(Items.DYE, 1, 4), 'w', Blocks.WOODEN_SLAB, 'p', "plateIron"));
//Cutting Machine
RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(AdvancedRocketryItems.itemIC, 4, 0), 300, 100, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,0));
RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(AdvancedRocketryItems.itemIC, 4, 2), 300, 100, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,1));
RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(AdvancedRocketryItems.itemWafer, 4, 0), 300, 100, "bouleSilicon");
//Lathe
RecipesMachine.getInstance().addRecipe(TileLathe.class, MaterialRegistry.getItemStackFromMaterialAndType("Iron", AllowedProducts.getProductByName("STICK")), 300, 100, "ingotIron");
//Precision Assembler recipes
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,0), 900, 100, Items.GOLD_INGOT, Items.REDSTONE, "waferSilicon");
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,1), 900, 100, Items.GOLD_INGOT, Blocks.REDSTONE_BLOCK, "waferSilicon");
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemDataUnit, 1, 0), 500, 60, Items.EMERALD, basicCircuit, Items.REDSTONE);
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, trackingCircuit, 900, 50, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,0), Items.ENDER_EYE, Items.REDSTONE);
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, itemIOBoard, 200, 10, "plateSilicon", "plateGold", basicCircuit, Items.REDSTONE);
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, controlCircuitBoard, 200, 10, "plateSilicon", "plateCopper", basicCircuit, Items.REDSTONE);
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, liquidIOBoard, 200, 10, "plateSilicon", new ItemStack(Items.DYE, 1, 4), basicCircuit, Items.REDSTONE);
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,0), 400, 1, Items.REDSTONE, Blocks.REDSTONE_TORCH, basicCircuit, controlCircuitBoard);
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,1), 400, 1, Items.FIRE_CHARGE, Items.DIAMOND, advancedCircuit, controlCircuitBoard);
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,2), 400, 1, AdvancedRocketryBlocks.blockMotor, "rodTitanium", advancedCircuit, controlCircuitBoard);
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,3), 400, 1, Items.LEATHER_BOOTS, Items.FEATHER, advancedCircuit, controlCircuitBoard);
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,4), 400, 1, LibVulpesItems.itemBattery, AdvancedRocketryItems.itemLens, advancedCircuit, controlCircuitBoard);
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemAtmAnalyser), 1000, 1, smallBattery, advancedCircuit, "plateTin", AdvancedRocketryItems.itemLens, userInterface);
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemBiomeChanger), 1000, 1, smallBattery, advancedCircuit, "plateTin", trackingCircuit, userInterface);
RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, biomeChanger, 1000, 1, new NumberedOreDictStack("stickCopper", 2), "stickTitanium", new NumberedOreDictStack("waferSilicon", 2), advancedCircuit);
//BlastFurnace
RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("Silicon").getProduct(AllowedProducts.getProductByName("INGOT")), 12000, 1, Blocks.SAND);
RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("Steel").getProduct(AllowedProducts.getProductByName("INGOT")), 6000, 1, "ingotIron", Items.COAL);
//TODO add 2Al2O3 as output
RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("TitaniumAluminide").getProduct(AllowedProducts.getProductByName("INGOT"), 3), 9000, 20, new NumberedOreDictStack("ingotAluminum", 7), new NumberedOreDictStack("ingotTitanium", 3)); //TODO titanium dioxide
//Chemical Reactor
RecipesMachine.getInstance().addRecipe(TileChemicalReactor.class, new Object[] {new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge,1, 0), new ItemStack(Items.COAL, 1, 1)}, 40, 20, new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge, 1, AdvancedRocketryItems.itemCarbonScrubberCartridge.getMaxDamage()));
RecipesMachine.getInstance().addRecipe(TileChemicalReactor.class, new ItemStack(Items.DYE,5,0xF), 100, 1, Items.BONE, new FluidStack(AdvancedRocketryFluids.fluidNitrogen, 10));
//Rolling Machine
RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 0), 100, 1, "sheetIron", "sheetIron");
RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 1), 200, 2, "sheetSteel", "sheetSteel");
RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 2), 100, 1, "sheetAluminum", "sheetAluminum");
RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 3), 1000, 8, "sheetTitanium", "sheetTitanium");
NetworkRegistry.INSTANCE.registerGuiHandler(this, new zmaster587.advancedRocketry.inventory.GuiHandler());
planetWorldType = new WorldTypePlanetGen("PlanetCold");
spaceWorldType = new WorldTypeSpace("Space");
AdvancedRocketryBiomes.moonBiome = new BiomeGenMoon(config.get(BIOMECATETORY, "moonBiomeId", 90).getInt(), true);
AdvancedRocketryBiomes.alienForest = new BiomeGenAlienForest(config.get(BIOMECATETORY, "alienForestBiomeId", 91).getInt(), true);
AdvancedRocketryBiomes.hotDryBiome = new BiomeGenHotDryRock(config.get(BIOMECATETORY, "hotDryBiome", 92).getInt(), true);
AdvancedRocketryBiomes.spaceBiome = new BiomeGenSpace(config.get(BIOMECATETORY, "spaceBiomeId", 93).getInt(), true);
AdvancedRocketryBiomes.stormLandsBiome = new BiomeGenStormland(config.get(BIOMECATETORY, "stormLandsBiomeId", 94).getInt(), true);
AdvancedRocketryBiomes.crystalChasms = new BiomeGenCrystal(config.get(BIOMECATETORY, "crystalChasmsBiomeId", 95).getInt(), true);
AdvancedRocketryBiomes.swampDeepBiome = new BiomeGenDeepSwamp(config.get(BIOMECATETORY, "deepSwampBiomeId", 96).getInt(), true);
AdvancedRocketryBiomes.marsh = new BiomeGenMarsh(config.get(BIOMECATETORY, "marsh", 97).getInt(), true);
AdvancedRocketryBiomes.oceanSpires = new BiomeGenOceanSpires(config.get(BIOMECATETORY, "oceanSpires", 98).getInt(), true);
AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.moonBiome);
AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.alienForest);
AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.hotDryBiome);
AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.spaceBiome);
AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.stormLandsBiome);
AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.crystalChasms);
AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.swampDeepBiome);
AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.marsh);
AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.oceanSpires);
String[] biomeBlackList = config.getStringList("BlacklistedBiomes", "Planet", new String[] {"7", "8", "9", "127", String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.alienForest))}, "List of Biomes to be blacklisted from spawning as BiomeIds, default is: river, sky, hell, void, alienForest");
String[] biomeHighPressure = config.getStringList("HighPressureBiomes", "Planet", new String[] { String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.swampDeepBiome)), String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.stormLandsBiome)) }, "Biomes that only spawn on worlds with pressures over 125, will override blacklist. Defaults: StormLands, DeepSwamp");
String[] biomeSingle = config.getStringList("SingleBiomes", "Planet", new String[] { String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.swampDeepBiome)), String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.crystalChasms)), String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.alienForest)), String.valueOf(Biome.getIdForBiome(Biomes.DESERT_HILLS)),
String.valueOf(Biome.getIdForBiome(Biomes.MUSHROOM_ISLAND)), String.valueOf(Biome.getIdForBiome(Biomes.EXTREME_HILLS)), String.valueOf(Biome.getIdForBiome(Biomes.ICE_PLAINS)) }, "Some worlds have a chance of spawning single biomes contained in this list. Defaults: deepSwamp, crystalChasms, alienForest, desert hills, mushroom island, extreme hills, ice plains");
config.save();
//Prevent these biomes from spawning normally
AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.moonBiome);
AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.hotDryBiome);
AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.spaceBiome);
//Read BlackList from config and register Blacklisted biomes
for(String string : biomeBlackList) {
try {
int id = Integer.parseInt(string);
Biome biome = Biome.getBiome(id, null);
if(biome == null)
logger.warning(String.format("Error blackListing biome id \"%d\", a biome with that ID does not exist!", id));
else
AdvancedRocketryBiomes.instance.registerBlackListBiome(biome);
} catch (NumberFormatException e) {
logger.warning("Error blackListing \"" + string + "\". It is not a valid number");
}
}
if(zmaster587.advancedRocketry.api.Configuration.blackListAllVanillaBiomes) {
AdvancedRocketryBiomes.instance.blackListVanillaBiomes();
}
//Read and Register High Pressure biomes from config
for(String string : biomeHighPressure) {
try {
int id = Integer.parseInt(string);
Biome biome = Biome.getBiome(id, null);
if(biome == null)
logger.warning(String.format("Error registering high pressure biome id \"%d\", a biome with that ID does not exist!", id));
else
AdvancedRocketryBiomes.instance.registerHighPressureBiome(biome);
} catch (NumberFormatException e) {
logger.warning("Error registering high pressure biome \"" + string + "\". It is not a valid number");
}
}
//Read and Register Single biomes from config
for(String string : biomeSingle) {
try {
int id = Integer.parseInt(string);
Biome biome = Biome.getBiome(id, null);
if(biome == null)
logger.warning(String.format("Error registering single biome id \"%d\", a biome with that ID does not exist!", id));
else
AdvancedRocketryBiomes.instance.registerSingleBiome(biome);
} catch (NumberFormatException e) {
logger.warning("Error registering single biome \"" + string + "\". It is not a valid number");
}
}
}
@EventHandler
public void postInit(FMLPostInitializationEvent event)
{
proxy.registerEventHandlers();
proxy.registerKeyBindings();
ARAchivements.register();
//TODO: debug
//ClientCommandHandler.instance.registerCommand(new Debugger());
PlanetEventHandler handle = new PlanetEventHandler();
MinecraftForge.EVENT_BUS.register(handle);
//MinecraftForge.EVENT_BUS.register(new BucketHandler());
CableTickHandler cable = new CableTickHandler();
MinecraftForge.EVENT_BUS.register(cable);
InputSyncHandler inputSync = new InputSyncHandler();
MinecraftForge.EVENT_BUS.register(inputSync);
MinecraftForge.EVENT_BUS.register(new MapGenLander());
/*if(Loader.isModLoaded("GalacticraftCore") && zmaster587.advancedRocketry.api.Configuration.overrideGCAir) {
GalacticCraftHandler eventHandler = new GalacticCraftHandler();
MinecraftForge.EVENT_BUS.register(eventHandler);
if(event.getSide().isClient())
FMLCommonHandler.instance().bus().register(eventHandler);
}*/
MinecraftForge.EVENT_BUS.register(SpaceObjectManager.getSpaceManager());
PacketHandler.init();
FuelRegistry.instance.registerFuel(FuelType.LIQUID, AdvancedRocketryFluids.fluidRocketFuel, 1);
GameRegistry.registerWorldGenerator(new OreGenerator(), 100);
ForgeChunkManager.setForcedChunkLoadingCallback(instance, new WorldEvents());
//AutoGenned Recipes
for(zmaster587.libVulpes.api.material.Material ore : MaterialRegistry.getAllMaterials()) {
if(AllowedProducts.getProductByName("ORE").isOfType(ore.getAllowedProducts()) && AllowedProducts.getProductByName("INGOT").isOfType(ore.getAllowedProducts()))
GameRegistry.addSmelting(ore.getProduct(AllowedProducts.getProductByName("ORE")), ore.getProduct(AllowedProducts.getProductByName("INGOT")), 0);
if(AllowedProducts.getProductByName("NUGGET").isOfType(ore.getAllowedProducts())) {
ItemStack nugget = ore.getProduct(AllowedProducts.getProductByName("NUGGET"));
nugget.stackSize = 9;
for(String str : ore.getOreDictNames()) {
GameRegistry.addRecipe(new ShapelessOreRecipe(nugget, AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str));
GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("INGOT")), "ooo", "ooo", "ooo", 'o', AllowedProducts.getProductByName("NUGGET").name().toLowerCase() + str));
}
}
if(AllowedProducts.getProductByName("CRYSTAL").isOfType(ore.getAllowedProducts())) {
for(String str : ore.getOreDictNames())
RecipesMachine.getInstance().addRecipe(TileCrystallizer.class, ore.getProduct(AllowedProducts.getProductByName("CRYSTAL")), 300, 20, AllowedProducts.getProductByName("DUST").name().toLowerCase() + str);
}
if(AllowedProducts.getProductByName("BOULE").isOfType(ore.getAllowedProducts())) {
for(String str : ore.getOreDictNames())
RecipesMachine.getInstance().addRecipe(TileCrystallizer.class, ore.getProduct(AllowedProducts.getProductByName("BOULE")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str, AllowedProducts.getProductByName("NUGGET").name().toLowerCase() + str);
}
if(AllowedProducts.getProductByName("STICK").isOfType(ore.getAllowedProducts()) && AllowedProducts.getProductByName("INGOT").isOfType(ore.getAllowedProducts())) {
for(String name : ore.getOreDictNames())
if(OreDictionary.doesOreNameExist(AllowedProducts.getProductByName("INGOT").name().toLowerCase() + name))
RecipesMachine.getInstance().addRecipe(TileLathe.class, ore.getProduct(AllowedProducts.getProductByName("STICK")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase() + name); //ore.getProduct(AllowedProducts.getProductByName("INGOT")));
}
if(AllowedProducts.getProductByName("PLATE").isOfType(ore.getAllowedProducts())) {
for(String oreDictNames : ore.getOreDictNames()) {
if(OreDictionary.doesOreNameExist(AllowedProducts.getProductByName("INGOT").name().toLowerCase() + oreDictNames)) {
RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, ore.getProduct(AllowedProducts.getProductByName("PLATE")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase() + oreDictNames);
if(AllowedProducts.getProductByName("BLOCK").isOfType(ore.getAllowedProducts()) || ore.isVanilla())
RecipesMachine.getInstance().addRecipe(BlockPress.class, ore.getProduct(AllowedProducts.getProductByName("PLATE"),3), 0, 0, AllowedProducts.getProductByName("BLOCK").name().toLowerCase() + oreDictNames);
}
}
}
if(AllowedProducts.getProductByName("SHEET").isOfType(ore.getAllowedProducts())) {
for(String oreDictNames : ore.getOreDictNames()) {
RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, ore.getProduct(AllowedProducts.getProductByName("SHEET")), 300, 200, AllowedProducts.getProductByName("PLATE").name().toLowerCase() + oreDictNames);
}
}
if(AllowedProducts.getProductByName("COIL").isOfType(ore.getAllowedProducts())) {
for(String str : ore.getOreDictNames())
GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("COIL")), "ooo", "o o", "ooo",'o', AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str));
}
if(AllowedProducts.getProductByName("FAN").isOfType(ore.getAllowedProducts())) {
for(String str : ore.getOreDictNames()) {
GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("FAN")), "p p", " r ", "p p", 'p', AllowedProducts.getProductByName("PLATE").name().toLowerCase() + str, 'r', AllowedProducts.getProductByName("STICK").name().toLowerCase() + str));
}
}
if(AllowedProducts.getProductByName("GEAR").isOfType(ore.getAllowedProducts())) {
for(String str : ore.getOreDictNames()) {
GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("GEAR")), "sps", " r ", "sps", 'p', AllowedProducts.getProductByName("PLATE").name().toLowerCase() + str, 's', AllowedProducts.getProductByName("STICK").name().toLowerCase() + str, 'r', AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str));
}
}
if(AllowedProducts.getProductByName("BLOCK").isOfType(ore.getAllowedProducts())) {
ItemStack ingot = ore.getProduct(AllowedProducts.getProductByName("INGOT"));
ingot.stackSize = 9;
for(String str : ore.getOreDictNames()) {
GameRegistry.addRecipe(new ShapelessOreRecipe(ingot, AllowedProducts.getProductByName("BLOCK").name().toLowerCase() + str));
GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("BLOCK")), "ooo", "ooo", "ooo", 'o', AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str));
}
}
if(AllowedProducts.getProductByName("DUST").isOfType(ore.getAllowedProducts())) {
for(String str : ore.getOreDictNames()) {
if(AllowedProducts.getProductByName("ORE").isOfType(ore.getAllowedProducts()) || ore.isVanilla())
RecipesMachine.getInstance().addRecipe(BlockPress.class, ore.getProduct(AllowedProducts.getProductByName("DUST")), 0, 0, AllowedProducts.getProductByName("ORE").name().toLowerCase() + str);
}
}
}
//Handle vanilla integration
if(zmaster587.advancedRocketry.api.Configuration.allowSawmillVanillaWood) {
for(int i = 0; i < 4; i++) {
RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(Blocks.PLANKS, 6, i), 80, 10, new ItemStack(Blocks.LOG,1, i));
}
RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(Blocks.PLANKS, 6, 4), 80, 10, new ItemStack(Blocks.LOG2,1, 0));
}
//Handle items from other mods
if(zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) {
for(Entry<AllowedProducts, HashSet<String>> entry : modProducts.entrySet()) {
if(entry.getKey() == AllowedProducts.getProductByName("PLATE")) {
for(String str : entry.getValue()) {
zmaster587.libVulpes.api.material.Material material = zmaster587.libVulpes.api.material.Material.valueOfSafe(str.toUpperCase());
if(OreDictionary.doesOreNameExist("ingot" + str) && OreDictionary.getOres("ingot" + str).size() > 0 && (material == null || !AllowedProducts.getProductByName("PLATE").isOfType(material.getAllowedProducts())) ) {
RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, OreDictionary.getOres("plate" + str).get(0), 300, 20, "ingot" + str);
}
}
}
else if(entry.getKey() == AllowedProducts.getProductByName("STICK")) {
for(String str : entry.getValue()) {
zmaster587.libVulpes.api.material.Material material = zmaster587.libVulpes.api.material.Material.valueOfSafe(str.toUpperCase());
if(OreDictionary.doesOreNameExist("ingot" + str) && OreDictionary.getOres("ingot" + str).size() > 0 && (material == null || !AllowedProducts.getProductByName("STICK").isOfType(material.getAllowedProducts())) ) {
//GT registers rods as sticks
if(OreDictionary.doesOreNameExist("rod" + str) && OreDictionary.getOres("rod" + str).size() > 0)
RecipesMachine.getInstance().addRecipe(TileLathe.class, OreDictionary.getOres("rod" + str).get(0), 300, 20, "ingot" + str);
else if(OreDictionary.doesOreNameExist("stick" + str) && OreDictionary.getOres("stick" + str).size() > 0) {
RecipesMachine.getInstance().addRecipe(TileLathe.class, OreDictionary.getOres("stick" + str).get(0), 300, 20, "ingot" + str);
}
}
}
}
}
}
//Register buckets
BucketHandler.INSTANCE.registerBucket(AdvancedRocketryBlocks.blockFuelFluid, AdvancedRocketryItems.itemBucketRocketFuel);
FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidRocketFuel, new ItemStack(AdvancedRocketryItems.itemBucketRocketFuel), new ItemStack(Items.BUCKET));
FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidNitrogen, new ItemStack(AdvancedRocketryItems.itemBucketNitrogen), new ItemStack(Items.BUCKET));
FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidHydrogen, new ItemStack(AdvancedRocketryItems.itemBucketHydrogen), new ItemStack(Items.BUCKET));
FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidOxygen, new ItemStack(AdvancedRocketryItems.itemBucketOxygen), new ItemStack(Items.BUCKET));
//Register mixed material's recipes
for(MixedMaterial material : MaterialRegistry.getMixedMaterialList()) {
RecipesMachine.getInstance().addRecipe(material.getMachine(), material.getProducts(), 100, 10, material.getInput());
}
//Register space dimension
net.minecraftforge.common.DimensionManager.registerDimension(zmaster587.advancedRocketry.api.Configuration.spaceDimId, DimensionManager.spaceDimensionType);
//Register Whitelisted Sealable Blocks
logger.fine("Start registering sealable blocks");
for(String str : sealableBlockWhileList) {
Block block = Block.getBlockFromName(str);
if(block == null)
logger.warning("'" + str + "' is not a valid Block");
else
SealableBlockHandler.INSTANCE.addSealableBlock(block);
}
logger.fine("End registering sealable blocks");
sealableBlockWhileList = null;
//Add mappings for multiblockmachines
//Data mapping 'D'
List<BlockMeta> list = new LinkedList<BlockMeta>();
list.add(new BlockMeta(AdvancedRocketryBlocks.blockLoader, 0));
list.add(new BlockMeta(AdvancedRocketryBlocks.blockLoader, 8));
TileMultiBlock.addMapping('D', list);
}
@EventHandler
public void serverStarted(FMLServerStartedEvent event) {
for (int dimId : DimensionManager.getInstance().getLoadedDimensions()) {
DimensionProperties properties = DimensionManager.getInstance().getDimensionProperties(dimId);
if(!properties.isNativeDimension) {
if(properties.getId() != zmaster587.advancedRocketry.api.Configuration.MoonId)
DimensionManager.getInstance().deleteDimension(properties.getId());
else if (!Loader.isModLoaded("GalacticraftCore"))
properties.isNativeDimension = true;
}
}
}
@EventHandler
public void serverStarting(FMLServerStartingEvent event) {
event.registerServerCommand(new WorldCommand());
//Register hard coded dimensions
if(!zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().loadDimensions(zmaster587.advancedRocketry.dimension.DimensionManager.filePath)) {
int numRandomGeneratedPlanets = 9;
int numRandomGeneratedGasGiants = 1;
File file = new File("./config/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/planetDefs.xml");
logger.info("Checking for config at " + file.getAbsolutePath());
if(file.exists()) {
logger.info("File found!");
XMLPlanetLoader loader = new XMLPlanetLoader();
try {
loader.loadFile(file);
List<DimensionProperties> list = loader.readAllPlanets();
for(DimensionProperties properties : list)
DimensionManager.getInstance().registerDim(properties, true);
numRandomGeneratedPlanets = loader.getMaxNumPlanets();
numRandomGeneratedGasGiants = loader.getMaxNumGasGiants();
} catch(IOException e) {
logger.severe("XML planet config exists but cannot be loaded! Defaulting to random gen.");
}
}
if(zmaster587.advancedRocketry.api.Configuration.MoonId == -1)
zmaster587.advancedRocketry.api.Configuration.MoonId = DimensionManager.getInstance().getNextFreeDim();
DimensionProperties dimensionProperties = new DimensionProperties(zmaster587.advancedRocketry.api.Configuration.MoonId);
dimensionProperties.setAtmosphereDensityDirect(0);
dimensionProperties.averageTemperature = 20;
dimensionProperties.gravitationalMultiplier = .166f; //Actual moon value
dimensionProperties.setName("Luna");
dimensionProperties.orbitalDist = 150;
dimensionProperties.addBiome(AdvancedRocketryBiomes.moonBiome);
dimensionProperties.setParentPlanet(DimensionManager.overworldProperties);
dimensionProperties.setStar(DimensionManager.getSol());
dimensionProperties.isNativeDimension = !Loader.isModLoaded("GalacticraftCore");
DimensionManager.getInstance().registerDimNoUpdate(dimensionProperties, !Loader.isModLoaded("GalacticraftCore"));
Random random = new Random(System.currentTimeMillis());
for(int i = 0; i < numRandomGeneratedGasGiants; i++) {
int baseAtm = 180;
int baseDistance = 100;
DimensionProperties properties = DimensionManager.getInstance().generateRandomGasGiant("",baseDistance + 50,baseAtm,125,100,100,75);
if(properties.gravitationalMultiplier >= 1f) {
int numMoons = random.nextInt(8);
for(int ii = 0; ii < numMoons; ii++) {
DimensionProperties moonProperties = DimensionManager.getInstance().generateRandom(properties.getName() + ": " + ii, 25,100, (int)(properties.gravitationalMultiplier/.02f), 25, 100, 50);
moonProperties.setParentPlanet(properties);
}
}
}
for(int i = 0; i < numRandomGeneratedPlanets; i++) {
int baseAtm = 75;
int baseDistance = 100;
if(i % 4 == 0) {
baseAtm = 0;
}
else if(i != 6 && (i+2) % 4 == 0)
baseAtm = 120;
if(i % 3 == 0) {
baseDistance = 170;
}
else if((i + 1) % 3 == 0) {
baseDistance = 30;
}
DimensionProperties properties = DimensionManager.getInstance().generateRandom(baseDistance,baseAtm,125,100,100,75);
if(properties.gravitationalMultiplier >= 1f) {
int numMoons = random.nextInt(4);
for(int ii = 0; ii < numMoons; ii++) {
DimensionProperties moonProperties = DimensionManager.getInstance().generateRandom(properties.getName() + ": " + ii, 25,100, (int)(properties.gravitationalMultiplier/.02f), 25, 100, 50);
moonProperties.setParentPlanet(properties);
}
}
}
}
else if(Loader.isModLoaded("GalacticraftCore") ) {
DimensionManager.getInstance().getDimensionProperties(zmaster587.advancedRocketry.api.Configuration.MoonId).isNativeDimension = false;
}
}
@EventHandler
public void serverStopped(FMLServerStoppedEvent event) {
zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().unregisterAllDimensions();
zmaster587.advancedRocketry.cable.NetworkRegistry.clearNetworks();
}
@SubscribeEvent
public void registerOre(OreRegisterEvent event) {
if(!zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods)
return;
for(AllowedProducts product : AllowedProducts.getAllAllowedProducts() ) {
if(event.getName().startsWith(product.name().toLowerCase())) {
HashSet<String> list = modProducts.get(product);
if(list == null) {
list = new HashSet<String>();
modProducts.put(product, list);
}
list.add(event.getName().substring(product.name().length()));
}
}
//GT uses stick instead of Rod
if(event.getName().startsWith("stick")) {
HashSet<String> list = modProducts.get(AllowedProducts.getProductByName("STICK"));
if(list == null) {
list = new HashSet<String>();
modProducts.put(AllowedProducts.getProductByName("STICK"), list);
}
list.add(event.getName().substring("stick".length()));
}
}
}
|
package net.java.sip.communicator.impl.gui.main.menus;
import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.event.*;
import net.java.sip.communicator.impl.gui.main.*;
import net.java.sip.communicator.plugin.desktoputil.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.gui.Container;
import net.java.sip.communicator.util.*;
import org.osgi.framework.*;
import java.awt.*;
/**
* The <tt>ViewMenu</tt> is a menu in the main application menu bar.
*
* @author Yana Stamcheva
*/
public class ViewMenu
extends SIPCommMenu
implements PluginComponentListener
{
private static final long serialVersionUID = 0L;
/**
* The logger.
*/
private final Logger logger = Logger.getLogger(ViewMenu.class);
/**
* Creates an instance of <tt>ViewMenu</tt>.
* @param mainFrame The parent <tt>MainFrame</tt> window.
*/
public ViewMenu(MainFrame mainFrame)
{
super(GuiActivator.getResources().getI18NString("service.gui.VIEW"));
this.setMnemonic(
GuiActivator.getResources().getI18nMnemonic("service.gui.VIEW"));
this.initPluginComponents();
}
/**
* Searches for already registered plugins.
*/
private void initPluginComponents()
{
// Search for plugin components registered through the OSGI bundle
// context.
ServiceReference[] serRefs = null;
String osgiFilter = "("
+ Container.CONTAINER_ID
+ "="+Container.CONTAINER_VIEW_MENU.getID()+")";
try
{
serRefs = GuiActivator.bundleContext.getServiceReferences(
PluginComponentFactory.class.getName(),
osgiFilter);
}
catch (InvalidSyntaxException exc)
{
logger.error("Could not obtain plugin reference.", exc);
}
if (serRefs != null)
{
for (ServiceReference serRef : serRefs)
{
PluginComponent component = (PluginComponent) GuiActivator
.bundleContext.getService(serRef);
this.add((Component)component.getComponent());
}
}
GuiActivator.getUIService().addPluginComponentListener(this);
}
/**
* Adds the plugin component contained in the event to this container.
* @param event the <tt>PluginComponentEvent</tt> that notified us
*/
public void pluginComponentAdded(PluginComponentEvent event)
{
PluginComponentFactory c = event.getPluginComponentFactory();
if(c.getContainer().equals(Container.CONTAINER_VIEW_MENU))
{
this.add((Component)c.getPluginComponentInstance(ViewMenu.this)
.getComponent());
this.revalidate();
this.repaint();
}
}
/**
* Indicates that a plugin component has been removed. Removes it from this
* container if it is contained in it.
* @param event the <tt>PluginComponentEvent</tt> that notified us
*/
public void pluginComponentRemoved(PluginComponentEvent event)
{
PluginComponentFactory c = event.getPluginComponentFactory();
if(c.getContainer().equals(Container.CONTAINER_VIEW_MENU))
{
this.remove((Component) c.getPluginComponentInstance(ViewMenu.this)
.getComponent());
}
}
}
|
package org.objectweb.asm.tree;
import java.util.ListIterator;
import junit.framework.TestCase;
/**
* InsnList unit tests.
*
* @author Eric Bruneton
*/
public class InsnListUnitTest extends TestCase {
InsnList l1;
InsnList l2;
InsnNode in1;
InsnNode in2;
protected void setUp() throws Exception {
super.setUp();
InsnList.check = true;
l1 = new InsnList();
l2 = new InsnList();
in1 = new InsnNode(0);
in2 = new InsnNode(0);
l2.add(in1);
l2.add(in2);
}
protected void assertEquals(
final AbstractInsnNode[] expected,
final AbstractInsnNode[] value)
{
assertEquals(expected.length, value.length);
for (int i = 0; i < value.length; ++i) {
assertEquals(expected[i], value[i]);
}
}
public void testSize() {
assertEquals(0, l1.size());
}
public void testGetFirst() {
assertEquals(null, l1.getFirst());
}
public void testGetLast() {
assertEquals(null, l1.getLast());
}
public void testInvalidGet() {
try {
l1.get(0);
fail();
} catch (IndexOutOfBoundsException e) {
}
}
public void testContains() {
assertEquals(false, l1.contains(new InsnNode(0)));
}
public void testIterator() {
InsnNode insn = new InsnNode(0);
// iteration
ListIterator it = l2.iterator();
assertTrue(it.hasNext());
assertEquals(in1, it.next());
assertTrue(it.hasNext());
assertEquals(in2, it.next());
assertFalse(it.hasNext());
assertTrue(it.hasPrevious());
assertEquals(in2, it.previous());
assertTrue(it.hasPrevious());
assertEquals(in1, it.previous());
assertFalse(it.hasPrevious());
l2.add(insn);
// remove()
it = l2.iterator();
assertTrue(it.hasNext());
assertEquals(in1, it.next());
assertTrue(it.hasNext());
assertEquals(in2, it.next());
assertTrue(it.hasNext());
it.remove(); // remove in2
assertTrue(it.hasNext());
assertEquals(insn, it.next());
assertFalse(it.hasNext());
assertTrue(it.hasPrevious());
it = l2.iterator();
assertTrue(it.hasNext());
assertEquals(in1, it.next());
assertTrue(it.hasNext());
assertEquals(insn, it.next());
assertFalse(it.hasNext());
l2.remove(insn);
l2.insert(in1, in2);
// add() then next()
it = l2.iterator();
assertTrue(it.hasNext());
assertEquals(in1, it.next());
it.add(insn);
assertEquals(in2, it.next());
l2.remove(insn);
// add() then previous()
it = l2.iterator();
assertTrue(it.hasNext());
assertEquals(in1, it.next());
it.add(insn);
assertEquals(insn, it.previous());
assertEquals(insn, it.next());
assertTrue(it.hasNext());
assertEquals(in2, it.next());
assertFalse(it.hasNext());
l2.remove(insn);
// set() then previous()
it = l2.iterator();
assertTrue(it.hasNext());
assertEquals(in1, it.next());
it.set(insn);
assertEquals(insn, it.previous());
assertEquals(insn, it.next());
assertTrue(it.hasNext());
l2.remove(insn);
l2.insertBefore(in2, in1);
// add() then next()
it = l2.iterator();
assertTrue(it.hasNext());
assertEquals(in1, it.next());
it.set(insn);
assertEquals(in2, it.next());
}
public void testIterator2() {
ListIterator it = l2.iterator(l2.size());
assertFalse(it.hasNext());
assertTrue(it.hasPrevious());
assertEquals(1, it.previousIndex());
assertEquals(in2, it.previous());
assertTrue(it.hasPrevious());
assertEquals(0, it.previousIndex());
assertEquals(in1, it.previous());
assertFalse(it.hasPrevious());
assertEquals(-1, it.previousIndex());
assertTrue(it.hasNext());
assertEquals(0, it.nextIndex());
assertEquals(in1, it.next());
assertTrue(it.hasNext());
assertEquals(1, it.nextIndex());
InsnNode insn = new InsnNode(0);
it.add(insn);
assertEquals(2, it.nextIndex());
assertEquals(in2, it.next());
assertFalse(it.hasNext());
assertEquals(3, it.nextIndex());
}
public void testInvalidIndexOf() {
try {
l1.indexOf(new InsnNode(0));
fail();
} catch (IllegalArgumentException e) {
}
}
public void testToArray() {
assertEquals(0, l1.toArray().length);
}
public void testInvalidSet() {
try {
l1.set(new InsnNode(0), new InsnNode(0));
fail();
} catch (IllegalArgumentException e) {
}
}
public void testSet() {
l1.add(new InsnNode(0));
AbstractInsnNode insn = new InsnNode(0);
l1.set(l1.getFirst(), insn);
assertEquals(1, l1.size());
assertEquals(insn, l1.getFirst());
l1.remove(insn);
l1.add(new InsnNode(0));
l1.set(l1.get(0), insn);
assertEquals(1, l1.size());
assertEquals(insn, l1.getFirst());
}
public void testInvalidAdd() {
try {
l1.add(in1);
fail();
} catch (IllegalArgumentException e) {
}
}
public void testAddEmpty() {
InsnNode insn = new InsnNode(0);
l1.add(insn);
assertEquals(1, l1.size());
assertEquals(insn, l1.getFirst());
assertEquals(insn, l1.getLast());
assertEquals(insn, l1.get(0));
assertEquals(true, l1.contains(insn));
assertEquals(0, l1.indexOf(insn));
assertEquals(new AbstractInsnNode[] { insn }, l1.toArray());
assertEquals(null, insn.getPrevious());
assertEquals(null, insn.getNext());
}
public void testAddNonEmpty() {
InsnNode insn = new InsnNode(0);
l1.add(new InsnNode(0));
l1.add(insn);
assertEquals(2, l1.size());
assertEquals(insn, l1.getLast());
assertEquals(insn, l1.get(1));
assertEquals(true, l1.contains(insn));
assertEquals(1, l1.indexOf(insn));
}
public void testAddEmptyList() {
l1.add(new InsnList());
assertEquals(0, l1.size());
assertEquals(null, l1.getFirst());
assertEquals(null, l1.getLast());
assertEquals(new AbstractInsnNode[0], l1.toArray());
}
public void testInvalidAddAll() {
try {
l1.add(l1);
fail();
} catch (IllegalArgumentException e) {
}
}
public void testAddAllEmpty() {
l1.add(l2);
assertEquals(2, l1.size());
assertEquals(in1, l1.getFirst());
assertEquals(in2, l1.getLast());
assertEquals(in1, l1.get(0));
assertEquals(true, l1.contains(in1));
assertEquals(true, l1.contains(in2));
assertEquals(0, l1.indexOf(in1));
assertEquals(1, l1.indexOf(in2));
assertEquals(new AbstractInsnNode[] { in1, in2 }, l1.toArray());
}
public void testAddAllNonEmpty() {
InsnNode insn = new InsnNode(0);
l1.add(insn);
l1.add(l2);
assertEquals(3, l1.size());
assertEquals(insn, l1.getFirst());
assertEquals(in2, l1.getLast());
assertEquals(insn, l1.get(0));
assertEquals(true, l1.contains(insn));
assertEquals(true, l1.contains(in1));
assertEquals(true, l1.contains(in2));
assertEquals(0, l1.indexOf(insn));
assertEquals(1, l1.indexOf(in1));
assertEquals(2, l1.indexOf(in2));
assertEquals(new AbstractInsnNode[] { insn, in1, in2 }, l1.toArray());
}
public void testInvalidInsert() {
try {
l1.insert(in1);
fail();
} catch (IllegalArgumentException e) {
}
}
public void testInsertEmpty() {
InsnNode insn = new InsnNode(0);
l1.insert(insn);
assertEquals(1, l1.size());
assertEquals(insn, l1.getFirst());
assertEquals(insn, l1.getLast());
assertEquals(insn, l1.get(0));
assertEquals(true, l1.contains(insn));
assertEquals(0, l1.indexOf(insn));
assertEquals(new AbstractInsnNode[] { insn }, l1.toArray());
}
public void testInsertNonEmpty() {
InsnNode insn = new InsnNode(0);
l1.add(new InsnNode(0));
l1.insert(insn);
assertEquals(2, l1.size());
assertEquals(insn, l1.getFirst());
assertEquals(insn, l1.get(0));
assertEquals(true, l1.contains(insn));
assertEquals(0, l1.indexOf(insn));
}
public void testInvalidInsertAll() {
try {
l1.insert(l1);
fail();
} catch (IllegalArgumentException e) {
}
}
public void testInsertAllEmptyList() {
l1.insert(new InsnList());
assertEquals(0, l1.size());
assertEquals(null, l1.getFirst());
assertEquals(null, l1.getLast());
assertEquals(new AbstractInsnNode[0], l1.toArray());
}
public void testInsertAllEmpty() {
l1.insert(l2);
assertEquals(2, l1.size(), 2);
assertEquals(in1, l1.getFirst());
assertEquals(in2, l1.getLast());
assertEquals(in1, l1.get(0));
assertEquals(true, l1.contains(in1));
assertEquals(true, l1.contains(in2));
assertEquals(0, l1.indexOf(in1));
assertEquals(1, l1.indexOf(in2));
assertEquals(new AbstractInsnNode[] { in1, in2 }, l1.toArray());
}
public void testInsertAllNonEmpty() {
InsnNode insn = new InsnNode(0);
l1.add(insn);
l1.insert(l2);
assertEquals(3, l1.size());
assertEquals(in1, l1.getFirst());
assertEquals(insn, l1.getLast());
assertEquals(in1, l1.get(0));
assertEquals(true, l1.contains(insn));
assertEquals(true, l1.contains(in1));
assertEquals(true, l1.contains(in2));
assertEquals(0, l1.indexOf(in1));
assertEquals(1, l1.indexOf(in2));
assertEquals(2, l1.indexOf(insn));
assertEquals(new AbstractInsnNode[] { in1, in2, insn }, l1.toArray());
}
public void testInvalidInsert2() {
try {
l1.insert(new InsnNode(0), new InsnNode(0));
fail();
} catch (IllegalArgumentException e) {
}
}
public void testInsert2NotLast() {
InsnNode insn = new InsnNode(0);
l2.insert(in1, insn);
assertEquals(3, l2.size());
assertEquals(in1, l2.getFirst());
assertEquals(in2, l2.getLast());
assertEquals(in1, l2.get(0));
assertEquals(true, l2.contains(insn));
assertEquals(1, l2.indexOf(insn));
assertEquals(new AbstractInsnNode[] { in1, insn, in2 }, l2.toArray());
}
public void testInsert2Last() {
InsnNode insn = new InsnNode(0);
l2.insert(in2, insn);
assertEquals(3, l2.size());
assertEquals(in1, l2.getFirst());
assertEquals(insn, l2.getLast());
assertEquals(in1, l2.get(0));
assertEquals(true, l2.contains(insn));
assertEquals(2, l2.indexOf(insn));
assertEquals(new AbstractInsnNode[] { in1, in2, insn }, l2.toArray());
}
public void testInsertBefore() {
InsnNode insn = new InsnNode(0);
l2.insertBefore(in2, insn);
assertEquals(3, l2.size());
assertEquals(in1, l2.getFirst());
assertEquals(in2, l2.getLast());
assertEquals(insn, l2.get(1));
assertEquals(true, l2.contains(insn));
assertEquals(1, l2.indexOf(insn));
assertEquals(new AbstractInsnNode[] { in1, insn, in2 }, l2.toArray());
}
public void testInsertBeforeFirst() {
InsnNode insn = new InsnNode(0);
l2.insertBefore(in1, insn);
assertEquals(3, l2.size());
assertEquals(insn, l2.getFirst());
assertEquals(in2, l2.getLast());
assertEquals(insn, l2.get(0));
assertEquals(true, l2.contains(insn));
assertEquals(0, l2.indexOf(insn));
assertEquals(new AbstractInsnNode[] { insn, in1, in2 }, l2.toArray());
}
public void testInvalidInsertBefore() {
try {
l1.insertBefore(new InsnNode(0), new InsnNode(0));
fail();
} catch (IllegalArgumentException e) {
}
}
public void testInvalidInsertAll2() {
try {
l1.insert(new InsnNode(0), new InsnList());
fail();
} catch (IllegalArgumentException e) {
}
}
public void testInsertAll2EmptyList() {
InsnNode insn = new InsnNode(0);
l1.add(insn);
l1.insert(insn, new InsnList());
assertEquals(1, l1.size());
assertEquals(insn, l1.getFirst());
assertEquals(insn, l1.getLast());
assertEquals(new AbstractInsnNode[] { insn }, l1.toArray());
}
public void testInsertAll2NotLast() {
InsnNode insn = new InsnNode(0);
l1.add(insn);
l1.add(new InsnNode(0));
l1.insert(insn, l2);
assertEquals(4, l1.size());
assertEquals(insn, l1.getFirst());
assertEquals(insn, l1.get(0));
assertEquals(true, l1.contains(insn));
assertEquals(true, l1.contains(in1));
assertEquals(true, l1.contains(in2));
assertEquals(0, l1.indexOf(insn));
assertEquals(1, l1.indexOf(in1));
assertEquals(2, l1.indexOf(in2));
}
public void testInsertAll2Last() {
InsnNode insn = new InsnNode(0);
l1.add(insn);
l1.insert(insn, l2);
assertEquals(3, l1.size());
assertEquals(insn, l1.getFirst());
assertEquals(in2, l1.getLast());
assertEquals(insn, l1.get(0));
assertEquals(true, l1.contains(insn));
assertEquals(true, l1.contains(in1));
assertEquals(true, l1.contains(in2));
assertEquals(0, l1.indexOf(insn));
assertEquals(1, l1.indexOf(in1));
assertEquals(2, l1.indexOf(in2));
assertEquals(new AbstractInsnNode[] { insn, in1, in2 }, l1.toArray());
}
public void testInvalidInsertBeforeAll() {
try {
l1.insertBefore(new InsnNode(0), new InsnList());
fail();
} catch (IllegalArgumentException e) {
}
}
public void testInsertBeforeAll2EmptyList() {
InsnNode insn = new InsnNode(0);
l1.add(insn);
l1.insertBefore(insn, new InsnList());
assertEquals(1, l1.size());
assertEquals(insn, l1.getFirst());
assertEquals(insn, l1.getLast());
assertEquals(new AbstractInsnNode[] { insn }, l1.toArray());
}
public void testInsertBeforeAll2NotLast() {
InsnNode insn = new InsnNode(0);
l1.add(new InsnNode(0));
l1.add(insn);
l1.insertBefore(insn, l2);
assertEquals(4, l1.size());
assertEquals(in1, l1.get(1));
assertEquals(in2, l1.get(2));
assertEquals(true, l1.contains(insn));
assertEquals(true, l1.contains(in1));
assertEquals(true, l1.contains(in2));
assertEquals(3, l1.indexOf(insn));
assertEquals(1, l1.indexOf(in1));
assertEquals(2, l1.indexOf(in2));
}
public void testInsertBeforeAll2First() {
InsnNode insn = new InsnNode(0);
l1.insert(insn);
l1.insertBefore(insn, l2);
assertEquals(3, l1.size());
assertEquals(in1, l1.getFirst());
assertEquals(insn, l1.getLast());
assertEquals(in1, l1.get(0));
assertEquals(true, l1.contains(insn));
assertEquals(true, l1.contains(in1));
assertEquals(true, l1.contains(in2));
assertEquals(2, l1.indexOf(insn));
assertEquals(0, l1.indexOf(in1));
assertEquals(1, l1.indexOf(in2));
assertEquals(new AbstractInsnNode[] { in1, in2, insn }, l1.toArray());
}
public void testInvalidRemove() {
try {
l1.remove(new InsnNode(0));
} catch (IllegalArgumentException e) {
}
}
public void testRemoveSingle() {
InsnNode insn = new InsnNode(0);
l1.add(insn);
l1.remove(insn);
assertEquals(0, l1.size());
assertEquals(null, l1.getFirst());
assertEquals(null, l1.getLast());
assertEquals(false, l1.contains(insn));
assertEquals(new AbstractInsnNode[0], l1.toArray());
assertEquals(null, insn.getPrevious());
assertEquals(null, insn.getNext());
}
public void testRemoveFirst() {
InsnNode insn = new InsnNode(0);
l1.add(insn);
l1.add(new InsnNode(0));
l1.remove(insn);
assertEquals(false, l1.contains(insn));
assertEquals(null, insn.getPrevious());
assertEquals(null, insn.getNext());
}
public void testRemoveMiddle() {
InsnNode insn = new InsnNode(0);
l1.add(new InsnNode(0));
l1.add(insn);
l1.add(new InsnNode(0));
l1.remove(insn);
assertEquals(false, l1.contains(insn));
assertEquals(null, insn.getPrevious());
assertEquals(null, insn.getNext());
}
public void testRemoveLast() {
InsnNode insn = new InsnNode(0);
l1.add(new InsnNode(0));
l1.add(insn);
l1.remove(insn);
assertEquals(false, l1.contains(insn));
assertEquals(null, insn.getPrevious());
assertEquals(null, insn.getNext());
}
public void testClear() {
InsnNode insn = new InsnNode(0);
l1.add(new InsnNode(0));
l1.add(insn);
l1.add(new InsnNode(0));
l1.clear();
assertEquals(0, l1.size());
assertEquals(null, l1.getFirst());
assertEquals(null, l1.getLast());
assertEquals(false, l1.contains(insn));
assertEquals(new AbstractInsnNode[0], l1.toArray());
assertEquals(null, insn.getPrevious());
assertEquals(null, insn.getNext());
}
}
|
package net.fortuna.ical4j.model.property;
import java.text.ParseException;
import junit.framework.TestSuite;
import net.fortuna.ical4j.model.PropertyTest;
/**
* @author fortuna
*
*/
public class CompletedTest extends PropertyTest {
/**
* @param property
* @param expectedValue
*/
public CompletedTest(Completed completed, String expectedValue) {
super(completed, expectedValue);
}
/**
* @return
* @throws ParseException
*/
public static TestSuite suite() throws ParseException {
TestSuite suite = new TestSuite();
suite.addTest(new CompletedTest(new Completed("20061121"), ""));
return suite;
}
}
|
package org.ensembl.healthcheck.testcase.eg_core;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.AbstractRowCountTestCase;
/**
* Test to find genes where display_xref_id is not set
*
* @author dstaines
*
*/
public class DisplayXrefId extends AbstractRowCountTestCase {
public DisplayXrefId() {
super();
this.addToGroup(AbstractEgCoreTestCase.EG_GROUP);
this.appliesToType(DatabaseType.CORE);
this.setTeamResponsible(Team.ENSEMBL_GENOMES);
this.setDescription("Test to find genes where display_xref_id is not set");
}
private final static String QUERY = "select count(*) from gene where status not in ('NOVEL','ANNOTATED') and display_xref_id is null";
/*
* (non-Javadoc)
*
* @see
* org.ensembl.healthcheck.testcase.AbstractRowCountTestCase#getExpectedCount
* ()
*/
@Override
protected int getExpectedCount() {
return 0;
}
/*
* (non-Javadoc)
*
* @see org.ensembl.healthcheck.testcase.AbstractIntegerTestCase#getSql()
*/
@Override
protected String getSql() {
return QUERY;
}
@Override
protected String getErrorMessage(int count) {
return count+" genes with non-novel status found with null display_xref_id";
}
}
|
package org.ow2.proactive_grid_cloud_portal;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.hibernate.collection.PersistentMap;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.api.PAFuture;
import org.ow2.proactive.scheduler.common.Scheduler;
import org.ow2.proactive.scheduler.common.SchedulerState;
import org.ow2.proactive.scheduler.common.SchedulerStatus;
import org.ow2.proactive.scheduler.common.exception.InternalSchedulerException;
import org.ow2.proactive.scheduler.common.exception.JobAlreadyFinishedException;
import org.ow2.proactive.scheduler.common.exception.JobCreationException;
import org.ow2.proactive.scheduler.common.exception.NotConnectedException;
import org.ow2.proactive.scheduler.common.exception.PermissionException;
import org.ow2.proactive.scheduler.common.exception.SubmissionClosedException;
import org.ow2.proactive.scheduler.common.exception.UnknownJobException;
import org.ow2.proactive.scheduler.common.exception.UnknownTaskException;
import org.ow2.proactive.scheduler.common.job.Job;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobPriority;
import org.ow2.proactive.scheduler.common.job.JobResult;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.job.factories.JobFactory;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.TaskState;
import org.ow2.proactive.scheduler.task.TaskResultImpl;
@XmlJavaTypeAdapter(value = PersistentMapConverter.class, type = PersistentMap.class)
@Path("/scheduler/")
public class SchedulerStateRest {
/** If the rest api was unable to instantiate the value from byte array representation*/
public static final String UNKNOWN_VALUE_TYPE = "Unknown value type";
@GET
@Path("jobs")
@Produces("application/json")
public List<String> getJobsIds(@HeaderParam("sessionid") String sessionId) throws NotConnectedException,
PermissionException {
Scheduler s = null;
s = checkAccess(sessionId);
List<JobState> jobs = new ArrayList<JobState>();
SchedulerState state = s.getState();
jobs.addAll(state.getPendingJobs());
jobs.addAll(state.getRunningJobs());
jobs.addAll(state.getFinishedJobs());
List<String> names = new ArrayList<String>();
for (JobState j : jobs) {
names.add(j.getId().toString());
}
return names;
}
@GET
@Path("jobsinfo")
@Produces({ "application/json", "application/xml" })
public List<UserJobInfo> jobs(@HeaderParam("sessionid") String sessionId) throws PermissionException,
NotConnectedException {
Scheduler s = checkAccess(sessionId);
List<JobState> jobs = new ArrayList<JobState>();
SchedulerState state = s.getState();
jobs.addAll(state.getPendingJobs());
jobs.addAll(state.getRunningJobs());
jobs.addAll(state.getFinishedJobs());
List<UserJobInfo> jobInfoList = new ArrayList<UserJobInfo>();
for (JobState j : jobs) {
jobInfoList.add(new UserJobInfo(j.getId().value(), j.getOwner(), j.getJobInfo()));
}
return jobInfoList;
}
@GET
@Path("state")
@Produces({ "application/json", "application/xml" })
public SchedulerState schedulerState(@HeaderParam("sessionid") String sessionId) throws PermissionException,
NotConnectedException {
Scheduler s = checkAccess(sessionId);
return PAFuture.getFutureValue(s.getState());
}
@GET
@Path("state/myjobsonly")
@Produces({ "application/json", "application/xml" })
public SchedulerState getSchedulerStateMyJobsOnly(@HeaderParam("sessionid") String sessionId) throws PermissionException,
NotConnectedException {
Scheduler s = checkAccess(sessionId);
return PAFuture.getFutureValue(s.getState(true));
}
@GET
@Path("jobs/{jobid}")
@Produces({ "application/json", "application/xml" })
@XmlJavaTypeAdapter(value = PersistentMapConverter.class, type = PersistentMap.class)
public JobState job(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId)
throws NotConnectedException, UnknownJobException, PermissionException {
Scheduler s = checkAccess(sessionId);
JobState js;
js = s.getJobState(jobId);
js = PAFuture.getFutureValue(js);
return js;
}
@GET
@Path("jobs/{jobid}/result")
@Produces("application/json")
public JobResult jobResult(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId)
throws NotConnectedException, PermissionException, UnknownJobException {
Scheduler s = checkAccess(sessionId);
return PAFuture.getFutureValue(s.getJobResult(jobId));
}
@GET
@Path("jobs/{jobid}/result/value")
@Produces("application/json")
public Map<String, Serializable> jobResultValue(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId)
throws NotConnectedException, PermissionException, UnknownJobException {
Scheduler s = checkAccess(sessionId);
JobResult jobResult = PAFuture.getFutureValue(s.getJobResult(jobId));
if (jobResult == null) {
return null;
}
Map<String, TaskResult> allResults = jobResult.getAllResults();
Map<String, Serializable> res = new HashMap<String, Serializable>(allResults.size());
for(final Entry<String, TaskResult> entry : allResults.entrySet()){
TaskResult taskResult = entry.getValue();
String value = null;
// No entry if the task had exception
if (taskResult.hadException()) {
value = taskResult.getException().getMessage();
} else {
try {
Serializable instanciatedValue = taskResult.value();
if (instanciatedValue != null) {
value = instanciatedValue.toString();
}
} catch (InternalSchedulerException e) {
value = UNKNOWN_VALUE_TYPE;
} catch (Throwable t) {
value = "Unable to get the value due to " + t.getMessage();
}
}
res.put(entry.getKey(), value);
}
return res;
}
@DELETE
@Path("jobs/{jobid}")
@Produces("application/json")
public boolean removeJob(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId)
throws NotConnectedException, UnknownJobException, PermissionException {
Scheduler s = checkAccess(sessionId);
return s.removeJob(jobId);
}
@POST
@Path("jobs/{jobid}/kill")
@Produces("application/json")
public boolean killJob(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId)
throws NotConnectedException, UnknownJobException, PermissionException {
Scheduler s = checkAccess(sessionId);
return s.killJob(jobId);
}
@GET
@Path("jobs/{jobid}/tasks")
@Produces("application/json")
public List<String> getJobTasksIds(@HeaderParam("sessionid") String sessionId,
@PathParam("jobid") String jobId) throws NotConnectedException, UnknownJobException,
PermissionException {
Scheduler s = checkAccess(sessionId);
JobState jobState;
jobState = s.getJobState(jobId);
List<String> tasksName = new ArrayList<String>();
for (TaskState ts : jobState.getTasks()) {
tasksName.add(ts.getId().getReadableName());
}
return tasksName;
}
@GET
@Path("jobs/{jobid}/taskstates")
@Produces("application/json")
public List<TaskState> getJobTaskStates(@HeaderParam("sessionid") String sessionId,
@PathParam("jobid") String jobId) throws NotConnectedException, UnknownJobException,
PermissionException {
Scheduler s = checkAccess(sessionId);
JobState jobState;
jobState = s.getJobState(jobId);
List<TaskState> tasks = new ArrayList<TaskState>();
for (TaskState ts : jobState.getTasks()) {
tasks.add(ts);
}
return tasks;
}
@GET
@Path("jobs/{jobid}/tasks/{taskname}")
@Produces("application/json")
public TaskState jobtasks(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId,
@PathParam("taskname") String taskname) throws NotConnectedException, UnknownJobException,
PermissionException, UnknownTaskException {
Scheduler s = checkAccess(sessionId);
JobState jobState;
jobState = s.getJobState(jobId);
for (TaskState ts : jobState.getTasks()) {
if (ts.getId().getReadableName().equals(taskname)) {
return ts;
}
}
throw new UnknownTaskException("task " + taskname + "not found");
}
@GET
@Path("jobs/{jobid}/tasks/{taskname}/result/value")
@Produces("*/*")
public Serializable valueOftaskresult(@HeaderParam("sessionid") String sessionId,
@PathParam("jobid") String jobId, @PathParam("taskname") String taskname) throws Throwable {
Scheduler s = checkAccess(sessionId);
// TaskResult taskResult = s.getTaskResult(jobId, taskname);
TaskResult taskResult = workaroundforSCHEDULING863(s, jobId, taskname);
if (taskResult==null){
// task is not finished yet
return null;
}
String value = null;
// No entry if the task had exception
if (taskResult.hadException()) {
value = taskResult.getException().getMessage();
} else {
try {
Serializable instanciatedValue = taskResult.value();
if (instanciatedValue != null) {
value = instanciatedValue.toString();
}
} catch (InternalSchedulerException e) {
value = UNKNOWN_VALUE_TYPE;
} catch (Throwable t) {
value = "Unable to get the value due to " + t.getMessage();
}
}
return value;
}
@GET
@Path("jobs/{jobid}/tasks/{taskname}/result/serializedvalue")
@Produces("*/*")
public Serializable serializedValueOftaskresult(@HeaderParam("sessionid") String sessionId,
@PathParam("jobid") String jobId, @PathParam("taskname") String taskname) throws Throwable {
Scheduler s = checkAccess(sessionId);
// TaskResult tr = s.getTaskResult(jobId, taskname);
TaskResult tr = workaroundforSCHEDULING863(s, jobId, taskname);
tr = PAFuture.getFutureValue(tr);
return ((TaskResultImpl)tr).getSerializedValue();
}
@GET
@Path("jobs/{jobid}/tasks/{taskname}/result")
@Produces("application/json")
public TaskResult taskresult(@HeaderParam("sessionid") String sessionId,
@PathParam("jobid") String jobId, @PathParam("taskname") String taskname) throws NotConnectedException, UnknownJobException, UnknownTaskException, PermissionException {
Scheduler s = checkAccess(sessionId);
// TaskResult tr = s.getTaskResult(jobId, taskname);
TaskResult tr = workaroundforSCHEDULING863(s, jobId, taskname);
return PAFuture.getFutureValue(tr);
}
@GET
@Path("jobs/{jobid}/tasks/{taskname}/result/log/all")
@Produces("*/*")
public String tasklog(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId,
@PathParam("taskname") String taskname) throws NotConnectedException, UnknownJobException,
UnknownTaskException, PermissionException {
Scheduler s = checkAccess(sessionId);
TaskResult tr = workaroundforSCHEDULING863(s, jobId, taskname);
return tr.getOutput().getAllLogs(true);
}
@GET
@Path("jobs/{jobid}/tasks/{taskname}/result/log/err")
@Produces("*/*")
public String tasklogErr(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId,
@PathParam("taskname") String taskname) throws NotConnectedException, UnknownJobException,
UnknownTaskException, PermissionException {
Scheduler s = checkAccess(sessionId);
TaskResult tr = workaroundforSCHEDULING863(s, jobId, taskname);
return tr.getOutput().getStderrLogs(true);
}
@GET
@Path("jobs/{jobid}/tasks/{taskname}/result/log/out")
@Produces("*/*")
public String tasklogout(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId,
@PathParam("taskname") String taskname) throws NotConnectedException, UnknownJobException,
UnknownTaskException, PermissionException {
Scheduler s = checkAccess(sessionId);
TaskResult tr = workaroundforSCHEDULING863(s, jobId, taskname);
return tr.getOutput().getStdoutLogs(true);
}
/**
* the method check is the session id is valid i.e. a scheduler client
* is associated to the session id in the session map. If not, a NotConnectedException
* is thrown specifying the invalid access *
* @param sessionId
* @return the scheduler linked to the session id, an NotConnectedException, if no
* such mapping exists.
* @throws NotConnectedException
*/
public Scheduler checkAccess(String sessionId) throws NotConnectedException {
Scheduler s = SchedulerSessionMapper.getInstance().getSessionsMap().get(sessionId);
if (s == null) {
throw new NotConnectedException("you are not connected to the scheduler, you should log on first");
}
return s;
}
// /**
// * @param sessionId
// * @param message
// * @throws WebApplicationException http status code 403 Forbidden
// */
// throw new WebApplicationException(Response.status(HttpURLConnection.HTTP_FORBIDDEN)
// .entity("you are not authorized to perform the action:" + message).build());
// /**
// * @param sessionId
// * @param jobId
// * @throws WebApplicationException http status code 404 Not Found
// */
// public void handleUnknowJobException(String sessionId, String jobId) throws WebApplicationException {
// throw new WebApplicationException(Response.status(HttpURLConnection.HTTP_NOT_FOUND)
// .entity("job " + jobId + "not found").build());
// /**
// * @param sessionId
// * @param jobId
// * @throws WebApplicationException http status code 404 Not Found
// */
// public void handleSubmissionClosedJobException(String sessionId) throws WebApplicationException {
// throw new WebApplicationException(Response.status(HttpURLConnection.HTTP_NOT_FOUND)
// .entity("the scheduler is stopped, you cannot submit a job").build());
// /**
// * @param sessionId
// * @param taskname
// * @throws WebApplicationException http status code 404 Not Found
// */
// public void handleUnknowTaskException(String sessionId, String taskname) throws WebApplicationException {
// throw new WebApplicationException(Response.status(HttpURLConnection.HTTP_NOT_FOUND)
// .entity("task " + taskname + "not found").build());
// /**
// * @param sessionId
// * @param taskname
// * @throws WebApplicationException http status code 404 Not Found
// */
// public void handleJobAlreadyFinishedException(String sessionId, String msg) throws WebApplicationException {
// throw new WebApplicationException(Response.status(HttpURLConnection.HTTP_NOT_FOUND)
// .entity(msg).build());
@POST
@Path("jobs/{jobid}/pause")
@Produces("application/json")
public boolean pauseJob(@HeaderParam("sessionid") final String sessionId,
@PathParam("jobid") final String jobId) throws NotConnectedException, UnknownJobException,
PermissionException {
final Scheduler s = checkAccess(sessionId);
return s.pauseJob(jobId);
}
@POST
@Path("jobs/{jobid}/resume")
@Produces("application/json")
public boolean resumeJob(@HeaderParam("sessionid") final String sessionId,
@PathParam("jobid") final String jobId) throws NotConnectedException, UnknownJobException,
PermissionException {
final Scheduler s = checkAccess(sessionId);
return s.resumeJob(jobId);
}
@POST
@Path("submit")
@Produces("application/json")
public JobId submit(@HeaderParam("sessionid") String sessionId, MultipartInput multipart)
throws IOException, JobCreationException, NotConnectedException, PermissionException,
SubmissionClosedException {
Scheduler s = checkAccess(sessionId);
File tmp;
tmp = File.createTempFile("prefix", "suffix");
for (InputPart part : multipart.getParts()) {
BufferedWriter outf = new BufferedWriter(new FileWriter(tmp));
outf.write(part.getBodyAsString());
outf.close();
}
Job j = JobFactory.getFactory().createJob(tmp.getAbsolutePath());
return s.submit(j);
}
@PUT
@Path("disconnect")
@Produces("application/json")
public void disconnect(@HeaderParam("sessionid") final String sessionId) throws NotConnectedException,
PermissionException {
final Scheduler s = checkAccess(sessionId);
s.disconnect();
PAActiveObject.terminateActiveObject(s, true);
SchedulerSessionMapper.getInstance().getSessionsMap().remove(sessionId);
}
@PUT
@Path("pause")
@Produces("application/json")
public boolean pauseScheduler(@HeaderParam("sessionid") final String sessionId)
throws NotConnectedException, PermissionException {
final Scheduler s = checkAccess(sessionId);
return s.pause();
}
@PUT
@Path("stop")
@Produces("application/json")
public boolean stopScheduler(@HeaderParam("sessionid") final String sessionId)
throws NotConnectedException, PermissionException {
final Scheduler s = checkAccess(sessionId);
return s.stop();
}
@PUT
@Path("resume")
@Produces("application/json")
public boolean resumeScheduler(@HeaderParam("sessionid") final String sessionId)
throws NotConnectedException, PermissionException {
final Scheduler s = checkAccess(sessionId);
return s.resume();
}
@PUT
@Path("jobs/{jobid}/priority/byname/{name}")
public void schedulerChangeJobPriorityByName(@HeaderParam("sessionid") final String sessionId,
@PathParam("jobid") final String jobId, @PathParam("name") String priorityName)
throws NotConnectedException, UnknownJobException, PermissionException,
JobAlreadyFinishedException {
final Scheduler s = checkAccess(sessionId);
s.changeJobPriority(jobId, JobPriority.findPriority(priorityName));
}
@PUT
@Path("jobs/{jobid}/priority/byvalue/{value}")
public void schedulerChangeJobPriorityByValue(@HeaderParam("sessionid") final String sessionId,
@PathParam("jobid") final String jobId, @PathParam("value") String priorityValue)
throws NumberFormatException, NotConnectedException, UnknownJobException, PermissionException,
JobAlreadyFinishedException {
final Scheduler s = checkAccess(sessionId);
s.changeJobPriority(jobId, JobPriority.findPriority(Integer.parseInt(priorityValue)));
}
@PUT
@Path("freeze")
@Produces("application/json")
public boolean freezeScheduler(@HeaderParam("sessionid") final String sessionId)
throws NotConnectedException, PermissionException {
final Scheduler s = checkAccess(sessionId);
return s.freeze();
}
@GET
@Path("status")
@Produces("application/json")
public SchedulerStatus getSchedulerStatus(@HeaderParam("sessionid") final String sessionId)
throws NotConnectedException, PermissionException {
final Scheduler s = checkAccess(sessionId);
return PAFuture.getFutureValue(s.getStatus());
}
@PUT
@Path("start")
@Produces("application/json")
public boolean startScheduler(@HeaderParam("sessionid") final String sessionId)
throws NotConnectedException, PermissionException {
final Scheduler s = checkAccess(sessionId);
return s.start();
}
@PUT
@Path("kill")
@Produces("application/json")
public boolean killScheduler(@HeaderParam("sessionid") final String sessionId)
throws NotConnectedException, PermissionException {
final Scheduler s = checkAccess(sessionId);
return s.kill();
}
@POST
@Path("linkrm")
@Produces("application/json")
public boolean killScheduler(@HeaderParam("sessionid") final String sessionId,
@FormParam("rmurl") String rmURL) throws NotConnectedException, PermissionException {
final Scheduler s = checkAccess(sessionId);
return s.linkResourceManager(rmURL);
}
@PUT
@Path("isconnected")
@Produces("application/json")
public boolean isConnected(@HeaderParam("sessionid") final String sessionId)
throws NotConnectedException, PermissionException {
final Scheduler s = checkAccess(sessionId);
return s.isConnected();
}
private TaskResult workaroundforSCHEDULING863(Scheduler s,String jobId, String taskName) throws UnknownTaskException, NotConnectedException, UnknownJobException, PermissionException {
try {
return s.getTaskResult(jobId, taskName);
} catch (RuntimeException e) {
if (e.getMessage().contains("has not been found in this job result")) {
throw new UnknownTaskException("Result of task " + taskName + " does not exist or task is not yet finished");
} else {
throw e;
}
}
}
}
|
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in th future.
package org.usfirst.frc330.Beachbot2013Java.commands;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc330.Beachbot2013Java.Robot;
/*
* $Log: ManualArm.java,v $
* Revision 1.7 2013-03-15 02:58:19 echan
* robotbuilder update
*
* Revision 1.6 2013-03-15 02:50:55 echan
* added cvs log comments
*
*/
public class ManualArm extends Command {
public ManualArm() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
requires(Robot.arm);
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
Robot.arm.manualArm();
SmartDashboard.putNumber("ArmPosition", Robot.arm.getArmPosition());
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
Robot.arm.set(0);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
end();
}
}
|
package org.jvnet.hudson.test;
import hudson.remoting.Which;
import hudson.FilePath;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
/**
* Ensures that <tt>jenkins.war</tt> is exploded.
*
* <p>
* Depending on where the test is run (for example, inside Maven vs IDE), this code attempts to
* use jenkins.war from the right place, thereby improving the productivity.
*
* @author Kohsuke Kawaguchi
*/
final class WarExploder {
public static File getExplodedDir() throws Exception {
// rethrow an exception every time someone tries to do this, so that when explode()
// fails, you can see the cause no matter which test case you look at.
if(FAILURE !=null) throw new Exception("Failed to initialize exploded war", FAILURE);
return EXPLODE_DIR;
}
private static File EXPLODE_DIR;
private static Exception FAILURE;
static {
try {
EXPLODE_DIR = explode();
} catch (Exception e) {
FAILURE = e;
}
}
/**
* Explodes hudson.war, if necessary, and returns its root dir.
*/
private static File explode() throws Exception {
// are we in the Jenkins main workspace? If so, pick up hudson/main/war/resources
// this saves the effort of packaging a war file and makes the debug cycle faster
File d = new File(".").getAbsoluteFile();
for( ; d!=null; d=d.getParentFile()) {
if(new File(d,".jenkins").exists()) {
File dir = new File(d,"war/target/jenkins");
if(dir.exists()) {
System.out.println("Using jenkins.war resources from "+dir);
return dir;
}
}
}
// locate hudson.war
URL winstone = WarExploder.class.getResource("/winstone.jar");
if(winstone==null)
// impossible, since the test harness pulls in hudson.war
throw new AssertionError("jenkins.war is not in the classpath.");
File war = Which.jarFile(Class.forName("executable.Executable"));
File explodeDir = new File("./target/jenkins-for-test").getAbsoluteFile();
File timestamp = new File(explodeDir,".timestamp");
if(!timestamp.exists() || (timestamp.lastModified()!=war.lastModified())) {
System.out.println("Exploding jenkins.war at "+war);
new FilePath(explodeDir).deleteRecursive();
new FilePath(war).unzip(new FilePath(explodeDir));
if(!explodeDir.exists()) // this is supposed to be impossible, but I'm investigating HUDSON-2605
throw new IOException("Failed to explode "+war);
new FileOutputStream(timestamp).close();
timestamp.setLastModified(war.lastModified());
} else {
System.out.println("Picking up existing exploded jenkins.war at "+explodeDir.getAbsolutePath());
}
return explodeDir;
}
}
|
package net.estinet.gFeatures.Feature.gHub.crystal;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import net.estinet.gFeatures.API.Inventory.EstiInventory;
import net.estinet.gFeatures.ClioteSky.API.CliotePing;
import net.estinet.gFeatures.Feature.gHub.Basis;
public class CrystalInteract {
public void init(Location location, Player player){
EstiInventory open = makeInventory(player, location);
open.open(player);
}
public EstiInventory makeInventory(Player p, Location loc){
MGServer mgs = Basis.crystals.get(loc);
try{
EstiInventory menu = new EstiInventory(ChatColor.GRAY + mgs.getName() + " Server Menu", 18, new EstiInventory.OptionClickEventHandler() {
@Override
public void onOptionClick(EstiInventory.OptionClickEvent event) {
if(event.getName().contains(ChatColor.GREEN + "")){
char[] subit = event.getName().toCharArray();
List<Character> strs = new ArrayList<>();
for(char ch : subit){
strs.add(ch);
}
String cache = "";
for(int i = 0; i < strs.size(); i++){
if(Character.isDigit(strs.get(i))){
cache += strs.get(i);
}
}
CliotePing cp = new CliotePing();
cp.sendMessage("redirect " + event.getPlayer().getName() + " " + mgs.getName() + cache, "Bungee");
event.setWillClose(true);
}
else{
}
}
}, Bukkit.getServer().getPluginManager().getPlugin("gFeatures"));
int iter = 0;
for(MGServerPlus mgsp : Basis.getServersWithType(mgs.getName())){
if(mgsp.getState().equals("WAIT")){
ItemStack ready = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 5);
ItemMeta im = ready.getItemMeta();
im.setDisplayName(ChatColor.GREEN + mgsp.getName() + ": Waiting!");
ready.setItemMeta(im);
menu.setOption(iter, ready);
}
else{
ItemStack ready = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 14);
ItemMeta im = ready.getItemMeta();
im.setDisplayName(ChatColor.RED + mgsp.getName() + ": Ingame!");
ready.setItemMeta(im);
menu.setOption(iter, ready);
}
iter++;
}
return menu;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public ItemStack createItem(Material material, String name, String ... lore){
ItemStack item = new ItemStack(material, 1);
List<String> lores = new ArrayList<>();
for(String lor : lore){
lores.add(lor);
}
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
meta.setLore(lores);
item.setItemMeta(meta);
return item;
}
}
|
package net.idlesoft.android.apps.github.ui.fragments;
import android.os.Bundle;
import android.os.Handler;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public
class DataFragment extends BaseFragment
{
public static
class DataTask
{
public static abstract
class DataTaskRunnable implements Runnable
{
public DataTask task;
@Override
public final
void run()
{
try {
if (task.callbacks != null) {
task.handler.post(new Runnable()
{
@Override
public
void run()
{
task.callbacks.onTaskStart();
}
});
}
runTask();
if (task.callbacks != null) {
task.handler.post(new Runnable()
{
@Override
public
void run()
{
task.callbacks.onTaskComplete();
}
});
}
} catch (InterruptedException e) {
if (task.callbacks != null) {
task.handler.post(new Runnable()
{
@Override
public
void run()
{
task.callbacks.onTaskCancelled();
}
});
}
}
}
public abstract
void runTask() throws InterruptedException;
}
public static
interface DataTaskCallbacks
{
public
void onTaskStart();
public
void onTaskCancelled();
public
void onTaskComplete();
}
private
DataTaskRunnable runnable;
private
Handler handler;
protected
DataTaskCallbacks callbacks;
public
DataTask(DataTaskRunnable runnable, Handler handler, DataTaskCallbacks callbacks)
{
this.runnable = runnable;
this.handler = handler;
this.callbacks = callbacks;
}
};
public static
class DataTaskExecutor
{
public
ExecutorService mThreadPool = Executors.newFixedThreadPool(3);
public
void execute(DataTask dataTask)
{
mThreadPool.execute(dataTask.runnable);
}
public
void shutdown()
{
mThreadPool.shutdown();
}
public
List<Runnable> shutdownNow()
{
return mThreadPool.shutdownNow();
}
}
private
Handler mHandler = new Handler();
private
DataTaskExecutor mThreadPool = new DataTaskExecutor();
private
boolean mRecreated;
@Override
public
void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public
void onUIFragmentReady()
{
}
@Override
public
void onStart()
{
super.onStart();
mRecreated = false;
}
@Override
public
void onPause()
{
super.onPause();
mRecreated = true;
setTargetFragment(null, 0);
}
public
boolean isRecreated()
{
return mRecreated;
}
public
UIFragment<DataFragment> getUIFragment()
{
return (UIFragment<DataFragment>) getTargetFragment();
}
public
Handler getHandler()
{
return mHandler;
}
public
DataTaskExecutor getThreadPool()
{
return mThreadPool;
}
public
DataTask executeNewTask(DataTask.DataTaskRunnable runnable,
DataTask.DataTaskCallbacks callbacks)
{
final DataTask task = new DataTask(runnable, getHandler(), callbacks);
runnable.task = task;
getThreadPool().execute(task);
return task;
}
}
|
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.TextTestRunner;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* Check mappings from Affymetrix probes to genome.
*
* Even though we *don't* provide Affymetrix data for all species the healthcheck follows the convention of failing if the data is missing.
*/
public class AffyProbes2Genome extends SingleDatabaseTestCase {
/**
* Runs test against a few databases on the server specified in database.properties.
*
* @param args ignored.
*/
public static void main(String[] args) {
TextTestRunner.main(new String[] { "-d", "homo_sapiens_core_3.*", "-d", "pan_troglodytes_core_3.*", "AffyProbes2Genome" });
}
/**
* Creates a new instance of FeatureAnalysis
*/
public AffyProbes2Genome() {
addToGroup("post_genebuild");
addToGroup("release");
}
/**
* This test only applies to core databases.
*/
public void types() {
removeAppliesToType(DatabaseType.EST);
removeAppliesToType(DatabaseType.CDNA);
removeAppliesToType(DatabaseType.VEGA);
}
/**
* Run the test.
*
* @param dbre The database to use.
* @return true if the test pased.
*
*/
public boolean run(DatabaseRegistryEntry dbre) {
Connection con = dbre.getConnection();
if (testAffyTablesPopulated(dbre)) {
return testProbsetSizesSet(con) && testAffyArraysInExternalDB(con);
} else {
return false;
}
}
private boolean testAffyArraysInExternalDB(Connection con) {
boolean result = true;
// We have to do some guessing and pattern matching to find the
// external database corresponding to this AffyArray because the
// names used in external_db.db_name do not quite match affy_array.name.
// 1 - get set of external_db.db_names
String[] xdbNames = getColumnValues(con, "SELECT db_name FROM external_db");
Set xdbNamesSet = new HashSet();
for (int i = 0; i < xdbNames.length; i++)
xdbNamesSet.add(xdbNames[i].toLowerCase());
// 2 - check to see if every affy_array.name is in the set of
// external_db.db_names.
String[] affyArrayNames = getColumnValues(con, "SELECT name FROM affy_array");
for (int i = 0; i < affyArrayNames.length; i++) {
String name = affyArrayNames[i];
Set possibleExternalDBNames = new HashSet();
possibleExternalDBNames.add(name.toLowerCase());
possibleExternalDBNames.add(name.toLowerCase().replace('-', '_'));
possibleExternalDBNames.add(("affy_" + name).toLowerCase().replace('-', '_'));
possibleExternalDBNames.add(("afyy_" + name).toLowerCase().replace('-', '_'));
possibleExternalDBNames.retainAll(xdbNamesSet);
if (possibleExternalDBNames.size() == 0) {
ReportManager.problem(this, con, "AffyArray (affy_array.name) " + name + " has no corresponding entry in external_db");
result = false;
}
}
return result;
}
/**
* Checks that all affy_* tables are populated.
*
* If at least one is not then the test fails.
*
* @param con
* @return true if all affy_* tables have rows, otherwise false.
*/
private boolean testAffyTablesPopulated(DatabaseRegistryEntry dbre) {
List emptyTables = new ArrayList();
String[] tables = { "affy_array", "affy_probe", "affy_feature" };
Species species = dbre.getSpecies();
Connection con = dbre.getConnection();
if (species == Species.HOMO_SAPIENS || species == Species.MUS_MUSCULUS || species == Species.RATTUS_NORVEGICUS
|| species == Species.GALLUS_GALLUS || species == Species.DANIO_RERIO) {
for (int i = 0; i < tables.length; i++)
if (Integer.parseInt(getRowColumnValue(con, "SELECT count(*) from " + tables[i])) == 0)
emptyTables.add(tables[i]);
}
if (emptyTables.size() == 0)
return true;
else {
ReportManager.problem(this, con, "Empty table(s): " + emptyTables);
return false;
}
}
private boolean testProbsetSizesSet(Connection con) {
boolean result = true;
try {
String sql = "SELECT name, probe_setsize FROM affy_array";
for (ResultSet rs = con.createStatement().executeQuery(sql); rs.next();) {
int probesetSize = rs.getInt("probe_setsize");
if (probesetSize < 1) {
ReportManager.problem(this, con, "affy_array.probeset_size not set for " + rs.getString("name"));
result = false;
}
}
} catch (SQLException e) {
result = false;
e.printStackTrace();
}
return result;
}
}
|
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* Check for HGNCs that have been assigned as display labels more than one gene.
*/
public class HGNCMultipleGenes extends SingleDatabaseTestCase {
/**
* Creates a new instance of HGNCMultipleGenes.
*/
public HGNCMultipleGenes() {
addToGroup("post_genebuild");
addToGroup("release");
setDescription("Check for HGNCs that have been assigned as display labels more than one gene.");
}
/**
* This test only applies to core databases.
*/
public void types() {
removeAppliesToType(DatabaseType.OTHERFEATURES);
removeAppliesToType(DatabaseType.ESTGENE);
removeAppliesToType(DatabaseType.VEGA);
removeAppliesToType(DatabaseType.CDNA);
}
/**
* Test various things about ditag features.
*
* @param dbre
* The database to use.
* @return Result.
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// this has to be done the slow way, don't think there's a way to do this all at once
int rows = getRowCount(con, "SELECT DISTINCT(x.display_label), COUNT(*) AS count FROM gene g, xref x, external_db e WHERE e.external_db_id=x.external_db_id AND e.db_name='HUGO' AND x.xref_id=g.display_xref_id GROUP BY x.display_label HAVING COUNT > 1");
if (rows > 0) {
ReportManager.problem(this, con, rows + " HGNC symbols have been assigned to more than one gene");
result = false;
} else {
ReportManager.correct(this, con, "All HGNC symbols only assigned to one gene");
}
return result;
}
}
|
// This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
package org.sosy_lab.java_smt.solvers.princess;
import static scala.collection.JavaConverters.asJava;
import static scala.collection.JavaConverters.collectionAsScalaIterableConverter;
import ap.SimpleAPI;
import ap.parser.BooleanCompactifier;
import ap.parser.Environment.EnvironmentException;
import ap.parser.IAtom;
import ap.parser.IConstant;
import ap.parser.IExpression;
import ap.parser.IFormula;
import ap.parser.IFunApp;
import ap.parser.IFunction;
import ap.parser.IIntFormula;
import ap.parser.ITerm;
import ap.parser.Parser2InputAbsy.TranslationException;
import ap.parser.PartialEvaluator;
import ap.parser.SMTLineariser;
import ap.parser.SMTParser2InputAbsy.SMTFunctionType;
import ap.parser.SMTParser2InputAbsy.SMTType;
import ap.terfor.ConstantTerm;
import ap.terfor.preds.Predicate;
import ap.theories.ExtArray;
import ap.theories.bitvectors.ModuloArithmetic;
import ap.types.Sort;
import ap.types.Sort$;
import ap.types.Sort.MultipleValueBool$;
import ap.util.Debug;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sosy_lab.common.Appender;
import org.sosy_lab.common.Appenders;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.FileOption;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.configuration.Option;
import org.sosy_lab.common.configuration.Options;
import org.sosy_lab.common.io.PathCounterTemplate;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType;
import org.sosy_lab.java_smt.api.SolverContext.ProverOptions;
import scala.Tuple2;
import scala.Tuple4;
import scala.collection.immutable.Seq;
@Options(prefix = "solver.princess")
class PrincessEnvironment {
@Option(
secure = true,
description =
"The number of atoms a term has to have before"
+ " it gets abbreviated if there are more identical terms.")
private int minAtomsForAbbreviation = 100;
@Option(
secure = true,
description =
"Enable additional assertion checks within Princess. "
+ "The main usage is debugging. This option can cause a performance overhead.")
private boolean enableAssertions = false;
public static final Sort BOOL_SORT = Sort$.MODULE$.Bool();
public static final Sort INTEGER_SORT = Sort.Integer$.MODULE$;
@Option(secure = true, description = "log all queries as Princess-specific Scala code")
private boolean logAllQueriesAsScala = false;
@Option(secure = true, description = "file for Princess-specific dump of queries as Scala code")
@FileOption(FileOption.Type.OUTPUT_FILE)
private PathCounterTemplate logAllQueriesAsScalaFile =
PathCounterTemplate.ofFormatString("princess-query-%03d-");
/**
* cache for variables, because they do not implement equals() and hashCode(), so we need to have
* the same objects.
*/
private final Map<String, IFormula> boolVariablesCache = new HashMap<>();
private final Map<String, ITerm> sortedVariablesCache = new HashMap<>();
private final Map<String, IFunction> functionsCache = new HashMap<>();
private final int randomSeed;
private final @Nullable PathCounterTemplate basicLogfile;
private final ShutdownNotifier shutdownNotifier;
/**
* The wrapped API is the first created API. It will never be used outside this class and never be
* closed. If a variable is declared, it is declared in the first api, then copied into all
* registered APIs. Each API has its own stack for formulas.
*/
private final SimpleAPI api;
private final List<PrincessAbstractProver<?, ?>> registeredProvers = new ArrayList<>();
PrincessEnvironment(
Configuration config,
@Nullable final PathCounterTemplate pBasicLogfile,
ShutdownNotifier pShutdownNotifier,
final int pRandomSeed)
throws InvalidConfigurationException {
config.inject(this);
basicLogfile = pBasicLogfile;
shutdownNotifier = pShutdownNotifier;
randomSeed = pRandomSeed;
// this api is only used local in this environment, no need for interpolation
api = getNewApi(false);
}
/**
* This method returns a new prover, that is registered in this environment. All variables are
* shared in all registered APIs.
*/
PrincessAbstractProver<?, ?> getNewProver(
boolean useForInterpolation,
PrincessFormulaManager mgr,
PrincessFormulaCreator creator,
Set<ProverOptions> pOptions) {
SimpleAPI newApi =
getNewApi(useForInterpolation || pOptions.contains(ProverOptions.GENERATE_UNSAT_CORE));
// add all symbols, that are available until now
boolVariablesCache.values().forEach(newApi::addBooleanVariable);
sortedVariablesCache.values().forEach(newApi::addConstant);
functionsCache.values().forEach(newApi::addFunction);
PrincessAbstractProver<?, ?> prover;
if (useForInterpolation) {
prover = new PrincessInterpolatingProver(mgr, creator, newApi, shutdownNotifier, pOptions);
} else {
prover = new PrincessTheoremProver(mgr, creator, newApi, shutdownNotifier, pOptions);
}
registeredProvers.add(prover);
return prover;
}
@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
private SimpleAPI getNewApi(boolean constructProofs) {
File directory = null;
String smtDumpBasename = null;
String scalaDumpBasename = null;
if (basicLogfile != null) {
Path logPath = basicLogfile.getFreshPath();
directory = getAbsoluteParent(logPath);
smtDumpBasename = logPath.getFileName().toString();
if (Files.getFileExtension(smtDumpBasename).equals("smt2")) {
// Princess adds .smt2 anyway
smtDumpBasename = Files.getNameWithoutExtension(smtDumpBasename);
}
smtDumpBasename += "-";
}
if (logAllQueriesAsScala && logAllQueriesAsScalaFile != null) {
Path logPath = logAllQueriesAsScalaFile.getFreshPath();
if (directory == null) {
directory = getAbsoluteParent(logPath);
}
scalaDumpBasename = logPath.getFileName().toString();
}
Debug.enableAllAssertions(enableAssertions);
final SimpleAPI newApi =
SimpleAPI.apply(
enableAssertions, // enableAssert, see above
false, // no sanitiseNames, because variable names may contain chars like "@" and ":".
smtDumpBasename != null, // dumpSMT
smtDumpBasename, // smtDumpBasename
scalaDumpBasename != null, // dumpScala
scalaDumpBasename, // scalaDumpBasename
directory, // dumpDirectory
SimpleAPI.apply$default$8(), // tightFunctionScopes
SimpleAPI.apply$default$9(), // genTotalityAxioms
new scala.Some<>(randomSeed) // randomSeed
);
if (constructProofs) { // needed for interpolation and unsat cores
newApi.setConstructProofs(true);
}
return newApi;
}
private File getAbsoluteParent(Path path) {
return Optional.ofNullable(path.getParent()).orElse(Path.of(".")).toAbsolutePath().toFile();
}
int getMinAtomsForAbbreviation() {
return minAtomsForAbbreviation;
}
void unregisterStack(PrincessAbstractProver<?, ?> stack) {
assert registeredProvers.contains(stack) : "cannot unregister stack, it is not registered";
registeredProvers.remove(stack);
}
/** unregister and close all stacks. */
void close() {
for (PrincessAbstractProver<?, ?> prover : ImmutableList.copyOf(registeredProvers)) {
prover.close();
}
api.shutDown();
api.reset();
Preconditions.checkState(registeredProvers.isEmpty());
}
public List<? extends IExpression> parseStringToTerms(String s, PrincessFormulaCreator creator) {
Tuple4<
Seq<IFormula>,
scala.collection.immutable.Map<IFunction, SMTFunctionType>,
scala.collection.immutable.Map<ConstantTerm, SMTType>,
scala.collection.immutable.Map<Predicate, SMTFunctionType>>
parserResult;
try {
parserResult = extractFromSTMLIB(s);
} catch (TranslationException | EnvironmentException nested) {
throw new IllegalArgumentException(nested);
}
final List<IFormula> formulas = asJava(parserResult._1());
ImmutableSet.Builder<IExpression> declaredFunctions = ImmutableSet.builder();
for (IExpression f : formulas) {
declaredFunctions.addAll(creator.extractVariablesAndUFs(f, true).values());
}
for (IExpression var : declaredFunctions.build()) {
if (var instanceof IConstant) {
sortedVariablesCache.put(((IConstant) var).c().name(), (ITerm) var);
addSymbol((IConstant) var);
} else if (var instanceof IAtom) {
boolVariablesCache.put(((IAtom) var).pred().name(), (IFormula) var);
addSymbol((IAtom) var);
} else if (var instanceof IFunApp) {
IFunction fun = ((IFunApp) var).fun();
functionsCache.put(fun.name(), fun);
addFunction(fun);
}
}
return formulas;
}
/**
* Parse a SMTLIB query and returns a triple of the asserted formulas, the defined functions and
* symbols.
*
* @throws EnvironmentException from Princess when the parsing fails
* @throws TranslationException from Princess when the parsing fails due to type mismatch
*/
/* EnvironmentException is not unused, but the Java compiler does not like Scala. */
@SuppressWarnings("unused")
private Tuple4<
Seq<IFormula>,
scala.collection.immutable.Map<IFunction, SMTFunctionType>,
scala.collection.immutable.Map<ConstantTerm, SMTType>,
scala.collection.immutable.Map<Predicate, SMTFunctionType>>
extractFromSTMLIB(String s) throws EnvironmentException, TranslationException {
// replace let-terms and function definitions by their full term.
final boolean fullyInlineLetsAndFunctions = true;
return api.extractSMTLIBAssertionsSymbols(new StringReader(s), fullyInlineLetsAndFunctions);
}
/**
* Utility helper method to hide a checked exception as RuntimeException.
*
* <p>The generic E simulates a RuntimeException at compile time and lets us throw the correct
* Exception at run time.
*/
@SuppressWarnings("unchecked")
private static <E extends Throwable> void throwCheckedAsUnchecked(Throwable e) throws E {
throw (E) e;
}
/**
* This method dumps a formula as SMTLIB2.
*
* <p>We avoid redundant sub-formulas by replacing them with abbreviations. The replacement is
* done "once" when calling this method.
*
* <p>We return an {@link Appender} to avoid storing larger Strings in memory. We sort the symbols
* and abbreviations for the export only "on demand".
*/
public Appender dumpFormula(IFormula formula, final PrincessFormulaCreator creator) {
// remove redundant expressions
// TODO do we want to remove redundancy completely (as checked in the unit
// tests (SolverFormulaIOTest class)) or do we want to remove redundancy up
// to the point we do it for formulas that should be asserted
Tuple2<IExpression, scala.collection.immutable.Map<IExpression, IExpression>> tuple =
api.abbrevSharedExpressionsWithMap(formula, 1);
final IExpression lettedFormula = tuple._1();
final Map<IExpression, IExpression> abbrevMap = asJava(tuple._2());
return new Appenders.AbstractAppender() {
@Override
public void appendTo(Appendable out) throws IOException {
try {
appendTo0(out);
} catch (scala.MatchError e) {
// exception might be thrown in case of interrupt, then we wrap it in an interrupt.
if (shutdownNotifier.shouldShutdown()) {
InterruptedException interrupt = new InterruptedException();
interrupt.addSuppressed(e);
throwCheckedAsUnchecked(interrupt);
} else {
// simply re-throw exception
throw e;
}
}
}
private void appendTo0(Appendable out) throws IOException {
Set<IExpression> allVars =
new LinkedHashSet<>(creator.extractVariablesAndUFs(lettedFormula, true).values());
// We use TreeMaps for deterministic/alphabetic ordering.
// For abbreviations, we use the ordering, but dump nested abbreviations/dependencies first.
Map<String, IExpression> symbols = new TreeMap<>();
Map<String, IFunApp> ufs = new TreeMap<>();
Map<String, IExpression> usedAbbrevs = new TreeMap<>();
collectAllSymbolsAndAbbreviations(allVars, symbols, ufs, usedAbbrevs);
// declare normal symbols
for (Entry<String, IExpression> symbol : symbols.entrySet()) {
out.append(
String.format(
"(declare-fun %s () %s)%n",
SMTLineariser.quoteIdentifier(symbol.getKey()),
getFormulaType(symbol.getValue()).toSMTLIBString()));
}
// declare UFs
for (Entry<String, IFunApp> function : ufs.entrySet()) {
List<String> argSorts =
Lists.transform(
asJava(function.getValue().args()), a -> getFormulaType(a).toSMTLIBString());
out.append(
String.format(
"(declare-fun %s (%s) %s)%n",
SMTLineariser.quoteIdentifier(function.getKey()),
Joiner.on(" ").join(argSorts),
getFormulaType(function.getValue()).toSMTLIBString()));
}
// now every symbol from the formula or from abbreviations are declared,
// let's add the abbreviations, too.
for (String abbrev : getOrderedAbbreviations(usedAbbrevs)) {
IExpression abbrevFormula = usedAbbrevs.get(abbrev);
IExpression fullFormula = abbrevMap.get(abbrevFormula);
out.append(
String.format(
"(define-fun %s () %s %s)%n",
SMTLineariser.quoteIdentifier(abbrev),
getFormulaType(fullFormula).toSMTLIBString(),
SMTLineariser.asString(fullFormula)));
}
// now add the final assert
out.append("(assert ").append(SMTLineariser.asString(lettedFormula)).append(')');
}
/**
* determine all used symbols and all used abbreviations by traversing the abbreviations
* transitively.
*
* @param allVars will be updated with further symbols and UFs.
* @param symbols will be updated with all found symbols.
* @param ufs will be updated with all found UFs.
* @param abbrevs will be updated with all found abbreviations.
*/
private void collectAllSymbolsAndAbbreviations(
final Set<IExpression> allVars,
final Map<String, IExpression> symbols,
final Map<String, IFunApp> ufs,
final Map<String, IExpression> abbrevs) {
final Deque<IExpression> waitlistSymbols = new ArrayDeque<>(allVars);
final Set<String> seenSymbols = new HashSet<>();
while (!waitlistSymbols.isEmpty()) {
IExpression var = waitlistSymbols.poll();
String name = getName(var);
// we don't want to declare variables twice
if (!seenSymbols.add(name)) {
continue;
}
if (isAbbreviation(var)) {
Preconditions.checkState(!abbrevs.containsKey(name));
abbrevs.put(name, var);
// for abbreviations, we go deeper and analyse the abbreviated formula.
Set<IExpression> varsFromAbbrev = getVariablesFromAbbreviation(var);
Sets.difference(varsFromAbbrev, allVars).forEach(waitlistSymbols::push);
allVars.addAll(varsFromAbbrev);
} else if (var instanceof IFunApp) {
Preconditions.checkState(!ufs.containsKey(name));
ufs.put(name, (IFunApp) var);
} else {
Preconditions.checkState(!symbols.containsKey(name));
symbols.put(name, var);
}
}
}
/**
* Abbreviations can be nested, and thus we need to sort them. The returned list (or iterable)
* contains each used abbreviation exactly once. Abbreviations with no dependencies come
* first, more complex ones later.
*/
private Iterable<String> getOrderedAbbreviations(Map<String, IExpression> usedAbbrevs) {
ArrayDeque<String> waitlist = new ArrayDeque<>(usedAbbrevs.keySet());
Set<String> orderedAbbreviations = new LinkedHashSet<>();
while (!waitlist.isEmpty()) {
String abbrev = waitlist.removeFirst();
boolean allDependenciesFinished = true;
for (IExpression var : getVariablesFromAbbreviation(usedAbbrevs.get(abbrev))) {
String name = getName(var);
if (isAbbreviation(var)) {
if (!orderedAbbreviations.contains(name)) {
allDependenciesFinished = false;
waitlist.addLast(name); // part 1: add dependency for later
}
}
}
if (allDependenciesFinished) {
orderedAbbreviations.add(abbrev);
} else {
waitlist.addLast(abbrev); // part 2: add again for later
}
}
return orderedAbbreviations;
}
private boolean isAbbreviation(IExpression symbol) {
return abbrevMap.containsKey(symbol);
}
private Set<IExpression> getVariablesFromAbbreviation(IExpression var) {
return ImmutableSet.copyOf(
creator.extractVariablesAndUFs(abbrevMap.get(var), true).values());
}
};
}
private static String getName(IExpression var) {
if (var instanceof IAtom) {
return ((IAtom) var).pred().name();
} else if (var instanceof IConstant) {
return var.toString();
} else if (var instanceof IFunApp) {
String fullStr = ((IFunApp) var).fun().toString();
return fullStr.substring(0, fullStr.indexOf('/'));
} else if (var instanceof IIntFormula) {
return getName(((IIntFormula) var).t());
}
throw new IllegalArgumentException("The given parameter is no variable or function");
}
static FormulaType<?> getFormulaType(IExpression pFormula) {
if (pFormula instanceof IFormula) {
return FormulaType.BooleanType;
} else if (pFormula instanceof ITerm) {
final Sort sort = Sort$.MODULE$.sortOf((ITerm) pFormula);
try {
return getFormulaTypeFromSort(sort);
} catch (IllegalArgumentException e) {
// add more info about the formula, then rethrow
throw new IllegalArgumentException(
String.format(
"Unknown formula type '%s' for formula '%s'.", pFormula.getClass(), pFormula),
e);
}
}
throw new IllegalArgumentException(
String.format(
"Unknown formula type '%s' for formula '%s'.", pFormula.getClass(), pFormula));
}
private static FormulaType<?> getFormulaTypeFromSort(final Sort sort) {
if (sort == PrincessEnvironment.BOOL_SORT) {
return FormulaType.BooleanType;
} else if (sort == PrincessEnvironment.INTEGER_SORT) {
return FormulaType.IntegerType;
} else if (sort instanceof ExtArray.ArraySort) {
Seq<Sort> indexSorts = ((ExtArray.ArraySort) sort).theory().indexSorts();
Sort elementSort = ((ExtArray.ArraySort) sort).theory().objSort();
assert indexSorts.iterator().size() == 1 : "unexpected index type in Array type:" + sort;
// assert indexSorts.size() == 1; // TODO Eclipse does not like simpler code.
return new ArrayFormulaType<>(
getFormulaTypeFromSort(indexSorts.iterator().next()), // get single index-sort
getFormulaTypeFromSort(elementSort));
} else if (sort instanceof MultipleValueBool$) {
return FormulaType.BooleanType;
} else {
scala.Option<Object> bitWidth = getBitWidth(sort);
if (bitWidth.isDefined()) {
return FormulaType.getBitvectorTypeWithSize((Integer) bitWidth.get());
}
}
throw new IllegalArgumentException(
String.format("Unknown formula type '%s' for sort '%s'.", sort.getClass(), sort));
}
static scala.Option<Object> getBitWidth(final Sort sort) {
scala.Option<Object> bitWidth = ModuloArithmetic.UnsignedBVSort$.MODULE$.unapply(sort);
if (!bitWidth.isDefined()) {
bitWidth = ModuloArithmetic.SignedBVSort$.MODULE$.unapply(sort);
}
return bitWidth;
}
public IExpression makeVariable(Sort type, String varname) {
if (type == BOOL_SORT) {
if (boolVariablesCache.containsKey(varname)) {
return boolVariablesCache.get(varname);
} else {
IFormula var = api.createBooleanVariable(varname);
addSymbol(var);
boolVariablesCache.put(varname, var);
return var;
}
} else {
if (sortedVariablesCache.containsKey(varname)) {
return sortedVariablesCache.get(varname);
} else {
ITerm var = api.createConstant(varname, type);
addSymbol(var);
sortedVariablesCache.put(varname, var);
return var;
}
}
}
/** This function declares a new functionSymbol with the given argument types and result. */
public IFunction declareFun(String name, Sort returnType, List<Sort> args) {
if (functionsCache.containsKey(name)) {
return functionsCache.get(name);
} else {
IFunction funcDecl =
api.createFunction(
name, toSeq(args), returnType, false, SimpleAPI.FunctionalityMode$.MODULE$.Full());
addFunction(funcDecl);
functionsCache.put(name, funcDecl);
return funcDecl;
}
}
public ITerm makeSelect(ITerm array, ITerm index) {
List<ITerm> args = ImmutableList.of(array, index);
ExtArray.ArraySort arraySort = (ExtArray.ArraySort) Sort$.MODULE$.sortOf(array);
return new IFunApp(arraySort.theory().select(), toSeq(args));
}
public ITerm makeStore(ITerm array, ITerm index, ITerm value) {
List<ITerm> args = ImmutableList.of(array, index, value);
ExtArray.ArraySort arraySort = (ExtArray.ArraySort) Sort$.MODULE$.sortOf(array);
return new IFunApp(arraySort.theory().store(), toSeq(args));
}
public boolean hasArrayType(IExpression exp) {
if (exp instanceof ITerm) {
final ITerm t = (ITerm) exp;
return Sort$.MODULE$.sortOf(t) instanceof ExtArray.ArraySort;
} else {
return false;
}
}
public IFormula elimQuantifiers(IFormula formula) {
return api.simplify(formula);
}
private void addSymbol(IFormula symbol) {
for (PrincessAbstractProver<?, ?> prover : registeredProvers) {
prover.addSymbol(symbol);
}
}
private void addSymbol(ITerm symbol) {
for (PrincessAbstractProver<?, ?> prover : registeredProvers) {
prover.addSymbol(symbol);
}
}
private void addFunction(IFunction funcDecl) {
for (PrincessAbstractProver<?, ?> prover : registeredProvers) {
prover.addSymbol(funcDecl);
}
}
static <T> Seq<T> toSeq(List<T> list) {
return collectionAsScalaIterableConverter(list).asScala().toSeq();
}
IExpression simplify(IExpression f) {
// TODO this method is not tested, check it!
if (f instanceof IFormula) {
f = BooleanCompactifier.apply((IFormula) f);
}
return PartialEvaluator.apply(f);
}
}
|
package pages;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Named
@Sessionscoped
public class Basket extends Page implements Serializable{
static List<Product> products = new ArrayList<Product>();
/**
*
* @return List<Products>
*/
public List<Products> getBasket(){
return products;
}
/**
*
** @param Product updated
*/
public void edit(Product old, Product updated){
int place = products.indexOf(old);
//products.addAt(place, updated);
products.remove(place);
product.add(updated);
}
/**
* @param selected
*
*/
public void remove(Product selected){
int place = products.indexOf(old);
products.remove(place);
}
/**
*
* @param Product item
*/
public void add(Product item){
product.add(item);
}
}
|
package org.jgroups.tests;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.net.InetAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.jgroups.Channel;
import org.jgroups.Global;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.blocks.GroupRequest;
import org.jgroups.blocks.MessageDispatcher;
import org.jgroups.blocks.RequestHandler;
import org.jgroups.protocols.MERGE2;
import org.jgroups.protocols.MPING;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.stack.Protocol;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.util.RspList;
import org.jgroups.util.Util;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
/**
* Tests concurrent startup
* @author Brian Goose
* @version $Id: ChannelConcurrencyTest.java,v 1.12 2008/06/27 21:29:31 vlada Exp $
*/
@Test(groups=Global.FLUSH,sequential=true)
public class ChannelConcurrencyTest extends ChannelTestBase{
public void testPlainChannel () throws Throwable{
testhelper(false);
}
public void testwithDispatcher () throws Throwable{
testhelper(true);
}
protected void testhelper(boolean useDispatcher) throws Throwable {
final int count=8;
final Executor executor=Executors.newFixedThreadPool(count);
final CountDownLatch latch=new CountDownLatch(count);
final JChannel[] channels=new JChannel[count];
final Task[] tasks=new Task[count];
final long start=System.currentTimeMillis();
for(int i=0;i < count;i++) {
if(i == 0)
channels[i]=createChannel(true, count);
else
channels[i]=createChannel(channels[0]);
tasks[i]=new Task(latch, channels[i],useDispatcher);
changeMergeInterval(channels[i]);
changeViewBundling(channels[i]);
replaceDiscoveryProtocol(channels[i]);
}
for(final Task t:tasks) {
executor.execute(t);
}
try {
// Wait for all channels to finish connecting
latch.await();
for(Task t:tasks) {
Throwable ex=t.getException();
if(ex != null)
throw ex;
}
// Wait for all channels to have the correct number of members in their
// current view
boolean converged=false;
for(int timeoutToConverge=120,counter=0;counter < timeoutToConverge && !converged;SECONDS.sleep(1),counter++) {
for(final JChannel channel:channels) {
converged = channel.getView().size() == count;
if(!converged)
break;
}
}
final long duration=System.currentTimeMillis() - start;
System.out.println("Converged to a single group after " + duration + " ms; group is:\n");
for(int i=0;i < channels.length;i++) {
System.out.println("#" + (i + 1) + ": " + channels[i].getLocalAddress() + ": " + channels[i].getView());
}
for(final JChannel channel:channels) {
AssertJUnit.assertSame("View ok for channel " + channel.getLocalAddress(), count, channel.getView().size());
}
}
finally {
System.out.print("closing channels: ");
for(int i=channels.length -1; i>= 0; i
Channel channel=channels[i];
channel.close();
//there are sometimes big delays until entire cluster shuts down
//use sleep to make a smoother shutdown so we avoid false positives
Util.sleep(300);
int tries=0;
while((channel.isConnected() || channel.isOpen()) && tries++ < 10) {
Util.sleep(1000);
}
}
System.out.println("OK");
for(final JChannel channel: channels) {
assertFalse("Channel connected", channel.isConnected());
}
}
}
private static void changeViewBundling(JChannel channel) {
ProtocolStack stack=channel.getProtocolStack();
GMS gms=(GMS)stack.findProtocol(GMS.class);
if(gms != null) {
gms.setViewBundling(true);
gms.setMaxBundlingTime(500);
}
}
private static void changeMergeInterval(JChannel channel) {
ProtocolStack stack=channel.getProtocolStack();
MERGE2 merge=(MERGE2)stack.findProtocol(MERGE2.class);
if(merge != null) {
merge.setMinInterval(5000);
merge.setMaxInterval(10000);
}
}
private static void replaceDiscoveryProtocol(JChannel ch) throws Exception {
ProtocolStack stack=ch.getProtocolStack();
Protocol discovery=stack.removeProtocol("TCPPING");
if(discovery != null){
Protocol transport = stack.getTransport();
MPING mping=new MPING();
mping.setBindAddr(InetAddress.getLocalHost());
stack.insertProtocol(mping, ProtocolStack.ABOVE, transport.getName());
mping.setProtocolStack(ch.getProtocolStack());
mping.init();
mping.start();
System.out.println("Replaced TCPPING with MPING. See http://wiki.jboss.org/wiki/Wiki.jsp?page=JGroupsMERGE2");
}
}
private static class Task implements Runnable {
private final Channel c;
private final CountDownLatch latch;
private Throwable exception=null;
private boolean useDispatcher = false;
public Task(CountDownLatch latch, Channel c,boolean useDispatcher) {
this.latch=latch;
this.c=c;
this.useDispatcher = useDispatcher;
}
public Throwable getException() {
return exception;
}
public void run() {
try {
c.connect("test");
if(useDispatcher) {
final MessageDispatcher md=new MessageDispatcher(c, null, null, new MyHandler());
for(int i=0;i < 10;i++) {
final RspList rsp=md.castMessage(null,
new Message(null, null, i),
GroupRequest.GET_ALL,
2500);
for(Object o:rsp.getResults()) {
assertEquals("Wrong result received at " + c.getLocalAddress(), i, o);
}
}
}
}
catch(final Exception e) {
exception=e;
e.printStackTrace();
}
finally {
latch.countDown();
}
}
}
private static class MyHandler implements RequestHandler {
public Object handle(Message msg) {
return msg.getObject();
}
}
}
|
package org.jgroups.tests;
import org.jgroups.ChannelException;
import org.jgroups.ExtendedReceiverAdapter;
import org.jgroups.JChannel;
import org.jgroups.View;
import org.jgroups.protocols.TP;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.util.Promise;
import org.jgroups.util.Util;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.*;
@Test(groups={"temp"}, sequential=true)
public class LargeStateTransferTest extends ChannelTestBase {
JChannel provider, requester;
Promise<Integer> p=new Promise<Integer>();
long start, stop;
final static int SIZE_1=100000, SIZE_2=1000000, SIZE_3=5000000, SIZE_4=10000000;
protected boolean useBlocking() {
return true;
}
@BeforeMethod
protected void setUp() throws Exception {
provider=createChannel(true, 2);
modifyStack(provider);
requester=createChannel(provider);
setOOBPoolSize(provider, requester);
}
@AfterMethod
protected void tearDown() throws Exception {
Util.close(requester, provider);
}
public void testStateTransfer1() throws ChannelException {
_testStateTransfer(SIZE_1, "testStateTransfer1");
}
public void testStateTransfer2() throws ChannelException {
_testStateTransfer(SIZE_2, "testStateTransfer2");
}
public void testStateTransfer3() throws ChannelException {
_testStateTransfer(SIZE_3, "testStateTransfer3");
}
public void testStateTransfer4() throws ChannelException {
_testStateTransfer(SIZE_4, "testStateTransfer4");
}
private void _testStateTransfer(int size, String suffix) throws ChannelException {
final String GROUP="LargeStateTransferTest-" + suffix;
provider.setReceiver(new Provider(size));
provider.connect(GROUP);
p.reset();
requester.setReceiver(new Requester(p));
requester.connect(GROUP);
View view=requester.getView();
assert view.size() == 2 : "view is " + view + ", but should have 2 members";
log("requesting state of " + size + " bytes");
start=System.currentTimeMillis();
boolean rc=requester.getState(provider.getLocalAddress(), 20000);
System.out.println("getState(): result=" + rc);
Object result=p.getResult(10000);
stop=System.currentTimeMillis();
log("result=" + result + " bytes (in " + (stop-start) + "ms)");
assertNotNull(result);
assertEquals(result, new Integer(size));
}
private static void setOOBPoolSize(JChannel... channels) {
for(JChannel channel: channels) {
TP transport=channel.getProtocolStack().getTransport();
transport.setOOBMinPoolSize(1);
transport.setOOBMaxPoolSize(2);
}
}
static void log(String msg) {
System.out.println(Thread.currentThread() + " -- "+ msg);
}
private static void modifyStack(JChannel ch) {
ProtocolStack stack=ch.getProtocolStack();
GMS gms=(GMS)stack.findProtocol(GMS.class);
if(gms != null)
gms.setLogCollectMessages(false);
}
private static class Provider extends ExtendedReceiverAdapter {
byte[] state;
public Provider(int size) {
state=new byte[size];
}
public byte[] getState() {
return state;
}
public void viewAccepted(View new_view) {
System.out.println("[provider] new_view = " + new_view);
}
public void getState(OutputStream ostream){
ObjectOutputStream oos =null;
try{
oos=new ObjectOutputStream(ostream);
oos.writeInt(state.length);
oos.write(state);
}
catch (IOException e){}
finally{
Util.close(ostream);
}
}
public void setState(byte[] state) {
throw new UnsupportedOperationException("not implemented by provider");
}
}
private static class Requester extends ExtendedReceiverAdapter {
Promise<Integer> p;
public Requester(Promise<Integer> p) {
this.p=p;
}
public void viewAccepted(View new_view) {
System.out.println("[requester] new_view = " + new_view);
}
public byte[] getState() {
throw new UnsupportedOperationException("not implemented by requester");
}
public void setState(byte[] state) {
p.setResult(new Integer(state.length));
}
public void setState(InputStream istream) {
ObjectInputStream ois=null;
int size=0;
try{
ois= new ObjectInputStream(istream);
size = ois.readInt();
byte []stateReceived= new byte[size];
ois.read(stateReceived);
}
catch (IOException e) {}
finally {
Util.close(ois);
}
p.setResult(new Integer(size));
}
}
}
|
package at.ac.tuwien.kr.alpha.solver;
import at.ac.tuwien.kr.alpha.grounder.Grounder;
import at.ac.tuwien.kr.alpha.solver.heuristics.BranchingHeuristicFactory;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import java.util.*;
import java.util.function.Function;
@RunWith(Parameterized.class)
public abstract class AbstractSolverTests {
@Parameters(name = "{0}")
public static Collection<Object[]> factories() {
boolean enableAdditionalInternalChecks = false;
return Arrays.asList(new Object[][]{
{
"NaiveSolver",
(Function<Grounder, Solver>) NaiveSolver::new
},
{
"DefaultSolver (random BerkMin)",
(Function<Grounder, Solver>) g -> {
return new DefaultSolver(g, new Random(), BranchingHeuristicFactory.BERKMIN, enableAdditionalInternalChecks);
}
},
{
"DefaultSolver (deterministic BerkMin)",
(Function<Grounder, Solver>) g -> {
return new DefaultSolver(g, new Random(0), BranchingHeuristicFactory.BERKMIN, enableAdditionalInternalChecks);
}
},
{
"DefaultSolver (random BerkMinLiteral)",
(Function<Grounder, Solver>) g -> {
return new DefaultSolver(g, new Random(), BranchingHeuristicFactory.BERKMINLITERAL, enableAdditionalInternalChecks);
}
},
{
"DefaultSolver (deterministic BerkMinLiteral)",
(Function<Grounder, Solver>) g -> {
return new DefaultSolver(g, new Random(0), BranchingHeuristicFactory.BERKMINLITERAL, enableAdditionalInternalChecks);
}
},
{
"DefaultSolver (random Naive)",
(Function<Grounder, Solver>) g -> {
return new DefaultSolver(g, new Random(), BranchingHeuristicFactory.NAIVE, enableAdditionalInternalChecks);
}
},
{
"DefaultSolver (deterministic Naive)",
(Function<Grounder, Solver>) g -> {
return new DefaultSolver(g, new Random(0), BranchingHeuristicFactory.NAIVE, enableAdditionalInternalChecks);
}
},
});
}
@Parameter(value = 0)
public String solverName;
@Parameter(value = 1)
public Function<Grounder, Solver> factory;
protected Solver getInstance(Grounder g) {
return factory.apply(g);
}
}
|
package com.datalogics.pdf.samples.printing;
import com.datalogics.pdf.samples.SampleTest;
import mockit.Mock;
import mockit.MockUp;
import org.junit.Test;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Pageable;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUIFactory;
import javax.print.attribute.Attribute;
import javax.print.attribute.AttributeSet;
import javax.print.attribute.PrintServiceAttribute;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.ResolutionSyntax;
import javax.print.attribute.standard.PrinterResolution;
import javax.print.event.PrintServiceAttributeListener;
/**
* Tests the PrintPdf sample.
*/
public class PrintPdfTest extends SampleTest {
@Test
public <T extends PrinterJob> void testMain() throws Exception {
// Mock the PrintServiceLookup.lookupDefaultPrintService() method to return a TestPrintService object
new MockUp<PrintServiceLookup>() {
@Mock(invocations = 1)
PrintService lookupDefaultPrintService() {
return new TestPrintService();
}
};
// Mock the PrinterJob.getPrinterJob() method to return a TestPrinterJob object
new MockUp<T>() {
@Mock(invocations = 1)
public PrinterJob getPrinterJob() {
return new TestPrinterJob();
}
};
// Call the main method
final String[] args = new String[0];
PrintPdf.main(args);
}
/*
* TestPrintService implements a 'fake' PrintService to be returned by our mock PrintServiceLookup.
*/
private static class TestPrintService implements PrintService {
/*
* Return a name for our 'fake' PrintService.
*/
@Override
public String getName() {
return "Virtual Test Printer";
}
/*
* Return default attribute values for our 'fake' PrintService. The only attribute we care about is
* PrinterResolution; all others return null.
*/
@Override
public Object getDefaultAttributeValue(final Class<? extends Attribute> category) {
if (category == PrinterResolution.class) {
return new PrinterResolution(400, 400, ResolutionSyntax.DPI);
} else {
return null;
}
}
/*
* The following methods are not used in the test, and are given stub implementations.
*/
@Override
public DocPrintJob createPrintJob() {
return null;
}
@Override
public void addPrintServiceAttributeListener(final PrintServiceAttributeListener listener) {}
@Override
public void removePrintServiceAttributeListener(final PrintServiceAttributeListener listener) {}
@Override
public PrintServiceAttributeSet getAttributes() {
return null;
}
@Override
public <T extends PrintServiceAttribute> T getAttribute(final Class<T> category) {
return null;
}
@Override
public DocFlavor[] getSupportedDocFlavors() {
return new DocFlavor[0];
}
@Override
public boolean isDocFlavorSupported(final DocFlavor flavor) {
return false;
}
@Override
public Class<?>[] getSupportedAttributeCategories() {
return new Class<?>[0];
}
@Override
public boolean isAttributeCategorySupported(final Class<? extends Attribute> category) {
return false;
}
@Override
public Object getSupportedAttributeValues(final Class<? extends Attribute> category, final DocFlavor flavor,
final AttributeSet attributes) {
return null;
}
@Override
public boolean isAttributeValueSupported(final Attribute attrval, final DocFlavor flavor,
final AttributeSet attributes) {
return false;
}
@Override
public AttributeSet getUnsupportedAttributes(final DocFlavor flavor, final AttributeSet attributes) {
return null;
}
@Override
public ServiceUIFactory getServiceUIFactory() {
return null;
}
}
/*
* TestPrinterJob implements a 'fake' PrinterJob to intercept print requests.
*/
private static class TestPrinterJob extends PrinterJob {
private Printable painter;
private PageFormat format;
/*
* Clones the PageFormat argument and alters the clone to a default page. No changes are required in this case.
*/
@Override
public PageFormat defaultPage(final PageFormat page) {
return (PageFormat) page.clone();
}
/*
* Return a validated page format.
*/
@Override
public PageFormat validatePage(final PageFormat page) {
return (PageFormat) page.clone();
}
/*
* Print the document.
*/
@Override
public void print() throws PrinterException {
// Create a BufferedImage to render into
final int width = (int) (format.getImageableWidth() - format.getImageableX());
final int height = (int) (format.getImageableHeight() - format.getImageableY());
final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D gfx2d = image.createGraphics();
int pageIndex = 0;
while (painter.print(gfx2d, format, pageIndex) == Printable.PAGE_EXISTS) {
// painter.print() disposed of the Graphics2D, obtain a new one
gfx2d = image.createGraphics();
pageIndex++;
// TODO: Save buffered image to disk and checksum
}
}
/*
* Calls painter to render the pages in the specified format.
*/
@Override
public void setPrintable(final Printable painter, final PageFormat format) {
this.painter = painter;
this.format = format;
}
/*
* The following methods are not used in the test, and are given stub implementations.
*/
@Override
public void setPrintable(final Printable painter) {}
@Override
public void setPageable(final Pageable document) throws NullPointerException {}
@Override
public boolean printDialog() throws HeadlessException {
return false;
}
@Override
public PageFormat pageDialog(final PageFormat page) throws HeadlessException {
return null;
}
@Override
public void setCopies(final int copies) {}
@Override
public int getCopies() {
return 0;
}
@Override
public String getUserName() {
return null;
}
@Override
public void setJobName(final String jobName) {}
@Override
public String getJobName() {
return null;
}
@Override
public void cancel() {}
@Override
public boolean isCancelled() {
return false;
}
}
}
|
package com.facebook.litho;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.util.SparseArray;
import android.view.accessibility.AccessibilityManager;
import com.facebook.litho.testing.testrunner.ComponentsTestRunner;
import com.facebook.litho.widget.Text;
import com.facebook.litho.testing.TestComponent;
import com.facebook.litho.testing.TestDrawableComponent;
import com.facebook.litho.testing.TestLayoutComponent;
import com.facebook.litho.testing.TestNullLayoutComponent;
import com.facebook.litho.testing.TestSizeDependentComponent;
import com.facebook.litho.testing.TestViewComponent;
import com.facebook.yoga.YogaAlign;
import com.facebook.yoga.YogaEdge;
import com.facebook.yoga.YogaFlexDirection;
import com.facebook.yoga.YogaJustify;
import com.facebook.yoga.YogaPositionType;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;
import org.powermock.reflect.Whitebox;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.shadows.ShadowAccessibilityManager;
import static android.content.Context.ACCESSIBILITY_SERVICE;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES;
import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE;
import static com.facebook.yoga.YogaEdge.BOTTOM;
import static com.facebook.yoga.YogaEdge.LEFT;
import static com.facebook.yoga.YogaEdge.RIGHT;
import static com.facebook.yoga.YogaEdge.TOP;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@PrepareForTest(Component.class)
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
@RunWith(ComponentsTestRunner.class)
public class LayoutStateCalculateTest {
@Rule
public PowerMockRule mPowerMockRule = new PowerMockRule();
@Before
public void setup() throws Exception {
}
@Test
public void testNoUnnecessaryLayoutOutputsForLayoutSpecs() {
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c)))
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY));
assertEquals(2, layoutState.getMountableOutputCount());
}
@Test
public void testLayoutOutputsForRootInteractiveLayoutSpecs() {
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.wrapInView()
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY));
assertEquals(2, layoutState.getMountableOutputCount());
}
@Test
public void testLayoutOutputsForSpecsWithClickHandling() {
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.clickHandler(c.newEventHandler(1)))
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY));
assertEquals(3, layoutState.getMountableOutputCount());
final NodeInfo nodeInfo = layoutState.getMountableOutputAt(1).getNodeInfo();
assertNotNull(nodeInfo);
assertNotNull(nodeInfo.getClickHandler());
assertNull(nodeInfo.getLongClickHandler());
assertNull(nodeInfo.getTouchHandler());
}
@Test
public void testLayoutOutputsForSpecsWithLongClickHandling() {
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.longClickHandler(c.newEventHandler(1)))
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY));
assertEquals(3, layoutState.getMountableOutputCount());
final NodeInfo nodeInfo = layoutState.getMountableOutputAt(1).getNodeInfo();
assertNotNull(nodeInfo);
assertNull(nodeInfo.getClickHandler());
assertNotNull(nodeInfo.getLongClickHandler());
assertNull(nodeInfo.getTouchHandler());
}
@Test
public void testLayoutOutputsForSpecsWithTouchHandling() {
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.touchHandler(c.newEventHandler(1)))
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY));
assertEquals(3, layoutState.getMountableOutputCount());
final NodeInfo nodeInfo = layoutState.getMountableOutputAt(1).getNodeInfo();
assertNotNull(nodeInfo);
assertNotNull(nodeInfo.getTouchHandler());
assertNull(nodeInfo.getClickHandler());
assertNull(nodeInfo.getLongClickHandler());
}
@Test
public void testLayoutOutputsForDeepLayoutSpecs() {
final int paddingSize = 5;
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.backgroundColor(0xFFFF0000)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.flexDirection(YogaFlexDirection.ROW)
.justifyContent(YogaJustify.SPACE_AROUND)
.alignItems(YogaAlign.CENTER)
.positionType(YogaPositionType.ABSOLUTE)
.positionPx(LEFT, 50)
.positionPx(TOP, 50)
.positionPx(RIGHT, 200)
.positionPx(BOTTOM, 50)
.child(
Text.create(c)
.text("textLeft1"))
.child(
Text.create(c)
.text("textRight1"))
.paddingPx(YogaEdge.ALL, paddingSize)
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.flexDirection(YogaFlexDirection.ROW)
.justifyContent(YogaJustify.SPACE_AROUND)
.alignItems(YogaAlign.CENTER)
.positionType(YogaPositionType.ABSOLUTE)
.positionPx(LEFT, 200)
.positionPx(TOP, 50)
.positionPx(RIGHT, 50)
.positionPx(BOTTOM, 50)
.child(
Text.create(c)
.text("textLeft2")
.withLayout().flexShrink(0)
.wrapInView()
.paddingPx(YogaEdge.ALL, paddingSize))
.child(
TestViewComponent.create(c)
.withLayout().flexShrink(0)
.wrapInView()))
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY));
// Check total layout outputs.
assertEquals(8, layoutState.getMountableOutputCount());
// Check quantity of HostComponents.
int totalHosts = 0;
for (int i = 0; i < layoutState.getMountableOutputCount(); i++) {
ComponentLifecycle lifecycle = getComponentAt(layoutState, i);
if (isHostComponent(lifecycle)) {
totalHosts++;
}
}
assertEquals(3, totalHosts);
//Check all the Layouts are in the correct position.
assertTrue(isHostComponent(getComponentAt(layoutState, 0)));
assertTrue(getComponentAt(layoutState, 1) instanceof DrawableComponent);
assertTrue(isHostComponent(getComponentAt(layoutState, 2)));
assertTrue(getComponentAt(layoutState, 3) instanceof Text);
assertTrue(getComponentAt(layoutState, 4) instanceof Text);
assertTrue(isHostComponent(getComponentAt(layoutState, 5)));
assertTrue(getComponentAt(layoutState, 6) instanceof Text);
assertTrue(getComponentAt(layoutState, 7) instanceof TestViewComponent);
// Check the text within the TextComponents.
assertEquals("textLeft1", getTextFromTextComponent(layoutState, 3));
assertEquals("textRight1", getTextFromTextComponent(layoutState, 4));
assertEquals("textLeft2", getTextFromTextComponent(layoutState, 6));
Rect textLayoutBounds = layoutState.getMountableOutputAt(6).getBounds();
Rect textBackgroundBounds = layoutState.getMountableOutputAt(5).getBounds();
assertEquals(textBackgroundBounds.left , textLayoutBounds.left - paddingSize);
assertEquals(textBackgroundBounds.top , textLayoutBounds.top - paddingSize);
assertEquals(textBackgroundBounds.right , textLayoutBounds.right + paddingSize);
assertEquals(textBackgroundBounds.bottom , textLayoutBounds.bottom + paddingSize);
}
@Test
public void testLayoutOutputMountBounds() {
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.widthPx(30)
.heightPx(30)
.wrapInView()
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.widthPx(10)
.heightPx(10)
.marginPx(YogaEdge.ALL, 10)
.wrapInView()
.child(
TestDrawableComponent.create(c)
.withLayout().flexShrink(0)
.widthPx(10)
.heightPx(10)))
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY));
Rect mountBounds = new Rect();
layoutState.getMountableOutputAt(0).getMountBounds(mountBounds);
assertEquals(new Rect(0, 0, 30, 30), mountBounds);
layoutState.getMountableOutputAt(1).getMountBounds(mountBounds);
assertEquals(new Rect(10, 10, 20, 20), mountBounds);
layoutState.getMountableOutputAt(2).getMountBounds(mountBounds);
assertEquals(new Rect(0, 0, 10, 10), mountBounds);
}
@Test
public void testLayoutOutputsForDeepLayoutSpecsWithBackground() {
final int paddingSize = 5;
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.backgroundColor(0xFFFF0000)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.flexDirection(YogaFlexDirection.ROW)
.justifyContent(YogaJustify.SPACE_AROUND)
.alignItems(YogaAlign.CENTER)
.positionType(YogaPositionType.ABSOLUTE)
.positionPx(LEFT, 50)
.positionPx(TOP, 50)
.positionPx(RIGHT, 200)
.positionPx(BOTTOM, 50)
.child(
Text.create(c)
.text("textLeft1"))
.child(
Text.create(c)
.text("textRight1"))
.backgroundColor(0xFFFF0000)
.foregroundColor(0xFFFF0000)
.paddingPx(YogaEdge.ALL, paddingSize)
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.flexDirection(YogaFlexDirection.ROW)
.justifyContent(YogaJustify.SPACE_AROUND)
.alignItems(YogaAlign.CENTER)
.positionType(YogaPositionType.ABSOLUTE)
.positionPx(LEFT, 200)
.positionPx(TOP, 50)
.positionPx(RIGHT, 50)
.positionPx(BOTTOM, 50)
.child(
Text.create(c)
.text("textLeft2")
.withLayout().flexShrink(0)
.wrapInView()
.backgroundColor(0xFFFF0000)
.paddingPx(YogaEdge.ALL, paddingSize))
.child(
TestViewComponent.create(c)
.withLayout().flexShrink(0)
.backgroundColor(0xFFFF0000)
.foregroundColor(0x0000FFFF)
.paddingPx(YogaEdge.ALL, paddingSize)))
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY));
// Account for Android version in the foreground. If >= M the foreground is part of the
// ViewLayoutOutput otherwise it has its own LayoutOutput.
boolean foregroundHasOwnOutput = Build.VERSION.SDK_INT < Build.VERSION_CODES.M;
// Check total layout outputs.
assertEquals(
foregroundHasOwnOutput ? 12 : 11,
layoutState.getMountableOutputCount());
// Check quantity of HostComponents.
int totalHosts = 0;
for (int i = 0; i < layoutState.getMountableOutputCount(); i++) {
ComponentLifecycle lifecycle = getComponentAt(layoutState, i);
if (isHostComponent(lifecycle)) {
totalHosts++;
}
}
assertEquals(3, totalHosts);
//Check all the Layouts are in the correct position.
assertTrue(isHostComponent(getComponentAt(layoutState, 0)));
assertTrue(getComponentAt(layoutState, 1) instanceof DrawableComponent);
assertTrue(isHostComponent(getComponentAt(layoutState, 2)));
assertTrue(getComponentAt(layoutState, 3) instanceof DrawableComponent);
assertTrue(getComponentAt(layoutState, 4) instanceof Text);
assertTrue(getComponentAt(layoutState, 5) instanceof Text);
assertTrue(getComponentAt(layoutState, 6) instanceof DrawableComponent);
assertTrue(isHostComponent(getComponentAt(layoutState, 7)));
assertTrue(getComponentAt(layoutState, 8) instanceof DrawableComponent);
assertTrue(getComponentAt(layoutState, 9) instanceof Text);
assertTrue(getComponentAt(layoutState, 10) instanceof TestViewComponent);
if (foregroundHasOwnOutput) {
assertTrue(getComponentAt(layoutState, 11) instanceof DrawableComponent);
}
// Check the text within the TextComponents.
assertEquals("textLeft1", getTextFromTextComponent(layoutState, 4));
assertEquals("textRight1", getTextFromTextComponent(layoutState, 5));
assertEquals("textLeft2", getTextFromTextComponent(layoutState, 9));
//Check that the backgrounds have the same size of the components to which they are associated
assertEquals(
layoutState.getMountableOutputAt(2).getBounds(),
layoutState.getMountableOutputAt(3).getBounds());
assertEquals(
layoutState.getMountableOutputAt(2).getBounds(),
layoutState.getMountableOutputAt(6).getBounds());
Rect textLayoutBounds = layoutState.getMountableOutputAt(9).getBounds();
Rect textBackgroundBounds = layoutState.getMountableOutputAt(8).getBounds();
assertEquals(textBackgroundBounds.left , textLayoutBounds.left - paddingSize);
assertEquals(textBackgroundBounds.top , textLayoutBounds.top - paddingSize);
assertEquals(textBackgroundBounds.right , textLayoutBounds.right + paddingSize);
assertEquals(textBackgroundBounds.bottom , textLayoutBounds.bottom + paddingSize);
assertEquals(layoutState.getMountableOutputAt(7).getBounds(),layoutState.getMountableOutputAt(8).getBounds());
ViewNodeInfo viewNodeInfo = layoutState.getMountableOutputAt(10).getViewNodeInfo();
assertNotNull(viewNodeInfo);
assertTrue(viewNodeInfo.getBackground() != null);
if (foregroundHasOwnOutput) {
assertTrue(viewNodeInfo.getForeground() == null);
} else {
assertTrue(viewNodeInfo.getForeground() != null);
}
assertTrue(viewNodeInfo.getPaddingLeft() == paddingSize);
assertTrue(viewNodeInfo.getPaddingTop() == paddingSize);
assertTrue(viewNodeInfo.getPaddingRight() == paddingSize);
assertTrue(viewNodeInfo.getPaddingBottom() == paddingSize);
}
@Test
public void testLayoutOutputsForMegaDeepLayoutSpecs() {
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
TestDrawableComponent.create(c)
.withLayout().flexShrink(0)
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.wrapInView())
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c)))
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestViewComponent.create(c)))
.wrapInView())
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY));
// Check total layout outputs.
assertEquals(18, layoutState.getMountableOutputCount());
// Check quantity of HostComponents.
int totalHosts = 0;
for (int i = 0; i < layoutState.getMountableOutputCount(); i++) {
ComponentLifecycle lifecycle = getComponentAt(layoutState, i);
if (isHostComponent(lifecycle)) {
totalHosts++;
}
}
assertEquals(7, totalHosts);
// Check all the Components match the right LayoutOutput positions.
// Tree One.
assertTrue(isHostComponent(getComponentAt(layoutState, 0)));
assertTrue(isHostComponent(getComponentAt(layoutState, 1)));
assertTrue(getComponentAt(layoutState, 2) instanceof TestDrawableComponent);
assertTrue(getComponentAt(layoutState, 3) instanceof TestDrawableComponent);
// Tree Two.
assertTrue(isHostComponent(getComponentAt(layoutState, 4)));
assertTrue(isHostComponent(getComponentAt(layoutState, 5)));
assertTrue(getComponentAt(layoutState, 6) instanceof TestDrawableComponent);
assertTrue(isHostComponent(getComponentAt(layoutState, 7)));
assertTrue(getComponentAt(layoutState, 8) instanceof TestDrawableComponent);
assertTrue(getComponentAt(layoutState, 9) instanceof TestDrawableComponent);
// Tree Three.
assertTrue(isHostComponent(getComponentAt(layoutState, 10)));
assertTrue(getComponentAt(layoutState, 11) instanceof TestDrawableComponent);
assertTrue(getComponentAt(layoutState, 12) instanceof TestDrawableComponent);
assertTrue(getComponentAt(layoutState, 13) instanceof TestDrawableComponent);
// Tree Four.
assertTrue(isHostComponent(getComponentAt(layoutState, 14)));
assertTrue(getComponentAt(layoutState, 15) instanceof TestDrawableComponent);
assertTrue(getComponentAt(layoutState, 16) instanceof TestDrawableComponent);
assertTrue(getComponentAt(layoutState, 17) instanceof TestViewComponent);
}
@Test
public void testLayoutOutputStableIds() {
final Component component1 = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.contentDescription("cd0"))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.contentDescription("cd1"))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestViewComponent.create(c))
.contentDescription("cd2"))
.build();
}
};
final Component component2 = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.contentDescription("cd0"))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.contentDescription("cd1"))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestViewComponent.create(c))
.contentDescription("cd2"))
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component1,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY));
LayoutState sameComponentLayoutState = calculateLayoutState(
RuntimeEnvironment.application,
component2,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY));
assertEquals(
layoutState.getMountableOutputCount(),
sameComponentLayoutState.getMountableOutputCount());
for (int i = 0; i < layoutState.getMountableOutputCount(); i++) {
assertEquals(
layoutState.getMountableOutputAt(i).getId(),
sameComponentLayoutState.getMountableOutputAt(i).getId());
}
}
@Test
public void testLayoutOutputStableIdsForMegaDeepComponent() {
final Component component1 = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
TestDrawableComponent.create(c)
.withLayout().flexShrink(0)
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.wrapInView())
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c)))
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestViewComponent.create(c)))
.wrapInView())
.build();
}
};
final Component component2 = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
TestDrawableComponent.create(c)
.withLayout().flexShrink(0)
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.wrapInView())
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c)))
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestViewComponent.create(c)))
.wrapInView())
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component1,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY));
LayoutState sameComponentLayoutState = calculateLayoutState(
RuntimeEnvironment.application,
component2,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY));
assertEquals(
layoutState.getMountableOutputCount(),
sameComponentLayoutState.getMountableOutputCount());
for (int i = 0; i < layoutState.getMountableOutputCount(); i++) {
assertEquals(
layoutState.getMountableOutputAt(i).getId(),
sameComponentLayoutState.getMountableOutputAt(i).getId());
}
}
@Test
public void testPartiallyStableIds() {
final Component component1 = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.build();
}
};
final Component component2 = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c)))
.build();
}
};
LayoutState layoutState1 = calculateLayoutState(
RuntimeEnvironment.application,
component1,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY));
LayoutState layoutState2 = calculateLayoutState(
RuntimeEnvironment.application,
component2,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY));
assertEquals(
layoutState1.getMountableOutputAt(0).getId(),
layoutState2.getMountableOutputAt(0).getId());
assertEquals(
layoutState1.getMountableOutputAt(1).getId(),
layoutState2.getMountableOutputAt(1).getId());
assertEquals(3, layoutState1.getMountableOutputCount());
assertEquals(4, layoutState2.getMountableOutputCount());
}
@Test
public void testDifferentIds() {
final Component component1 = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.build();
}
};
final Component component2 = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
TestDrawableComponent.create(c)
.withLayout().flexShrink(0)
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.wrapInView())
.build();
}
};
LayoutState layoutState1 = calculateLayoutState(
RuntimeEnvironment.application,
component1,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY));
LayoutState layoutState2 = calculateLayoutState(
RuntimeEnvironment.application,
component2,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY));
assertNotEquals(
layoutState1.getMountableOutputAt(1).getId(),
layoutState2.getMountableOutputAt(1).getId());
}
@Test
public void testLayoutOutputsWithInteractiveLayoutSpecAsLeafs() {
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestLayoutComponent.create(c))
.wrapInView())
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY));
// Check total layout outputs.
assertEquals(3, layoutState.getMountableOutputCount());
assertTrue(isHostComponent(getComponentAt(layoutState, 0)));
assertTrue(getComponentAt(layoutState, 1) instanceof TestDrawableComponent);
assertTrue(isHostComponent(getComponentAt(layoutState, 2)));
}
private static ComponentLifecycle getComponentAt(LayoutState layoutState, int index) {
return layoutState.getMountableOutputAt(index).getComponent().getLifecycle();
}
private static CharSequence getTextFromTextComponent(LayoutState layoutState, int index) {
return Whitebox.getInternalState(layoutState.getMountableOutputAt(index).getComponent(), "text");
}
private static boolean isHostComponent(ComponentLifecycle component) {
return component instanceof HostComponent;
}
@Test
public void testNoMeasureOnNestedComponentWithSameSpecs() {
final ComponentContext c = new ComponentContext(RuntimeEnvironment.application);
final Size size = new Size();
final TestComponent innerComponent =
TestDrawableComponent.create(c, 0, 0, false, true, true, false, false).build();
final int widthSpec = SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY);
final int heightSpec = SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY);
innerComponent.measure(
c,
widthSpec,
heightSpec,
size);
InternalNode internalNode = ((Component) innerComponent).getCachedLayout();
internalNode.setLastWidthSpec(widthSpec);
internalNode.setLastHeightSpec(heightSpec);
internalNode.setLastMeasuredWidth(internalNode.getWidth());
internalNode.setLastMeasuredHeight(internalNode.getHeight());
innerComponent.resetInteractions();
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Layout.create(c, innerComponent).flexShrink(0)
.widthPx(100)
.heightPx(100))
.build();
}
};
calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY));
assertFalse(innerComponent.wasMeasureCalled());
}
@Test
public void testNoMeasureOnNestedComponentWithNewMeasureSpecExact() {
final ComponentContext c = new ComponentContext(RuntimeEnvironment.application);
final Size size = new Size();
final TestComponent innerComponent =
TestDrawableComponent.create(c, 0, 0, false, true, true, false, false).build();
final int widthSpec = SizeSpec.makeSizeSpec(100, SizeSpec.AT_MOST);
final int heightSpec = SizeSpec.makeSizeSpec(100, SizeSpec.AT_MOST);
innerComponent.measure(
c,
widthSpec,
heightSpec,
size);
InternalNode internalNode = ((Component) innerComponent).getCachedLayout();
internalNode.setLastWidthSpec(widthSpec);
internalNode.setLastHeightSpec(heightSpec);
internalNode.setLastMeasuredWidth(100);
internalNode.setLastMeasuredHeight(100);
innerComponent.resetInteractions();
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Layout.create(c, innerComponent).flexShrink(0)
.widthPx(100)
.heightPx(100))
.build();
}
};
calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY));
assertFalse(innerComponent.wasMeasureCalled());
}
@Test
public void testNoMeasureOnNestedComponentWithNewMeasureSpecOldUnspecified() {
final ComponentContext c = new ComponentContext(RuntimeEnvironment.application);
final Size size = new Size();
final TestComponent innerComponent =
TestDrawableComponent.create(c, 0, 0, false, true, true, false, false).build();
final int widthSpec = SizeSpec.makeSizeSpec(0, SizeSpec.UNSPECIFIED);
final int heightSpec = SizeSpec.makeSizeSpec(0, SizeSpec.UNSPECIFIED);
innerComponent.measure(
c,
widthSpec,
heightSpec,
size);
InternalNode internalNode = ((Component) innerComponent).getCachedLayout();
internalNode.setLastWidthSpec(widthSpec);
internalNode.setLastHeightSpec(heightSpec);
internalNode.setLastMeasuredWidth(99);
internalNode.setLastMeasuredHeight(99);
innerComponent.resetInteractions();
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(innerComponent)
.build();
}
};
calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.AT_MOST),
SizeSpec.makeSizeSpec(100, SizeSpec.AT_MOST));
assertFalse(innerComponent.wasMeasureCalled());
}
@Test
public void testNoMeasureOnNestedComponentWithOldAndNewAtMost() {
final ComponentContext c = new ComponentContext(RuntimeEnvironment.application);
final Size size = new Size();
final TestComponent innerComponent =
TestDrawableComponent.create(c, 0, 0, false, true, true, false, false).build();
final int widthSpec = SizeSpec.makeSizeSpec(100, SizeSpec.AT_MOST);
final int heightSpec = SizeSpec.makeSizeSpec(100, SizeSpec.AT_MOST);
innerComponent.measure(
c,
widthSpec,
heightSpec,
size);
InternalNode internalNode = ((Component) innerComponent).getCachedLayout();
internalNode.setLastWidthSpec(widthSpec);
internalNode.setLastHeightSpec(heightSpec);
internalNode.setLastMeasuredWidth(50);
internalNode.setLastMeasuredHeight(50);
innerComponent.resetInteractions();
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(innerComponent)
.build();
}
};
calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(50, SizeSpec.AT_MOST),
SizeSpec.makeSizeSpec(50, SizeSpec.AT_MOST));
assertFalse(innerComponent.wasMeasureCalled());
}
@Test
public void testLayoutOutputsForTwiceNestedComponent() {
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c)))
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c)))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))))
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY));
assertEquals(5, layoutState.getMountableOutputCount());
long hostMarkerRoot = layoutState.getMountableOutputAt(0).getId();
long hostMarkerOne = layoutState.getMountableOutputAt(1).getId();
// First output is the inner host for the click handler
assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(1).getHostMarker());
// Second output is the child of the inner host
assertEquals(hostMarkerOne, layoutState.getMountableOutputAt(2).getHostMarker());
// Third and fourth outputs are children of the root view.
assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(3).getHostMarker());
assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(4).getHostMarker());
}
@Test
public void testLayoutOutputsForComponentWithBackgrounds() {
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.backgroundColor(0xFFFF0000)
.foregroundColor(0xFFFF0000)
.child(TestDrawableComponent.create(c))
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY));
assertEquals(4, layoutState.getMountableOutputCount());
// First and third output are the background and the foreground
assertTrue(getComponentAt(layoutState, 1) instanceof DrawableComponent);
assertTrue(getComponentAt(layoutState, 3) instanceof DrawableComponent);
}
@Test
public void testLayoutOutputsForNonComponentClickableNode() {
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.wrapInView())
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestViewComponent.create(c))
.wrapInView())
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY));
assertEquals(9, layoutState.getMountableOutputCount());
long hostMarkerRoot = layoutState.getMountableOutputAt(0).getHostMarker();
long hostMarkerZero = layoutState.getMountableOutputAt(1).getHostMarker();
long hostMarkerTwo = layoutState.getMountableOutputAt(4).getHostMarker();
long hostMarkerThree = layoutState.getMountableOutputAt(7).getHostMarker();
assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(1).getHostMarker());
assertEquals(hostMarkerZero, layoutState.getMountableOutputAt(3).getHostMarker());
assertEquals(hostMarkerTwo, layoutState.getMountableOutputAt(5).getHostMarker());
assertEquals(hostMarkerZero, layoutState.getMountableOutputAt(6).getHostMarker());
assertEquals(hostMarkerThree, layoutState.getMountableOutputAt(8).getHostMarker());
assertTrue(isHostComponent(getComponentAt(layoutState, 0)));
assertTrue(isHostComponent(getComponentAt(layoutState, 1)));
assertTrue(getComponentAt(layoutState, 2) instanceof TestDrawableComponent);
assertTrue(isHostComponent(getComponentAt(layoutState, 3)));
assertTrue(getComponentAt(layoutState, 4) instanceof TestDrawableComponent);
assertTrue(getComponentAt(layoutState, 5) instanceof TestDrawableComponent);
assertTrue(isHostComponent(getComponentAt(layoutState, 6)));
assertTrue(getComponentAt(layoutState, 7) instanceof TestDrawableComponent);
assertTrue(getComponentAt(layoutState, 8) instanceof TestViewComponent);
}
@Test
public void testLayoutOutputsForNonComponentContentDescriptionNode() {
enableAccessibility();
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.contentDescription("cd0"))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestDrawableComponent.create(c))
.contentDescription("cd1"))
.child(
Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.child(TestViewComponent.create(c))
.contentDescription("cd2"))
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY));
assertEquals(9, layoutState.getMountableOutputCount());
long hostMarkerRoot = layoutState.getMountableOutputAt(0).getHostMarker();
long hostMarkerZero = layoutState.getMountableOutputAt(1).getHostMarker();
long hostMarkerTwo = layoutState.getMountableOutputAt(4).getHostMarker();
long hostMarkerThree = layoutState.getMountableOutputAt(7).getHostMarker();
assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(1).getHostMarker());
assertEquals(hostMarkerZero, layoutState.getMountableOutputAt(3).getHostMarker());
assertEquals(hostMarkerTwo, layoutState.getMountableOutputAt(5).getHostMarker());
assertEquals(hostMarkerZero, layoutState.getMountableOutputAt(6).getHostMarker());
assertEquals(hostMarkerThree, layoutState.getMountableOutputAt(8).getHostMarker());
assertTrue(isHostComponent(getComponentAt(layoutState, 0)));
assertTrue(isHostComponent(getComponentAt(layoutState, 1)));
assertTrue(getComponentAt(layoutState, 2) instanceof TestDrawableComponent);
assertTrue(isHostComponent(getComponentAt(layoutState, 3)));
assertTrue(getComponentAt(layoutState, 4) instanceof TestDrawableComponent);
assertTrue(getComponentAt(layoutState, 5) instanceof TestDrawableComponent);
assertTrue(isHostComponent(getComponentAt(layoutState, 6)));
assertTrue(getComponentAt(layoutState, 7) instanceof TestDrawableComponent);
assertTrue(getComponentAt(layoutState, 8) instanceof TestViewComponent);
}
@Test
public void testLayoutOutputsForFocusableOnRoot() {
final Component component = new InlineLayoutSpec() {
@Override
protected ComponentLayout onCreateLayout(ComponentContext c) {
return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START)
.child(TestDrawableComponent.create(c))
.focusable(true)
.build();
}
};
LayoutState layoutState = calculateLayoutState(
RuntimeEnvironment.application,
component,
-1,
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY),
SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY));
assertEquals(2, layoutState.getMountableOutputCount());
long hostMarkerZero = layoutState.getMountableOutputAt(0).getHostMarker();
assertEquals(hostMarkerZero, layoutState.getMountableOutputAt(1).getHostMarker());
|
package greed;
import com.topcoder.client.contestant.ProblemComponentModel;
import com.topcoder.shared.problem.Renderer;
import greed.code.CodeByLine;
import greed.code.LanguageManager;
import greed.code.transform.AppendingTransformer;
import greed.code.transform.CutBlockRemover;
import greed.code.transform.EmptyCutBlockCleaner;
import greed.code.transform.ContinuousBlankLineRemover;
import greed.conf.schema.GreedConfig;
import greed.conf.schema.LanguageConfig;
import greed.conf.schema.TemplateConfig;
import greed.model.*;
import greed.template.TemplateEngine;
import greed.ui.ConfigurationDialog;
import greed.ui.GreedEditorPanel;
import greed.util.*;
import javax.swing.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
/**
* Greed is good! Cheers!
*/
@SuppressWarnings("unused")
public class Greed {
private Language currentLang;
private Problem currentProb;
private Contest currentContest;
private HashMap<String, Object> currentTemplateModel;
private GreedEditorPanel talkingWindow;
private boolean firstUsing;
public Greed() {
// Entrance of all program
Log.i("Create Greed Plugin Instance");
this.talkingWindow = new GreedEditorPanel(this);
this.firstUsing = true;
}
// Greed signature in the code
public String getSignature() {
return String.format("%s Powered by %s %s",
LanguageManager.getInstance().getTrait(currentLang).getCommentPrefix(), AppInfo.getAppName(), AppInfo.getVersion());
}
// Cache the editor
public boolean isCacheable() {
return !Debug.developmentMode;
}
// Called when open the coding frame
// Like FileEdit, a log window is used
public JPanel getEditorPanel() {
return talkingWindow;
}
// Ignore the given source code
public void setSource(String source) {
}
public void startUsing() {
Log.i("Start using called");
talkingWindow.clear();
if (firstUsing) {
talkingWindow.say(String.format("Hi, this is %s.", AppInfo.getAppName()));
} else {
talkingWindow.say(String.format("So we meet again :>"));
}
firstUsing = false;
try {
Utils.initialize();
} catch (greed.conf.ConfigException e) {
Log.e("Exception while loading config", e);
talkingWindow.say("Something wrong when loading config saying \"" + e.getMessage() + "\", try fix it.");
}
}
public void stopUsing() {
Log.i("Stop using called");
}
public void configure() {
new ConfigurationDialog().setVisible(true);
}
public void setProblemComponent(ProblemComponentModel componentModel, com.topcoder.shared.language.Language language, Renderer renderer) {
currentContest = Convert.convertContest(componentModel);
currentLang = Convert.convertLanguage(language);
currentProb = Convert.convertProblem(componentModel, currentLang);
talkingWindow.say("Hmm, it's a problem with " + currentProb.getScore() + " points. Good choice!");
generateCode(false);
}
public void generateCode(boolean forceOverride) {
// Check whether workspace is set
if (Configuration.getWorkspace() == null || "".equals(Configuration.getWorkspace())) {
talkingWindow.setEnabled(false);
talkingWindow.say("It seems that you haven't set your workspace, go set it!");
Log.e("Workspace not set");
return;
}
talkingWindow.setEnabled(true);
try {
setProblem(currentContest, currentProb, currentLang, forceOverride);
} catch (Throwable e) {
talkingWindow.say("Oops, something wrong! It says \"" + e.getMessage() + "\"");
talkingWindow.say("Please see the logs for details.");
Log.e("Set problem failed", e);
}
}
private void setProblem(Contest contest, Problem problem, Language language, boolean forceOverride) {
GreedConfig config = Utils.getGreedConfig();
LanguageConfig langConfig = config.getLanguage().get(Language.getName(language));
if (langConfig == null) {
talkingWindow.say("Unsupported language " + language.toString());
return;
}
// Create model map
currentTemplateModel = new HashMap<String, Object>();
currentTemplateModel.put("Contest", contest);
currentTemplateModel.put("Problem", problem);
// Bind problem template model
currentTemplateModel.put("ClassName", problem.getClassName());
currentTemplateModel.put("Method", problem.getMethod());
currentTemplateModel.put("Examples", problem.getTestcases());
currentTemplateModel.put("NumOfExamples", problem.getTestcases().length);
boolean useArray = problem.getMethod().getReturnType().isArray();
currentTemplateModel.put("ReturnsArray", useArray);
for (Param param : problem.getMethod().getParams()) useArray |= param.getType().isArray();
currentTemplateModel.put("HasArray", useArray);
boolean useString = problem.getMethod().getReturnType().isString();
currentTemplateModel.put("ReturnsString", useString);
for (Param param : problem.getMethod().getParams()) useString |= param.getType().isString();
currentTemplateModel.put("HasString", useString);
currentTemplateModel.put("CreateTime", System.currentTimeMillis() / 1000);
currentTemplateModel.put("CutBegin", langConfig.getCutBegin());
currentTemplateModel.put("CutEnd", langConfig.getCutEnd());
TemplateEngine.switchLanguage(language);
// Generate templates
for (String templateName : langConfig.getTemplates()) {
TemplateConfig template = langConfig.getTemplateDef().get(templateName);
talkingWindow.say(String.format("Generating template [" + templateName + "]"));
// Generate code from templates
String code;
try {
CodeByLine codeLines = CodeByLine.fromString(TemplateEngine.render(
FileSystem.getInputStream(template.getTemplateFile()),
currentTemplateModel
));
codeLines = new EmptyCutBlockCleaner(langConfig.getCutBegin(), langConfig.getCutEnd()).transform(codeLines);
codeLines = new ContinuousBlankLineRemover().transform(codeLines);
code = codeLines.toString();
} catch (FileNotFoundException e) {
talkingWindow.say("Template file \"" + template.getTemplateFile() + "\" not found");
continue;
}
// Output to model
if (template.getOutputKey() != null) {
currentTemplateModel.put(template.getOutputKey(), code);
}
// Output to file
if (template.getOutputFile() != null) {
String filePath = config.getCodeRoot() + "/" +
TemplateEngine.render(template.getOutputFile(), currentTemplateModel);
String fileFolder = FileSystem.getParentPath(filePath);
if (!FileSystem.exists(fileFolder)) {
talkingWindow.say("Creating folder " + fileFolder);
FileSystem.createFolder(fileFolder);
}
boolean exists = FileSystem.exists(filePath);
boolean override = forceOverride || template.isOverride();
talkingWindow.say("Writing to " + filePath);
if (exists && !override) {
talkingWindow.say("Skip due to override policy");
continue;
}
writeFileWithBackup(filePath, code, exists);
}
// TODO: After gen hook
}
talkingWindow.say("All set, good luck!");
talkingWindow.say("");
}
public String getSource() {
GreedConfig config = Utils.getGreedConfig();
LanguageConfig langConfig = config.getLanguage().get(Language.getName(currentLang));
String filePath = config.getCodeRoot() +
TemplateEngine.render(langConfig.getTemplateDef().get(langConfig.getSubmitTemplate()).getOutputFile(), currentTemplateModel);
talkingWindow.say("Submitting " + filePath);
if (!FileSystem.exists(filePath)) {
talkingWindow.say("Cannot found your source code");
return "";
}
try {
CodeByLine code = CodeByLine.fromInputStream(FileSystem.getInputStream(filePath));
if (LanguageManager.getInstance().getPostTransformer(currentLang) != null)
code = LanguageManager.getInstance().getPostTransformer(currentLang).transform(code);
code = new CutBlockRemover(langConfig.getCutBegin(), langConfig.getCutEnd()).transform(code);
code = new AppendingTransformer(getSignature()).transform(code);
return code.toString();
} catch (IOException e) {
talkingWindow.say("Err... Cannot fetch your source code. Please check the logs, and make sure your source code is present");
Log.e("Error getting the source", e);
return "";
}
}
private void writeFileWithBackup(String path, String content, boolean exists) {
if (content != null) {
if (exists) {
talkingWindow.say("Overriding \"" + path + "\", old files will be renamed");
if (FileSystem.getSize(path) == content.length()) {
talkingWindow.say("Seems the current file is the same as the code to write, skipped");
} else
FileSystem.backup(path); // Backup the old files
}
FileSystem.writeFile(path, content);
}
}
}
|
package com.fatboyindustrial.gsonjodatime;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Duration;
import org.joda.time.Interval;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.LocalTime;
import org.joda.time.Period;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/**
* Tests for {@link Converters}.
*/
public class ConvertersTest
{
/**
* Tests that the {@link Converters#registerAll} method registers the converters successfully.
*/
@Test
public void testRegisterAll()
{
final Gson gson = Converters.registerAll(new GsonBuilder()).create();
final Container original = new Container();
//noinspection deprecation
original.dm = new DateMidnight();
original.dt = new DateTime();
original.dtz = DateTimeZone.forID("UTC");
original.d = Duration.standardMinutes(30L);
original.ld = new LocalDate();
original.ldt = new LocalDateTime();
original.lt = new LocalTime();
original.i = new Interval(DateTime.now().minusDays(14), DateTime.now().plusDays(2));
original.p = Period.days(2);
final Container reconstituted = gson.fromJson(gson.toJson(original), Container.class);
assertThat(reconstituted.dm, is(original.dm));
assertThat(reconstituted.dt, is(original.dt));
assertThat(reconstituted.dtz, is(original.dtz));
assertThat(reconstituted.d, is(original.d));
assertThat(reconstituted.ld, is(original.ld));
assertThat(reconstituted.ldt, is(original.ldt));
assertThat(reconstituted.lt, is(original.lt));
assertThat(reconstituted.i, is(original.i));
assertThat(reconstituted.p, is(original.p));
}
/**
* Container for serialising many fields.
*/
private static class Container
{
@SuppressWarnings("deprecation")
private DateMidnight dm;
private DateTime dt;
private DateTimeZone dtz;
private Duration d;
private LocalDate ld;
private LocalDateTime ldt;
private LocalTime lt;
private Interval i;
private Period p;
}
}
|
package jena;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.Reader;
import com.hp.hpl.jena.n3.turtle.Turtle2NTriples;
import com.hp.hpl.jena.n3.turtle.TurtleParseException;
import com.hp.hpl.jena.n3.turtle.parser.ParseException;
import com.hp.hpl.jena.n3.turtle.parser.TokenMgrError;
import com.hp.hpl.jena.n3.turtle.parser.TurtleParser;
import com.hp.hpl.jena.shared.JenaException;
import com.hp.hpl.jena.util.FileUtils;
public class turtle
{
/** Run the Turtle parser - produce N-triples */
public static void main(String[] args)
{
if ( args.length == 0 )
{
parse("http://example/BASE", System.in) ;
return ;
}
for ( int i = 0 ; i < args.length ; i++ )
{
String fn = args[i] ;
parse("http://base/", fn) ;
}
}
public static void parse(String baseURI, String filename)
{
InputStream in = null ;
try {
in = new FileInputStream(filename) ;
} catch (FileNotFoundException ex)
{
System.err.println("File not found: "+filename) ;
return ;
}
parse(baseURI, in) ;
}
public static void parse(String baseURI, InputStream in)
{
Reader reader = FileUtils.asUTF8(in) ;
try {
TurtleParser parser = new TurtleParser(reader) ;
//parser.setEventHandler(new TurtleEventDump()) ;
parser.setEventHandler(new Turtle2NTriples(System.out)) ;
parser.setBaseURI(baseURI) ;
parser.parse() ;
}
catch (ParseException ex)
{ throw new TurtleParseException(ex.getMessage()) ; }
catch (TokenMgrError tErr)
{ throw new TurtleParseException(tErr.getMessage()) ; }
catch (TurtleParseException ex) { throw ex ; }
catch (JenaException ex) { throw new TurtleParseException(ex.getMessage(), ex) ; }
catch (Error err)
{
throw new TurtleParseException(err.getMessage() , err) ;
}
catch (Throwable th)
{
throw new TurtleParseException(th.getMessage(), th) ;
}
}
}
|
package com.hartveld.rx.tests;
import static java.util.Collections.emptyList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
public class SynchronousExecutorService implements ExecutorService {
private boolean shutdown = false;
@Override
public void shutdown() {
shutdown = true;
}
@Override
public List<Runnable> shutdownNow() {
return emptyList();
}
@Override
public boolean isShutdown() {
return shutdown;
}
@Override
public boolean isTerminated() {
return shutdown;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) {
return true;
}
@Override
public void execute(Runnable command) {
if (shutdown) {
throw new RejectedExecutionException("Synchronous executor service is already shut down.");
}
command.run();
}
@Override
public <T> Future<T> submit(Callable<T> task) {
if (shutdown) {
throw new RejectedExecutionException("Synchronous executor service is already shut down.");
}
FutureTask<T> futureTask = new FutureTask<>(task);
futureTask.run();
return futureTask;
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
if (shutdown) {
throw new RejectedExecutionException("Synchronous executor service is already shut down.");
}
FutureTask<T> futureTask = new FutureTask<>(task, result);
futureTask.run();
return futureTask;
}
@Override
public Future<?> submit(Runnable task) {
if (shutdown) {
throw new RejectedExecutionException("Synchronous executor service is already shut down.");
}
FutureTask<?> futureTask = new FutureTask<>(task, null);
task.run();
return futureTask;
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
throw new RuntimeException("Method not implemented");
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) {
throw new RuntimeException("Method not implemented");
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) {
throw new RuntimeException("Method not implemented");
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) {
throw new RuntimeException("Method not implemented");
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).toString();
}
}
|
package launch;
import java.io.File;
import org.apache.catalina.startup.Tomcat;
/**
* TODO: Document me!
*
* @author Maxim Kharchenko (kharchenko.max@gmail.com)
*/
public class Main {
public static void main(String[] args) throws Exception {
String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
// The port that we should run on can be set into an environment
// variable
// Look for that variable and default to 8080 if it isn't there.
String webPort = System.getenv("PORT");
if (webPort == null || webPort.isEmpty()) {
webPort = "8080";
}
tomcat.setPort(Integer.valueOf(webPort));
tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
System.out.println("configuring app with basedir: "
+ new File("./" + webappDirLocation).getAbsolutePath());
tomcat.start();
tomcat.getServer().await();
}
}
|
package il.ac.bgu.cs.bp.bpjs.analysis;
import il.ac.bgu.cs.bp.bpjs.analysis.bprogramio.BProgramSyncSnapshotIO;
import il.ac.bgu.cs.bp.bpjs.internal.ExecutorServiceMaker;
import il.ac.bgu.cs.bp.bpjs.model.BProgram;
import il.ac.bgu.cs.bp.bpjs.model.SingleResourceBProgram;
import il.ac.bgu.cs.bp.bpjs.model.eventselection.*;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
/**
* Basic benchmarks in Snapshot cloner
*
* @author acepace
*/
public class SnapshotBenchmarks {
private static int ITERATIONS = 10;
public static void main(String[] args) throws Exception {
VariableSizedArraysBenchmark.benchmarkVariableSizedArrays();
EventSelectionBenchmark.benchmarkEventSelection();
}
static abstract class Benchmark {
static String IMPLEMENTATION = "TESTFILE.js";
static String TEST_NAME = "TESTNAME";
static int INITIAL_ARRAY_SIZE = 1;
static int ARRAY_STEP = 5; //Size of each step, how many objects are we adding
static int NUM_STEPS = 10; // How many steps to take
static void outputBenchResults(BenchmarkResult result) throws IOException {
result.outputMemoryStats();
result.outputTimes();
result.outputToCsv(Paths.get("."));
}
static BProgram makeBProgram(String baseFile, Map<String, Object> init_values) {
final BProgram bprog = new SingleResourceBProgram(baseFile);
init_values.forEach(bprog::putInGlobalScope);
StringBuilder name = new StringBuilder(bprog.getName());
init_values.forEach((k, v) -> name.append(String.format("_%s_%s", k, v)));
bprog.setName(name.toString());
return bprog;
}
static int[] getStateSizes(BProgram program) throws Exception {
System.out.println("Measuring state size");
ExecutorService execSvc = ExecutorServiceMaker.makeWithName("SnapshotStore");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
List<Node> snapshots = new ArrayList<>();
BProgramSyncSnapshotIO io = new BProgramSyncSnapshotIO(program);
ArrayList<Integer> snapshotSizes = new ArrayList<>();
Node initial = Node.getInitialNode(program, execSvc);
snapshots.add(initial);
Node next = initial;
//Iteration 1,starts already at request state A
for (int i = 0; i < NUM_STEPS; i++) {
snapshotSizes.add(io.serialize(next.getSystemState()).length);
next = sut.getUnvisitedNextNode(next, execSvc);
snapshots.add(next);
}
execSvc.shutdown();
return snapshotSizes.stream().mapToInt(i -> i).toArray();
}
static long getVerificationTime(DfsBProgramVerifier vfr, BProgram prog) {
try {
VerificationResult res = vfr.verify(prog);
return res.getTimeMillies();
} catch (Exception e) {
return 0;
}
}
static long[] getVerificationTime(DfsBProgramVerifier vfr, String programPath, Map<String, Object> valueMap, int iteration_count) {
return LongStream.range(0, iteration_count).map(i -> {
BProgram prog = makeBProgram(programPath, valueMap);
return getVerificationTime(vfr, prog);
}).toArray();
}
}
/*
This benchmarks a program of variableSizedArrays
For verification time benchmarks, each test is run ITERATIONS times, with a larger array step every time.
These should be pretty much identical
For snapshot size benchmarks, each test is run once, and we measure the snapshot size for each step.
Snapshot size should grow linearly.
*/
static class VariableSizedArraysBenchmark extends Benchmark {
static String IMPLEMENTATION = "benchmarks/variableSizedArrays.js";
static String TEST_NAME = "variableSizedArrays";
static int INITIAL_ARRAY_SIZE = 1;
static int ARRAY_STEP = 5; //Size of each step, how many objects are we adding
static int NUM_STEPS = 10; // How many steps to take
static void benchmarkVariableSizedArrays() throws Exception {
BenchmarkResult integerResults = measureIntegerSizes();
BenchmarkResult objectResults = measureObjectSize();
outputBenchResults(integerResults);
outputBenchResults(objectResults);
}
private static BenchmarkResult measureIntegerSizes() throws Exception {
System.out.println("Measuring effect of integer size");
return measureProgram(0);
}
private static BenchmarkResult measureObjectSize() throws Exception {
System.out.println("Measuring effect of object size");
return measureProgram(1);
}
private static BenchmarkResult measureProgram(int objectType) throws Exception {
VisitedStateStore store = new BThreadSnapshotVisitedStateStore();
VisitedStateStore storeHash = new HashVisitedStateStore();
DfsBProgramVerifier verifier = new DfsBProgramVerifier();
String testName = TEST_NAME + ((objectType == 1) ? "object" : "integer");
/*
Test for variable num_steps
we want to see if there's a non linear increase in snapshot size
*/
int[][] snapshotSet = new int[ITERATIONS][];
long[][] verificationTimes = new long[ITERATIONS][];
long[][] verificationTimesHash = new long[ITERATIONS][];
BProgram[] programs = new BProgram[ITERATIONS];
for (int i = 0; i < ITERATIONS; i++) {
System.out.printf("Measuring for array step of %d size\n", ARRAY_STEP + i);
Map<String, Object> valueMap = new HashMap<>();
valueMap.put("INITIAL_ARRAY_SIZE", INITIAL_ARRAY_SIZE);
valueMap.put("ARRAY_STEP", ARRAY_STEP + i);
valueMap.put("NUM_STEPS", NUM_STEPS);
valueMap.put("OBJECT_TYPE", objectType);
BProgram programToTest = makeBProgram(IMPLEMENTATION, valueMap);
programs[i] = programToTest;
//have to clone the object because BPrograms are not reusable
System.gc();
snapshotSet[i] = getStateSizes(makeBProgram(IMPLEMENTATION, valueMap));
System.gc();
verifier.setVisitedNodeStore(store);
verificationTimes[i] = getVerificationTime(verifier, IMPLEMENTATION, valueMap, ITERATIONS);
verifier.setVisitedNodeStore(storeHash);
verificationTimesHash[i] = getVerificationTime(verifier, IMPLEMENTATION, valueMap, ITERATIONS);
System.gc();
}
return new BenchmarkResult(testName, programs, snapshotSet, verificationTimes, verificationTimesHash);
}
}
static class EventSelectionBenchmark extends Benchmark {
static String IMPLEMENTATION = "benchmarks/eventSelection.js";
static String TEST_NAME = "eventSelection";
static int INITIAL_ARRAY_SIZE = 1;
static int ARRAY_STEP = 5; //Size of each step, how many objects are we adding
static int NUM_STEPS = 10; // How many steps to take
static void benchmarkEventSelection() throws Exception {
BenchmarkResult simpleEventSelectionResults = measureProgram(new SimpleEventSelectionStrategy());
BenchmarkResult orderedEventSelectionResults = measureProgram(new OrderedEventSelectionStrategy());
//BenchmarkResult PrioritizedBSyncEventSelectionResults = measureProgram(new PrioritizedBSyncEventSelectionStrategy());
//BenchmarkResult PrioritizedBThreadsEventSelectionResults = measureProgram(new PrioritizedBThreadsEventSelectionStrategy());
outputBenchResults(simpleEventSelectionResults);
outputBenchResults(orderedEventSelectionResults);
}
private static BenchmarkResult measureProgram(EventSelectionStrategy strategy) throws Exception {
VisitedStateStore store = new BThreadSnapshotVisitedStateStore();
VisitedStateStore storeHash = new HashVisitedStateStore();
DfsBProgramVerifier verifier = new DfsBProgramVerifier();
/*
Test for variable num_steps
we want to see if there's a non linear increase in snapshot size
*/
int[][] snapshotSet = new int[ITERATIONS][];
long[][] verificationTimes = new long[ITERATIONS][];
long[][] verificationTimesHash = new long[ITERATIONS][];
BProgram[] programs = new BProgram[ITERATIONS];
for (int i = 0; i < ITERATIONS; i++) {
System.out.printf("Measuring for array step of %d size\n", ARRAY_STEP + i);
Map<String, Object> valueMap = new HashMap<>();
valueMap.put("INITIAL_ARRAY_SIZE", INITIAL_ARRAY_SIZE);
valueMap.put("ARRAY_STEP", ARRAY_STEP + i);
valueMap.put("NUM_STEPS", NUM_STEPS);
//Initial copy
BProgram programToTest = makeBProgram(IMPLEMENTATION, valueMap, strategy);
programs[i] = programToTest;
//Cleanup GC before and after, opportunistic
//have to clone the program because BPrograms are not reusable
System.gc();
snapshotSet[i] = getStateSizes(makeBProgram(IMPLEMENTATION, valueMap, strategy));
System.gc();
verifier.setVisitedNodeStore(store);
verificationTimes[i] = getVerificationTime(verifier, IMPLEMENTATION, valueMap, ITERATIONS, strategy);
verifier.setVisitedNodeStore(storeHash);
verificationTimesHash[i] = getVerificationTime(verifier, IMPLEMENTATION, valueMap, ITERATIONS, strategy);
System.gc();
}
return new BenchmarkResult(TEST_NAME + strategy.getClass().getName(), programs, snapshotSet, verificationTimes, verificationTimesHash);
}
private static BProgram makeBProgram(String programPath, Map<String, Object> value_map, EventSelectionStrategy strategy) {
// prepare b-program
BProgram bprog = makeBProgram(programPath, value_map);
bprog.setEventSelectionStrategy(strategy);
return bprog;
}
static long[] getVerificationTime(DfsBProgramVerifier vfr, String programPath, Map<String, Object> valueMap, int iteration_count, EventSelectionStrategy strategy) {
return LongStream.range(0, iteration_count).map(i -> {
BProgram prog = makeBProgram(programPath, valueMap, strategy);
return getVerificationTime(vfr, prog);
}).toArray();
}
}
/**
* This consolidates benchmark results, not generic enough yet
*/
static class BenchmarkResult {
final String benchName;
final BProgram[] programs;
final int[][] snapshotSizes;
final long[][] verificationTimesNoHash;
final long[][] verificationTimesHash;
final ArrayList<String> verificationHeaders = new ArrayList<>(Collections.singletonList("Iteration count"));
final ArrayList<String> snapshot_headers = new ArrayList<>(Collections.singletonList("Run instance"));
BenchmarkResult(String name, BProgram[] programs, int[][] snapshotSizes, long[][] verificationTimesNoHash, long[][] verificationTimesHash) {
this.benchName = name;
this.programs = programs;
this.snapshotSizes = snapshotSizes;
this.verificationTimesNoHash = verificationTimesNoHash;
this.verificationTimesHash = verificationTimesHash;
//assume they're all identical, they better be
IntStream.range(0, this.snapshotSizes[0].length).forEach(i -> snapshot_headers.add("raw " + i));
IntStream.range(0, this.verificationTimesNoHash[0].length).forEach(i -> verificationHeaders.add("raw " + i));
}
/**
* Outputs memory statistics only for the last 5 steps.
*/
void outputMemoryStats() {
outputMemoryStats(5);
}
void outputMemoryStats(int num_final_steps) {
for (int i = snapshotSizes[0].length - num_final_steps; i < snapshotSizes[0].length; i++) {
final int currentStep = i;
IntSummaryStatistics stats = Arrays.stream(snapshotSizes).mapToInt(x -> x[currentStep]).summaryStatistics();
int min = stats.getMin();
int max = stats.getMax();
double avg = stats.getAverage();
long distinct = Arrays.stream(snapshotSizes).mapToInt(x -> x[currentStep]).distinct().count();
System.out.printf("At step %d the memory values for the snapshots " +
"\n\tmin %d\n\tmax %d\n\tavg %f\n", i, min, max, avg);
if (distinct != ITERATIONS) {
System.out.print("WARNING: Identical results despite different settings!\n");
}
System.out.println();
}
}
void outputTimes() {
for (int i = 0; i < verificationTimesNoHash.length; i++) {
LongSummaryStatistics stats = Arrays.stream(verificationTimesNoHash[i]).summaryStatistics();
long min = stats.getMin();
long max = stats.getMax();
double avg = stats.getAverage();
System.out.printf("The verification stats for the program at test iteration %d are " + "\n\tmin %d\n\tmax %d\n\tavg %f\n", i, min, max, avg);
System.out.println();
}
}
void outputToCsv(Path basePath) throws IOException {
outputTimesToCsv(basePath.resolve(benchName + "_times.csv"), verificationTimesNoHash);
outputTimesToCsv(basePath.resolve(benchName + "_timesHash.csv"), verificationTimesHash);
outputSnapToCsv(basePath.resolve(benchName + "_memory.csv"));
}
void outputTimesToCsv(Path filePath, long[][] verificationTimes) throws IOException {
BufferedWriter out = Files.newBufferedWriter(filePath);
try (CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT
.withHeader(verificationHeaders.toArray(new String[0])))) {
for (int i = 0; i < verificationTimes.length; i++) {
Object[] toPrint = new Object[verificationTimes[i].length + 1];
toPrint[0] = i;
for (int j = 0; j < verificationTimes[i].length; j++) {
toPrint[j + 1] = verificationTimes[i][j];
}
printer.printRecord(toPrint);
}
}
}
void outputSnapToCsv(Path filePath) throws IOException {
BufferedWriter out = Files.newBufferedWriter(filePath);
try (CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT
.withHeader(snapshot_headers.toArray(new String[0])))) {
for (int i = 0; i < this.snapshotSizes.length; i++) {
Object[] toPrint = new Object[snapshotSizes[i].length + 1];
toPrint[0] = i;
for (int j = 0; j < snapshotSizes[i].length; j++) {
toPrint[j + 1] = snapshotSizes[i][j];
}
printer.printRecord(toPrint);
}
}
}
}
}
|
package mci;
import kr.ac.kaist.se.simulator.BaseAction;
import kr.ac.kaist.se.simulator.BaseConstituent;
import kr.ac.kaist.se.simulator.ConstituentInterface;
import java.util.ArrayList;
public abstract class BasePTS extends BaseConstituent implements ConstituentInterface{
private int curPos;
private int PTS_STATUS; // 0: IDLE, 1: Go to Patient, 2: Return to Hospital
public BasePTS(){
this.curPos = 50;
this.PTS_STATUS = 0;
}
/**
* normal Action method
* Rescue the patient
* The elapsedTime will never exceed the maximum distance of this PTS.
* @param elapsedTime
*/
@Override
public void normalAction(int elapsedTime) {
RescueAction currentAction = (RescueAction) this.getCurrentAction();
if(this.PTS_STATUS == 1){ // Go to Patient
if(currentAction.getRaisedLoc() < 50){
int distance = this.curPos - currentAction.getRaisedLoc();
if(elapsedTime > distance){
movePTS( (-1) * distance );
int remainTime = elapsedTime - distance;
this.PTS_STATUS = 2;
movePTS(remainTime);
}else{
movePTS((-1) * elapsedTime);
}
}else{
int distance = currentAction.getRaisedLoc() - this.curPos;
if(elapsedTime > distance){
movePTS(distance);
int remainTime = elapsedTime - distance;
this.PTS_STATUS = 2;
movePTS((-1) * remainTime);
}else
movePTS(elapsedTime);
}
}else if(this.PTS_STATUS == 2){
if(this.curPos < 50){
int distance = 50 - this.curPos;
if(elapsedTime > distance){
movePTS(distance);
}else{
movePTS(elapsedTime);
}
}else if(this.curPos > 50){
int distance = this.curPos - 50;
if(elapsedTime > distance){
movePTS((-1) * distance);
}else{
movePTS((-1) * elapsedTime);
}
}
if(this.curPos == 50){
RescueAction.PatientStatus pStat = currentAction.getPatientStatus();
if(pStat != RescueAction.PatientStatus.Dead){
System.out.println(this.hashCode() + " PTS saved a patient!");
this.updateCostBenefit(0, 1, 1);
readyForPatient();
}
this.PTS_STATUS = 0;
}
}
}
/**
* Move the PTS moveVal value in GeoMap
* @param moveVal
*/
private void movePTS(int moveVal){
RescueAction currentAction = (RescueAction) this.getCurrentAction();
this.curPos += moveVal;
if(this.PTS_STATUS == 2)
currentAction.setCurPos(curPos);
currentAction.treatAction(moveVal);
}
/**
* immediate Action method
* choose the patient to save
* this method will get best patient to save using choosePatient method.
* @return the Base Action that which patient will be rescued by this TS.
*/
@Override
public BaseAction immediateAction() {
if(this.getStatus() != Status.IDLE && this.getStatus() != Status.SELECTION)
return null;
if(this.getStatus() == Status.SELECTION) {
RescueAction action = choosePatient();
if (action != null && action.getStatus() == BaseAction.Status.RAISED) {
this.setCurrentAction(action);
action.addPerformer(this);
this.gotoPatient();
}else{
action = null;
}
if(action == null) // action IDLE
this.setStatus(Status.IDLE);
return action;
}
this.setStatus(Status.IDLE);
return null;
}
@Override
public BaseConstituent clone() {
return null;
}
private void gotoPatient(){
this.PTS_STATUS = 1;
this.setStatus(Status.OPERATING);
RescueAction currentAction = (RescueAction) this.getCurrentAction();
currentAction.startHandle();
}
public RescueAction choosePatient() {
RescueAction bestAction = null;
for(MapPoint map : Hospital.GeoMap){
int candidateSize = map.getCurActions().size();
if(candidateSize == 0)
continue;
bestAction = pickBest(map.getCurActions());
}
return bestAction;
}
private RescueAction pickBest(ArrayList<RescueAction> aList){
if(aList.size() == 1 && aList.get(0).getStatus() == BaseAction.Status.RAISED)
return aList.get(0);
else if(aList.size() > 1){
RescueAction candidate = aList.get(0);
for(RescueAction a : aList){
if(a.getStatus() != BaseAction.Status.RAISED)
continue;
if(getUtility(candidate) < getUtility(a))
candidate = a;
}
return candidate;
}else{
return null;
}
}
public int getPTS_STATUS(){
return this.PTS_STATUS;
}
public int getCurPos(){
return this.curPos;
}
private void readyForPatient(){
this.setStatus(Status.IDLE);
this.PTS_STATUS = 0;
this.setCurrentAction(null);
}
}
|
package im.nll.data.extractor.impl;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
/**
* @author <a href="mailto:fivesmallq@gmail.com">fivesmallq</a>
* @version Revision: 1.0
* @date 15/12/29 10:33
*/
public class JSONPathExtractorTest {
private String json;
private JSONPathExtractor jsonPathExtractor;
@Before
public void before() {
try {
json = Resources.toString(Resources.getResource("example.json"), Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testExtract() throws Exception {
String author0 = new JSONPathExtractor("$.store.book[0].author").extract(json);
String author1 = new JSONPathExtractor("$.store.book[1].author").extract(json);
Assert.assertEquals(author0, "Nigel Rees");
Assert.assertEquals(author1, "Evelyn Waugh");
}
@Test
public void testExtractList() throws Exception {
List<String> authors = new JSONPathExtractor("$.store.book[*].author").extractList(json);
Assert.assertNotNull(authors);
Assert.assertEquals(authors.size(), 4);
Assert.assertEquals(authors.get(0), "Nigel Rees");
List<String> listBeanString = new JSONPathExtractor("$..book[0,1]").extractList(json);
Assert.assertNotNull(listBeanString);
Assert.assertEquals(listBeanString.size(), 2);
Assert.assertEquals("{category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}", listBeanString.get(0));
}
}
|
package pjson;
import java.nio.charset.Charset;
/**
* Fast simple json parser.<br/>
* The code is ugly but the aim is performance.
*
* @TODO Test parse messages with escape characters
* @TODO test assoc then asString on maps and vectors
* @TODO test LazyMap and LazyVector
* @TODO Test JSONAssociative structures
*/
public final class PJSON {
private static final char OBJECT_START = '{';
private static final char OBJECT_END = '}';
private static final char ARR_START = '[';
private static final char ARR_END = ']';
private static final int STR_MARK = '\"';
private static final char STR_COMMA = ',';
private static final char STR_ESCAPE = '\\';
private static final char STR_SPACE = ' ';
private static final char STR_DOT = '.';
private static final char STR_T = 'T';
private static final char STR_F = 'F';
private static final char STR_t = 't';
private static final char STR_f = 'f';
private static final char STR_COL = ':';
public static final void lazyParse(final Charset charset, final byte[] bts, final int start, final int len, final JSONListener events){
//final char chars[] = StringUtil.decode(bts, start, len);
final char[] chars = StringUtil.toCharArrayFromBytes(bts, charset, start, len);
lazyParse(chars, 0, chars.length, events);
}
/**
* Parses the byte array for json data and create lazy objects
* @param bts byte array
* @param start start offset
* @param end the end index
* @param events JSONListener, all events will be sent to this instance.
*/
public static final int lazyParse(final char[] bts, final int start, final int end, final JSONListener events){
final int btsLen = end;
char bt;
int i;
for(i = start; i < btsLen; i++){
bt = CharArrayTool.getChar(bts, i);
switch(bt){
case '{':
events.objectStart();
int strStart = CharArrayTool.indexOf(bts, i+1, end, '"') + 1;
int idx = CharArrayTool.endOfString(bts, strStart, end);
//create string here
if(idx >= btsLen){
events.objectEnd();
return btsLen;
}
events.string(StringUtil.fastToString(bts, strStart, idx - strStart));
idx = CharArrayTool.indexOf(bts, idx+1, end, ':');
idx++;
for(; idx < btsLen; idx++){
idx = CharArrayTool.skipWhiteSpace(bts, idx, btsLen);
bt = CharArrayTool.getChar(bts, idx);
switch (bt){
case '}':
events.objectEnd();
break;
case '"':
final int strStart2 = idx + 1;
idx = CharArrayTool.endOfString(bts, strStart2, end);
events.string(StringUtil.fastToString(bts, strStart2, idx - strStart2));
break;
case 'n':
events.string(null);
idx += 3; //add 3 we are already at n
break;
case 't':
events.number(Boolean.TRUE);
idx += 3; //add 3 we are already at T
break;
case 'T':
events.number(Boolean.TRUE);
idx += 3; //add 3 we are already at T
break;
case 'f':
events.number(Boolean.FALSE);
idx += 4; ////add 4 we are already at F
break;
case 'F':
events.number(Boolean.FALSE);
idx += 4; ////add 4 we are already at F
break;
case '{':
int endIndex = CharArrayTool.indexOfEndOfObject(bts, idx+1, btsLen, '{', '}');
events.lazyObject(bts, idx, endIndex);
idx = endIndex;
break;
case '[':
endIndex = CharArrayTool.indexOfEndOfObject(bts, idx+1, btsLen, '[', ']');
events.lazyArr(bts, idx, endIndex);
idx = endIndex;
break;
case '-':
idx++;
bt = CharArrayTool.getChar(bts, idx);
if(Character.isDigit(bt)) {
endIndex = CharArrayTool.indexFirstNonNumeric(bts, idx, end);
if (bts[endIndex] == '.') {
idx
int idx2 = CharArrayTool.indexFirstNonNumeric(bts, endIndex + 1, end);
parseDouble(bts, idx, idx2, events);
idx = idx2 - 1;
} else {
parseInt(bts, idx, endIndex, events, true);
idx = endIndex - 1;
}
}
break;
default:
if(Character.isDigit(bt)) {
endIndex = CharArrayTool.indexFirstNonNumeric(bts, idx, end);
if (bts[endIndex] == '.') {
int idx2 = CharArrayTool.indexFirstNonNumeric(bts, endIndex + 1, end);
parseDouble(bts, idx, idx2, events);
idx = idx2-1;
}else {
parseInt(bts, idx, endIndex, events, false);
idx = endIndex-1;
}
}
}
}
return idx;
case '[':
events.arrStart();
idx = CharArrayTool.skipWhiteSpace(bts, i+1, btsLen);
for(; idx < btsLen; idx++){
idx = CharArrayTool.skipWhiteSpace(bts, idx, btsLen);
bt = CharArrayTool.getChar(bts, idx);
switch (bt){
case ']':
events.arrEnd();
break;
case '"':
final int strStart2 = idx + 1;
idx = CharArrayTool.endOfString(bts, strStart2, end);
events.string(StringUtil.fastToString(bts, strStart2, idx - strStart2));
break;
case 'n':
events.string(null);
idx += 3; //add 3 we are already at n
break;
case 't':
events.number(Boolean.TRUE);
idx += 3; //add 3 we are already at T
break;
case 'T':
events.number(Boolean.TRUE);
idx += 3; //add 3 we are already at T
break;
case 'f':
events.number(Boolean.FALSE);
idx += 4; //add 4 we are already at F
break;
case 'F':
events.number(Boolean.FALSE);
idx += 4; //add 4 we are already at F
break;
case '{':
int endIndex = CharArrayTool.indexOfEndOfObject(bts, idx+1, btsLen, '{', '}');
events.lazyObject(bts, idx, endIndex);
idx = endIndex;
break;
case '[':
endIndex = CharArrayTool.indexOfEndOfObject(bts, idx+1, btsLen, '[', ']');
events.lazyArr(bts, idx, endIndex);
idx = endIndex;
break;
case '-':
idx++;
bt = CharArrayTool.getChar(bts, idx);
if(Character.isDigit(bt)) {
endIndex = CharArrayTool.indexFirstNonNumeric(bts, idx, end);
if (bts[endIndex] == '.') {
idx
int idx2 = CharArrayTool.indexFirstNonNumeric(bts, endIndex + 1, end);
parseDouble(bts, idx, idx2, events);
idx = idx2 - 1;
} else {
parseInt(bts, idx, endIndex, events, true);
idx = endIndex - 1;
}
}
break;
default:
if(Character.isDigit(bt)) {
endIndex = CharArrayTool.indexFirstNonNumeric(bts, idx, end);
if (bts[endIndex] == '.') {
int idx2 = CharArrayTool.indexFirstNonNumeric(bts, endIndex + 1, end);
parseDouble(bts, idx, idx2, events);
idx = idx2 - 1;
} else {
parseInt(bts, idx, endIndex, events, false);
idx = endIndex - 1;
}
}
}
}
return idx;
default:
break;
}
}
return i;
}
private static final void parseInt(char[] bts, int offset, int end, JSONListener events, boolean isNeg){
int len = end-offset;
long l;
switch(len){
case 1:
l = NumberUtil.parse_1(bts, offset); break;
case 2:
l = NumberUtil.parse_2(bts, offset); break;
case 3:
l = NumberUtil.parse_3(bts, offset); break;
case 4:
l = NumberUtil.parse_4(bts, offset); break;
case 5:
l = NumberUtil.parse_5(bts, offset); break;
case 6:
l = NumberUtil.parse_6(bts, offset); break;
case 7:
l = NumberUtil.parse_7(bts, offset); break;
case 8:
l = NumberUtil.parse_8(bts, offset); break;
case 9:
l = NumberUtil.parse_9(bts, offset); break;
case 10:
l = NumberUtil.parse_10(bts, offset); break;
case 11:
l = NumberUtil.parse_11(bts, offset); break;
case 12:
l = NumberUtil.parse_12(bts, offset); break;
case 13:
l = NumberUtil.parse_13(bts, offset); break;
case 14:
l = NumberUtil.parse_14(bts, offset); break;
case 15:
l = NumberUtil.parse_15(bts, offset); break;
case 16:
l = NumberUtil.parse_16(bts, offset); break;
case 17:
l = NumberUtil.parse_17(bts, offset); break;
case 18:
l = NumberUtil.parse_18(bts, offset); break;
case 19:
l = NumberUtil.parse_19(bts, offset); break;
default:
throw new NumberFormatException("Number out of range " + StringUtil.fastToString(bts, offset, end-offset));
}
events.number(new Long(isNeg ? l * -1 : l));
}
private static final void parseDouble(char[] bts, int offset, int end, JSONListener events){
final String str = StringUtil.fastToString(bts, offset, end-offset);
events.number(Double.valueOf(str));
}
/**
* Parse the bts byte array from offset start and to < len.
* @param bts
* @param start
* @param len
* @return Object Map or Collection
*/
public static final Object defaultLazyParse(final Charset charset, final byte[] bts, final int start, final int len){
final DefaultListener list = new DefaultListener();
//lazyParse(final char[] bts, final int start, final int end, final JSONListener events
lazyParse(charset, bts, start, len, list);
return list.getValue();
}
public static final Object defaultLazyParse(final Charset charset, final char[] bts, final int start, final int len){
final DefaultListener list = new DefaultListener();
//lazyParse(final char[] bts, final int start, final int end, final JSONListener events
lazyParse(bts, 0, bts.length, list);
return list.getValue();
}
/**
* Parse the whole byte array bts.
* @param bts
* @return Object Map or Collection.
*/
public static final Object defaultLazyParse(final Charset charset, final char[] bts){
return defaultLazyParse(charset, bts, 0, bts.length);
}
/**
* Parse the whole byte array bts.
* @param bts
* @return Object Map or Collection.
*/
public static final Object defaultLazyParse(final Charset charset, final byte[] bts){
return defaultLazyParse(charset, bts, 0, bts.length);
}
}
|
package org.jboss.test.virtual.support;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.jboss.virtual.VFS;
import org.jboss.virtual.VirtualFile;
import org.jboss.virtual.VirtualFileFilter;
/**
* ClassPathIterator logic used by UCL package mapping
*
* @author Scott.Stark@jboss.org
* @version $Revision:$
*/
public class ClassPathIterator
{
ZipInputStream zis;
FileIterator fileIter;
File file;
VirtualFileIterator vfIter;
VirtualFile vf;
int rootLength;
public ClassPathIterator(URL url) throws IOException
{
String protocol = url != null ? url.getProtocol() : null;
if( protocol == null )
{
}
else if( protocol.equals("file") )
{
File tmp = new File(url.getFile());
if( tmp.isDirectory() )
{
rootLength = tmp.getPath().length() + 1;
fileIter = new FileIterator(tmp);
}
else
{
// Assume this is a jar archive
InputStream is = new FileInputStream(tmp);
zis = new ZipInputStream(is);
}
}
else if( protocol.startsWith("vfs") )
{
VFS vfs = VFS.getVFS(url);
vf = vfs.getRoot();
rootLength = vf.getPathName().length() + 1;
vfIter = new VirtualFileIterator(vf);
}
else
{
// Assume this points to a jar
InputStream is = url.openStream();
zis = new ZipInputStream(is);
}
}
public ClassPathEntry getNextEntry() throws IOException
{
ClassPathEntry entry = null;
if( zis != null )
{
ZipEntry zentry = zis.getNextEntry();
if( zentry != null )
entry = new ClassPathEntry(zentry);
}
else if( fileIter != null )
{
File fentry = fileIter.getNextEntry();
if( fentry != null )
entry = new ClassPathEntry(fentry, rootLength);
file = fentry;
}
else if( vfIter != null )
{
VirtualFile fentry = vfIter.getNextEntry();
if( fentry != null )
entry = new ClassPathEntry(fentry, rootLength);
vf = fentry;
}
return entry;
}
InputStream getInputStream() throws IOException
{
InputStream is = zis;
if( zis == null )
{
is = new FileInputStream(file);
}
return is;
}
public void close() throws IOException
{
if( zis != null )
zis.close();
}
static class FileIterator
{
LinkedList subDirectories = new LinkedList();
FileFilter filter;
File[] currentListing;
int index = 0;
FileIterator(File start)
{
String name = start.getName();
// Don't recurse into wars
boolean isWar = name.endsWith(".war");
if( isWar )
currentListing = new File[0];
else
currentListing = start.listFiles();
}
FileIterator(File start, FileFilter filter)
{
String name = start.getName();
// Don't recurse into wars
boolean isWar = name.endsWith(".war");
if( isWar )
currentListing = new File[0];
else
currentListing = start.listFiles(filter);
this.filter = filter;
}
File getNextEntry()
{
File next = null;
if( index >= currentListing.length && subDirectories.size() > 0 )
{
do
{
File nextDir = (File) subDirectories.removeFirst();
currentListing = nextDir.listFiles(filter);
} while( currentListing.length == 0 && subDirectories.size() > 0 );
index = 0;
}
if( index < currentListing.length )
{
next = currentListing[index ++];
if( next.isDirectory() )
subDirectories.addLast(next);
}
return next;
}
}
static class VirtualFileIterator
{
LinkedList<VirtualFile> subDirectories = new LinkedList<VirtualFile>();
VirtualFileFilter filter;
List<VirtualFile> currentListing;
int index = 0;
VirtualFileIterator(VirtualFile start) throws IOException
{
this(start, null);
}
VirtualFileIterator(VirtualFile start, VirtualFileFilter filter) throws IOException
{
String name = start.getName();
// Don't recurse into wars
boolean isWar = name.endsWith(".war");
if( isWar )
currentListing = new ArrayList<VirtualFile>();
else
currentListing = start.getChildren();
this.filter = filter;
}
VirtualFile getNextEntry()
throws IOException
{
VirtualFile next = null;
if( index >= currentListing.size() && subDirectories.size() > 0 )
{
do
{
VirtualFile nextDir = subDirectories.removeFirst();
currentListing = nextDir.getChildren(filter);
} while( currentListing.size() == 0 && subDirectories.size() > 0 );
index = 0;
}
if( index < currentListing.size() )
{
next = currentListing.get(index);
if( next.isLeaf() == false )
subDirectories.addLast(next);
}
return next;
}
}
public static class ClassPathEntry
{
public String name;
public ZipEntry zipEntry;
public File fileEntry;
public VirtualFile vfEntry;
ClassPathEntry(ZipEntry zipEntry)
{
this.zipEntry = zipEntry;
this.name = zipEntry.getName();
}
ClassPathEntry(File fileEntry, int rootLength)
{
this.fileEntry = fileEntry;
this.name = fileEntry.getPath().substring(rootLength);
}
ClassPathEntry(VirtualFile vfEntry, int rootLength)
{
this.vfEntry = vfEntry;
this.name = vfEntry.getPathName().substring(rootLength);
}
String getName()
{
return name;
}
/** Convert the entry path to a package name
*/
String toPackageName()
{
String pkgName = name;
char separatorChar = zipEntry != null ? '/' : File.separatorChar;
int index = name.lastIndexOf(separatorChar);
if( index > 0 )
{
pkgName = name.substring(0, index);
pkgName = pkgName.replace(separatorChar, '.');
}
else
{
// This must be an entry in the default package (e.g., X.class)
pkgName = "";
}
return pkgName;
}
boolean isDirectory()
{
boolean isDirectory = false;
if( zipEntry != null )
isDirectory = zipEntry.isDirectory();
else
isDirectory = fileEntry.isDirectory();
return isDirectory;
}
}
}
|
package rmblworx.tools.timey.gui;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.loadui.testfx.utils.FXTestUtils;
import rmblworx.tools.timey.vo.TimeDescriptor;
@Category(TimeyGuiTest.class)
public class StopwatchControllerTest extends FxmlGuiControllerTest {
private Scene scene;
/**
* {@inheritDoc}
*/
protected final String getFxmlFilename() {
return "Stopwatch.fxml";
}
@Before
public final void setUp() {
scene = stage.getScene();
}
@Test
public final void testStopwatchStartStopResetButtonStates() {
final Button stopwatchStartButton = (Button) scene.lookup("#stopwatchStartButton");
final Button stopwatchStopButton = (Button) scene.lookup("#stopwatchStopButton");
final Button stopwatchResetButton = (Button) scene.lookup("#stopwatchResetButton");
assertTrue(stopwatchStartButton.isVisible());
assertFalse(stopwatchStartButton.isDisabled());
// assertTrue(stopwatchStartButton.isFocused()); // muss nicht unbedingt der Fall sein
assertFalse(stopwatchStopButton.isVisible());
assertFalse(stopwatchStopButton.isDisabled());
assertTrue(stopwatchResetButton.isVisible());
assertFalse(stopwatchResetButton.isDisabled());
// Stoppuhr starten
stopwatchStartButton.fire();
FXTestUtils.awaitEvents();
verify(getController().getGuiHelper().getFacade()).startStopwatch();
assertFalse(stopwatchStartButton.isVisible());
assertFalse(stopwatchStartButton.isDisabled());
assertTrue(stopwatchStopButton.isVisible());
assertFalse(stopwatchStopButton.isDisabled());
assertTrue(stopwatchStopButton.isFocused());
assertTrue(stopwatchResetButton.isVisible());
assertFalse(stopwatchResetButton.isDisabled());
// Stoppuhr stoppen
stopwatchStopButton.fire();
FXTestUtils.awaitEvents();
verify(getController().getGuiHelper().getFacade()).stopStopwatch();
assertTrue(stopwatchStartButton.isVisible());
assertFalse(stopwatchStartButton.isDisabled());
assertTrue(stopwatchStartButton.isFocused());
assertFalse(stopwatchStopButton.isVisible());
assertFalse(stopwatchStopButton.isDisabled());
assertTrue(stopwatchResetButton.isVisible());
assertFalse(stopwatchResetButton.isDisabled());
stopwatchResetButton.fire();
FXTestUtils.awaitEvents();
verify(getController().getGuiHelper().getFacade()).resetStopwatch();
assertTrue(stopwatchStartButton.isVisible());
assertFalse(stopwatchStartButton.isDisabled());
assertTrue(stopwatchStartButton.isFocused());
assertFalse(stopwatchStopButton.isVisible());
assertFalse(stopwatchStopButton.isDisabled());
assertTrue(stopwatchResetButton.isVisible());
assertFalse(stopwatchResetButton.isDisabled());
}
/**
* Testet die Darstellung der Zeit mit und ohne Millisekunden-Anteil.
*/
@Test
public final void testStopwatchTimeLabelMilliseconds() {
final CheckBox stopwatchShowMillisecondsCheckbox = (CheckBox) scene.lookup("#stopwatchShowMillisecondsCheckbox");
final Label stopwatchTimeLabel = (Label) scene.lookup("#stopwatchTimeLabel");
// Ausgangszustand
assertTrue(stopwatchShowMillisecondsCheckbox.isSelected());
assertEquals("00:00:00.000", stopwatchTimeLabel.getText());
// Millisekunden-Anteil ausblenden
stopwatchShowMillisecondsCheckbox.fire();
FXTestUtils.awaitEvents();
assertEquals("00:00:00", stopwatchTimeLabel.getText());
// Millisekunden-Anteil wieder ausblenden
stopwatchShowMillisecondsCheckbox.fire();
FXTestUtils.awaitEvents();
assertEquals("00:00:00.000", stopwatchTimeLabel.getText());
}
/**
* Testet die Anzeige der gemessenen Zeit.
*/
@Test
public final void testStopwatchStartStopTimeMeasured() {
final Button stopwatchStartButton = (Button) scene.lookup("#stopwatchStartButton");
final Button stopwatchStopButton = (Button) scene.lookup("#stopwatchStopButton");
final Label stopwatchTimeLabel = (Label) scene.lookup("#stopwatchTimeLabel");
// Stoppuhr starten
when(getController().getGuiHelper().getFacade().startStopwatch()).thenReturn(new TimeDescriptor(50));
stopwatchStartButton.fire();
FXTestUtils.awaitEvents();
// Stoppuhr stoppen
stopwatchStopButton.fire();
FXTestUtils.awaitEvents();
// gemessene Zeit muss angezeigt sein
assertEquals("00:00:00.050", stopwatchTimeLabel.getText());
when(getController().getGuiHelper().getFacade().startStopwatch()).thenReturn(new TimeDescriptor(200));
stopwatchStartButton.fire();
FXTestUtils.awaitEvents();
// Stoppuhr wieder stoppen
stopwatchStopButton.fire();
FXTestUtils.awaitEvents();
// gemessene Zeit muss angezeigt sein
assertEquals("00:00:00.200", stopwatchTimeLabel.getText());
}
@Test
public final void testStopwatchReset() {
final Button stopwatchStartButton = (Button) scene.lookup("#stopwatchStartButton");
final Button stopwatchStopButton = (Button) scene.lookup("#stopwatchStopButton");
final Button stopwatchResetButton = (Button) scene.lookup("#stopwatchResetButton");
final Label stopwatchTimeLabel = (Label) scene.lookup("#stopwatchTimeLabel");
stopwatchResetButton.fire();
FXTestUtils.awaitEvents();
verify(getController().getGuiHelper().getFacade()).resetStopwatch();
assertEquals("00:00:00.000", stopwatchTimeLabel.getText());
// Stoppuhr starten
when(getController().getGuiHelper().getFacade().startStopwatch()).thenReturn(new TimeDescriptor(9876));
stopwatchStartButton.fire();
FXTestUtils.awaitEvents();
// gemessene Zeit muss angezeigt sein
assertEquals("00:00:09.876", stopwatchTimeLabel.getText());
// Stoppuhr stoppen
stopwatchStopButton.fire();
FXTestUtils.awaitEvents();
stopwatchResetButton.fire();
FXTestUtils.awaitEvents();
assertEquals("00:00:00.000", stopwatchTimeLabel.getText());
}
@Test
public final void testStopwatchResetWhileRunning() {
final Button stopwatchStartButton = (Button) scene.lookup("#stopwatchStartButton");
final Button stopwatchStopButton = (Button) scene.lookup("#stopwatchStopButton");
final Button stopwatchResetButton = (Button) scene.lookup("#stopwatchResetButton");
final Label stopwatchTimeLabel = (Label) scene.lookup("#stopwatchTimeLabel");
// Stoppuhr starten
when(getController().getGuiHelper().getFacade().startStopwatch()).thenReturn(new TimeDescriptor(50));
stopwatchStartButton.fire();
FXTestUtils.awaitEvents();
verify(getController().getGuiHelper().getFacade()).startStopwatch();
stopwatchResetButton.fire();
FXTestUtils.awaitEvents();
verify(getController().getGuiHelper().getFacade()).resetStopwatch();
// gemessene Zeit muss angezeigt sein
assertEquals("00:00:00.050", stopwatchTimeLabel.getText());
// Stoppuhr stoppen
stopwatchStopButton.fire();
FXTestUtils.awaitEvents();
verify(getController().getGuiHelper().getFacade()).stopStopwatch();
}
}
|
package app.action;
import app.output.Output;
import app.shipper.BasicShipper;
import app.shipper.CompositeShipper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class ActionTest {
@Mock
private CompositeShipper compositeShipperMocked;
@Mock
private BasicShipper basicShipper;
@Mock
private Output outputMock;
private CompositeShipperAction collectDrone;
@Before
public void setUp() {
collectDrone = new Collect(compositeShipperMocked, basicShipper);
collectDrone.addObserver(outputMock);
when(compositeShipperMocked.getName()).thenReturn("compositeShipperMocked");
}
@Test
public void anAction_WhenStartIsCalled_ShouldNotifyObservers() {
collectDrone.start();
verify(outputMock).update(any(), any());
}
@Test
public void anAction_WhenStartIsCalled_ShouldNotifyObserversWithProperParameter() {
collectDrone.start();
verify(outputMock).update(collectDrone, ActionEvent.STARTED);
}
@Test
public void anAction_WhenEndIsCalled_ShouldNotifyObservers() {
collectDrone.end();
verify(outputMock).update(any(), any());
}
@Test
public void anAction_WhenEndIsCalled_ShouldNotifyObserversWithProperParameter() {
collectDrone.end();
verify(outputMock).update(collectDrone, ActionEvent.ENDED);
}
@Test
public void anAction_WhenQueuing_ShouldQueueItSelfIntoItsInternalTarget() {
collectDrone.queue();
verify(compositeShipperMocked).queueAction(collectDrone);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.