hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
84b3a6e2d81aa2f115579ec257ab467faf841a60 | 315 | package net.minecraftforge.accesstransformer.testJar;
@SuppressWarnings("unused")
public class ATTestClass {
private final String finalPrivateField = "EMPTY";
private String privateField = "EMPTY";
private void privateMethod() {
}
public void otherMethod() {
privateMethod();
}
}
| 21 | 53 | 0.698413 |
dfbd28f1821b9b84f852e946ff29468a9180b6a6 | 20,480 | /* Copyright (c) 2015-2016 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Gabriel Roldan (Boundless) - initial implementation
*/
package org.locationtech.geogig.model.internal;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.eclipse.jdt.annotation.Nullable;
import org.locationtech.geogig.model.Bucket;
import org.locationtech.geogig.model.CanonicalNodeNameOrder;
import org.locationtech.geogig.model.Node;
import org.locationtech.geogig.model.ObjectId;
import org.locationtech.geogig.model.RevTree;
import org.locationtech.geogig.model.impl.RevTreeBuilder;
import org.locationtech.geogig.model.internal.DAG.STATE;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
/**
* Base class for strategy objects that define the internal structure of a {@link RevTree}.
*
* @apiNote instances of this class might hold references to temporary resources that need to be
* cleaned up after usage, hence the use of the {@link #dispose()} method is mandatory. In
* general, the {@link RevTreeBuilder} that's using this object will do so as part of its
* own clean up phase before returning from its own {@code build()} method.
*/
public abstract class ClusteringStrategy {
final DAGStorageProvider storageProvider;
protected static final TreeId ROOT_ID = new TreeId(new byte[0]);
protected final DAG root;
@VisibleForTesting
final RevTree original;
@VisibleForTesting
final DAGCache dagCache;
protected ClusteringStrategy(RevTree original, DAGStorageProvider storageProvider) {
checkNotNull(original);
checkNotNull(storageProvider);
this.original = original;
this.storageProvider = storageProvider;
this.dagCache = new DAGCache(storageProvider);
this.root = new DAG(ROOT_ID, original.getId());
this.root.setTotalChildCount(original.size());
}
abstract int normalizedSizeLimit(final int depthIndex);
/**
* @return the {@link NodeId} that matches the given node
*/
public @Nullable abstract NodeId computeId(Node node);
/**
* Computes the bucket a given {@link NodeId} lays into for a given tree depth.
*
* @param depthIndex the tree depth for which to return the bucket index for this node
* @return a positive integer (in the range of an unsigned byte value) or {@code -1} if this
* node can't be added at the specified depth, and hence the node shall be kept at the
* current tree node (hence creating a mixed {@link RevTree} with both direct children
* and buckets).
*/
public abstract int bucket(NodeId nodeId, int depthIndex);
/**
* @return the bucket corresponding to {@code nodeId} at depth {@code depthIndex} as mandated by
* {@link CanonicalNodeNameOrder}
*/
public final int canonicalBucket(final NodeId nodeId, final int depthIndex) {
int bucket = CanonicalNodeNameOrder.bucket(nodeId.name(), depthIndex);
return bucket;
}
/**
* @see #getOrCreateDAG(TreeId, ObjectId)
*/
DAG getOrCreateDAG(TreeId treeId) {
return getOrCreateDAG(treeId, RevTree.EMPTY_TREE_ID);
}
/**
* Returns the mutable tree (DAG) associated to the given {@link TreeId}, creating it if it
* doesn't exist and setting it's original {@link RevTree} identifier as {@code originalTreeId}
*/
protected DAG getOrCreateDAG(TreeId treeId, ObjectId originalTreeId) {
DAG dag = dagCache.getOrCreate(treeId, originalTreeId);
return dag;
}
public List<DAG> getDagTrees(Set<TreeId> ids) {
List<DAG> trees = dagCache.getAll(ids);
return trees;
}
@VisibleForTesting
Node getNode(NodeId nodeId) {
SortedMap<NodeId, Node> nodes = getNodes(ImmutableSet.of(nodeId));
return nodes.get(nodeId);
}
/**
* Returns a set of {@link Node} objects by their {@link NodeId}s in the order imposed by the
* clustering strategy, to be held as direct children of a leaf {@link RevTree}.
* <p>
* For a canonical tree, the order must follow the one imposed by
* {@link CanonicalNodeNameOrder}.
* <p>
* For an index tree, the order is first mandated by the natural order of the index attribute
* values, followed by canonical order.
*/
public SortedMap<NodeId, Node> getNodes(Set<NodeId> nodeIds) {
Map<NodeId, Node> nodes = storageProvider.getNodes(nodeIds);
Comparator<NodeId> nodeOrdering = getNodeOrdering();
TreeMap<NodeId, Node> sorted = new TreeMap<>(nodeOrdering);
sorted.putAll(nodes);
return sorted;
}
protected abstract Comparator<NodeId> getNodeOrdering();
public void dispose() {
this.dagCache.dispose();
this.storageProvider.dispose();
}
public int depth() {
return depth(buildRoot());
}
int depth(DAG root) {
if (0 == root.numBuckets()) {
return 0;
}
final AtomicInteger maxDepth = new AtomicInteger();// cause an int can't be used from inside
// the lambda
root.forEachBucket((bucketId) -> {
DAG bucket = getOrCreateDAG(bucketId);
int bucketDepth = depth(bucket);
maxDepth.set(Math.max(maxDepth.get(), bucketDepth));
});
return 1 + maxDepth.get();
}
public boolean remove(Node node) {
if (!node.getObjectId().isNull()) {
node = node.update(ObjectId.NULL);
}
int delta = put(node);
return -1 == delta;
}
/**
* Replaces {@code oldNode} by {@code newNode}
* <p>
* This default implemetation just calls {@link #remove(Node) remove(oldNode)} and then
* {@link #put(Node) put(newNode)}. Subclasses are encouraged to override with optimized
* versions whenever possible.
*
* @return {@code 0} if the operation resulted in no change, {@code 1} if the node was
* inserted/updated, {@code -1} if the node was deleted
*/
public int update(Node oldNode, Node newNode) {
Preconditions.checkArgument(oldNode.getName().equals(newNode.getName()));
if (remove(oldNode)) {
return put(newNode);
}
return 0;
}
private Lock writeLock = new ReentrantLock();
/**
* @param
* @return {@code 0} if the operation resulted in no change, {@code 1} if the node was
* inserted/updated, {@code -1} if the node was deleted
*/
public int put(final Node node) {
@Nullable
final NodeId nodeId = computeId(node);
if (null == nodeId) {
return 0;
}
// nodeId can be null if it's not to be added to the tree at all (e.g. a non spatial
// feature in a spatial index)
boolean remove = node.getObjectId().isNull();
int delta;
writeLock.lock();
try {
delta = put(root, nodeId, remove);
dagCache.prune();
} finally {
writeLock.unlock();
}
if (!remove) {
storageProvider.saveNode(nodeId, node);
}
return delta;
}
public DAG buildRoot() {
return root;
}
/**
* @param dagId
* @param dag
* @param nodeId
* @param remove
* @param dagDepth zero based depth of {@code dag} (not a depth index, which is
* {@code depth - 1}
* @return
*/
private int put(final DAG dag, final NodeId nodeId, final boolean remove) {
checkNotNull(dag);
checkNotNull(nodeId);
final int dagDepth = dag.getId().depthLength();
mergeRoot(dag, nodeId);
boolean changed = false;
final int deltaSize;
final int normalizedSizeLimit = normalizedSizeLimit(dagDepth);
if (dag.numBuckets() > 0) {
final @Nullable TreeId bucketId = computeBucketId(nodeId, dagDepth + 1);
if (bucketId != null) {
DAG bucketDAG = getOrCreateDAG(bucketId);
dag.addBucket(bucketId);
deltaSize = put(bucketDAG, nodeId, remove);
changed = bucketDAG.getState() == STATE.CHANGED;
if (bucketDAG.getTotalChildCount() == 0) {
dag.removeBucket(bucketId);
}
} else {
deltaSize = 0;
}
} else {
if (remove) {
deltaSize = dag.removeChild(nodeId) ? -1 : 0;
} else {
changed = true;// contents changed, independently of children.add return code
deltaSize = dag.addChild(nodeId) ? +1 : 0;
}
final int size = dag.numChildren();
if (size > normalizedSizeLimit) {
ListMultimap<TreeId, NodeId> promotions = ArrayListMultimap.create();
dag.forEachChild((childId) -> {
TreeId bucketId = computeBucketId(childId, dagDepth + 1);
checkNotNull(bucketId);
promotions.put(bucketId, childId);
});
promotions.asMap().forEach((bucketId, childIds) -> {
DAG bucketDAG = getOrCreateDAG(bucketId);
dag.addBucket(bucketId);
for (NodeId childId : childIds) {
put(bucketDAG, childId, remove);
}
});
dag.clearChildren();
}
}
if (deltaSize != 0) {
changed = true;
dag.setTotalChildCount(dag.getTotalChildCount() + deltaSize);
shrinkIfUnderflow(dag, nodeId, dagDepth);
}
if (changed) {
dag.setChanged();
}
return deltaSize;
}
private void shrinkIfUnderflow(final DAG bucketsDAG, NodeId nodeId, int depth) {
final long childCount = bucketsDAG.getTotalChildCount();
final int normalizedSizeLimit = normalizedSizeLimit(depth);
if (childCount <= normalizedSizeLimit && bucketsDAG.numBuckets() > 0) {
Set<NodeId> childrenRecursive = getChildrenRecursive(bucketsDAG, nodeId, depth);
checkState(childrenRecursive.size() == childCount, "expected %s, got %s, at: %s",
childCount, childrenRecursive.size(), bucketsDAG);
bucketsDAG.clearBuckets();
childrenRecursive.forEach((id) -> bucketsDAG.addChild(id));
}
}
private Set<NodeId> getChildrenRecursive(final DAG dag, final NodeId nodeId, final int depth) {
Set<NodeId> children = new HashSet<>();
dag.forEachChild((id) -> children.add(id));
if (!children.isEmpty()) {
return children;
}
dag.forEachBucket((bucketId) -> {
DAG bucket = getOrCreateDAG(bucketId);
mergeRoot(bucket, nodeId);
Set<NodeId> bucketChildren = getChildrenRecursive(bucket, nodeId, depth + 1);
children.addAll(bucketChildren);
});
return children;
}
/**
* Makes sure the DAG has the same structure than the original tree following the path to the
* node (i.e.) loading only the {@link RevTree trees} necessary to reach the node being added.
*
* @param root
* @param nodeId
* @param nodeDepth depth, not depth index
* @return
* @return
*/
protected void mergeRoot(DAG root, final NodeId nodeId) {
checkNotNull(root);
checkNotNull(nodeId);
if (root.getState() == STATE.INITIALIZED) {
final RevTree original = getOriginalTree(root.originalTreeId());
root.setTotalChildCount(original.size());
final boolean originalIsLeaf = original.buckets().isEmpty();
if (originalIsLeaf) {
final Map<NodeId, DAGNode> origNodes = lazyNodes(original);
if (!origNodes.isEmpty()) {
// TODO: avoid saving nodes already in RevTrees
storageProvider.saveNodes(origNodes);
origNodes.keySet().forEach((id) -> root.addChild(id));
}
} else {
final int dagDepth = root.getId().depthLength();
final TreeId nodeBucketId = computeBucketId(nodeId, dagDepth + 1);
final ImmutableSortedMap<Integer, Bucket> buckets = original.buckets();
if (root.getState() == STATE.INITIALIZED) {
// make DAG a bucket tree
checkState(root.numChildren() == 0);
// initialize buckets
preload(buckets.values());
for (Entry<Integer, Bucket> e : buckets.entrySet()) {
Integer bucketIndex = e.getKey();
TreeId dagBucketId = computeBucketId(nodeBucketId, bucketIndex);
ObjectId bucketId = e.getValue().getObjectId();
// make sure the DAG exists and is initialized
DAG dag = getOrCreateDAG(dagBucketId, bucketId);
root.addBucket(dagBucketId);
}
}
}
root.setMirrored();
}
}
private void preload(ImmutableCollection<Bucket> values) {
this.storageProvider.getTreeCache()
.preload(Iterables.transform(values, (b) -> b.getObjectId()));
}
protected RevTree getOriginalTree(@Nullable ObjectId originalId) {
final RevTree original;
if (originalId == null || RevTree.EMPTY_TREE_ID.equals(originalId)) {
original = RevTree.EMPTY;
} else {
// System.err.println("Loading tree " + originalId);
original = storageProvider.getTree(originalId);
}
return original;
}
TreeId computeBucketId(final NodeId nodeId, final int childDepth) {
byte[] treeId = new byte[childDepth];
int unpromotableDepthIndex = -1;
for (int depthIndex = 0; depthIndex < childDepth; depthIndex++) {
int bucketIndex = bucket(nodeId, depthIndex);
if (bucketIndex == -1) {
unpromotableDepthIndex = depthIndex;
break;
}
treeId[depthIndex] = (byte) bucketIndex;
}
if (unpromotableDepthIndex > -1) {
final int extraBucketIndex = unpromotableBucketIndex(unpromotableDepthIndex);
treeId[unpromotableDepthIndex] = (byte) extraBucketIndex;
unpromotableDepthIndex++;
final int missingDepthCount = childDepth - unpromotableDepthIndex;
for (int i = 0; i < missingDepthCount; i++, unpromotableDepthIndex++) {
int bucketIndex = canonicalBucket(nodeId, i);
treeId[unpromotableDepthIndex] = (byte) bucketIndex;
}
}
return new TreeId(treeId);
}
protected int unpromotableBucketIndex(final int depthIndex) {
throw new UnsupportedOperationException();
}
private TreeId computeBucketId(final TreeId treeId, final Integer leafOverride) {
byte[] bucketIndicesByDepth = treeId.bucketIndicesByDepth.clone();
bucketIndicesByDepth[bucketIndicesByDepth.length - 1] = leafOverride.byteValue();
return new TreeId(bucketIndicesByDepth);
}
private Map<NodeId, DAGNode> lazyNodes(final RevTree tree) {
if (tree.isEmpty()) {
return ImmutableMap.of();
}
final TreeCache treeCache = storageProvider.getTreeCache();
final int cacheTreeId = treeCache.getTreeId(tree).intValue();
Map<NodeId, DAGNode> dagNodes = new HashMap<>();
List<Node> treeNodes = tree.trees();
for (int i = 0; i < treeNodes.size(); i++) {
NodeId nodeId = computeId(treeNodes.get(i));
DAGNode dagNode = DAGNode.treeNode(cacheTreeId, i);
dagNodes.put(nodeId, dagNode);
}
ImmutableList<Node> featureNodes = tree.features();
for (int i = 0; i < featureNodes.size(); i++) {
NodeId nodeId = computeId(featureNodes.get(i));
DAGNode dagNode = DAGNode.featureNode(cacheTreeId, i);
dagNodes.put(nodeId, dagNode);
}
return dagNodes;
}
@VisibleForTesting
class DAGCache {
private DAGStorageProvider store;
@VisibleForTesting
final Map<TreeId, DAG> treeBuff = new ConcurrentHashMap<>();
private Set<TreeId> dirty = new HashSet<>();
DAGCache(DAGStorageProvider store) {
this.store = store;
}
public void dispose() {
treeBuff.clear();
}
/**
* Returns all the DAG's for the argument ids, which must already exist
*/
public List<DAG> getAll(Set<TreeId> ids) {
List<DAG> all = new ArrayList<>();
Set<TreeId> missing = new HashSet<>();
for (TreeId id : ids) {
DAG dag;
if (ROOT_ID.equals(id)) {
dag = ClusteringStrategy.this.root;
} else {
dag = treeBuff.get(id);
}
if (dag == null) {
missing.add(id);
} else {
all.add(dag);
}
}
List<DAG> uncached = store.getTrees(missing);
all.addAll(uncached);
return all;
}
public DAG getOrCreate(TreeId treeId, ObjectId originalTreeId) {
DAG dag = treeBuff.get(treeId);
if (dag == null) {
dag = store.getOrCreateTree(treeId, originalTreeId);
dag.changeListener = this::changed;
DAG existing = treeBuff.putIfAbsent(treeId, dag);
if (existing != null) {
dag = existing;
}
}
return dag;
}
/**
* Decides whether to mark a changed DAG as "dirty" (candidate to be returned to the DAG
* store)
*/
private void changed(DAG dag) {
// currently keeps all bucket DAGs in the cache, and flushes leaf DAGs to the underlying
// temporary store
if (dag.numChildren() > 64) {
dirty.add(dag.getId());
}
}
public void prune() {
final int dirtySize = dirty.size();
if (dirtySize < 10_000) {
return;
}
// Stopwatch sw = Stopwatch.createStarted();
Map<TreeId, DAG> toSave = new HashMap<>();
for (TreeId id : dirty) {
DAG saveme = treeBuff.remove(id);
checkNotNull(saveme);
toSave.put(id, saveme);
}
dirty.clear();
store.save(toSave);
// System.err.printf("Saved %,d dirty DAGs in %s, remaining %,d\n", toSave.size(),
// sw.stop(), treeBuff.size());
}
@VisibleForTesting
public void add(DAG dag) {
treeBuff.put(dag.getId(), dag);
}
}
} | 35.679443 | 100 | 0.593018 |
e7841d24177633324f8309e26f582e67409b8daf | 2,655 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.dialect;
import java.sql.Types;
import org.hibernate.dialect.function.DB2SubstringFunction;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.type.descriptor.sql.CharTypeDescriptor;
import org.hibernate.type.descriptor.sql.ClobTypeDescriptor;
import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
/**
* An SQL dialect for DB2 9.7.
*
* @author Gail Badner
*/
public class DB297Dialect extends DB2Dialect {
public DB297Dialect() {
super();
registerFunction( "substring", new DB2SubstringFunction() );
}
@Override
public String getCrossJoinSeparator() {
// DB2 9.7 and later support "cross join"
return " cross join ";
}
@Override
public MultiTableBulkIdStrategy getDefaultMultiTableBulkIdStrategy() {
// Starting in DB2 9.7, "real" global temporary tables that can be shared between sessions
// are supported; (obviously) data is not shared between sessions.
return new GlobalTemporaryTableBulkIdStrategy(
new IdTableSupportStandardImpl() {
@Override
public String generateIdTableName(String baseName) {
return super.generateIdTableName( baseName );
}
@Override
public String getCreateIdTableCommand() {
return "create global temporary table";
}
@Override
public String getCreateIdTableStatementOptions() {
return "not logged";
}
},
AfterUseAction.CLEAN
);
}
@Override
protected SqlTypeDescriptor getSqlTypeDescriptorOverride(int sqlCode) {
// See HHH-12753
// It seems that DB2's JDBC 4.0 support as of 9.5 does not support the N-variant methods like
// NClob or NString. Therefore here we overwrite the sql type descriptors to use the non-N variants
// which are supported.
switch ( sqlCode ) {
case Types.NCHAR:
return CharTypeDescriptor.INSTANCE;
case Types.NCLOB:
if ( useInputStreamToInsertBlob() ) {
return ClobTypeDescriptor.STREAM_BINDING;
}
else {
return ClobTypeDescriptor.CLOB_BINDING;
}
case Types.NVARCHAR:
return VarcharTypeDescriptor.INSTANCE;
default:
return super.getSqlTypeDescriptorOverride( sqlCode );
}
}
}
| 29.5 | 102 | 0.744256 |
a60092d71bcc99a2a25984ada38a7e9f99186c66 | 18,037 | /*
* Copyright © 2020 LambdAurora <aurora42lambda@gmail.com>
*
* This file is part of LambdaControls.
*
* Licensed under the MIT license. For more information,
* see the LICENSE file.
*/
package me.lambdaurora.lambdacontrols.client.gui;
import me.lambdaurora.lambdacontrols.ControlsMode;
import me.lambdaurora.lambdacontrols.LambdaControls;
import me.lambdaurora.lambdacontrols.client.LambdaControlsClient;
import me.lambdaurora.lambdacontrols.client.controller.Controller;
import me.lambdaurora.spruceui.SpruceButtonWidget;
import me.lambdaurora.spruceui.SpruceLabelWidget;
import me.lambdaurora.spruceui.SpruceTexts;
import me.lambdaurora.spruceui.Tooltip;
import me.lambdaurora.spruceui.option.*;
import net.fabricmc.fabric.api.network.ClientSidePacketRegistry;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawableHelper;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.options.ControlsOptionsScreen;
import net.minecraft.client.gui.widget.ButtonListWidget;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.options.Option;
import net.minecraft.client.resource.language.I18n;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.LiteralText;
import net.minecraft.text.MutableText;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Formatting;
import net.minecraft.util.Util;
import org.lwjgl.glfw.GLFW;
/**
* Represents the LambdaControls settings screen.
*/
public class LambdaControlsSettingsScreen extends Screen
{
public static final String GAMEPAD_TOOL_URL = "https://generalarcade.com/gamepadtool/";
final LambdaControlsClient mod;
private final Screen parent;
private final boolean hideControls;
// General options
private final Option autoSwitchModeOption;
private final Option rotationSpeedOption;
private final Option mouseSpeedOption;
private final Option resetOption;
// Gameplay options
private final Option autoJumpOption;
private final Option fastBlockPlacingOption;
private final Option frontBlockPlacingOption;
private final Option verticalReacharoundOption;
private final Option flyDriftingOption;
private final Option flyVerticalDriftingOption;
// Controller options
private final Option controllerOption;
private final Option secondControllerOption;
private final Option controllerTypeOption;
private final Option deadZoneOption;
private final Option invertsRightXAxis;
private final Option invertsRightYAxis;
private final Option unfocusedInputOption;
private final Option virtualMouseOption;
private final Option virtualMouseSkinOption;
// Hud options
private final Option hudEnableOption;
private final Option hudSideOption;
private final MutableText controllerMappingsUrlText = new LiteralText("(")
.append(new LiteralText(GAMEPAD_TOOL_URL).formatted(Formatting.GOLD))
.append("),");
private ButtonListWidget list;
private SpruceLabelWidget gamepadToolUrlLabel;
public LambdaControlsSettingsScreen(Screen parent, boolean hideControls)
{
super(new TranslatableText("lambdacontrols.title.settings"));
this.mod = LambdaControlsClient.get();
this.parent = parent;
this.hideControls = hideControls;
// General options
this.autoSwitchModeOption = new SpruceBooleanOption("lambdacontrols.menu.auto_switch_mode", this.mod.config::hasAutoSwitchMode,
this.mod.config::setAutoSwitchMode, new TranslatableText("lambdacontrols.tooltip.auto_switch_mode"), true);
this.rotationSpeedOption = new SpruceDoubleOption("lambdacontrols.menu.rotation_speed", 0.0, 100.0, 0.5F, this.mod.config::getRotationSpeed,
newValue -> {
synchronized (this.mod.config) {
this.mod.config.setRotationSpeed(newValue);
}
}, option -> option.getDisplayText(new LiteralText(String.valueOf(option.get()))),
new TranslatableText("lambdacontrols.tooltip.rotation_speed"));
this.mouseSpeedOption = new SpruceDoubleOption("lambdacontrols.menu.mouse_speed", 0.0, 150.0, 0.5F, this.mod.config::getMouseSpeed,
newValue -> {
synchronized (this.mod.config) {
this.mod.config.setMouseSpeed(newValue);
}
}, option -> option.getDisplayText(new LiteralText(String.valueOf(option.get()))),
new TranslatableText("lambdacontrols.tooltip.mouse_speed"));
this.resetOption = new SpruceResetOption(btn -> {
this.mod.config.reset();
MinecraftClient client = MinecraftClient.getInstance();
this.init(client, client.getWindow().getScaledWidth(), client.getWindow().getScaledHeight());
});
// Gameplay options
this.autoJumpOption = SpruceBooleanOption.fromVanilla("options.autoJump", Option.AUTO_JUMP, null, true);
this.fastBlockPlacingOption = new SpruceBooleanOption("lambdacontrols.menu.fast_block_placing", this.mod.config::hasFastBlockPlacing,
this.mod.config::setFastBlockPlacing, new TranslatableText("lambdacontrols.tooltip.fast_block_placing"), true);
this.frontBlockPlacingOption = new SpruceBooleanOption("lambdacontrols.menu.reacharound.horizontal", this.mod.config::hasFrontBlockPlacing,
this.mod.config::setFrontBlockPlacing, new TranslatableText("lambdacontrols.tooltip.reacharound.horizontal"), true);
this.verticalReacharoundOption = new SpruceBooleanOption("lambdacontrols.menu.reacharound.vertical", this.mod.config::hasVerticalReacharound,
this.mod.config::setVerticalReacharound, new TranslatableText("lambdacontrols.tooltip.reacharound.vertical"), true);
this.flyDriftingOption = new SpruceBooleanOption("lambdacontrols.menu.fly_drifting", this.mod.config::hasFlyDrifting,
this.mod.config::setFlyDrifting, new TranslatableText("lambdacontrols.tooltip.fly_drifting"), true);
this.flyVerticalDriftingOption = new SpruceBooleanOption("lambdacontrols.menu.fly_drifting_vertical", this.mod.config::hasFlyVerticalDrifting,
this.mod.config::setFlyVerticalDrifting, new TranslatableText("lambdacontrols.tooltip.fly_drifting_vertical"), true);
// Controller options
this.controllerOption = new SpruceCyclingOption("lambdacontrols.menu.controller", amount -> {
int id = this.mod.config.getController().getId();
id += amount;
if (id > GLFW.GLFW_JOYSTICK_LAST)
id = GLFW.GLFW_JOYSTICK_1;
this.mod.config.setController(Controller.byId(id));
}, option -> {
String controllerName = this.mod.config.getController().getName();
if (!this.mod.config.getController().isConnected())
return option.getDisplayText(new LiteralText(controllerName).formatted(Formatting.RED));
else if (!this.mod.config.getController().isGamepad())
return option.getDisplayText(new LiteralText(controllerName).formatted(Formatting.GOLD));
else
return option.getDisplayText(new LiteralText(controllerName));
}, null);
this.secondControllerOption = new SpruceCyclingOption("lambdacontrols.menu.controller2",
amount -> {
int id = this.mod.config.getSecondController().map(Controller::getId).orElse(-1);
id += amount;
if (id > GLFW.GLFW_JOYSTICK_LAST)
id = -1;
this.mod.config.setSecondController(id == -1 ? null : Controller.byId(id));
}, option -> this.mod.config.getSecondController().map(controller -> {
String controllerName = controller.getName();
if (!controller.isConnected())
return option.getDisplayText(new LiteralText(controllerName).formatted(Formatting.RED));
else if (!controller.isGamepad())
return option.getDisplayText(new LiteralText(controllerName).formatted(Formatting.GOLD));
else
return option.getDisplayText(new LiteralText(controllerName));
}).orElse(option.getDisplayText(SpruceTexts.OPTIONS_OFF.shallowCopy().formatted(Formatting.RED))),
new TranslatableText("lambdacontrols.tooltip.controller2"));
this.controllerTypeOption = new SpruceCyclingOption("lambdacontrols.menu.controller_type",
amount -> this.mod.config.setControllerType(this.mod.config.getControllerType().next()),
option -> option.getDisplayText(this.mod.config.getControllerType().getTranslatedText()),
new TranslatableText("lambdacontrols.tooltip.controller_type"));
this.deadZoneOption = new SpruceDoubleOption("lambdacontrols.menu.dead_zone", 0.05, 1.0, 0.05F, this.mod.config::getDeadZone,
newValue -> {
synchronized (this.mod.config) {
this.mod.config.setDeadZone(newValue);
}
}, option -> {
String value = String.valueOf(option.get());
return option.getDisplayText(new LiteralText(value.substring(0, Math.min(value.length(), 5))));
}, new TranslatableText("lambdacontrols.tooltip.dead_zone"));
this.invertsRightXAxis = new SpruceBooleanOption("lambdacontrols.menu.invert_right_x_axis", this.mod.config::doesInvertRightXAxis,
newValue -> {
synchronized (this.mod.config) {
this.mod.config.setInvertRightXAxis(newValue);
}
}, null, true);
this.invertsRightYAxis = new SpruceBooleanOption("lambdacontrols.menu.invert_right_y_axis", this.mod.config::doesInvertRightYAxis,
newValue -> {
synchronized (this.mod.config) {
this.mod.config.setInvertRightYAxis(newValue);
}
}, null, true);
this.unfocusedInputOption = new SpruceBooleanOption("lambdacontrols.menu.unfocused_input", this.mod.config::hasUnfocusedInput,
this.mod.config::setUnfocusedInput, new TranslatableText("lambdacontrols.tooltip.unfocused_input"), true);
this.virtualMouseOption = new SpruceBooleanOption("lambdacontrols.menu.virtual_mouse", this.mod.config::hasVirtualMouse,
this.mod.config::setVirtualMouse, new TranslatableText("lambdacontrols.tooltip.virtual_mouse"), true);
this.virtualMouseSkinOption = new SpruceCyclingOption("lambdacontrols.menu.virtual_mouse.skin",
amount -> this.mod.config.setVirtualMouseSkin(this.mod.config.getVirtualMouseSkin().next()),
option -> option.getDisplayText(this.mod.config.getVirtualMouseSkin().getTranslatedText()),
null);
// HUD options
this.hudEnableOption = new SpruceBooleanOption("lambdacontrols.menu.hud_enable", this.mod.config::isHudEnabled,
this.mod::setHudEnabled, new TranslatableText("lambdacontrols.tooltip.hud_enable"), true);
this.hudSideOption = new SpruceCyclingOption("lambdacontrols.menu.hud_side",
amount -> this.mod.config.setHudSide(this.mod.config.getHudSide().next()),
option -> option.getDisplayText(this.mod.config.getHudSide().getTranslatedText()),
new TranslatableText("lambdacontrols.tooltip.hud_side"));
}
@Override
public void removed()
{
this.mod.config.save();
super.removed();
}
@Override
public void onClose()
{
this.mod.config.save();
super.onClose();
}
private int getTextHeight()
{
return (5 + this.textRenderer.fontHeight) * 3 + 5;
}
@Override
protected void init()
{
super.init();
int buttonHeight = 20;
SpruceButtonWidget controlsModeBtn = new SpruceButtonWidget(this.width / 2 - 155, 18, this.hideControls ? 310 : 150, buttonHeight,
new TranslatableText("lambdacontrols.menu.controls_mode").append(": ").append(new TranslatableText(this.mod.config.getControlsMode().getTranslationKey())),
btn -> {
ControlsMode next = this.mod.config.getControlsMode().next();
btn.setMessage(new TranslatableText("lambdacontrols.menu.controls_mode").append(": ").append(new TranslatableText(next.getTranslationKey())));
this.mod.config.setControlsMode(next);
this.mod.config.save();
if (this.client.player != null) {
ClientSidePacketRegistry.INSTANCE.sendToServer(LambdaControls.CONTROLS_MODE_CHANNEL, this.mod.makeControlsModeBuffer(next));
}
});
controlsModeBtn.setTooltip(new TranslatableText("lambdacontrols.tooltip.controls_mode"));
this.addButton(controlsModeBtn);
if (!this.hideControls)
this.addButton(new ButtonWidget(this.width / 2 - 155 + 160, 18, 150, buttonHeight, new TranslatableText("options.controls"),
btn -> {
if (this.mod.config.getControlsMode() == ControlsMode.CONTROLLER)
this.client.openScreen(new ControllerControlsScreen(this, true));
else
this.client.openScreen(new ControlsOptionsScreen(this, this.client.options));
}));
this.list = new ButtonListWidget(this.client, this.width, this.height, 43, this.height - 29 - this.getTextHeight(), 25);
// General options
this.list.addSingleOptionEntry(new SpruceSeparatorOption("lambdacontrols.menu.title.general", true, null));
this.list.addOptionEntry(this.rotationSpeedOption, this.mouseSpeedOption);
this.list.addSingleOptionEntry(this.autoSwitchModeOption);
// Gameplay options
this.list.addSingleOptionEntry(new SpruceSeparatorOption("lambdacontrols.menu.title.gameplay", true, null));
this.list.addOptionEntry(this.autoJumpOption, this.fastBlockPlacingOption);
this.list.addOptionEntry(this.frontBlockPlacingOption, this.verticalReacharoundOption);
this.list.addSingleOptionEntry(this.flyDriftingOption);
this.list.addSingleOptionEntry(this.flyVerticalDriftingOption);
this.list.addOptionEntry(Option.SNEAK_TOGGLED, Option.SPRINT_TOGGLED);
// Controller options
this.list.addSingleOptionEntry(new SpruceSeparatorOption("lambdacontrols.menu.title.controller", true, null));
this.list.addSingleOptionEntry(this.controllerOption);
this.list.addSingleOptionEntry(this.secondControllerOption);
this.list.addOptionEntry(this.controllerTypeOption, this.deadZoneOption);
this.list.addOptionEntry(this.invertsRightXAxis, this.invertsRightYAxis);
this.list.addOptionEntry(this.unfocusedInputOption, this.virtualMouseOption);
this.list.addSingleOptionEntry(this.virtualMouseSkinOption);
this.list.addSingleOptionEntry(new ReloadControllerMappingsOption());
this.list.addSingleOptionEntry(new SpruceSimpleActionOption("lambdacontrols.menu.mappings.open_input_str",
btn -> this.client.openScreen(new MappingsStringInputScreen(this))));
// HUD options
this.list.addSingleOptionEntry(new SpruceSeparatorOption("lambdacontrols.menu.title.hud", true, null));
this.list.addOptionEntry(this.hudEnableOption, this.hudSideOption);
this.children.add(this.list);
this.gamepadToolUrlLabel = new SpruceLabelWidget(this.width / 2, this.height - 29 - (5 + this.textRenderer.fontHeight) * 2, this.controllerMappingsUrlText, this.width,
label -> Util.getOperatingSystem().open(GAMEPAD_TOOL_URL), true);
this.gamepadToolUrlLabel.setTooltip(new TranslatableText("chat.link.open"));
this.children.add(this.gamepadToolUrlLabel);
this.addButton(this.resetOption.createButton(this.client.options, this.width / 2 - 155, this.height - 29, 150));
this.addButton(new ButtonWidget(this.width / 2 - 155 + 160, this.height - 29, 150, buttonHeight, SpruceTexts.GUI_DONE,
btn -> this.client.openScreen(this.parent)));
}
@Override
public void render(MatrixStack matrices, int mouseX, int mouseY, float delta)
{
this.renderBackground(matrices);
this.list.render(matrices, mouseX, mouseY, delta);
super.render(matrices, mouseX, mouseY, delta);
drawCenteredString(matrices, this.textRenderer, I18n.translate("lambdacontrols.menu.title"), this.width / 2, 8, 16777215);
drawCenteredString(matrices, this.textRenderer, I18n.translate("lambdacontrols.controller.mappings.1", Formatting.GREEN.toString(), Formatting.RESET.toString()), this.width / 2, this.height - 29 - (5 + this.textRenderer.fontHeight) * 3, 10526880);
this.gamepadToolUrlLabel.render(matrices, mouseX, mouseY, delta);
drawCenteredString(matrices, this.textRenderer, I18n.translate("lambdacontrols.controller.mappings.3", Formatting.GREEN.toString(), Formatting.RESET.toString()), this.width / 2, this.height - 29 - (5 + this.textRenderer.fontHeight), 10526880);
Tooltip.renderAll(matrices);
}
}
| 61.770548 | 255 | 0.67234 |
96ab5e16c7aa2f4d8c60d8aac164f54818a8af99 | 25,437 | package coffeeshop.ejb;
import coffeeshop.entity.Category;
import coffeeshop.entity.Image;
import coffeeshop.entity.Ingredient;
import coffeeshop.entity.IngredientCategory;
import coffeeshop.entity.Nutrition;
import coffeeshop.entity.Product;
import coffeeshop.entity.SeasonSpecial;
import coffeeshop.entity.Store;
import coffeeshop.entity.UserInfo;
import coffeeshop.facade.CategoryFacade;
import coffeeshop.facade.ImageFacade;
import coffeeshop.facade.IngredientCategoryFacade;
import coffeeshop.facade.IngredientFacade;
import coffeeshop.facade.NutritionFacade;
import coffeeshop.facade.ProductFacade;
import coffeeshop.facade.SeasonSpecialFacade;
import java.io.IOException;
import javax.ejb.EJB;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
@RolesAllowed("admin")
@Stateless
public class InitManager {
private static final Logger LOG = Logger.getLogger(InitManager.class.getName());
private static final String DEFAULT_ADMIN_USERNAME = "admin";
private static final String DEFAULT_ADMIN_PASSWORD = "admin";
@EJB
private UserManager userManager;
@EJB
private CustomerInfoManager customerInfoManager;
@EJB
private StoreManager storeManager;
@EJB
private CategoryFacade categoryFacade;
@EJB
private ProductFacade productFacade;
@EJB
private NutritionFacade nutritionFacade;
@EJB
private IngredientCategoryFacade ingredientCategoryFacade;
@EJB
private IngredientFacade ingredientFacade;
@EJB
private ImageFacade imageFacade;
@EJB
private SeasonSpecialFacade seasonSpecialFacade;
@PermitAll
public void checkAndAddDefaultAdminUser() throws UserManagerException {
if (!userManager.isUserExisting(DEFAULT_ADMIN_USERNAME)) {
LOG.log(Level.INFO, "Default admin user does not exists");
userManager.addAdmin(DEFAULT_ADMIN_USERNAME, DEFAULT_ADMIN_PASSWORD);
LOG.log(Level.INFO, "New admin user added, username: {0}, password: {1}", new String[]{
DEFAULT_ADMIN_USERNAME,
DEFAULT_ADMIN_PASSWORD
});
}
}
public void insertDemoData() throws IOException, URISyntaxException, UserManagerException {
Category categoryDrinks = createCategory("Drinks");
Category categoryFood = createCategory("Food");
Category categoryCoffeeBean = createCategory("Coffee Bean");
Category categoryCup = createCategory("Cup");
IngredientCategory ingredientCategorySize = createIngredientCategory("Size");
IngredientCategory ingredientCategorySweetness = createIngredientCategory("Sweetness");
IngredientCategory ingredientCategoryIce = createIngredientCategory("Ice");
IngredientCategory ingredientCategoryMilk = createIngredientCategory("Milk");
IngredientCategory ingredientCategoryCream = createIngredientCategory("Cream");
IngredientCategory ingredientCategoryEspresso = createIngredientCategory("Espresso");
IngredientCategory ingredientCategorySyrup = createIngredientCategory("Syrup");
IngredientCategory ingredientCategoryCocoaNibs = createIngredientCategory("Cocoa Nibs");
Ingredient ingredientSizeMedium = createIngredient(
"MEDIUM", "355ml", new BigDecimal(0), ingredientCategorySize);
Ingredient ingredientSizeGrande = createIngredient(
"GRANDE", "473ml", new BigDecimal(3), ingredientCategorySize);
Ingredient ingredientSizeVenti = createIngredient(
"VENTI", "592ml", new BigDecimal(3), ingredientCategorySize);
Ingredient ingredientSweetnessSugarFree = createIngredient(
"Sugar-free", "0 spoon", BigDecimal.ZERO, ingredientCategorySweetness);
Ingredient ingredientSweetnessSemiSweet = createIngredient(
"Semi-sweet", "1 spoon", BigDecimal.ZERO, ingredientCategorySweetness);
Ingredient ingredientSweetnessFullSweet = createIngredient(
"Full-sweet", "2 spoon", BigDecimal.ZERO, ingredientCategorySweetness);
Ingredient ingredientIceNoIce = createIngredient(
"No ice", "cold", BigDecimal.ZERO, ingredientCategoryIce);
Ingredient ingredientIceLessIce = createIngredient(
"Less ice", "cold", BigDecimal.ZERO, ingredientCategoryIce);
Ingredient ingredientIceOnTheRocks = createIngredient(
"On the rocks", "very cold", BigDecimal.ZERO, ingredientCategoryIce);
Ingredient ingredientMilkFull = createIngredient(
"Full milk", null, new BigDecimal(2), ingredientCategoryMilk);
Ingredient ingredientMilkSkimmed = createIngredient(
"Skimmed milk", null, new BigDecimal(2), ingredientCategoryMilk);
Ingredient ingredientCreamAdd = createIngredient(
"Add cream", null, new BigDecimal(2), ingredientCategoryCream);
Ingredient ingredientEspressoUse = createIngredient(
"Espresso coffee", null, new BigDecimal(4), ingredientCategoryEspresso);
Ingredient ingredientSyrupCaramel = createIngredient(
"Caramel syrup", null, new BigDecimal(3), ingredientCategorySyrup);
Ingredient ingredientSyrupVanilla = createIngredient(
"Vanilla syrup", null, new BigDecimal(3), ingredientCategorySyrup);
Ingredient ingredientCocoaNibsAdd = createIngredient(
"Add cocoa nibs", null, new BigDecimal(4), ingredientCategoryCocoaNibs);
// 1
Product productColdFoamCascaraColdBrew = createProduct("Cold Foam Cascara Cold Brew",
"Sweetened cold foam is flavored with our Cascara syrup (for subtle notes of dark brown sugar and luscious maple) atop our bold, smooth Starbucks Cold Brew, and finished with just a hint of vanilla syrup.",
new BigDecimal(36), categoryDrinks, createNutrition(60, 0, 13, 0, 1, 25));
enableProductIngredient(productColdFoamCascaraColdBrew,
ingredientCategorySize, ingredientCategorySweetness, ingredientCategoryIce, ingredientCategoryMilk,
ingredientCategoryEspresso, ingredientCategoryCocoaNibs);
addToSeasonSpecial(productColdFoamCascaraColdBrew);
// 2
Product productColdFoamCascaraNitro = createProduct("Cold Foam Cascara Nitro",
"Our velvety-smooth Nitro Cold Brew served cold, straight from the tap, is capped with Cascara flavored Cold Foam for subtle notes of dark brown sugar. Our most craveable cup of Nitro Cold Brew yet.",
new BigDecimal(37), categoryDrinks, createNutrition(60, 0, 12, 0, 1, 20));
enableProductIngredient(productColdFoamCascaraNitro,
ingredientCategorySize, ingredientCategorySweetness, ingredientCategoryIce, ingredientCategoryMilk,
ingredientCategoryCream, ingredientCategoryEspresso, ingredientCategoryCocoaNibs);
addToSeasonSpecial(productColdFoamCascaraNitro);
// 3
Product productIcedCoffee = createProduct("Iced Coffee",
"Freshly brewed Starbucks Iced Coffee Blend served chilled and lightly sweetened over ice",
new BigDecimal(30), categoryDrinks, createNutrition(0, 0, 0, 0, 0, 0));
enableProductIngredient(productIcedCoffee,
ingredientCategorySize, ingredientCategorySweetness, ingredientCategoryIce, ingredientCategoryCream,
ingredientCategoryEspresso, ingredientCategorySyrup, ingredientCategoryCocoaNibs);
addToSeasonSpecial(productIcedCoffee);
// 4
Product productIcedCoffeeWithMilk = createProduct("Iced Coffee with Milk",
"Freshly brewed Starbucks Iced Coffee Blend with milk - served chilled and lightly sweetened over ice.",
new BigDecimal(35), categoryDrinks, null);
enableProductIngredient(productIcedCoffeeWithMilk,
ingredientCategorySize, ingredientCategorySweetness, ingredientCategoryIce, ingredientCategoryMilk,
ingredientCategoryCream, ingredientCategoryEspresso, ingredientCategorySyrup, ingredientCategoryCocoaNibs);
// 5
Product productNitroColdBrew = createProduct("Nitro Cold Brew",
"Our small-batch cold brew - slow-steeped for a super smooth taste—gets even better. We're infusing it with nitrogen for a naturally sweet flavor and cascading, velvety crema. Perfection is served.",
new BigDecimal(36), categoryDrinks, createNutrition(5, 0, 0, 0, 0, 10));
enableProductIngredient(productNitroColdBrew,
ingredientCategorySweetness, ingredientCategoryIce, ingredientCategoryCream, ingredientCategorySyrup);
//6
Product productNitroColdBrewwithSweetCream = createProduct("Nitro Cold Brew with Sweet Cream",
"Served cold, straight from the tap, our Nitro Cold Brew is topped with a float of house-made vanilla sweet cream. The result is a subtly-sweet cascade of velvety coffee that is more sippable than ever.",
new BigDecimal(38), categoryDrinks, createNutrition(70, 5, 5, 0, 1, 15));
enableProductIngredient(productNitroColdBrewwithSweetCream,
ingredientCategorySize, ingredientCategorySweetness, ingredientCategoryIce, ingredientCategoryMilk,
ingredientCategoryEspresso, ingredientCategorySyrup, ingredientCategoryCocoaNibs);
// 7
Product productColdBrewCoffee = createProduct("Cold Brew Coffee",
"Our custom blend of beans are grown to steep long and cold for a super-smooth flavor. Starbucks Cold brew is handcrafted in small batches daily, slow-steeped in cool water for 20 hours, without touching heat.",
new BigDecimal(30), categoryDrinks, createNutrition(5, 0, 0, 0, 0, 10));
enableProductIngredient(productColdBrewCoffee,
ingredientCategorySweetness, ingredientCategoryIce, ingredientCategoryCream,
ingredientCategoryEspresso, ingredientCategorySyrup, ingredientCategoryCocoaNibs);
// 8
Product productColdBrewCoffeeWithMilk = createProduct("Cold Brew Coffee with Milk",
"Our custom blend of beans are grown to steep long and cold for a super-smooth flavor. Starbucks Cold brew is handcrafted in small batches daily, slow-steeped in cool water for 20 hours, without touching heat and finished with a splash of milk.",
new BigDecimal(33), categoryDrinks, createNutrition(0, 0, 0, 0, 0, 10));
enableProductIngredient(productColdBrewCoffeeWithMilk,
ingredientCategorySweetness, ingredientCategoryIce, ingredientCategoryMilk, ingredientCategoryCream,
ingredientCategoryEspresso, ingredientCategorySyrup, ingredientCategoryCocoaNibs);
// 9
Product productVanillaSweetCreamColdBrew = createProduct("Vanilla Sweet Cream Cold Brew",
"Just before serving, our slow-steeped custom blend Starbucks? Cold Brew Coffee is topped with a delicate float of house-made vanilla sweet cream that cascades throughout the cup.",
new BigDecimal(35), categoryDrinks, createNutrition(100, 6, 12, 0, 1, 20));
enableProductIngredient(productVanillaSweetCreamColdBrew,
ingredientCategorySweetness, ingredientCategoryIce, ingredientCategoryMilk,
ingredientCategoryEspresso, ingredientCategorySyrup, ingredientCategoryCocoaNibs);
// 10
Product productHotChocolate = createProduct("Hot Chocolate",
"Steamed milk with vanilla- and mocha-flavored syrups. Topped with sweetened whipped cream and chocolate-flavored drizzle.",
new BigDecimal(32), categoryDrinks, createNutrition(250, 7, 37, 3, 11, 125));
enableProductIngredient(productHotChocolate,
ingredientCategorySize, ingredientCategorySweetness, ingredientCategoryMilk, ingredientCategoryCream,
ingredientCategoryEspresso, ingredientCategorySyrup, ingredientCategoryCocoaNibs);
// 11
Product productSaltedCaramelHotChocolate = createProduct("Salted Caramel Hot Chocolate",
"Steamed milk and mocha sauce are combined with toffee nut and vanilla syrups, then topped with sweetened whipped cream, caramel sauce and a blend of turbinado sugar and sea salt. The sweet is never as sweet without the salt.",
new BigDecimal(38), categoryDrinks, createNutrition(300, 7, 51, 3, 10, 220));
enableProductIngredient(productSaltedCaramelHotChocolate,
ingredientCategorySize, ingredientCategoryMilk, ingredientCategoryCream, ingredientCategoryEspresso,
ingredientCategoryCocoaNibs);
// 12
Product productSteamedAppleJuice = createProduct("Steamed Apple Juice",
"Freshly steamed 100% pressed apple juice (not from concentrate).",
new BigDecimal(33), categoryDrinks, null);
enableProductIngredient(productSteamedAppleJuice,
ingredientCategorySize, ingredientCategorySweetness, ingredientCategoryIce);
// 13
Product productMangoDragonfruitLemonade = createProduct("Mango Dragonfruit Lemonade",
"This tropical-inspired pick-me-up is crafted with a clever combination of vibrant lemonade, sweet mango and refreshing dragonfruit flavors, then handshaken with ice and a scoop of real diced dragon fruit.",
new BigDecimal(32), categoryDrinks, createNutrition(110, 0, 26, 0, 0, 10));
enableProductIngredient(productMangoDragonfruitLemonade,
ingredientCategorySize, ingredientCategorySweetness, ingredientCategoryIce);
// 14
Product productMangoDragonfruit = createProduct("Mango Dragonfruit",
"This tropical-inspired pick-me-up is crafted with a refreshing combination of sweet mango and dragonfruit flavors, handshaken with ice and a scoop of real diced dragon fruit.",
new BigDecimal(32), categoryDrinks, createNutrition(70, 0, 17, 0, 0, 10));
enableProductIngredient(productMangoDragonfruit,
ingredientCategorySize, ingredientCategorySweetness, ingredientCategoryIce);
// 15
Product productStrawberryAcaiLemonade = createProduct("Strawberry Acai Lemonade",
"Sweet strawberry flavors, passion fruit and acai notes are balanced with the delightful zing of lemonade. Caffeinated with Green Coffee Extract and served over ice, this is the pick-me-up your afternoon is calling for.",
new BigDecimal(32), categoryDrinks, createNutrition(110, 0, 27, 1, 0, 10));
enableProductIngredient(productStrawberryAcaiLemonade,
ingredientCategorySize, ingredientCategorySweetness, ingredientCategoryIce);
Product productChongaBagel = createProduct("Chonga Bagel",
"A bagel topped with Cheddar cheese, poppy seeds, sesame seeds, onion and garlic.",
new BigDecimal(18), categoryFood, createNutrition(300, 5, 50, 3, 12, 530));
Product productGrainRoll = createProduct("Grain Roll",
"A wholesome multigrain roll with raisins.",
new BigDecimal(16), categoryFood, createNutrition(380, 6, 70, 7, 10, 480));
Product productAlmondCroissant = createProduct("Almond Croissant",
"Our rich, almond flan is enveloped in a flaky, buttery croissant, then topped with sliced almonds. It's the perfect combination of sweet and savory.",
new BigDecimal(15), categoryFood, createNutrition(410, 22, 45, 3, 10, 390));
Product productAppleCiderDoughnut = createProduct("Apple Cider Doughnut",
"Our secret ingredient to this doughnut's bright flavor? Apple cider. This pastry is then slathered with sweet vanilla icing and a dusting of turbinado sanding sugar for a lovely crunch.",
new BigDecimal(18), categoryFood, createNutrition(400, 17, 59, 1, 4, 320));
Product productBananaNutBread = createProduct("Banana Nut Bread",
"Bananas, walnuts and pecans in moist, nutty, classic banana bread.",
new BigDecimal(15), categoryFood, createNutrition(420, 22, 52, 2, 6, 320));
Product productBlueberryMuffin = createProduct("Blueberry Muffin",
"This delicious muffin is dotted throughout with sweet, juicy blueberries and a hint of lemon. We dust the top with granulated sugar for a delightfully crunchy texture.",
new BigDecimal(16), categoryFood, createNutrition(360, 15, 52, 1, 5, 270));
Product productBlueberryScone = createProduct("Blueberry Scone",
"A traditional scone with blueberries, buttermilk and lemon.",
new BigDecimal(20), categoryFood, createNutrition(380, 17, 54, 2, 6, 350));
Product productButterCroissant = createProduct("Butter Croissant",
"This classic Croissant is made with 100 percent butter to create a golden, crunchy top and soft, flakey layers inside. The perfect match for a cup of Pike Place Roast.",
new BigDecimal(14), categoryFood, createNutrition(260, 15, 27, 1, 5, 320));
Product productFallBlend = createProduct("Fall Blend",
"All the flavors of fall are blended for a cup of something worth savoring.",
new BigDecimal(188), categoryCoffeeBean, null);
Product productPumpkinSpice = createProduct("Pumpkin Spice",
"Add a splash of cream and a bit of sugar to evoke deliciously familiar fall flavors inspired by our Pumpkin Spice Latte.",
new BigDecimal(198), categoryCoffeeBean, null);
Product productBrightSkyBlend = createProduct("Bright Sky Blend",
"A gentle and well-rounded Starbucks Blonde Roast coffee with hints of nut and nice acidity.",
new BigDecimal(188), categoryCoffeeBean, null);
Product productVerandaBlend = createProduct("Veranda Blend",
"Subtle with delicate nuances of soft cocoa and lightly toasted nuts.",
new BigDecimal(208), categoryCoffeeBean, null);
Product productOrganicYukonBlend = createProduct("Organic Yukon Blend",
"Bold, lively, and adventurous coffee with deep and hearty taste to make an all-around great cup of coffee.",
new BigDecimal(198), categoryCoffeeBean, null);
Product productClassicDoubleWallGlassMug = createProduct("Classic Double Wall Glass Mug",
"Classic Double Wall Glass Mug",
new BigDecimal(88), categoryCup, null);
Product productClassicSirenTumbler = createProduct("Classic Siren Tumbler",
"Classic Siren Tumbler",
new BigDecimal(88), categoryCup, null);
Product productStarrySkyStainlessSteelColdCup = createProduct("Starry Sky Stainless Steel Cold Cup",
"Starry Sky Stainless Steel Cold Cup",
new BigDecimal(78), categoryCup, null);
Product productHarvestWheatStainlessSteelTumbler = createProduct("Harvest Wheat Stainless Steel Tumbler",
"Harvest Wheat Stainless Steel Tumbler",
new BigDecimal(78), categoryCup, null);
Product productCopperStainlessSteelColdCup = createProduct("Copper Stainless Steel Cold Cup",
"Copper Stainless Steel Cold Cup",
new BigDecimal(98), categoryCup, null);
UserInfo userLuShijun = userManager.addCustomer("lushijun", "test", "Lu Shijun");
customerInfoManager.addAddress(userLuShijun.getCustomer(),
"China", "Beijing", "Beijing", "Haidian",
"Xue 5 Beijing University of Posts and Telecommunications 10 Xitucheng Rd.",
"Lu Shijun", "+86 111 1111 1111");
customerInfoManager.addAddress(userLuShijun.getCustomer(),
"China", "Guangxi", "Nanning", "Qingxiu",
"10 Yun Jing Lu",
"Lu Shijun", "+86 111 1111 1111");
UserInfo userWangNianyi = userManager.addCustomer("wangnianyi", "test", "Wang Nianyi");
customerInfoManager.addAddress(userWangNianyi.getCustomer(),
"China", "Beijing", "Beijing", "Haidian",
"Xue 5 Beijing University of Posts and Telecommunications 10 Xitucheng Rd.",
"Wang Nianyi", "+86 222 2222 2222");
Store storeBupt = storeManager.addStore("China", "Beijing", "Beijing", "Haidian",
"BUPT Flagship Beijing University of Posts and Telecommunications 10 Xitucheng Rd");
Store storeBnu = storeManager.addStore("China", "Beijing", "Beijing", "Haidian",
"BNU 19 Xinjiekouwaidajie");
UserInfo userRenyaoDanjun = userManager.addStaff("renyaodanjun", "test", storeBupt);
UserInfo userMaZuanjie = userManager.addStaff("mazuanjie", "test", storeBnu);
}
private Product createProduct(String name, String description,
BigDecimal price, Category category, Nutrition nutrition)
throws IOException, URISyntaxException {
Product product = new Product();
product.setName(name);
product.setDescription(description);
product.setCost(price);
product.setCategoryId(category);
product.setNutritionId(nutrition);
product.setLastUpdate(new Date());
product.setIsAvailable((short)1);
Image image = createImage(category.getName(), name);
product.setImageUuid(image);
image.setProduct(product);
product.setIngredientCategoryList(new ArrayList<>());
category.getProductList().add(product);
productFacade.create(product);
imageFacade.edit(image);
categoryFacade.edit(category);
return product;
}
private Nutrition createNutrition(int calories, int fat, int carton, int fiber, int protein, int sodium) {
Nutrition nutrition = new Nutrition();
nutrition.setCalories(calories);
nutrition.setFat(fat);
nutrition.setCarbon(carton);
nutrition.setProtein(protein);
nutrition.setFiber(fiber);
nutrition.setSodium(sodium);
nutritionFacade.create(nutrition);
return nutrition;
}
private Category createCategory(String name) {
Category category = new Category(null, name);
category.setProductList(new ArrayList<>());
categoryFacade.create(category);
return category;
}
private IngredientCategory createIngredientCategory(String name) {
IngredientCategory ingredientCategory = new IngredientCategory();
ingredientCategory.setName(name);
ingredientCategory.setIngredientList(new ArrayList<>());
ingredientCategory.setProductList(new ArrayList<>());
ingredientCategoryFacade.create(ingredientCategory);
return ingredientCategory;
}
private Ingredient createIngredient(String name, String description,
BigDecimal cost, IngredientCategory ingredientCategory) {
Ingredient ingredient = new Ingredient();
ingredient.setName(name);
ingredient.setDescription(description);
ingredient.setCost(cost);
ingredient.setIngredientCategoryId(ingredientCategory);
ingredientCategory.getIngredientList().add(ingredient);
ingredientFacade.create(ingredient);
ingredientCategoryFacade.edit(ingredientCategory);
return ingredient;
}
private void enableProductIngredient(Product product, IngredientCategory... categories) {
product.getIngredientCategoryList().addAll(Arrays.asList(categories));
for (IngredientCategory category : categories) {
category.getProductList().add(product);
}
for (IngredientCategory category : categories) {
ingredientCategoryFacade.edit(category);
}
productFacade.edit(product);
}
private byte[] readResourceFile(String name) throws IOException, URISyntaxException {
LOG.log(Level.INFO, "About to read resource image: {0}", name);
ClassLoader classLoader = getClass().getClassLoader();
return Files.readAllBytes(Paths.get(classLoader.getResource(name).toURI()));
}
private Image createImage(String category, String product) throws IOException, URISyntaxException {
Image image = new Image();
image.setContent(readResourceFile("coffeeshop/setup/images/"
+ category + "/" + product + ".jpg"));
image.setMediaType("image/jpeg");
String uuid = null;
do {
uuid = UUID.randomUUID().toString();
} while (imageFacade.find(uuid) != null);
image.setUuid(uuid);
imageFacade.create(image);
return image;
}
private void addToSeasonSpecial(Product product) {
SeasonSpecial special = new SeasonSpecial();
special.setProduct(product);
product.setSeasonSpecial(special);
seasonSpecialFacade.create(special);
productFacade.edit(product);
}
}
| 59.155814 | 262 | 0.702166 |
42645e0a132dacfd7a70aff34bd0439565516611 | 5,630 | /*
* XML Type: SecurityPrincipal
* Namespace: http://schemas.microsoft.com/crm/2006/CoreTypes
* Java type: com.microsoft.schemas.crm._2006.coretypes.SecurityPrincipal
*
* Automatically generated - do not modify.
*/
package com.microsoft.schemas.crm._2006.coretypes.impl;
/**
* An XML SecurityPrincipal(@http://schemas.microsoft.com/crm/2006/CoreTypes).
*
* This is a complex type.
*/
public class SecurityPrincipalImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements com.microsoft.schemas.crm._2006.coretypes.SecurityPrincipal
{
public SecurityPrincipalImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName PRINCIPALID$0 =
new javax.xml.namespace.QName("http://schemas.microsoft.com/crm/2006/CoreTypes", "PrincipalId");
private static final javax.xml.namespace.QName TYPE$2 =
new javax.xml.namespace.QName("http://schemas.microsoft.com/crm/2006/CoreTypes", "Type");
/**
* Gets the "PrincipalId" element
*/
public java.lang.String getPrincipalId()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(PRINCIPALID$0, 0);
if (target == null)
{
return null;
}
return target.getStringValue();
}
}
/**
* Gets (as xml) the "PrincipalId" element
*/
public com.microsoft.wsdl.types.Guid xgetPrincipalId()
{
synchronized (monitor())
{
check_orphaned();
com.microsoft.wsdl.types.Guid target = null;
target = (com.microsoft.wsdl.types.Guid)get_store().find_element_user(PRINCIPALID$0, 0);
return target;
}
}
/**
* Sets the "PrincipalId" element
*/
public void setPrincipalId(java.lang.String principalId)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(PRINCIPALID$0, 0);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(PRINCIPALID$0);
}
target.setStringValue(principalId);
}
}
/**
* Sets (as xml) the "PrincipalId" element
*/
public void xsetPrincipalId(com.microsoft.wsdl.types.Guid principalId)
{
synchronized (monitor())
{
check_orphaned();
com.microsoft.wsdl.types.Guid target = null;
target = (com.microsoft.wsdl.types.Guid)get_store().find_element_user(PRINCIPALID$0, 0);
if (target == null)
{
target = (com.microsoft.wsdl.types.Guid)get_store().add_element_user(PRINCIPALID$0);
}
target.set(principalId);
}
}
/**
* Gets the "Type" element
*/
public com.microsoft.schemas.crm._2006.coretypes.SecurityPrincipalType.Enum getType()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(TYPE$2, 0);
if (target == null)
{
return null;
}
return (com.microsoft.schemas.crm._2006.coretypes.SecurityPrincipalType.Enum)target.getEnumValue();
}
}
/**
* Gets (as xml) the "Type" element
*/
public com.microsoft.schemas.crm._2006.coretypes.SecurityPrincipalType xgetType()
{
synchronized (monitor())
{
check_orphaned();
com.microsoft.schemas.crm._2006.coretypes.SecurityPrincipalType target = null;
target = (com.microsoft.schemas.crm._2006.coretypes.SecurityPrincipalType)get_store().find_element_user(TYPE$2, 0);
return target;
}
}
/**
* Sets the "Type" element
*/
public void setType(com.microsoft.schemas.crm._2006.coretypes.SecurityPrincipalType.Enum type)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(TYPE$2, 0);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(TYPE$2);
}
target.setEnumValue(type);
}
}
/**
* Sets (as xml) the "Type" element
*/
public void xsetType(com.microsoft.schemas.crm._2006.coretypes.SecurityPrincipalType type)
{
synchronized (monitor())
{
check_orphaned();
com.microsoft.schemas.crm._2006.coretypes.SecurityPrincipalType target = null;
target = (com.microsoft.schemas.crm._2006.coretypes.SecurityPrincipalType)get_store().find_element_user(TYPE$2, 0);
if (target == null)
{
target = (com.microsoft.schemas.crm._2006.coretypes.SecurityPrincipalType)get_store().add_element_user(TYPE$2);
}
target.set(type);
}
}
}
| 34.329268 | 168 | 0.581883 |
ba9bfa689845ce8e514edfa9345618d6f7dec5cf | 3,744 | /*
* Copyright 2019-2022 The Polypheny Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.polypheny.db.sql.sql.ddl.altertable;
import static org.polypheny.db.util.Static.RESOURCE;
import java.util.List;
import java.util.Objects;
import org.polypheny.db.adapter.DataStore;
import org.polypheny.db.catalog.Catalog.TableType;
import org.polypheny.db.catalog.entity.CatalogTable;
import org.polypheny.db.ddl.DdlManager;
import org.polypheny.db.ddl.exception.LastPlacementException;
import org.polypheny.db.ddl.exception.PlacementNotExistsException;
import org.polypheny.db.languages.ParserPos;
import org.polypheny.db.languages.QueryParameters;
import org.polypheny.db.nodes.Node;
import org.polypheny.db.prepare.Context;
import org.polypheny.db.sql.sql.SqlIdentifier;
import org.polypheny.db.sql.sql.SqlNode;
import org.polypheny.db.sql.sql.SqlWriter;
import org.polypheny.db.sql.sql.ddl.SqlAlterTable;
import org.polypheny.db.transaction.Statement;
import org.polypheny.db.util.CoreUtil;
import org.polypheny.db.util.ImmutableNullableList;
/**
* Parse tree for {@code ALTER TABLE name DROP PLACEMENT ON STORE storeName} statement.
*/
public class SqlAlterTableDropPlacement extends SqlAlterTable {
private final SqlIdentifier table;
private final SqlIdentifier storeName;
public SqlAlterTableDropPlacement( ParserPos pos, SqlIdentifier table, SqlIdentifier storeName ) {
super( pos );
this.table = Objects.requireNonNull( table );
this.storeName = Objects.requireNonNull( storeName );
}
@Override
public List<Node> getOperandList() {
return ImmutableNullableList.of( table, storeName );
}
@Override
public List<SqlNode> getSqlOperandList() {
return ImmutableNullableList.of( table, storeName );
}
@Override
public void unparse( SqlWriter writer, int leftPrec, int rightPrec ) {
writer.keyword( "ALTER" );
writer.keyword( "TABLE" );
table.unparse( writer, leftPrec, rightPrec );
writer.keyword( "DROP" );
writer.keyword( "PLACEMENT" );
writer.keyword( "ON" );
writer.keyword( "STORE" );
storeName.unparse( writer, leftPrec, rightPrec );
}
@Override
public void execute( Context context, Statement statement, QueryParameters parameters ) {
CatalogTable catalogTable = getCatalogTable( context, table );
DataStore storeInstance = getDataStoreInstance( storeName );
if ( catalogTable.tableType != TableType.TABLE ) {
throw new RuntimeException( "Not possible to use ALTER TABLE because " + catalogTable.name + " is not a table." );
}
try {
DdlManager.getInstance().dropDataPlacement( catalogTable, storeInstance, statement );
} catch ( PlacementNotExistsException e ) {
throw CoreUtil.newContextException(
storeName.getPos(),
RESOURCE.placementDoesNotExist( catalogTable.name, storeName.getSimple() ) );
} catch ( LastPlacementException e ) {
throw CoreUtil.newContextException(
storeName.getPos(),
RESOURCE.onlyOnePlacementLeft() );
}
}
}
| 34.990654 | 126 | 0.707799 |
b3d26b062d0a5196490664010026a3cddd99b150 | 10,582 | /*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.netconf.device.impl;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.onlab.util.Tools.delay;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.slf4j.Logger;
import com.tailf.jnc.Capabilities;
import com.tailf.jnc.JNCException;
import com.tailf.jnc.SSHConnection;
import com.tailf.jnc.SSHSession;
/**
* This is a logical representation of actual NETCONF device, carrying all the
* necessary information to connect and execute NETCONF operations.
*/
public class NetconfDevice {
private final Logger log = getLogger(NetconfDevice.class);
/**
* The Device State is used to determine whether the device is active or
* inactive. This state infomation will help Device Creator to add or delete
* the device from the core.
*/
public static enum DeviceState {
/* Used to specify Active state of the device */
ACTIVE,
/* Used to specify inactive state of the device */
INACTIVE,
/* Used to specify invalid state of the device */
INVALID
}
private static final int DEFAULT_SSH_PORT = 22;
private static final int DEFAULT_CON_TIMEOUT = 0;
private static final String XML_CAPABILITY_KEY = "capability";
private static final int EVENTINTERVAL = 2000;
private static final int CONNECTION_CHECK_INTERVAL = 3;
private static final String INPUT_HELLO_XML_MSG = new StringBuilder(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.append("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">")
.append("<capabilities><capability>urn:ietf:params:netconf:base:1.0</capability>")
.append("</capabilities></hello>").toString();
private String sshHost;
private int sshPort = DEFAULT_SSH_PORT;
private int connectTimeout = DEFAULT_CON_TIMEOUT;
private String username;
private String password;
private boolean reachable = false;
private List<String> capabilities = new ArrayList<String>();
private SSHConnection sshConnection = null;
private DeviceState deviceState = DeviceState.INVALID;
protected NetconfDevice(String sshHost, int sshPort, String username,
String password) {
this.username = checkNotNull(username,
"Netconf Username Cannot be null");
this.sshHost = checkNotNull(sshHost, "Netconf Device IP cannot be null");
this.sshPort = checkNotNull(sshPort,
"Netconf Device SSH port cannot be null");
this.password = password;
}
/**
* This will try to connect to NETCONF device and find all the capabilities.
*
* @throws Exception if unable to connect to the device
*/
// FIXME: this should not be a generic Exception; perhaps wrap in some RuntimeException
public void init() throws Exception {
try {
if (sshConnection == null) {
sshConnection = new SSHConnection(sshHost, sshPort, connectTimeout);
sshConnection.authenticateWithPassword(username, password);
}
// Send hello message to retrieve capabilities.
} catch (IOException e) {
log.error("Fatal Error while creating connection to the device: "
+ deviceInfo(), e);
throw e;
} catch (JNCException e) {
log.error("Failed to connect to the device: " + deviceInfo(), e);
throw e;
}
hello();
}
private void hello() {
SSHSession ssh = null;
try {
ssh = new SSHSession(sshConnection);
String helloRequestXML = INPUT_HELLO_XML_MSG.trim();
log.debug("++++++++++++++++++++++++++++++++++Sending Hello: "
+ sshConnection.getGanymedConnection().getHostname()
+ "++++++++++++++++++++++++++++++++++");
printPrettyXML(helloRequestXML);
ssh.print(helloRequestXML);
// ssh.print(endCharSeq);
ssh.flush();
String xmlResponse = null;
int i = CONNECTION_CHECK_INTERVAL;
while (!ssh.ready() && i > 0) {
delay(EVENTINTERVAL);
i--;
}
if (ssh.ready()) {
StringBuffer readOne = ssh.readOne();
if (readOne == null) {
log.error("The Hello Contains No Capabilites");
throw new JNCException(
JNCException.SESSION_ERROR,
"server does not support NETCONF base capability: "
+ Capabilities.NETCONF_BASE_CAPABILITY);
} else {
xmlResponse = readOne.toString().trim();
log.debug("++++++++++++++++++++++++++++++++++Reading Capabilities: "
+ sshConnection.getGanymedConnection()
.getHostname()
+ "++++++++++++++++++++++++++++++++++");
printPrettyXML(xmlResponse);
processCapabilities(xmlResponse);
}
}
reachable = true;
} catch (IOException e) {
log.error("Fatal Error while sending Hello Message to the device: "
+ deviceInfo(), e);
} catch (JNCException e) {
log.error("Fatal Error while sending Hello Message to the device: "
+ deviceInfo(), e);
} finally {
log.debug("Closing the session after successful execution");
if (ssh != null) {
ssh.close();
}
}
}
private void processCapabilities(String xmlResponse) throws JNCException {
if (xmlResponse.isEmpty()) {
log.error("The capability response cannot be empty");
throw new JNCException(
JNCException.SESSION_ERROR,
"server does not support NETCONF base capability: "
+ Capabilities.NETCONF_BASE_CAPABILITY);
}
try {
Document doc = new SAXBuilder()
.build(new StringReader(xmlResponse));
Element rootElement = doc.getRootElement();
processCapabilities(rootElement);
} catch (Exception e) {
log.error("ERROR while parsing the XML " + xmlResponse);
}
}
private void processCapabilities(Element rootElement) {
List<Element> children = rootElement.getChildren();
if (children.isEmpty()) {
return;
}
for (Element child : children) {
if (child.getName().equals(XML_CAPABILITY_KEY)) {
capabilities.add(child.getValue());
}
if (!child.getChildren().isEmpty()) {
processCapabilities(child);
}
}
}
private void printPrettyXML(String xmlstring) {
try {
Document doc = new SAXBuilder().build(new StringReader(xmlstring));
XMLOutputter xmOut = new XMLOutputter(Format.getPrettyFormat());
String outputString = xmOut.outputString(doc);
log.debug(outputString);
} catch (Exception e) {
log.error("ERROR while parsing the XML " + xmlstring, e);
}
}
/**
* This would return host IP and host Port, used by this particular Netconf
* Device.
* @return Device Information.
*/
public String deviceInfo() {
return new StringBuilder("host: ").append(sshHost).append(". port: ")
.append(sshPort).toString();
}
/**
* This will terminate the device connection.
*/
public void disconnect() {
sshConnection.close();
reachable = false;
}
/**
* This will list down all the capabilities supported on the device.
* @return Capability list.
*/
public List<String> getCapabilities() {
return capabilities;
}
/**
* This api is intended to know whether the device is connected or not.
* @return true if connected
*/
public boolean isReachable() {
return reachable;
}
/**
* This will return the IP used connect ssh on the device.
* @return Netconf Device IP
*/
public String getSshHost() {
return sshHost;
}
/**
* This will return the SSH Port used connect the device.
* @return SSH Port number
*/
public int getSshPort() {
return sshPort;
}
/**
* The usename used to connect Netconf Device.
* @return Device Username
*/
public String getUsername() {
return username;
}
/**
* Retrieve current state of the device.
* @return Current Device State
*/
public DeviceState getDeviceState() {
return deviceState;
}
/**
* This is set the state information for the device.
* @param deviceState Next Device State
*/
public void setDeviceState(DeviceState deviceState) {
this.deviceState = deviceState;
}
/**
* Check whether the device is in Active state.
* @return true if the device is Active
*/
public boolean isActive() {
return deviceState == DeviceState.ACTIVE ? true : false;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
}
| 34.695082 | 117 | 0.58127 |
da51b39358de0e42356cf8344e7911e9ff5ac0c2 | 213 | package cn.medemede.leecode.demos;
public interface ThreadPool {
void execute(Runnable job);
void addWorksNum(int num);
void removeWorksNum(int num);
void shutDown();
int getJobSize();
}
| 14.2 | 34 | 0.685446 |
b61d07abc4767c65793db5cede25abf167d39d70 | 1,274 | package com.bah.ode.filter;
import java.util.List;
import com.bah.ode.model.HasKey;
import com.bah.ode.model.OdeFilterable;
import com.bah.ode.model.OdeMetadata;
import com.bah.ode.model.OdeRoadSegment;
public class KeyFilter extends BaseFilter {
private List<OdeRoadSegment> segments;
public KeyFilter() {
super();
}
public KeyFilter(OdeMetadata metadata) {
super();
setMetadata(metadata);
}
@Override
public boolean pass(OdeFilterable data) {
if (data instanceof HasKey) {
HasKey hasKey = (HasKey) data;
if (segments != null && hasKey.getKey() != null && !hasKey.getKey().isEmpty()) {
for (OdeRoadSegment segment : segments){
if (hasKey.getKey().equalsIgnoreCase(segment.getId()))
return true;
}
return false;
}
}
return true;
}
@Override
public BaseFilter setMetadata(OdeMetadata metadata) {
super.setMetadata(metadata);
if (getMetadata() != null &&
getMetadata().getOdeRequest() != null &&
getMetadata().getOdeRequest().getPolyline() != null) {
segments = getMetadata().getOdeRequest().getPolyline().getSegments();
}
return this;
}
}
| 25.48 | 89 | 0.610675 |
bb861d0390373bf5ba335d833e0764387f670d86 | 648 | package com.wy.netty.chat.model;
public interface ResultCode {
/**
* 成功
*/
int SUCCESS = 0;
/**
* 找不到命令
*/
int NO_INVOKER = 1;
/**
* 参数异常
*/
int AGRUMENT_ERROR = 2;
/**
* 未知异常
*/
int UNKOWN_EXCEPTION = 3;
/**
* 玩家名或密码不能为空
*/
int PLAYERNAME_NULL = 4;
/**
* 玩家名已使用
*/
int PLAYER_EXIST = 5;
/**
* 玩家不存在
*/
int PLAYER_NO_EXIST = 6;
/**
* 密码错误
*/
int PASSWARD_ERROR = 7;
/**
* 您已登录
*/
int HAS_LOGIN = 8;
/**
* 登录失败
*/
int LOGIN_FAIL = 9;
/**
* 玩家不在线
*/
int PLAYER_NO_ONLINE = 10;
/**
* 请先登录
*/
int LOGIN_PLEASE = 11;
/**
* 不能私聊自己
*/
int CAN_CHAT_YOUSELF = 12;
} | 9.391304 | 32 | 0.516975 |
02438070666eaf800582c93e7b7f13ba28f5e456 | 1,142 | package org.spring.seek.domain;
import java.util.List;
import org.springframework.data.util.Streamable;
/**
* The result of a {@link SeekRequest}. Contains class holding the records retrieved from the
* database.
*
* @author Elliot Ball
*/
public interface SeekResult<T> {
/**
* Returns the content of the SEEK result content as a list.
*
* @return the content
*/
List<T> getContent();
/**
* Returns the total number of elements returned by the {@link SeekResult}.
*
* @return the total number of elements in this {@link SeekResult}
*/
long getTotalElements();
/**
* Returns true if the content returned from tge SEEK request has any content.
*
* @return true if the content list has any elements, else false
*/
boolean hasResults();
/**
* Fetches the next 'page' of content with a given limit. Automatically determines the {@link
* SeekRequest#getLastSeenId()} from the {@link SeekResult#getContent()}
*
* @param limit the maximum number of records to fetch
* @return a new {@link SeekRequest} to fetch the next 'page'
*/
SeekRequest getNextPage(int limit);
}
| 25.954545 | 95 | 0.686515 |
2e86b40c95c7d13b348431c7ef9c743c0b72d5ed | 371 | package io.github.forezp.netty.rpc.core.monitor.warm;
/**
* Email miles02@163.com
*
* @author fangzhipeng
* create 2018-06-22
**/
public class TimeoutEvent extends Event {
private String messageId;
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
}
| 17.666667 | 53 | 0.668464 |
dcf831638d7393a04665a8e9aa4f777da503c566 | 1,083 | package jp.westbrook.android.testappjava;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menuItem_settings:
return onSettings();
}
return super.onOptionsItemSelected(item);
}
private boolean onSettings() {
Intent intent = new Intent(getApplication(), SettingsActivity.class);
startActivity(intent);
return true;
}
}
| 27.075 | 77 | 0.697138 |
7f9d106ec44fd5e8e3a3bd1ac173aa833baf596a | 218 | package com.talmacel.iosif.wearebase.models;
import java.io.Serializable;
/**
* Created by Iosif on 18/03/2018.
*/
public class UrlData implements Serializable {
public String url;
public String website;
} | 18.166667 | 46 | 0.733945 |
c2dca799545acb5921f5b8b59db0f9fdce9ab1c3 | 1,854 | package com.intuit.wasabi.api;
import com.intuit.wasabi.authenticationobjects.UserInfo.Username;
import com.intuit.wasabi.email.EmailLinksList;
import com.intuit.wasabi.email.EmailService;
import com.intuit.wasabi.experimentobjects.Application;
import org.eclipse.jetty.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import javax.ws.rs.core.Response;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class EmailResourceTest {
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
EmailService mock;
EmailResource resource;
@Before
public void setUp() {
resource = new EmailResource(mock, new HttpHeader("apbcc", "600"));
}
@Test
public void testSendEmailServiceNotActive() {
when(mock.isActive()).thenReturn(false);
Response result = resource.postEmail(Application.Name.valueOf("a1"), Username.valueOf("u1"),
EmailLinksList.newInstance().build());
assertThat(result.getEntity(), is("The email service is not activated at the moment."));
assertThat(result.getStatus(), is(HttpStatus.SERVICE_UNAVAILABLE_503));
}
@Test
public void testSendEmailServiceActive() {
when(mock.isActive()).thenReturn(true);
Response result = resource.postEmail(Application.Name.valueOf("a1"), Username.valueOf("u1"),
EmailLinksList.newInstance().build());
assertThat(result.getEntity(), is("An email has been sent to the administrators of a1 to ask for access for user u1 with links "));
assertThat(result.getStatus(), is(HttpStatus.OK_200));
}
}
| 35.653846 | 139 | 0.730852 |
6b9f494992f809de7f095670fc560658a33efe16 | 2,514 | /*
* Copyright (c) 2015 EMC Corporation
* All Rights Reserved
*/
package com.emc.storageos.volumecontroller.impl.smis;
import java.net.URI;
import java.util.List;
import com.emc.storageos.db.client.model.StorageSystem;
import com.emc.storageos.exceptions.DeviceControllerException;
import com.emc.storageos.volumecontroller.TaskCompleter;
/**
* Interface for block mirror operations.
* - Operations for create
*/
public interface MirrorOperations {
public static final String CREATE_ERROR_MSG_FORMAT = "Failed to create single mirror %s";
public static final String DETACH_ERROR_MSG_FORMAT = "Failed to detach mirror %s from source %s";
void createSingleVolumeMirror(StorageSystem storage, URI mirror, Boolean createInactive, TaskCompleter taskCompleter)
throws DeviceControllerException;
void fractureSingleVolumeMirror(StorageSystem storage, URI mirror, Boolean sync, TaskCompleter taskCompleter)
throws DeviceControllerException;
void resumeSingleVolumeMirror(StorageSystem storage, URI mirror, TaskCompleter taskCompleter) throws DeviceControllerException;
void establishVolumeNativeContinuousCopyGroupRelation(StorageSystem storage, URI sourceVolume,
URI mirror, TaskCompleter taskCompleter) throws DeviceControllerException;
void detachSingleVolumeMirror(StorageSystem storage, URI mirror, TaskCompleter taskCompleter) throws DeviceControllerException;
void deleteSingleVolumeMirror(StorageSystem storage, URI mirror, TaskCompleter taskCompleter) throws DeviceControllerException;
void createGroupMirrors(StorageSystem storage, List<URI> mirrorList, Boolean createInactive, TaskCompleter taskCompleter)
throws DeviceControllerException;
void fractureGroupMirrors(StorageSystem storage, List<URI> mirrorList, Boolean sync, TaskCompleter taskCompleter)
throws DeviceControllerException;
void resumeGroupMirrors(StorageSystem storage, List<URI> mirrorList, TaskCompleter taskCompleter) throws DeviceControllerException;
void detachGroupMirrors(StorageSystem storage, List<URI> mirrorList, Boolean deleteGroup, TaskCompleter taskCompleter)
throws DeviceControllerException;
void deleteGroupMirrors(StorageSystem storage, List<URI> mirrorList, TaskCompleter taskCompleter) throws DeviceControllerException;
void removeMirrorFromDeviceMaskingGroup(StorageSystem system, List<URI> mirrorList, TaskCompleter completer)
throws DeviceControllerException;
}
| 47.433962 | 135 | 0.806683 |
065758cfd6b9915e06c063f66d823f3eb38d0df8 | 4,491 | package org.mockito_inside;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito_inside_prod.VeryComplexObject;
import org.mockito_inside_prod.VeryDifficultToCreateService;
import java.util.Objects;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.mockito.AdditionalMatchers.or;
import static org.mockito.Mockito.*;
class Mockito_verify_Test {
private final VeryDifficultToCreateService mock = mock( VeryDifficultToCreateService.class );
@Test
void verification_mode_and_argument_matchers() {
// somewhere in production
mock.getObject( "1" );
mock.getObject( "2" );
mock.getObject( "3" );
// in test
verify( mock, times( 3 ) ).getObject( any() );
verify( mock ).getObject( "1" );
verify( mock ).getObject( "2" );
verify( mock ).getObject( "3" );
verify( mock, times( 2 ) ).getObject( or( eq( "1" ), eq( "2" ) ) );
verify( mock, atLeastOnce() ).getObject( "2" );
verify( mock, atMost( 1 ) ).getObject( "3" );
verifyNoMoreInteractions( mock );
}
@Test
void verificationMode_once() {
// somewhere in production
mock.getObject( "1" );
// mock.getObject();
// in test
verify( mock, only() ).getObject( any() );
}
@Test
void argument_captors_single_parameter() {
// somewhere in production
mock.getObject( "1" );
mock.getObject( "2" );
// in test
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass( Object.class );
verify( mock, atLeastOnce() ).getObject( captor.capture() );
assertThat( captor.getAllValues() ).containsExactly( "1", "2" );
assertThat( captor.getValue() ).isEqualTo( "2" );
}
@Test
void argument_captors_multi_parameter() {
// somewhere in production
mock.getObject( "a", "b", 1 );
mock.getObject( "1", "2", 2 );
mock.getObject( null, null, 3 );
// in test
ArgumentCaptor<Object> captor1 = ArgumentCaptor.forClass( Object.class );
ArgumentCaptor<Object> captor2 = ArgumentCaptor.forClass( Object.class );
ArgumentCaptor<Object> captor3 = ArgumentCaptor.forClass( Object.class );
verify( mock, times( 3 ) ).getObject( captor1.capture(), captor2.capture(), captor3.capture() );
assertThat( captor1.getValue() ).isNull();
assertThat( captor2.getValue() ).isNull();
assertThat( captor3.getValue() ).isEqualTo( 3 );
assertThat( captor1.getAllValues() ).containsExactly( "a", "1", null );
assertThat( captor2.getAllValues() ).containsExactly( "b", "2", null );
assertThat( captor3.getAllValues() ).containsExactly( 1, 2, 3 );
}
@Test
void verification_order() {
VeryComplexObject mock2 = mock( VeryComplexObject.class );
// somewhere in production
mock.getObject( "1" );
mock.getInt( 2 );
mock2.getString();
mock.getObject();
mock.getObject( "2" );
mock.getString();
mock2.getComplexObject();
mock.getObject( "x", "y", "z" );
assertAll(
() -> {
InOrder orderAll = inOrder( mock, mock2 );
orderAll.verify( mock ).getObject( "1" );
orderAll.verify( mock ).getInt( 2 );
orderAll.verify( mock2 ).getString();
orderAll.verify( mock ).getObject();
orderAll.verify( mock ).getObject( anyString() );
orderAll.verify( mock ).getString();
orderAll.verify( mock2 ).getComplexObject();
orderAll.verify( mock ).getObject( eq( "x" ), anyString(), any() );
},
() -> {
InOrder orderMock2 = inOrder( mock2 );
orderMock2.verify( mock2 ).getString();
orderMock2.verify( mock2 ).getComplexObject();
}
);
}
@Test
void verify_ignores_invocations_for_stubbing() {
when( mock.getObject() ).thenReturn( "abc" );
verify( mock, never() ).getObject(); // verify ignores invocations during stubbing
}
@Test
void do_not_verify_stub() {
// in test
when( mock.getObject() ).thenReturn( "abc" );
// somewhere in production
if( !Objects.equals( "abc", mock.getObject() ) ) throw new IllegalArgumentException();
// in test
verify( mock ).getObject(); // it is possible, but it is pointless
}
@Test
void verify_after() {
verify( mock, after( 1000 ).never() ).getObject();
}
@Test
void verify_timeout() {
new Thread( this::mockGetObjectAfter ).start();
verify( mock, timeout( 1000 ).times( 1 ) ).getObject();
}
@SneakyThrows
private void mockGetObjectAfter() {
Thread.sleep( 300 ); // NOSONAR
mock.getObject();
Thread.sleep( 3000 ); // NOSONAR
mock.getObject();
}
}
| 27.552147 | 98 | 0.676019 |
43753192607f73594a8cc76e87ca51e197959671 | 2,357 | package baekjoon;
import java.io.*;
import java.util.*;
// @author : blog.naver.com/kerochuu
// @date : 2021. 6. 28.
public class 문명 {
private static class Node {
int x, y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
}
static int N, K, count = 1, T = 0;
static int[][] map;
static int[] parents;
static int[] dx = { -1, 1, 0, 0 };
static int[] dy = { 0, 0, -1, 1 };
static Queue<Node> q = new LinkedList<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = stoi(st.nextToken());
K = stoi(st.nextToken());
init();
for (int i = 1; i <= K; i++) {
st = new StringTokenizer(br.readLine());
input(i, stoi(st.nextToken()) - 1, stoi(st.nextToken()) - 1);
}
while (count != K && bfs(T++)) {}
System.out.println(T);
}
private static boolean bfs(int time) {
int size = q.size();
for (int s = 0; s < size; s++) {
Node now = q.poll();
for (int i = 0; i < 4; i++) {
int nx = now.x + dx[i];
int ny = now.y + dy[i];
if (isRange(nx, ny) && map[nx][ny] == 0) {
map[nx][ny] = map[now.x][now.y];
q.add(new Node(nx, ny));
int tx = nx + dx[i];
int ty = ny + dy[i];
if (isRange(tx, ty) && map[nx][ny] != map[tx][ty] && map[tx][ty] != 0) {
if (union(map[nx][ny], map[tx][ty]) && ++count == K) {
return false;
}
}
}
}
}
return true;
}
private static boolean isRange(int x, int y) {
return x >= 0 && y >= 0 && x < N && y < N;
}
private static void input(int idx, int x, int y) {
q.add(new Node(x, y));
map[x][y] = idx;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (isRange(nx, ny) && map[nx][ny] != 0 && union(map[nx][ny], map[x][y])) {
count++;
}
}
}
static int find(int a) {
return parents[a] < 0 ? a : (parents[a] = find(parents[a]));
}
static boolean union(int a, int b) {
if ((a = find(a)) != (b = find(b))) {
parents[b] = a;
return true;
}
return false;
}
private static void init() {
map = new int[N][N];
parents = new int[K + 1];
for (int i = 1; i <= K; i++) parents[i] = -1;
}
private static int stoi(String input) {
return Integer.parseInt(input);
}
}
| 21.427273 | 78 | 0.523123 |
8219cf645b4a695cfbad2b211609dcedc85de825 | 1,667 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
import com.ctre.phoenix.motorcontrol.ControlMode;
import com.ctre.phoenix.motorcontrol.NeutralMode;
import com.ctre.phoenix.motorcontrol.can.TalonSRX;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.PneumaticsModuleType;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
public class ShooterSubsystem extends SubsystemBase {
/** Creates a new ShooterSubsystem. */
private DoubleSolenoid m_solenoid;
private TalonSRX m_motor;
private boolean m_shooterOn = false;
public ShooterSubsystem() {
m_solenoid = new DoubleSolenoid(PneumaticsModuleType.CTREPCM, Constants.SHOOTER_SOLENOID_1, Constants.SHOOTER_SOLENOID_2);
m_motor = new TalonSRX(Constants.SHOOTER_MOTOR_ID);
m_motor.configFactoryDefault();
m_motor.setInverted(Constants.SHOOTER_INVERT);
m_motor.setNeutralMode(NeutralMode.Coast);
m_solenoid.set(Constants.SHOOTER_DEFAULT_POSITION);
}
public void toggleSolenoid() {
m_solenoid.toggle();
}
public void toggleShooter() {
m_shooterOn = !m_shooterOn;
if (m_shooterOn)
m_motor.set(ControlMode.PercentOutput, Constants.SHOOTER_SPEED);
else
m_motor.set(ControlMode.PercentOutput, 0.0);
}
public void stopShooter() {
m_shooterOn = false;
m_motor.set(ControlMode.PercentOutput, 0.0);
}
@Override
public void periodic() {
// This method will be called once per scheduler run
}
}
| 29.767857 | 126 | 0.762448 |
56f6c33a82057d752ded4f07690619f30de71ef2 | 394 | package org.talend.daikon.annotation;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
/**
* A marker to check if annotation has default value or not
* @see Call#service()
*/
public abstract class DefaultHystrixCommand extends HystrixCommand {
protected DefaultHystrixCommand(HystrixCommandGroupKey group) {
super(group);
}
}
| 24.625 | 68 | 0.766497 |
e9a7c06f2d69e6579c3e1a0db54c05838d5f4c7e | 6,144 | package com.google.mu.util.stream;
import static com.google.mu.util.stream.Cases.TinyContainer.toTinyContainer;
import static com.google.mu.util.stream.Cases.onlyElement;
import static com.google.mu.util.stream.Cases.onlyElements;
import static com.google.mu.util.stream.Cases.cases;
import static com.google.mu.util.stream.Cases.when;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static java.util.function.Function.identity;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.google.common.testing.NullPointerTester;
import com.google.mu.util.stream.Cases.TinyContainer;
import java.util.stream.Stream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public final class CasesTest {
@Test public void when_zeroElement() {
assertThat(Stream.of(1).collect(when(() -> "zero"))).isEmpty();
assertThat(Stream.empty().collect(when(() -> "zero"))).hasValue("zero");
}
@Test public void when_oneElement() {
assertThat(Stream.of(1).collect(when(i -> i + 1))).hasValue(2);
assertThat(Stream.of(1, 2).collect(when(i -> i + 1))).isEmpty();
assertThat(Stream.of(1).collect(when(x -> x == 1, i -> i + 1))).hasValue(2);
assertThat(Stream.of(1).collect(when(x -> x == 2, i -> i + 1))).isEmpty();
}
@Test public void when_twoElements() {
assertThat(Stream.of(2, 3).collect(when((a, b) -> a * b))).hasValue(6);
assertThat(Stream.of(2, 3, 4).collect(when((a, b) -> a * b))).isEmpty();
assertThat(Stream.of(2, 3).collect(when((x, y) -> x < y, (a, b) -> a * b))).hasValue(6);
assertThat(Stream.of(2, 3).collect(when((x, y) -> x > y, (a, b) -> a * b))).isEmpty();
}
@Test public void only_oneElement() {
String result = Stream.of("foo").collect(onlyElement());
assertThat(result).isEqualTo("foo");
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class, () -> Stream.of(1, 2, 3).collect(onlyElement()));
assertThat(thrown).hasMessageThat().contains("size: 3");
}
@Test public void only_twoElements() {
int result = Stream.of(2, 3).collect(onlyElements((a, b) -> a * b));
assertThat(result).isEqualTo(6);
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class, () -> Stream.of(1).collect(onlyElements((a, b) -> a * b)));
assertThat(thrown).hasMessageThat().contains("size: 1");
}
@Test public void cases_firstCaseMatch() {
String result = Stream.of("foo", "bar").collect(cases(when((a, b) -> a + b), when(a -> a)));
assertThat(result).isEqualTo("foobar");
}
@Test public void cases_secondCaseMatch() {
String result = Stream.of("foo").collect(cases(when((a, b) -> a + b), when(a -> a)));
assertThat(result).isEqualTo("foo");
}
@Test public void cases_noMatchingCase() {
IllegalArgumentException thrown =
assertThrows(
IllegalArgumentException.class,
() -> Stream.of(1, 2, 3).collect(cases(when((a, b) -> a + b), when(a -> a))));
assertThat(thrown).hasMessageThat().contains("size: 3");
}
@Test public void toTinyContainer_empty() {
assertThat(Stream.empty().collect(toTinyContainer()).size()).isEqualTo(0);
}
@Test public void toTinyContainer_oneElement() {
assertThat(Stream.of("foo").collect(toTinyContainer()).when(x -> true, "got:"::concat))
.hasValue("got:foo");
}
@Test public void toTinyContainer_twoElements() {
assertThat(Stream.of(2, 3).collect(toTinyContainer()).when((x, y) -> true, Integer::max))
.hasValue(3);
}
@Test public void tinyContainer_addAll_fromEmpty() {
TinyContainer<String> empty = new TinyContainer<>();
assertThat(Stream.empty().collect(toTinyContainer()).addAll(empty).size()).isEqualTo(0);
assertThat(Stream.of("foo").collect(toTinyContainer()).addAll(empty).size()).isEqualTo(1);
assertThat(Stream.of("foo", "bar").collect(toTinyContainer()).addAll(empty).size())
.isEqualTo(2);
assertThat(Stream.of("foo", "bar", "baz").collect(toTinyContainer()).addAll(empty).size())
.isEqualTo(3);
}
@Test public void tinyContainer_addAll_fromOneElement() {
TinyContainer<String> source = Stream.of("foo").collect(toTinyContainer());
assertThat(Stream.empty().collect(toTinyContainer()).addAll(source).when(x -> true, identity()))
.hasValue("foo");
assertThat(Stream.of("bar").collect(toTinyContainer()).addAll(source).when((x, y) -> true, (a, b) -> a + b))
.hasValue("barfoo");
assertThat(Stream.of("a", "b").collect(toTinyContainer()).addAll(source).size())
.isEqualTo(3);
assertThat(Stream.of("a", "b", "c").collect(toTinyContainer()).addAll(source).size())
.isEqualTo(4);
}
@Test public void tinyContainer_addAll_fromTwoElements() {
TinyContainer<String> source = Stream.of("a", "b").collect(toTinyContainer());
assertThat(Stream.<String>empty().collect(toTinyContainer()).addAll(source).when((x, y) -> true, (a, b) -> a + b))
.hasValue("ab");
assertThat(Stream.of("c").collect(toTinyContainer()).addAll(source).size())
.isEqualTo(3);
assertThat(Stream.of("c", "d").collect(toTinyContainer()).addAll(source).size())
.isEqualTo(4);
assertThat(Stream.of("c", "d", "e").collect(toTinyContainer()).addAll(source).size())
.isEqualTo(5);
}
@Test public void tinyContainer_addAll_fromThreeElements() {
TinyContainer<String> source = Stream.of("a", "b", "c").collect(toTinyContainer());
assertThat(Stream.empty().collect(toTinyContainer()).addAll(source).size())
.isEqualTo(3);
assertThat(Stream.of("c").collect(toTinyContainer()).addAll(source).size())
.isEqualTo(4);
assertThat(Stream.of("c", "d").collect(toTinyContainer()).addAll(source).size())
.isEqualTo(5);
assertThat(Stream.of("c", "d", "e").collect(toTinyContainer()).addAll(source).size())
.isEqualTo(6);
}
@Test public void nullChecks() {
new NullPointerTester().testAllPublicStaticMethods(Cases.class);
}
}
| 43.574468 | 118 | 0.664388 |
e2bdc6f6f3a65e8977f52329d2dd2b34ab686ef4 | 1,222 | package com.purbon.kafka.streams.config;
import com.purbon.kafka.streams.config.schema.Ssl;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
@ConfigurationProperties("spring.kafka.properties.schema.registry")
@Data
@NoArgsConstructor
public class SchemaRegistryConfig {
private String url;
private Ssl ssl;
public Map<String, String> asMap() {
Map<String, String> config = new HashMap<>();
config.put("schema.registry.url", url);
if (url.startsWith("https://")) {
config.put("schema.registry.ssl.keystore.password", ssl.getKeystore().getPassword());
config.put("schema.registry.ssl.keystore.location", ssl.getKeystore().getLocation());
config.put("schema.registry.ssl.truststore.password", ssl.getTruststore().getPassword());
config.put("schema.registry.ssl.truststore.location", ssl.getTruststore().getLocation());
config.put("schema.registry.ssl.key.password", ssl.getKey().getPassword());
}
return config;
}
}
| 35.941176 | 101 | 0.711129 |
b8a794c143f9b32b139c65854597760217068590 | 7,200 | /**
* Copyright 2015-2016 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.swarm.plugin.maven;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Enumeration;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Execute;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
/**
* @author Bob McWhirter
*/
@Mojo(name = "analyze",
requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME,
requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME)
@Execute(phase = LifecyclePhase.PACKAGE)
public class AnalyzeMojo extends AbstractMojo {
private static Pattern ARTIFACT = Pattern.compile("<artifact name=\"([^\"]+)\"");
private static Pattern MODULE = Pattern.compile("<module name=\"([^\"]+)\".*(slot=\"[^\"]+\")?");
@Parameter(defaultValue = "${project.build.directory}")
protected String projectBuildDir;
@Parameter(defaultValue = "${project}", readonly = true)
protected MavenProject project;
@Parameter(alias = "gav", defaultValue = "${gav}", required = true)
private String gav;
private Path dir;
private Path modulesDir;
private Graph graph = new Graph();
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info("Analyzing for " + this.gav);
this.dir = Paths.get(this.projectBuildDir, "wildfly-swarm-archive");
this.modulesDir = this.dir.resolve("modules");
try {
walkModulesDir();
walkDependencies();
} catch (IOException e) {
throw new MojoFailureException("Unable to inspect modules/ dir", e);
}
Graph.Artifact artifact = this.graph.getClosestArtifact(this.gav);
if (artifact == null) {
throw new MojoFailureException("Unable to find artifact: " + this.gav);
}
DumpGraphVisitor visitor = new DumpGraphVisitor();
artifact.accept(visitor);
}
protected void walkModulesDir() throws IOException {
Files.walkFileTree(this.modulesDir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.getFileName().toString().equals("module.xml")) {
Path dir = file.getParent();
Path relative = modulesDir.relativize(dir);
String slot = relative.getFileName().toString();
String module = relative.getParent().toString().replace(File.separatorChar, '.');
analyzeModuleXml(module, slot, new FileInputStream(file.toFile()));
}
return super.visitFile(file, attrs);
}
});
}
protected void walkDependencies() throws IOException {
Set<Artifact> deps = this.project.getArtifacts();
for (Artifact each : deps) {
walkDependency(each);
}
}
protected void walkDependency(Artifact artifact) throws IOException {
if (artifact.getFile() != null && artifact.getType().equals("jar")) {
try (JarFile jar = new JarFile(artifact.getFile())) {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().startsWith("modules/") && entry.getName().endsWith("module.xml")) {
String[] parts = entry.getName().split("/");
String slot = parts[parts.length - 2];
String module = null;
for (int i = 1; i < parts.length - 2; ++i) {
if (module != null) {
module = module + ".";
;
} else {
module = "";
}
module = module + parts[i];
}
analyzeModuleXml(module, slot, jar.getInputStream(entry));
}
}
}
}
}
protected void analyzeModuleXml(String module, String slot, InputStream in) throws IOException {
Graph.Module curModule = this.graph.getModule(module, slot);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
String line = null;
while ((line = reader.readLine()) != null) {
Matcher matcher = null;
matcher = ARTIFACT.matcher(line);
if (matcher.find()) {
String gav = matcher.group(1);
String parts[] = gav.split(":");
String groupId = parts[0];
String artifactId = parts[1];
String version = parts[2];
String classifier = null;
if (parts.length >= 4) {
classifier = parts[3];
}
curModule.addArtifact(this.graph.getArtifact(groupId, artifactId, version, classifier));
} else {
matcher = MODULE.matcher(line);
if (matcher.find()) {
String depModule = matcher.group(1);
String depSlot = "main";
if (matcher.groupCount() >= 3) {
depSlot = matcher.group(3);
}
curModule.addDependency(this.graph.getModule(depModule, depSlot));
}
}
}
}
}
}
| 37.305699 | 108 | 0.591667 |
758ed74ab5bc649b81deb792717e96126ff7ea9f | 2,261 | package domts.level1.core;
import org.w3c.dom.*;
import java.util.*;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
/**
* Appends a document fragment containing a CDATASection to an attribute.
* @author Curt Arnold
* @see <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-637646024">http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-637646024</a>
* @see <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-952280727">http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-952280727</a>
*/
class HC_Attr_Insert_Before_7_Test extends domts.DOMTestCase {
@BeforeEach
void setup() {
feature("XML");
// check if loaded documents are supported for content type
String contentType = getContentType();
preload(contentType, "hc_staff", true);
}
@Test
@DisplayName("http://www.w3.org/2001/DOM_Test_Suite/level1/core/hc_attrinsertbefore7")
void run() throws Throwable {
Document doc;
NodeList acronymList;
Node testNode;
NamedNodeMap attributes;
Attr titleAttr;
String value;
Text terNode;
Node dayNode;
DocumentFragment docFrag;
Node retval;
Node firstChild;
Node lastChild;
Node refChild = null;
doc = (Document) load("hc_staff", true);
acronymList = doc.getElementsByTagName("acronym");
testNode = acronymList.item(3);
attributes = testNode.getAttributes();
titleAttr = (Attr) attributes.getNamedItem("title");
terNode = doc.createTextNode("ter");
if (("text/html".equals(getContentType()))) {
{
boolean success = false;
try {
dayNode = doc.createCDATASection("day");
} catch (DOMException ex) {
success = (ex.code == DOMException.NOT_SUPPORTED_ERR);
}
assertTrue(success, "throw_NOT_SUPPORTED_ERR");
}
} else {
dayNode = doc.createCDATASection("day");
docFrag = doc.createDocumentFragment();
retval = docFrag.appendChild(terNode);
retval = docFrag.appendChild(dayNode);
{
boolean success = false;
try {
retval = titleAttr.insertBefore(docFrag, refChild);
} catch (DOMException ex) {
success = (ex.code == DOMException.HIERARCHY_REQUEST_ERR);
}
assertTrue(success, "throw_HIERARCHY_REQUEST_ERR");
}
}
}
} | 33.25 | 178 | 0.710305 |
ccbf7f1a036c0fb2f8d9b0d3cd895c93edc50fad | 1,190 | package liquibase.ext.maxdb.sqlgenerator;
import liquibase.database.Database;
import liquibase.ext.maxdb.database.MaxDBDatabase;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.sqlgenerator.core.DropForeignKeyConstraintGenerator;
import liquibase.statement.core.DropForeignKeyConstraintStatement;
public class DropForeignKeyConstraintGeneratorMaxDB extends DropForeignKeyConstraintGenerator {
@Override
public boolean supports(DropForeignKeyConstraintStatement statement, Database database) {
return database instanceof MaxDBDatabase;
}
@Override
public int getPriority() {
return PRIORITY_DATABASE;
}
@Override
public Sql[] generateSql(DropForeignKeyConstraintStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
return new Sql[] { new UnparsedSql("ALTER TABLE " + database.escapeTableName(statement.getBaseTableCatalogName(), statement.getBaseTableSchemaName(), statement.getBaseTableName()) + " DROP FOREIGN KEY " + database.escapeConstraintName(statement.getConstraintName()), getAffectedForeignKey(statement)) };
}
}
| 44.074074 | 311 | 0.805882 |
0b9a33584f2f78195e8f5b1a65e39c5f69fab4bc | 3,982 | package com.sts.travlan;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.model.mapper.Member_NotifyMapper;
import com.model.mapper.Member_ScrapMapper;
import com.model.mapper.PostMapper;
import com.model.member.Member_NotifyDTO;
import com.model.member.Member_ScrapDTO;
import com.model.post.PostDTO;
import com.sts.travlan.Utility;
@Controller
public class Member_ScrapController {
Utility util = new Utility();
@Autowired
private Member_ScrapMapper mapper;
@Autowired
private PostMapper post_mapper;
@Autowired
private Member_NotifyMapper notify_mapper;
@GetMapping("/scraplist")
public String scraplist(HttpSession session, Model model) {
List<Member_ScrapDTO> list = mapper.list((Integer)session.getAttribute("num"));
model.addAttribute("list", list);
return util.isLoginFilter(session, "/scraplist");
}
@ResponseBody
@PostMapping(value = "/scrap", produces = "application/json;charset=utf-8")
public Map<String, Object> scrap(int post_num, String memo, HttpSession session) {
Member_ScrapDTO dto = new Member_ScrapDTO();
dto.setPost_num(post_num);
dto.setMember_num((Integer)session.getAttribute("num"));
dto.setMemo(memo);
Map<String, Object> return_data = new HashMap<String, Object>();
if((Integer)session.getAttribute("num") == post_mapper.getPost(post_num)) {
return_data.put("flag", "N");
}
if(mapper.scrap(dto) > 0) {
return_data.put("flag", "Y");
Member_NotifyDTO notify_dto = new Member_NotifyDTO();
PostDTO post_dto = post_mapper.read(dto.getPost_num());
notify_dto.setMember_num(post_dto.getMember_num());
notify_dto.setPost_num(post_dto.getPost_num());
notify_dto.setContent("누군가 '" + post_dto.getTitle() + "' 글을 좋아합니다.");
notify_mapper.create(notify_dto);
} else {
return_data.put("flag", "N");
}
return return_data;
}
@ResponseBody
@PostMapping(value = "/deleteScrap", produces = "application/json;charset=utf-8")
public Map<String, Object> deleteScrap(int post_num, HttpSession session) {
Map map = new HashMap();
map.put("member_num", (Integer)session.getAttribute("num"));
map.put("post_num", post_num);
int isDelete = mapper.deleteScrap(map);
Map<String, Object> return_data = new HashMap<String, Object>();
if(isDelete > 0) {
return_data.put("flag", "Y");
} else {
return_data.put("flag", "N");
}
return return_data;
}
@ResponseBody
@PostMapping(value = "/scrapedPost", produces = "application/json;charset=utf-8")
public Map<String, Object> scrapedPost(int post_num, int member_num, HttpSession session) {
Map scrap = new HashMap();
scrap.put("member_num", member_num);
scrap.put("post_num", post_num);
Member_ScrapDTO dto = mapper.scrapedPost(scrap);
Map<String, Object> return_data = new HashMap<String, Object>();
if(dto != null) {
return_data.put("flag", "Y");
return_data.put("dto", dto);
} else {
return_data.put("flag", "N");
}
return return_data;
}
@ResponseBody
@PostMapping(value = "/updateScrap", produces = "application/json;charset=utf-8")
public Map<String, Object> updateScrap(int post_num, String memo, HttpSession session) {
Map map = new HashMap();
map.put("member_num", (Integer)session.getAttribute("num"));
map.put("post_num", post_num);
map.put("memo", memo);
int isUpdate = mapper.updateScrap(map);
Map<String, Object> return_data = new HashMap<String, Object>();
if(isUpdate > 0) {
return_data.put("flag", "Y");
} else {
return_data.put("flag", "N");
}
return return_data;
}
} | 27.846154 | 92 | 0.716474 |
3173de49ce9958455efc869fc50a3111b90e54bc | 3,434 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.messages;
import android.animation.Animator;
import org.chromium.base.Callback;
import org.chromium.base.supplier.Supplier;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.modelutil.PropertyModel;
/**
* This class implements public MessageDispatcher interface, delegating the actual work to
* MessageQueueManager.
*/
public class MessageDispatcherImpl implements ManagedMessageDispatcher {
private final MessageQueueManager mMessageQueueManager = new MessageQueueManager();
private final MessageContainer mMessageContainer;
private final Supplier<Integer> mMessageMaxTranslationSupplier;
private final MessageAutodismissDurationProvider mAutodismissDurationProvider;
private final Callback<Animator> mAnimatorStartCallback;
/**
* Build a new message dispatcher
* @param messageContainer A container view for displaying message banners.
* @param messageMaxTranslation A {@link Supplier} that supplies the maximum translation Y value
* the message banner can have as a result of the animations or the gestures.
* @param autodismissDurationProvider A {@link MessageAutodismissDurationProvider} providing
* autodismiss duration for message banner.
* @param animatorStartCallback The {@link Callback} that will be used by the message to
* delegate starting the animations to the {@link WindowAndroid}.
*/
public MessageDispatcherImpl(MessageContainer messageContainer,
Supplier<Integer> messageMaxTranslation,
MessageAutodismissDurationProvider autodismissDurationProvider,
Callback<Animator> animatorStartCallback) {
mMessageContainer = messageContainer;
mMessageMaxTranslationSupplier = messageMaxTranslation;
mAnimatorStartCallback = animatorStartCallback;
mAutodismissDurationProvider = autodismissDurationProvider;
}
@Override
public void enqueueMessage(PropertyModel messageProperties, WebContents webContents,
@MessageScopeType int scopeType, boolean highPriority) {
MessageStateHandler messageStateHandler = new SingleActionMessage(mMessageContainer,
messageProperties, this::dismissMessage, mMessageMaxTranslationSupplier,
mAutodismissDurationProvider, mAnimatorStartCallback);
ScopeKey scopeKey = new ScopeKey(scopeType, webContents);
mMessageQueueManager.enqueueMessage(
messageStateHandler, messageProperties, scopeKey, highPriority);
}
@Override
public void dismissMessage(PropertyModel messageProperties, @DismissReason int dismissReason) {
mMessageQueueManager.dismissMessage(messageProperties, dismissReason);
}
@Override
public void dismissAllMessages(@DismissReason int dismissReason) {
mMessageQueueManager.dismissAllMessages(dismissReason);
}
@Override
public int suspend() {
return mMessageQueueManager.suspend();
}
@Override
public void resume(int token) {
mMessageQueueManager.resume(token);
}
@Override
public void setDelegate(MessageQueueDelegate delegate) {
mMessageQueueManager.setDelegate(delegate);
}
}
| 42.395062 | 100 | 0.754222 |
cce1b7aa311b95054aa4157dbb0540ce670d28f4 | 4,361 | package com.userfront.domain.tennis;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.userfront.domain.User;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Entity
public class Tournoi {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
@JsonIgnore
private User user;
@ManyToOne(cascade = {CascadeType.ALL, CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE, CascadeType.REFRESH, CascadeType.DETACH})
@JoinColumn(name = "billet_id")
private Billet billet;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@ManyToMany(mappedBy = "tournois")
private List<Joueur> joueurs = new ArrayList<>();
@OneToMany(mappedBy = "tournoi", cascade = {CascadeType.ALL, CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE, CascadeType.REFRESH, CascadeType.DETACH})
private List<TypeTournoi> typeTournois = new ArrayList<>();
@OneToMany(mappedBy = "tournoi", cascade = {CascadeType.ALL, CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE, CascadeType.REFRESH, CascadeType.DETACH}, orphanRemoval = true)
private List<DateTournoi> dateTournois = new ArrayList<>();
@Column(name = "date_debut_tournoi")
private Date date_debut_tournoi;
@Column(name = "date_fin_tournoi")
private Date date_fin_tournoi;
@Column(name = "nom_tournoi")
private String nom_tournoi;
@Column(name = "nbr_inscrit")
private String nbr_inscrit;
@Column(name = "nbr_tour")
private String nbr_tour;
@Column(name = "nbre_joueurs_max")
private String nbre_joueurs_max;
public Billet getBillet() {
return billet;
}
public void setBillet(Billet billet) {
this.billet = billet;
}
public String getNbre_joueurs_max() {
return nbre_joueurs_max;
}
public void setNbre_joueurs_max(String nbre_joueurs_max) {
this.nbre_joueurs_max = nbre_joueurs_max;
}
public String getNbr_tour() {
return nbr_tour;
}
public void setNbr_tour(String nbr_tour) {
this.nbr_tour = nbr_tour;
}
public String getNbr_inscrit() {
return nbr_inscrit;
}
public void setNbr_inscrit(String nbr_inscrit) {
this.nbr_inscrit = nbr_inscrit;
}
public String getNom_tournoi() {
return nom_tournoi;
}
public void setNom_tournoi(String nom_tournoi) {
this.nom_tournoi = nom_tournoi;
}
public Date getDate_fin_tournoi() {
return date_fin_tournoi;
}
public void setDate_fin_tournoi(Date date_fin_tournoi) {
this.date_fin_tournoi = date_fin_tournoi;
}
public Date getDate_debut_tournoi() {
return date_debut_tournoi;
}
public void setDate_debut_tournoi(Date date_debut_tournoi) {
this.date_debut_tournoi = date_debut_tournoi;
}
public List<DateTournoi> getDateTournois() {
return dateTournois;
}
public void setDateTournois(List<DateTournoi> dateTournois) {
this.dateTournois = dateTournois;
}
public List<TypeTournoi> getTypeTournois() {
return typeTournois;
}
public void setTypeTournois(List<TypeTournoi> typeTournois) {
this.typeTournois = typeTournois;
}
public List<Joueur> getJoueurs() {
return joueurs;
}
public void setJoueurs(List<Joueur> joueurs) {
this.joueurs = joueurs;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String toString() {
return "Tournoi{" +
"tournoiId=" + id +
", joueurs=" + joueurs +
", typeTournois=" + typeTournois +
", dateTournois=" + dateTournois +
", date_debut_tournoi=" + date_debut_tournoi +
", date_fin_tournoi=" + date_fin_tournoi +
", nom_tournoi='" + nom_tournoi + '\'' +
", nbr_inscrit='" + nbr_inscrit + '\'' +
", nbr_tour='" + nbr_tour + '\'' +
", nbre_joueurs_max='" + nbre_joueurs_max + '\'' +
'}';
}
}
| 25.804734 | 188 | 0.640908 |
0a2fdb8fbf22a295fdc2592e750fb11b322d38ad | 556 | public class rotateArray {
class Solution {
public void rotate(int[] nums, int k) {
k %= nums.length;
k--;
reverse(nums, 0, nums.length-1);
reverse(nums, 0, k);
reverse(nums, k+1, nums.length-1);
}
void reverse(int[] arr, int i, int j)
{
int s = i, e = j;
while(s < e)
{
int t = arr[s];
arr[s] = arr[e];
arr[e] = t;
s++; e--;
}
}
}
}
| 22.24 | 47 | 0.352518 |
314e6024666ea17f56519acd6cf0a6b291aeb68a | 5,668 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.tdb2.store;
import static org.junit.Assert.assertEquals;
import java.io.StringReader;
import java.util.Iterator;
import org.apache.jena.atlas.iterator.Iter;
import org.apache.jena.atlas.lib.StrUtils;
import org.apache.jena.dboe.base.file.Location;
import org.apache.jena.dboe.transaction.txn.TransactionException;
import org.apache.jena.query.Dataset;
import org.apache.jena.query.TxnType;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.sparql.core.Quad;
import org.apache.jena.system.Txn;
import org.apache.jena.tdb2.TDB2Factory;
import org.apache.jena.tdb2.sys.TDBInternal;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/** Transactions and store connections - extended tests assuming the
* basics work. Hence these tests use memory databases.
*
* For tests of StoreConnection basics:
* @see AbstractTestStoreConnectionBasics
* @see TestStoreConnectionDirect
* @see TestStoreConnectionMapped
* @see TestStoreConnectionMem
*/
public class TestTransactions
{
// Per-test unique-ish.
static int count = 0;
long x = System.currentTimeMillis()+(count++);
String ns = "http://example/TestTransactions#";
String data1 = StrUtils.strjoinNL
("prefix : <"+ns+">"
,":s :p '000-"+x+"' ."
,":s :p '111-"+x+"' ."
," :g {"
," :s :p '222-"+x+"' ."
," :s :p '333-"+x+"' ."
," :s :p '444-"+x+"' ."
,"}"
);
String data2 = StrUtils.strjoinNL
("prefix : <"+ns+">"
,":s :p 'AAA-"+x+"' ."
,":s :p 'BBB-"+x+"' ."
,":s :p 'CCC-"+x+"' ."
,":s :p 'DDD-"+x+"' ."
);
Dataset dataset;
Location location;
@Before public void before() {
location = Location.mem();
dataset = TDB2Factory.connectDataset(location);
}
@After public void after() {
dataset.close();
TDBInternal.expel(dataset.asDatasetGraph());
}
// Models across transactions
@Test public void trans_01() {
Model named = dataset.getNamedModel(ns+"g");
Txn.executeWrite(dataset, ()->{
RDFDataMgr.read(dataset, new StringReader(data1), null, Lang.TRIG);
});
Txn.executeRead(dataset, ()->{
long x1 = Iter.count(dataset.getDefaultModel().listStatements());
assertEquals(2, x1);
long x2 = Iter.count(named.listStatements());
assertEquals(3, x2);
});
}
@Test public void trans_02() {
Model model = dataset.getDefaultModel();
Txn.executeWrite(dataset, ()->{
RDFDataMgr.read(model, new StringReader(data2), null, Lang.TURTLE);
});
Txn.executeRead(dataset, ()->{
assertEquals(4, model.size());
});
}
// Iterators and trasnaxction scope.
private void load(String data) {
Txn.executeWrite(dataset, ()->{
RDFDataMgr.read(dataset, new StringReader(data), null, Lang.TURTLE);
});
}
public void iterator_01() {
load(data2);
dataset.begin(TxnType.READ);
Iterator<Quad> iter = TDBInternal.getDatasetGraphTDB(dataset).find();
Iter.consume(iter);
dataset.end();
}
@Test(expected=TransactionException.class)
public void iterator_02() {
load(data2);
dataset.begin(TxnType.READ);
Iterator<Quad> iter = dataset.asDatasetGraph().find();
dataset.end();
Quad q = iter.next();
System.err.println("iterator_02: Unexpected: "+q);
}
@Test(expected=TransactionException.class)
public void iterator_03() {
load(data2);
dataset.begin(TxnType.READ);
Iterator<Quad> iter = TDBInternal.getDatasetGraphTDB(dataset).find();
dataset.end();
Quad q = iter.next();
System.err.println("iterator_03: Unexpected: "+q);
}
@Test(expected=TransactionException.class)
public void iterator_04() {
load(data2);
Iterator<Statement> iter = Txn.calculateRead(dataset, ()->dataset.getDefaultModel().listStatements());
Statement q = iter.next();
System.err.println("iterator_04: Unexpected: "+q);
}
@Test(expected=TransactionException.class)
public void iterator_05() {
load(data2);
Iterator<Statement> iter = Txn.calculateWrite(dataset, ()->dataset.getDefaultModel().listStatements());
iter.next();
}
@Test(expected=TransactionException.class)
public void iterator_06() {
load(data2);
Iterator<Quad> iter = Txn.calculateRead(dataset, ()->dataset.asDatasetGraph().find());
dataset.begin(TxnType.READ);
iter.next();
dataset.end();
}
}
| 30.804348 | 111 | 0.635321 |
ab508d3fd3a05ae6ea2e4408bd174b47bb8a684c | 251 | package org.jiuwo.ratel.contract;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
/**
* @author Steven Han
*/
@Getter
@Setter
public class TestData {
/**
* 需要测试的接口列表
*/
private List<ApiDetail> testDataList;
} | 13.210526 | 41 | 0.673307 |
886d1e907a2319b1b7315aa8784482fcd89e01aa | 430 | package com.lsh.wms.core.dao.csi;
import com.lsh.wms.core.dao.MyBatisRepository;
import com.lsh.wms.model.csi.CsiSku;
import java.util.List;
import java.util.Map;
@MyBatisRepository
public interface CsiSkuDao {
void insert(CsiSku csiSku);
void update(CsiSku csiSku);
CsiSku getCsiSkuById(Integer id);
Integer countCsiSku(Map<String, Object> params);
List<CsiSku> getCsiSkuList(Map<String, Object> params);
} | 19.545455 | 59 | 0.755814 |
42b7af8b54e9b2d85a483bdb56f99dd2700b5892 | 317 | package br.puc.pss.INF2125T2.repository;
import java.util.List;
import br.puc.pss.INF2125T2.model.Aluno;
import br.puc.pss.INF2125T2.model.enumeration.TipoDeAluno;
public interface AlunoRepository {
public void saveAluno(Aluno aluno);
public Aluno findAlunoById(int id);
public List<Aluno> getAllAlunos();
} | 19.8125 | 58 | 0.788644 |
429fd0374c54a39b1a8bec03f4eac1c753dce96a | 1,035 | package com.schening.phoenix.security.web.impl;
import com.schening.phoenix.security.po.OrderPO;
import com.schening.phoenix.security.web.LoginResource;
import com.schening.phoenix.security.web.OrderResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author schening
* @date 2020/7/13
*/
@RestController
public class OrderResourceImpl implements OrderResource {
@Resource
private LoginResource loginResource;
private final static String PREFIX = "/order";
@Override
@GetMapping(PREFIX)
public String listOrders() {
return loginResource.getUserName() + "查询订单信息";
}
@Override
@GetMapping(PREFIX + "/{no}")
public OrderPO getOrder(@PathVariable("no") String no) {
OrderPO orderPO = new OrderPO();
orderPO.setNo("1");
orderPO.setName("订单1");
return orderPO;
}
}
| 25.875 | 62 | 0.723671 |
cff044b8490f1966005fe91f533adf3dad461c01 | 5,088 | package ee.ioc.cs.vsle.vclass;
/*-
* #%L
* CoCoViLa
* %%
* Copyright (C) 2003 - 2017 Institute of Cybernetics at Tallinn University of Technology
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.awt.Graphics2D;
/**
* <p>The abstract class {@code ClassPainter} provides an extension point
* to the Scheme Editor where every visual class can customize its default
* appearance and create additional visual artifacts on the scheme.</p>
* <p>Two steps are necessary to make use of this extension. First,
* the package creator has to implement the painter's code in a Java
* class that extends the abstract class {@code ClassPainter}.
* A definition of the abstract method {@link #paint(Graphics2D, float) paint}
* is needed. The simplest possible example which draws the name of the
* visual class at the coordinates of the object's top left corner is:<br />
* <pre>
* import java.awt.Graphics2D;
* import ee.ioc.cs.vsle.vclass.ClassPainter;
*
* public class MyClassPainter extends ClassPainter {
* public void paint(Graphics2D graphics, float scale) {
* graphics.drawString("My name is " + vclass.getName(),
* vclass.getX(), vclass.getY());
* }
* }
* </pre>
* </p>
*
* <p>Second, the name of the painter class has to be declared in the package
* description XML file. For example, a relevant part of the package description might
* look as follows:
* <pre>
* ...
* <class type="class">
* <name>MyClass</name>
* ...
* <graphics>
* <i><painter>MyClassPainter</painter></i>
* </graphics>
* ...
* </class>
* ...
* </pre>
* In the above example the line in italics specifies that there exists a Java source code
* file {@code MyClassPainter.java} in the package directory containing a class
* with the {@code ClassPainter} interface. The source will be automatically (re)compiled
* when the package is loaded. For each visual class of type {@code MyClass} on the scheme
* a new instance of {@code MyClassPainter} is created.</p>
* <p>Please note that although the {@code ClassPainter} has a reference to the
* scheme description and could modify it directly, the scheme description including the
* visual class {@code vclass} itself should be considered read-only at present.
* Unexpected things will happen if this rule is ignored. In future versions there
* will be another interface for modifying the scheme in a thread safe way.</p>
*
* @see GObj
* @see Scheme
*/
public abstract class ClassPainter implements Cloneable {
/**
* Reference to the instance of a visual class this {@code ClassPainter}
* is responsible for.
*/
protected GObj vclass;
/**
* The scheme description.
*/
protected Scheme scheme;
/**
* This method is called every time the scheme is being repainted.
* It is possible to draw almost anything on the scheme without
* any restrictions. However, long computations should be avoided
* or the user interface will become unresponsive.
*
* To paint visual class's original graphics,
* call vclass.drawClassGraphics( graphics, scale );
*
* @param graphics the graphics object in which the whole scheme is painted
* @param scale the factor by which the scheme view is currently scaled
*/
public abstract void paint(Graphics2D graphics, float scale);
/**
* Sets the instance of a visual class this painter is associated to.
* This method is guaranteed to be called with a non-{@code null} argument
* before the first {@code paint} call. The referenced {@code vclass}
* should not be modified here.
*
* @param vclass the instance of a visual class the painter is responsible for
*/
public void setVClass(final GObj vclass) {
this.vclass = vclass;
}
/**
* Sets the scheme description before the first call to {@code paint}
* method. It is probably not a good idea to modify the scheme directly.
*
* @param scheme the scheme description
*/
public void setScheme(final Scheme scheme) {
this.scheme = scheme;
}
/**
* Used internally for creating new instances from a prototype.
*/
@Override
public ClassPainter clone() {
ClassPainter clone = null;
try {
clone = (ClassPainter) super.clone();
} catch (CloneNotSupportedException e) {
// Object does support clone()
}
return clone;
}
}
| 36.342857 | 90 | 0.680621 |
49e55b8a5b4c652097c306dbd161d940387df197 | 595 | package io.github.froger.mahmoud.ui.activity;
import android.net.Uri;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.StorageReference;
/**
* Created by Moustafa on 12/15/2017.
*/
public class Post {
private static final int GALLERY_REQUEST=2;
private Uri uri =null;
private StorageReference storageRefrence;
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
}
| 27.045455 | 95 | 0.789916 |
dfa72524e65a405cc6c5d853c9c2ab9ce92d77e2 | 30,672 | /*
Derby - Class org.apache.derby.impl.sql.compile.LikeEscapeOperatorNode
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derby.impl.sql.compile;
import java.sql.Types;
import java.util.Arrays;
import java.util.List;
import org.apache.derby.shared.common.error.StandardException;
import org.apache.derby.shared.common.reference.Limits;
import org.apache.derby.shared.common.reference.SQLState;
import org.apache.derby.iapi.services.classfile.VMOpcode;
import org.apache.derby.iapi.services.compiler.MethodBuilder;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.iapi.types.DataTypeDescriptor;
import org.apache.derby.iapi.types.Like;
import org.apache.derby.iapi.types.StringDataValue;
import org.apache.derby.iapi.types.TypeId;
/**
This node represents a like comparison operator (no escape)
If the like pattern is a constant or a parameter then if possible
the like is modified to include a >= and < operator. In some cases
the like can be eliminated. By adding =, >= or < operators it may
allow indexes to be used to greatly narrow the search range of the
query, and allow optimizer to estimate number of rows to affected.
constant or parameter LIKE pattern with prefix followed by optional wild
card e.g. Derby%
CHAR(n), VARCHAR(n) where n < 255
>= prefix padded with '\u0000' to length n -- e.g. Derby\u0000\u0000
<= prefix appended with '\uffff' -- e.g. Derby\uffff
[ can eliminate LIKE if constant. ]
CHAR(n), VARCHAR(n), LONG VARCHAR where n >= 255
>= prefix backed up one characer
<= prefix appended with '\uffff'
no elimination of like
parameter like pattern starts with wild card e.g. %Derby
CHAR(n), VARCHAR(n) where n <= 256
>= '\u0000' padded with '\u0000' to length n
<= '\uffff'
no elimination of like
CHAR(n), VARCHAR(n), LONG VARCHAR where n > 256
>= NULL
<= '\uffff'
Note that the Unicode value '\uffff' is defined as not a character value
and can be used by a program for any purpose. We use it to set an upper
bound on a character range with a less than predicate. We only need a single
'\uffff' appended because the string 'Derby\uffff\uffff' is not a valid
String because '\uffff' is not a valid character.
**/
public final class LikeEscapeOperatorNode extends TernaryOperatorNode
{
/**************************************************************************
* Fields of the class
**************************************************************************
*/
boolean addedEquals;
String escape;
/**
* Constructor for a LikeEscapeOperatorNode
*
* receiver like pattern [ escape escapeValue ]
*
* @param receiver The left operand of the like:
* column, CharConstant or Parameter
* @param leftOperand The right operand of the like: the pattern
* @param rightOperand The optional escape clause, null if not present
* @param cm The context manager
*/
LikeEscapeOperatorNode(
ValueNode receiver,
ValueNode leftOperand,
ValueNode rightOperand,
ContextManager cm)
{
/* By convention, the method name for the like operator is "like" */
super(receiver,
leftOperand,
rightOperand,
TernaryOperatorNode.K_LIKE,
cm);
}
/**
* implement binding for like expressions.
* <p>
* overrides BindOperatorNode.bindExpression because like has special
* requirements for parameter binding.
*
* @return The new top of the expression tree.
*
* @exception StandardException thrown on failure
*/
@Override
ValueNode bindExpression(
FromList fromList, SubqueryList subqueryList, List<AggregateNode> aggregates)
throws StandardException
{
super.bindExpression(fromList, subqueryList, aggregates);
String pattern = null;
// pattern must be a string or a parameter
if (!(leftOperand.requiresTypeFromContext()) &&
!(leftOperand.getTypeId().isStringTypeId()))
{
throw StandardException.newException(
SQLState.LANG_DB2_FUNCTION_INCOMPATIBLE, "LIKE", "FUNCTION");
}
// escape must be a string or a parameter
if ((rightOperand != null) &&
!(rightOperand.requiresTypeFromContext()) &&
!(rightOperand.getTypeId().isStringTypeId()))
{
throw StandardException.newException(
SQLState.LANG_DB2_FUNCTION_INCOMPATIBLE, "LIKE", "FUNCTION");
}
// deal with operand parameters
/*
* Is there a ? parameter on the left? ie. "? like 'Derby'"
*
* Do left first because its length is always maximum;
* a parameter on the right copies its length from
* the left, since it won't match if it is any longer than it.
*/
if (receiver.requiresTypeFromContext())
{
receiver.setType(
new DataTypeDescriptor(
TypeId.getBuiltInTypeId(Types.VARCHAR), true));
//check if this parameter can pick up it's collation from pattern
//or escape clauses in that order. If not, then it will take it's
//collation from the compilation schema.
if (!leftOperand.requiresTypeFromContext()) {
receiver.setCollationInfo(leftOperand.getTypeServices());
} else if (rightOperand != null && !rightOperand.requiresTypeFromContext()) {
receiver.setCollationInfo(rightOperand.getTypeServices());
} else {
receiver.setCollationUsingCompilationSchema();
}
}
/*
* Is there a ? parameter for the PATTERN of LIKE? ie. "column like ?"
*
* Copy from the receiver -- legal if both are parameters,
* both will be max length.
* REMIND: should nullability be copied, or set to true?
*/
if (leftOperand.requiresTypeFromContext())
{
/*
* Set the pattern to the type of the left parameter, if
* the left is a string, otherwise set it to be VARCHAR.
*/
if (receiver.getTypeId().isStringTypeId())
{
leftOperand.setType(receiver.getTypeServices());
}
else
{
leftOperand.setType(
new DataTypeDescriptor(
TypeId.getBuiltInTypeId(Types.VARCHAR), true));
}
//collation of ? operand should be picked up from the context.
//By the time we come here, receiver will have correct collation
//set on it and hence we can rely on it to get correct collation
//for the other ? in LIKE clause
leftOperand.setCollationInfo(receiver.getTypeServices());
}
/*
* Is there a ? parameter for the ESCAPE of LIKE?
* Copy from the receiver -- legal if both are parameters,
* both will be max length. nullability is set to true.
*/
if (rightOperand != null && rightOperand.requiresTypeFromContext())
{
/*
* Set the pattern to the type of the left parameter, if
* the left is a string, otherwise set it to be VARCHAR.
*/
if (receiver.getTypeId().isStringTypeId())
{
rightOperand.setType(receiver.getTypeServices());
}
else
{
rightOperand.setType(
new DataTypeDescriptor(
TypeId.getBuiltInTypeId(Types.VARCHAR), true));
}
//collation of ? operand should be picked up from the context.
//By the time we come here, receiver will have correct collation
//set on it and hence we can rely on it to get correct collation
//for the other ? in LIKE clause
rightOperand.setCollationInfo(receiver.getTypeServices());
}
bindToBuiltIn();
/* The receiver must be a string type
*/
if (! receiver.getTypeId().isStringTypeId())
{
throw StandardException.newException(
SQLState.LANG_DB2_FUNCTION_INCOMPATIBLE, "LIKE", "FUNCTION");
}
/* If either the left or right operands are non-string types,
* then we generate an implicit cast to VARCHAR.
*/
if (!leftOperand.getTypeId().isStringTypeId())
{
leftOperand = castArgToString(leftOperand);
}
if (rightOperand != null)
{
rightOperand = castArgToString(rightOperand);
}
/*
* Remember whether or not the right side (the like pattern) is a string
* constant. We need to remember here so that we can transform LIKE
* 'constant' into = 'constant' for non unicode based collation columns.
*/
boolean leftConstant = (leftOperand instanceof CharConstantNode);
if (leftConstant)
{
pattern = ((CharConstantNode) leftOperand).getString();
}
boolean rightConstant = (rightOperand instanceof CharConstantNode);
if (rightConstant)
{
escape = ((CharConstantNode) rightOperand).getString();
if (escape.length() != 1)
{
throw StandardException.newException(
SQLState.LANG_INVALID_ESCAPE_CHARACTER, escape);
}
}
else if (rightOperand == null)
{
// No Escape clause: Let optimization continue for the = case below
rightConstant = true;
}
/* If we are comparing a UCS_BASIC char with a terriotry based char
* then we generate a cast above the receiver to force preprocess to
* not attempt any of the > <= optimizations since there is no
* way to determine the 'next' character for the <= operand.
*
* TODO-COLLATE - probably need to do something about different
* collation types here.
*/
// The left and the pattern of the LIKE must be same collation type
// and derivation.
if (!receiver.getTypeServices().compareCollationInfo(
leftOperand.getTypeServices()))
{
// throw error.
throw StandardException.newException(
SQLState.LANG_LIKE_COLLATION_MISMATCH,
receiver.getTypeServices().getSQLstring(),
receiver.getTypeServices().getCollationName(),
leftOperand.getTypeServices().getSQLstring(),
leftOperand.getTypeServices().getCollationName());
}
/* If the left side of LIKE is a ColumnReference and right side is a
* string constant without a wildcard (eg. column LIKE 'Derby') then we
* transform the LIKE into the equivalent LIKE AND =.
* If we have an escape clause it also must be a constant
* (eg. column LIKE 'Derby' ESCAPE '%').
*
* These types of transformations are normally done at preprocess time,
* but we make an exception and do this one at bind time because we
* transform a NOT LIKE 'a' into (a LIKE 'a') = false prior to
* preprocessing.
*
* The transformed tree will become:
*
* AND
* / \
* LIKE =
*/
if ((receiver instanceof ColumnReference) &&
leftConstant &&
rightConstant)
{
if (Like.isOptimizable(pattern))
{
String newPattern = null;
/*
* If our pattern has no pattern chars (after stripping them out
* for the ESCAPE case), we are good to apply = to this match
*/
if (escape != null)
{
/* we return a new pattern stripped of ESCAPE chars */
newPattern =
Like.stripEscapesNoPatternChars(
pattern, escape.charAt(0));
}
else if (pattern.indexOf('_') == -1 &&
pattern.indexOf('%') == -1)
{
// no pattern characters.
newPattern = pattern;
}
if (newPattern != null)
{
// met all conditions, transform LIKE into a "LIKE and ="
ValueNode leftClone = receiver.getClone();
// Remember that we did xform, see preprocess()
addedEquals = true;
// create equals node of the form (eg. column like 'Derby' :
// =
// / \
// column 'Derby'
BinaryComparisonOperatorNode equals =
new BinaryRelationalOperatorNode(
BinaryRelationalOperatorNode.K_EQUALS,
leftClone,
new CharConstantNode(newPattern,
getContextManager()),
false,
getContextManager());
// Set forQueryRewrite to bypass comparability checks
equals.setForQueryRewrite(true);
equals = (BinaryComparisonOperatorNode)
equals.bindExpression(
fromList, subqueryList, aggregates);
// create new and node and hook in "equals" the new "=' node
//
// AND
// / \
// LIKE =
// / \
// column 'Derby'
AndNode newAnd =
new AndNode(this, equals, getContextManager());
finishBindExpr();
newAnd.postBindFixup();
return newAnd;
}
}
}
finishBindExpr();
return this;
}
private void finishBindExpr()
throws StandardException
{
// deal with compatability of operands and result type
bindComparisonOperator();
/*
** The result type of LIKE is Boolean
*/
boolean nullableResult =
receiver.getTypeServices().isNullable() ||
leftOperand.getTypeServices().isNullable();
if (rightOperand != null)
{
nullableResult |= rightOperand.getTypeServices().isNullable();
}
setType(new DataTypeDescriptor(TypeId.BOOLEAN_ID, nullableResult));
}
/**
* Bind this operator
*
* @exception StandardException Thrown on error
*/
public void bindComparisonOperator()
throws StandardException
{
TypeId receiverType = receiver.getTypeId();
TypeId leftType = leftOperand.getTypeId();
/*
** Check the type of the operands - this function is allowed only on
** string types.
*/
if (!receiverType.isStringTypeId())
{
throw StandardException.newException(
SQLState.LANG_LIKE_BAD_TYPE, receiverType.getSQLTypeName());
}
if (!leftType.isStringTypeId())
{
throw StandardException.newException(
SQLState.LANG_LIKE_BAD_TYPE, leftType.getSQLTypeName());
}
if (rightOperand != null && ! rightOperand.getTypeId().isStringTypeId())
{
throw StandardException.newException(
SQLState.LANG_LIKE_BAD_TYPE,
rightOperand.getTypeId().getSQLTypeName());
}
}
/**
* Preprocess an expression tree. We do a number of transformations
* here (including subqueries, IN lists, LIKE and BETWEEN) plus
* subquery flattening.
* NOTE: This is done before the outer ResultSetNode is preprocessed.
*
* @param numTables Number of tables in the DML Statement
* @param outerFromList FromList from outer query block
* @param outerSubqueryList SubqueryList from outer query block
* @param outerPredicateList PredicateList from outer query block
*
* @return The modified expression
*
* @exception StandardException Thrown on error
*/
@Override
ValueNode preprocess(
int numTables,
FromList outerFromList,
SubqueryList outerSubqueryList,
PredicateList outerPredicateList)
throws StandardException
{
boolean eliminateLikeComparison = false;
String greaterEqualString = null;
String lessThanString = null;
/* We must 1st preprocess the component parts */
super.preprocess(
numTables, outerFromList, outerSubqueryList, outerPredicateList);
/* Don't try to optimize for (C)LOB type since it doesn't allow
* comparison.
* RESOLVE: should this check be for LONG VARCHAR also?
*/
if (receiver.getTypeId().getSQLTypeName().equals("CLOB"))
{
return this;
}
/* No need to consider transformation if we already did transformation
* that added = * at bind time.
*/
if (addedEquals)
{
return this;
}
/* if like pattern is not a constant and not a parameter,
* then can't optimize, eg. column LIKE column
*/
if (!(leftOperand instanceof CharConstantNode) &&
!(leftOperand.requiresTypeFromContext()))
{
return this;
}
/* This transformation is only worth doing if it is pushable, ie, if
* the receiver is a ColumnReference.
*/
if (!(receiver instanceof ColumnReference))
{
// We also do an early return here if in bindExpression we found
// we had a territory based Char and put a CAST above the receiver.
//
return this;
}
/*
* In first implementation of non default collation don't attempt
* any transformations for LIKE.
*
* Future possibilities:
* o is it valid to produce a >= clause for a leading constant with
* a wildcard that works across all possible collations? Is
* c1 like a% the same as c1 like a% and c1 >= a'\u0000''\u0000',... ?
*
* This is what was done for national char's. It seems like a
* given collation could sort: ab, a'\u0000'. Is there any guarantee
* about the sort of the unicode '\u0000'.
*
* o National char's didn't try to produce a < than, is there a way
* in collation?
*/
if (receiver.getTypeServices().getCollationType() !=
StringDataValue.COLLATION_TYPE_UCS_BASIC)
{
// don't do any < or >= transformations for non default collations.
return this;
}
/* This is where we do the transformation for LIKE to make it
* optimizable.
* c1 LIKE 'asdf%' -> c1 LIKE 'asdf%' AND c1 >= 'asdf' AND c1 < 'asdg'
* c1 LIKE ? -> c1 LIKE ? and c1 >= ?
* where ? gets calculated at the beginning of execution.
*/
// Build String constants if right side (pattern) is a constant
if (leftOperand instanceof CharConstantNode)
{
String pattern = ((CharConstantNode) leftOperand).getString();
if (!Like.isOptimizable(pattern))
{
return this;
}
int maxWidth = receiver.getTypeServices().getMaximumWidth();
// DERBY-6477: Skip this optimization if the receiver column has
// a very high maximum width (typically columns in the system
// tables, as they don't have the same restrictions as columns
// in user tables). Since greaterEqualString and lessThanString
// are padded to the maximum width, this optimization may cause
// OOME if the maximum width is high.
if (maxWidth > Limits.DB2_LONGVARCHAR_MAXWIDTH) {
return this;
}
greaterEqualString =
Like.greaterEqualString(pattern, escape, maxWidth);
lessThanString =
Like.lessThanString(pattern, escape, maxWidth);
eliminateLikeComparison =
!Like.isLikeComparisonNeeded(pattern);
}
/* For some unknown reason we need to clone the receiver if it is
* a ColumnReference because reusing them in Qualifiers for a scan
* does not work.
*/
/* The transformed tree has to be normalized. Either:
* AND AND
* / \ / \
* LIKE AND OR: LIKE AND
* / \ / \
* >= AND >= TRUE
* / \
* < TRUE
* unless the like string is of the form CONSTANT%, in which
* case we can do away with the LIKE altogether:
* AND AND
* / \ / \
* >= AND OR: >= TRUE
* / \
* < TRUE
*/
AndNode newAnd = null;
ValueNode trueNode = new BooleanConstantNode(true, getContextManager());
/* Create the AND <, if lessThanString is non-null or
* leftOperand is a parameter.
*/
if (lessThanString != null ||
leftOperand.requiresTypeFromContext())
{
ValueNode likeLTopt;
if (leftOperand.requiresTypeFromContext())
{
// pattern string is a parameter
likeLTopt =
setupOptimizeStringFromParameter(
leftOperand,
rightOperand,
"lessThanStringFromParameter",
receiver.getTypeServices().getMaximumWidth());
}
else
{
// pattern string is a constant
likeLTopt =
new CharConstantNode(lessThanString, getContextManager());
}
BinaryComparisonOperatorNode lessThan =
new BinaryRelationalOperatorNode(
BinaryRelationalOperatorNode.K_LESS_THAN,
receiver.getClone(),
likeLTopt,
false,
getContextManager());
// Disable comparability checks
lessThan.setForQueryRewrite(true);
/* Set type info for the operator node */
lessThan.bindComparisonOperator();
// Use between selectivity for the <
lessThan.setBetweenSelectivity();
/* Create the AND */
newAnd = new AndNode(lessThan, trueNode, getContextManager());
newAnd.postBindFixup();
}
/* Create the AND >=. Right side could be a CharConstantNode or a
* ParameterNode.
*/
ValueNode likeGEopt;
if (leftOperand.requiresTypeFromContext())
{
// the pattern is a ?, eg. c1 LIKE ?
// Create an expression off the parameter
// new SQLChar(Like.greaterEqualString(?));
likeGEopt =
setupOptimizeStringFromParameter(
leftOperand,
rightOperand,
"greaterEqualStringFromParameter",
receiver.getTypeServices().getMaximumWidth());
}
else
{
// the pattern is a constant, eg. c1 LIKE 'Derby'
likeGEopt =
new CharConstantNode(greaterEqualString, getContextManager());
}
// greaterEqual from (reciever LIKE pattern):
// >=
// / \
// reciever pattern
BinaryComparisonOperatorNode greaterEqual =
new BinaryRelationalOperatorNode(
BinaryRelationalOperatorNode.K_GREATER_EQUALS,
receiver.getClone(),
likeGEopt,
false,
getContextManager());
// Disable comparability checks
greaterEqual.setForQueryRewrite(true);
/* Set type info for the operator node */
greaterEqual.bindComparisonOperator();
// Use between selectivity for the >=
greaterEqual.setBetweenSelectivity();
/* Create the AND */
if (newAnd == null)
{
newAnd = new AndNode(greaterEqual, trueNode, getContextManager());
}
else
{
newAnd = new AndNode(greaterEqual, newAnd, getContextManager());
}
newAnd.postBindFixup();
/* Finally, we put an AND LIKE on top of the left deep tree, but
* only if it is still necessary.
*/
if (!eliminateLikeComparison)
{
newAnd = new AndNode(this, newAnd, getContextManager());
newAnd.postBindFixup();
}
/* Mark this node as transformed so that we don't get
* calculated into the selectivity multiple times.
*/
setTransformed();
return newAnd;
}
/**
* Do code generation for this binary operator.
*
* This code was copied from BinaryOperatorNode and stripped down
*
* @param acb The ExpressionClassBuilder for the class we're generating
* @param mb The method the code to place the code
*
*
* @exception StandardException Thrown on error
*/
@Override
void generateExpression(
ExpressionClassBuilder acb, MethodBuilder mb)
throws StandardException
{
/*
** if i have a operator.getOrderableType() == constant, then just cache
** it in a field. if i have QUERY_INVARIANT, then it would be good to
** cache it in something that is initialized each execution,
** but how?
*/
/*
** let the receiver type be determined by an
** overridable method so that if methods are
** not implemented on the lowest interface of
** a class, they can note that in the implementation
** of the node that uses the method.
*/
// receiverType = getReceiverInterfaceName();
/*
** Generate LHS (field = <receiver operand>). This assignment is
** used as the receiver of the method call for this operator.
**
** (<receiver operand>).method(
** <left operand>,
** <right operand>,
** [<escaperightOp>,]
** result field>)
*/
receiver.generateExpression(acb, mb); // first arg
receiverInterfaceType = receiver.getTypeCompiler().interfaceName();
mb.upCast(receiverInterfaceType); // cast the method instance
leftOperand.generateExpression(acb, mb);
mb.upCast(leftInterfaceType); // first arg with cast
if (rightOperand != null)
{
rightOperand.generateExpression(acb, mb);
mb.upCast(rightInterfaceType); // second arg with cast
}
/* Figure out the result type name */
// resultTypeName = getTypeCompiler().interfaceName();
mb.callMethod(
VMOpcode.INVOKEINTERFACE,
null,
methodName,
resultInterfaceType,
rightOperand == null ? 1 : 2);
}
private ValueNode setupOptimizeStringFromParameter(
ValueNode parameterNode,
ValueNode escapeNode,
String methodName,
int maxWidth)
throws StandardException
{
if (escapeNode != null)
{
methodName += "WithEsc";
}
StaticMethodCallNode methodCall = new StaticMethodCallNode(
methodName,
"org.apache.derby.iapi.types.Like",
getContextManager());
// using a method call directly, thus need internal sql capability
methodCall.internalCall = true;
NumericConstantNode maxWidthNode = new NumericConstantNode(
TypeId.getBuiltInTypeId(Types.INTEGER),
Integer.valueOf(maxWidth),
getContextManager());
ValueNode[] param = (escapeNode == null) ?
new ValueNode[] { parameterNode, maxWidthNode } :
new ValueNode[] { parameterNode, escapeNode, maxWidthNode };
methodCall.addParms(Arrays.asList(param));
ValueNode java2SQL =
new JavaToSQLValueNode(methodCall, getContextManager());
java2SQL = java2SQL.bindExpression(null, null, null);
CastNode likeOpt = new CastNode(
java2SQL,
parameterNode.getTypeServices(),
getContextManager());
likeOpt.bindCastNodeOnly();
return likeOpt;
}
}
| 35.013699 | 89 | 0.55699 |
887a19f2b2817f74c1cdb109cb8425d5bc3591e1 | 12,452 | /*
* Copyright 2015 Jim Alexander, Aesthetic Software, Inc. (jhaood@gmail.com)
* Apache Version 2 license: http://www.apache.org/licenses/LICENSE-2.0
*/
package com.aestheticsw.jobkeywords.service.termextractor.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import com.aestheticsw.jobkeywords.config.DatabaseTestBehavior;
import com.aestheticsw.jobkeywords.service.termextractor.domain.QueryKey;
import com.aestheticsw.jobkeywords.service.termextractor.domain.SearchParameters;
import com.aestheticsw.jobkeywords.service.termextractor.domain.TermFrequency;
import com.aestheticsw.jobkeywords.service.termextractor.domain.TermFrequencyResults;
@RunWith(SpringJUnit4ClassRunner.class)
@DatabaseTestBehavior
@TransactionConfiguration(defaultRollback = false, transactionManager = "transactionManager")
public class TermFrequencyResultsRepositoryTest {
@Autowired
private TermFrequencyResultsRepository termFrequencyResultsRepository;
@Autowired
private SearchParametersRepository searchParametersRepository;
@Autowired
private QueryKeyRepository queryKeyRepository;
@Autowired
PlatformTransactionManager transactionManager;
@Test
public void loadContext() {
assertNotNull(termFrequencyResultsRepository);
assertNotNull(searchParametersRepository);
assertNotNull(transactionManager);
}
@Test
public void saveAndRetrieve() {
TermFrequency tf1 = new TermFrequency(new String[] { "java", "3", "1" });
TermFrequency tf2 = new TermFrequency(new String[] { "spring", "2", "1" });
List<TermFrequency> list1 = new ArrayList<>();
list1.add(tf1);
list1.add(tf2);
TransactionStatus status = transactionManager.getTransaction(null);
QueryKey key1 = new QueryKey("query-one", Locale.US, "");
{
QueryKey dbKey = queryKeyRepository.findByCompoundKey(key1);
if (dbKey != null) {
key1 = dbKey;
}
}
SearchParameters param1 = new SearchParameters(key1, 1, 1, 0, "");
{
SearchParameters dbParam = searchParametersRepository.findByCompoundKey(param1);
if (dbParam != null) {
param1 = dbParam;
}
}
{
TermFrequencyResults tfr;
if (key1.getId() != null) {
TermFrequencyResults dbTfr;
dbTfr = termFrequencyResultsRepository.findByQueryKey(key1);
if (dbTfr != null) {
termFrequencyResultsRepository.delete(dbTfr);
}
}
}
transactionManager.commit(status);
status = transactionManager.getTransaction(null);
{
{
QueryKey dbKey = queryKeyRepository.findByCompoundKey(key1);
if (dbKey != null) {
key1 = dbKey;
}
}
{
SearchParameters dbParam = searchParametersRepository.findByCompoundKey(param1);
if (dbParam != null) {
param1 = dbParam;
}
}
TermFrequencyResults tfr;
tfr = new TermFrequencyResults(key1);
tfr.accumulateTermFrequencyList(param1, list1);
termFrequencyResultsRepository.save(tfr);
}
transactionManager.commit(status);
status = transactionManager.getTransaction(null);
{
TermFrequencyResults dbTfr1 = termFrequencyResultsRepository.findByQueryKey(param1.getQueryKey());
assertNotNull(dbTfr1);
assertNotNull(dbTfr1.getQueryKey());
List<SearchParameters> dbSearchParameters = dbTfr1.getSearchParametersList();
assertNotNull(dbSearchParameters);
// Can't assert the size because this test-class doesn't roll back - MySQL may already have 2 SearchParams.
// assertEquals(1, dbSearchParameters.size());
assertTrue(dbSearchParameters.contains(param1));
List<TermFrequency> dbTerms = dbTfr1.getSortedTermFrequencyList();
assertNotNull(dbTerms);
assertEquals(2, dbTerms.size());
assertEquals("java", dbTerms.get(0).getTerm());
assertEquals(3, dbTerms.get(0).getFrequency());
assertEquals("spring", dbTerms.get(1).getTerm());
assertEquals(2, dbTerms.get(1).getFrequency());
}
transactionManager.commit(status);
status = transactionManager.getTransaction(null);
{
QueryKey dbKey = queryKeyRepository.findByCompoundKey(key1);
SearchParameters param1_2 = new SearchParameters(dbKey, 1, 2, 0, "");
{
SearchParameters dbParam = searchParametersRepository.findByCompoundKey(param1_2);
if (dbParam != null) {
param1_2 = dbParam;
}
}
TermFrequencyResults dbTfr1 = termFrequencyResultsRepository.findByQueryKey(dbKey);
dbTfr1.accumulateTermFrequencyList(param1_2, list1);
termFrequencyResultsRepository.save(dbTfr1);
}
transactionManager.commit(status);
status = transactionManager.getTransaction(null);
{
TermFrequencyResults dbTfr2 = termFrequencyResultsRepository.findByQueryKey(param1.getQueryKey());
assertNotNull(dbTfr2);
assertNotNull(dbTfr2.getQueryKey());
List<SearchParameters> dbSearchParameters = dbTfr2.getSearchParametersList();
assertNotNull(dbSearchParameters);
assertEquals(2, dbSearchParameters.size());
List<TermFrequency> dbTerms = dbTfr2.getSortedTermFrequencyList();
assertNotNull(dbTerms);
assertEquals(2, dbTerms.size());
assertEquals("java", dbTerms.get(0).getTerm());
assertEquals(6, dbTerms.get(0).getFrequency());
assertEquals("spring", dbTerms.get(1).getTerm());
assertEquals(4, dbTerms.get(1).getFrequency());
}
}
@Test
public void distinctQueryKeys() {
TransactionStatus status = transactionManager.getTransaction(null);
TermFrequency tf1 = new TermFrequency(new String[] { "java", "3", "1" });
TermFrequency tf2 = new TermFrequency(new String[] { "spring", "2", "1" });
List<TermFrequency> list1 = new ArrayList<>();
list1.add(tf1);
list1.add(tf2);
QueryKey key1 = new QueryKey("query-two", Locale.US, "");
{
QueryKey dbKey = queryKeyRepository.findByCompoundKey(key1);
if (dbKey != null) {
key1 = dbKey;
}
}
SearchParameters param1 = new SearchParameters(key1, 1, 1, 0, "");
{
SearchParameters dbParam = searchParametersRepository.findByCompoundKey(param1);
if (dbParam != null) {
param1 = dbParam;
}
}
{
TermFrequencyResults tfr;
if (key1.getId() != null) {
TermFrequencyResults dbTfr;
dbTfr = termFrequencyResultsRepository.findByQueryKey(key1);
if (dbTfr != null) {
termFrequencyResultsRepository.delete(dbTfr);
}
}
}
transactionManager.commit(status);
status = transactionManager.getTransaction(null);
{
{
QueryKey dbKey = queryKeyRepository.findByCompoundKey(key1);
if (dbKey != null) {
key1 = dbKey;
}
}
{
SearchParameters dbParam = searchParametersRepository.findByCompoundKey(param1);
if (dbParam != null) {
param1 = dbParam;
}
}
TermFrequencyResults tfr;
if (key1.getId() != null) {
tfr = termFrequencyResultsRepository.findByQueryKey(key1);
if (tfr == null) {
tfr = new TermFrequencyResults(key1);
}
} else {
tfr = new TermFrequencyResults(key1);
}
tfr.accumulateTermFrequencyList(param1, list1);
termFrequencyResultsRepository.save(tfr);
}
transactionManager.commit(status);
status = transactionManager.getTransaction(null);
{
QueryKey dbKey1 = queryKeyRepository.findByCompoundKey(key1);
SearchParameters param1_2 = new SearchParameters(dbKey1, 1, 2, 0, "");
TermFrequencyResults tfr = termFrequencyResultsRepository.findByQueryKey(dbKey1);
assertNotNull(tfr);
tfr.accumulateTermFrequencyList(param1_2, list1);
termFrequencyResultsRepository.save(tfr);
}
transactionManager.commit(status);
status = transactionManager.getTransaction(null);
{
QueryKey key2 = new QueryKey("query-three", Locale.US, "");
{
QueryKey dbKey = queryKeyRepository.findByCompoundKey(key2);
if (dbKey != null) {
key2 = dbKey;
}
}
SearchParameters param2 = new SearchParameters(key2, 1, 1, 0, "");
{
SearchParameters dbParam = searchParametersRepository.findByCompoundKey(param2);
if (dbParam != null) {
param2 = dbParam;
}
}
TermFrequencyResults tfr;
if (key2.getId() != null) {
tfr = termFrequencyResultsRepository.findByQueryKey(key2);
if (tfr == null) {
tfr = new TermFrequencyResults(key2);
}
} else {
tfr = new TermFrequencyResults(key2);
}
tfr.accumulateTermFrequencyList(param2, list1);
termFrequencyResultsRepository.save(tfr);
}
}
// expected exception handling doesn't work correctly if @Transaction method will commit. BUG in Spring.
@Test(expected = DataIntegrityViolationException.class)
// This is required to avoid a RollbackException after the last transaction completes
@Rollback(true)
public void distinctQueryKeyException() {
QueryKey key1 = new QueryKey("query-four", Locale.US, "");
SearchParameters param1 = new SearchParameters(key1, 1, 1, 0, "");
SearchParameters param1_2 = new SearchParameters(key1, 1, 2, 0, "");
QueryKey key3 = new QueryKey("query-five", Locale.US, "");
SearchParameters param2 = new SearchParameters(key3, 1, 1, 0, "");
TermFrequency tf1 = new TermFrequency(new String[] { "java", "3", "1" });
TermFrequency tf2 = new TermFrequency(new String[] { "spring", "2", "1" });
List<TermFrequency> list1 = new ArrayList<>();
list1.add(tf1);
list1.add(tf2);
TransactionStatus status = transactionManager.getTransaction(null);
{
TermFrequencyResults tfr = new TermFrequencyResults(key1);
tfr.accumulateTermFrequencyList(param1, list1);
termFrequencyResultsRepository.save(tfr);
}
transactionManager.commit(status);
status = transactionManager.getTransaction(null);
{
TermFrequencyResults tfr = new TermFrequencyResults(key1);
tfr.accumulateTermFrequencyList(param1_2, list1);
termFrequencyResultsRepository.save(tfr);
fail("Expected constraint violation exception on the term_frequency_results.query_key_id foreign-key constraint");
}
}
}
| 38.9125 | 126 | 0.617411 |
7e79c26e389e3d267e6f5cb00588b6e3def2fffe | 528 | package com.kenshine.dwr;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
/**
* @author :kenshine
* @date :Created in 2021/11/26 22:09
* @description:DwrApp
* @modified By:
* @version: $
*/
@SpringBootApplication
@ImportResource("classpath*:spring/spring.xml")
public class DwrApp {
public static void main(String[] args) {
SpringApplication.run(DwrApp.class,args);
}
}
| 25.142857 | 68 | 0.751894 |
1a9803691471d0b9be1e59e3ee59e335e23e2376 | 439 | /* Copyright 2010, 2017, Oracle and/or its affiliates. All rights reserved. */
package demo.controller;
import oracle.adf.controller.v2.context.LifecycleContext;
import oracle.adf.controller.v2.lifecycle.PageController;
public class PageLoadExamplePageController extends PageController {
public PageLoadExamplePageController() {
}
public void prepareModel(LifecycleContext context) {
super.prepareModel(context);
}
}
| 36.583333 | 78 | 0.783599 |
6857cc21d2ef74ee7cf5b03c68ce9f135661f3de | 936 | // By Iacon1
// Created 09/12/2021
//
package GameEngine;
public class Point2D implements Cloneable
{
public int x;
public int y;
public Point2D(int x, int y)
{
this.x = x;
this.y = y;
}
public Point2D add(Point2D delta)
{
return new Point2D(this.x + delta.x, this.y + delta.y);
}
public Point2D multiply(int factor)
{
return new Point2D(this.x * factor, this.y * factor);
}
public Point2D subtract(Point2D delta)
{
return add(delta.multiply(-1));
}
public Point2D divide(int factor)
{
return new Point2D(this.x / factor, this.y / factor);
}
@Override
public Point2D clone()
{
return new Point2D(this.x, this.y);
}
@Override
public boolean equals(Object obj)
{
if (obj.getClass() != this.getClass()) return false;
else
{
Point2D point = (Point2D) obj;
return (x == point.x) && (y == point.y);
}
}
@Override
public int hashCode()
{
return (x + ", " + y).hashCode();
}
}
| 16.714286 | 57 | 0.637821 |
7dd2213d8af4aabff42ff730dc3515bb4d249f50 | 6,545 | package lexxzone.fightx.models;
/**
* Created by Alex Dvoryaninov on 10.02.18
*/
public class Fighter {
private String name;
private String fighterClass; // unused
private int power; // unused
private int dexterity; // unused
private int strength; // unused
private int hp;
private int shield; // unused
private int experience = 0; // unused
private int fighterLevel = 1; // unused
private String [] classes = {"человек", "эльф", "киборг", "орк"};
private boolean isMaxLevel; // unused
public Fighter (String name) {
this.name = name;
this.fighterClass = setFighterClass();
int a = 10;
int b = 10;
this.power = a + (int) (Math.random() * b);
this.dexterity =a + (int) (Math.random() * b);
this.strength = a + (int) (Math.random() * b);
this.hp = 20 + (int) (Math.random() * 15);
}
private String setFighterClass () {
String fighterClass;
int choice = (int) (Math.random() * (this.classes.length-1));
fighterClass = this.classes[choice];
return fighterClass;
}
public int hitHead() {
int hitPoints = 6;
System.out.println(this.getName() + " Проводит удар в голову: " + hitPoints);
return hitPoints;
}
public int hitChest() {
int hitPoints = 3;
System.out.println(this.getName() + " Проводит удар в грудь: " + hitPoints);
return hitPoints;
}
public int hitHands() {
int hitPoints = 1;
System.out.println(this.getName() + " Проводит удар по рукам: " + hitPoints);
return hitPoints;
}
public int hitStomach() {
int hitPoints = 2;
System.out.println(this.getName() + " Проводит удар в живот: " + hitPoints);
return hitPoints;
}
public int hitKnee() {
int hitPoints = 5;
System.out.println(this.getName() + " Проводит удар по коленям: " + hitPoints);
return hitPoints;
}
public int hitLegs() {
int hitPoints = 2;
System.out.println(this.getName() + " Проводит удар по ногам: " + hitPoints);
return hitPoints;
}
public int hitOut() {
int hitPoints = 0;
System.out.println(this.getName() + " Удара нет - игрок промахивается.");
return hitPoints;
}
public int hitSuper() {
int hitPoints = 10;
System.out.println(this.getName() + " Проводит СУПЕР-УДАР: " + hitPoints);
return hitPoints;
}
public boolean isLife() {
return this.hp > 0;
}
private int makeHit () {
int totalHit = 0;
return totalHit;
}
public int hit () {
int totalHit = 0;
int hitType = (int) (Math.random() * 8);
if (hitType == 0) {
totalHit = this.hitHead();
} else if (hitType == 1) {
totalHit = this.hitChest();
} else if (hitType == 2) {
totalHit = this.hitHands();
} else if (hitType == 3) {
totalHit = this.hitStomach();
} else if (hitType == 4) {
totalHit = this.hitKnee();
} else if (hitType == 5) {
totalHit = this.hitLegs();
} else if (hitType == 6) {
totalHit = this.hitOut();
} else if (hitType == 7) {
totalHit = this.hitSuper();
}
return totalHit;
}
// получение урона от соперника
public void damage (int value) {
this.hp -= value;
System.out.println("У бойца " + getName() + " осталось " + getHp() + " единицы здоровья");
}
// восстановление здоровья
public void heal (int value) {
this.hp += value;
}
// проверка - требуется ли обновление уровня
public void checkUpdate() {
if (this.experience >= 100) {
if (!isMaxLevel) {
this.updateLevel();
this.experience = this.experience - 100;
}
}
}
// Обновление уровня // unused
public void updateLevel () {
this.setFighterLevel(this.getFighterLevel()+1);
this.setDexterity(this.getDexterity()+1);
this.setPower(this.getPower()+1);
this.setStrength(this.getStrength()+1);
}
// вывод информации о бойце
public void getInfo (){
System.out.println("\n\n* * * * * * * * * * * * * * * * * * * \n\n Информация об игроке:\n");
System.out.println("Имя Бойца: "+ this.getName());
System.out.println("Класс Бойца: "+ this.getFighterClass());
System.out.println("Сила Бойца: "+ this.getPower());
System.out.println("Ловкость Бойца: "+ this.getDexterity());
System.out.println("Стойкость Бойца: "+ this.getStrength());
System.out.println("Здоровье Бойца: "+ this.getHp());
System.out.println("Щит Бойца: "+ this.getShield());
System.out.println("Уровень Бойца: "+ this.getFighterLevel());
System.out.println("Опыт Бойца: "+ this.getExperience());
System.out.println(isMaxLevel? "Достигнут максимальный уровень" : "Максимальный уровень еще не достигнут" );
System.out.println("* * * * * * * * * * * * * * * * * * * \n\n\n\n");
}
public String getName() {
return name;
}
public String getFighterClass() {
return fighterClass;
}
public int getPower() {
return power;
}
public int getDexterity() {
return dexterity;
}
public int getStrength() {
return strength;
}
public int getHp() {
return hp;
}
public int getShield() {
return shield;
}
public int getExperience() {
return experience;
}
public int getFighterLevel() {
return fighterLevel;
}
public void setName(String name) {
this.name = name;
}
public void setFighterClass(String fighterClass) {
this.fighterClass = fighterClass;
}
public void setPower(int power) {
this.power = power;
}
public void setDexterity(int dexterity) {
this.dexterity = dexterity;
}
public void setStrength(int strength) {
this.strength = strength;
}
public void setHp(int hp) {
this.hp = hp;
}
public void setShield(int shield) {
this.shield = shield;
}
public void setExperience(int experience) { // unused
this.experience = experience;
}
public void setFighterLevel(int fighterLevel) { // unused
this.fighterLevel = fighterLevel;
}
}
| 27.733051 | 116 | 0.560581 |
1b3e40c3b786d92b77e697a2c47bc02e90bdb1c6 | 2,583 | package com.wangsong.system.controller;
import java.util.HashMap;
import java.util.Map;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.wangsong.common.controller.BaseController;
import com.wangsong.common.util.UserUtil;
import com.wangsong.system.model.Resources;
import com.wangsong.system.model.User;
import com.wangsong.system.service.ResourcesService;
@Controller
@RequestMapping("/system/resources")
public class ResourcesController extends BaseController {
@Autowired
private ResourcesService resourcesService;
@RequestMapping(value="/toList")
public String toList() {
return "system/resources/list";
}
@RequestMapping(value="/toAdd")
public ModelAndView toAdd(String pid) {
ModelAndView mav= new ModelAndView("system/resources/add");
mav.addObject("pid", pid);
return mav;
}
@RequiresPermissions("/system/resources/add")
@RequestMapping(value="/add")
@ResponseBody
public Object add(Resources resources) {
Map<String, Object> map=new HashMap<>();
resourcesService.insert(resources);
return map;
}
@RequiresPermissions("/system/resources/delete")
@RequestMapping(value="/delete")
@ResponseBody
public Object delete(String[] id) {
Map<String, Object> map=new HashMap<>();
resourcesService.delete(id);
return map;
}
@RequestMapping(value="/toUpdate")
public ModelAndView toUpdate(String id) {
ModelAndView mav= new ModelAndView("system/resources/update");
mav.addObject("id", id);
return mav;
}
@RequiresPermissions("/system/resources/update")
@RequestMapping(value="/update")
@ResponseBody
public Object update(Resources mresources) {
Map<String, Object> map=new HashMap<>();
resourcesService.updateByPrimaryKey(mresources);
return map;
}
@RequiresPermissions("/system/resources/list")
@RequestMapping(value="/list")
@ResponseBody
public Object list() {
return resourcesService.findResources();
}
@RequestMapping(value="/findResourcesEMUByResources")
@ResponseBody
public Object findResourcesEMUByResources() {
return resourcesService.findResourcesEMUByResources((User)UserUtil.getUser());
}
@RequestMapping(value="/selectByPrimaryKey")
@ResponseBody
public Object selectByPrimaryKey(String id) {
return resourcesService.selectByPrimaryKey(id);
}
}
| 26.357143 | 80 | 0.773906 |
8d5ce13ca646d8ea7cdf5ca93e38309084482f54 | 1,723 | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Author: Mani Afschar
*
* Creation Date: 10.10.2011
*
* Completion Time: 10.10.2011
*
*******************************************************************************/
package org.oscm.paymentservice.local;
import java.io.IOException;
import javax.ejb.Local;
import javax.wsdl.WSDLException;
import javax.xml.parsers.ParserConfigurationException;
import org.oscm.paymentservice.adapter.PaymentServiceProviderAdapter;
/**
* The local interface for port locator of the payment processing.
*
* @author Mani Afschar
*
*/
@Local
public interface PortLocatorLocal {
/**
* Determines all currently non-handled BillingResult objects and, if the
* customer uses a PSP relevant PaymentInfo, invokes the payment process for
* it.
*
* @return <code>true</code> in case the charging operations succeeded for
* all open bills, <code>false</code> otherwise.
*/
public PaymentServiceProviderAdapter getPort(String wsdl)
throws IOException, WSDLException, ParserConfigurationException;
}
| 38.288889 | 83 | 0.42484 |
c82dddc5a2c4d877a9f1d9d256184c5938c40885 | 4,306 | package io.cucumber.junit.platform.engine;
import io.cucumber.core.plugin.Options;
import io.cucumber.core.snippets.SnippetType;
import org.junit.jupiter.api.Test;
import java.net.URI;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CucumberEngineOptionsTest {
@Test
void getPluginNames() {
MapConfigurationParameters html = new MapConfigurationParameters(
Constants.PLUGIN_PROPERTY_NAME,
"html:path/to/report.html"
);
assertEquals(
singletonList("html:path/to/report.html"),
new CucumberEngineOptions(html).plugins().stream()
.map(Options.Plugin::pluginString)
.collect(toList())
);
CucumberEngineOptions htmlAndJson = new CucumberEngineOptions(
new MapConfigurationParameters(Constants.PLUGIN_PROPERTY_NAME, "html:path/with spaces/to/report.html, message:path/with spaces/to/report.ndjson")
);
assertEquals(
asList("html:path/with spaces/to/report.html", "message:path/with spaces/to/report.ndjson"),
htmlAndJson.plugins().stream()
.map(Options.Plugin::pluginString)
.collect(toList())
);
}
@Test
void isMonochrome() {
MapConfigurationParameters ansiColors = new MapConfigurationParameters(
Constants.ANSI_COLORS_DISABLED_PROPERTY_NAME,
"true"
);
assertTrue(new CucumberEngineOptions(ansiColors).isMonochrome());
MapConfigurationParameters noAnsiColors = new MapConfigurationParameters(
Constants.ANSI_COLORS_DISABLED_PROPERTY_NAME,
"false"
);
assertFalse(new CucumberEngineOptions(noAnsiColors).isMonochrome());
}
@Test
void getGlue() {
MapConfigurationParameters glue = new MapConfigurationParameters(
Constants.GLUE_PROPERTY_NAME,
"com.example.app, com.example.glue"
);
assertEquals(
asList(URI.create("classpath:/com/example/app"), URI.create("classpath:/com/example/glue")),
new CucumberEngineOptions(glue).getGlue()
);
}
@Test
void isDryRun() {
MapConfigurationParameters dryRun = new MapConfigurationParameters(
Constants.EXECUTION_DRY_RUN_PROPERTY_NAME,
"true"
);
assertTrue(new CucumberEngineOptions(dryRun).isDryRun());
MapConfigurationParameters noDryRun = new MapConfigurationParameters(
Constants.EXECUTION_DRY_RUN_PROPERTY_NAME,
"false"
);
assertFalse(new CucumberEngineOptions(noDryRun).isDryRun());
}
@Test
void getSnippetType() {
MapConfigurationParameters underscore = new MapConfigurationParameters(
Constants.SNIPPET_TYPE_PROPERTY_NAME,
"underscore"
);
assertEquals(SnippetType.UNDERSCORE, new CucumberEngineOptions(underscore).getSnippetType());
MapConfigurationParameters camelcase = new MapConfigurationParameters(
Constants.SNIPPET_TYPE_PROPERTY_NAME,
"camelcase"
);
assertEquals(SnippetType.CAMELCASE, new CucumberEngineOptions(camelcase).getSnippetType());
}
@Test
void isParallelExecutionEnabled() {
MapConfigurationParameters enabled = new MapConfigurationParameters(
Constants.PARALLEL_EXECUTION_ENABLED_PROPERTY_NAME,
"true"
);
assertTrue(new CucumberEngineOptions(enabled).isParallelExecutionEnabled());
MapConfigurationParameters disabled = new MapConfigurationParameters(
Constants.PARALLEL_EXECUTION_ENABLED_PROPERTY_NAME,
"false"
);
assertFalse(new CucumberEngineOptions(disabled).isParallelExecutionEnabled());
MapConfigurationParameters absent = new MapConfigurationParameters(
"some key", "some value"
);
assertFalse(new CucumberEngineOptions(absent).isParallelExecutionEnabled());
}
}
| 35.586777 | 157 | 0.677427 |
52741fff2b09d47eb0e831c55dd4cb66a0a2ecad | 1,021 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: metadata.proto
package com.samsung.sds.brightics.common.network.proto.metadata;
public interface ResultDataMessageOrBuilder extends
// @@protoc_insertion_point(interface_extends:com.samsung.sds.brightics.common.network.proto.metadata.ResultDataMessage)
com.google.protobuf.MessageOrBuilder {
/**
* <code>.com.samsung.sds.brightics.common.network.proto.MessageStatus messageStatus = 1;</code>
*/
int getMessageStatusValue();
/**
* <code>.com.samsung.sds.brightics.common.network.proto.MessageStatus messageStatus = 1;</code>
*/
com.samsung.sds.brightics.common.network.proto.MessageStatus getMessageStatus();
/**
* <code>.google.protobuf.Any result = 2;</code>
*/
boolean hasResult();
/**
* <code>.google.protobuf.Any result = 2;</code>
*/
com.google.protobuf.Any getResult();
/**
* <code>.google.protobuf.Any result = 2;</code>
*/
com.google.protobuf.AnyOrBuilder getResultOrBuilder();
}
| 31.90625 | 124 | 0.719882 |
f113002ca1855a36ec4804925bfa1f04279f3186 | 7,431 | package com.homeaway.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.homeaway.constants.Environment;
import com.homeaway.constants.FilePath;
import com.homeaway.utils.GlobalVariables;
import com.homeaway.utils.aws.RDSInstance;
import com.homeaway.utils.db.GlobalRDSInstance;
import com.homeaway.utils.db.SqlServer;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.IOException;
import java.util.*;
@Slf4j
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class InputJson {
public InputJson() {
}
public InputJson(String fileName) {
FrameInputJson(fileName);
if(Environment.parallelExecution) {
if (GlobalVariables.threadIds == null)
GlobalVariables.threadIds = new HashSet<>();
long threadId = Thread.currentThread().getId();
GlobalVariables.threadIds.add(threadId);
cluster.setPipelinename(cluster.getPipelinename() + "-pe-" + threadId);
}
}
public InputJson(String fileName, long threadId) {
FrameInputJson(fileName);
if(threadId > 0) {
cluster.setPipelinename(cluster.getPipelinename() + "-pe-" + threadId);
}
}
@JsonProperty("useremailaddress")
private String useremailaddress;
@JsonProperty("migrations")
private List<Migration> migrations = null;
@JsonProperty("cluster")
private Cluster cluster;
@JsonProperty("parallelmigrations")
private Boolean parallelmigrations;
@JsonProperty("jsoninputfile")
private JsonInputFile jsonInputFile;
@JsonProperty("sparkjarfile")
private String sparkJarFile;
@JsonProperty("migration_failure_threshold")
private String migrationThreshold;
private void FrameInputJson(String fileName) {
File inputJsonFile = new File(FilePath.INPUT_JSON_FILE_PATH + fileName + ".json");
File globalConfig = new File(FilePath.GLOBAL_CONFIG_FILE);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
JsonNode updatedNode = UpdateClusterDetails(inputJsonFile, globalConfig);
InputJson updatedJson = UpdateDBDetails(updatedNode, globalConfig);
useremailaddress = Environment.userEmailAddress;
migrations = updatedJson.migrations;
cluster = updatedJson.cluster;
parallelmigrations = updatedJson.parallelmigrations;
jsonInputFile = updatedJson.jsonInputFile;
sparkJarFile = updatedJson.sparkJarFile;
}
private JsonNode UpdateClusterDetails(File inputFile, File detailsToUpdate) {
ObjectNode inputNode = null;
ObjectMapper mapper = new ObjectMapper();
try {
inputNode = (ObjectNode) mapper.readTree(inputFile);
ObjectNode emr = (ObjectNode) mapper.readTree(detailsToUpdate).get("cluster");
inputNode.set("cluster", emr);
} catch (IOException e) {
e.printStackTrace();
}
return inputNode;
}
private InputJson UpdateDBDetails(JsonNode InputNode, File DBDetailsFile) {
InputJson finalJsonToReturn = null;
try {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
if (InputNode.has("migrations")) {
Iterator<JsonNode> migrationNodes = InputNode.findValue("migrations").iterator();
while (migrationNodes.hasNext()) {
ObjectNode migrationsNode = (ObjectNode) migrationNodes.next();
Iterator<JsonNode> childNodes = migrationsNode.iterator();
while (childNodes.hasNext()) {
JsonNode currentNode = childNodes.next();
if(currentNode.isArray()) {
for (JsonNode node : currentNode) {
updateNode(node, DBDetailsFile);
}
} else {
updateNode(currentNode,DBDetailsFile);
}
}
}
}
finalJsonToReturn = mapper.readValue(InputNode.toString(), InputJson.class);
} catch (Exception ex) {
ex.printStackTrace();
}
return finalJsonToReturn;
}
private void updateNode(JsonNode node, File DBDetailsFile) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
if (node.has("platform")) {
ObjectNode dbDetailToChange;
String platform = node.get("platform").asText().toLowerCase().trim();
dbDetailToChange = (ObjectNode) mapper.readTree(DBDetailsFile).get(platform);
if (dbDetailToChange != null)
((ObjectNode) node).setAll(dbDetailToChange);
else
System.out.println("Platform" + platform + "not present in the GlobalConfig.json file");
if (Arrays.stream(Environment.rdsInstanceRequired).anyMatch(x -> x.toLowerCase().trim().equals(platform))) {
Map<String, String> details = new HashMap<>();
RDSInstance rdsInstance = GlobalRDSInstance.GetRDSInstance(platform, true);
if (rdsInstance != null) {
rdsInstance.waitTillRDSAvailability();
details.put("server", rdsInstance.rdsEndPoint);
details.put("login", rdsInstance.rdsSpec.username);
details.put("password", rdsInstance.rdsSpec.password);
if (platform.equals("mssql")) {
SqlServer connection = new SqlServer(details.get("server"), details.get("login"), details.get("password"), "");
String dataBase = node.get("database").asText();
connection.createDataBase(dataBase);
details.put("database", dataBase);
connection.closeConnection();
} else {
details.put("database", rdsInstance.rdsSpec.dbName);
}
ObjectNode serverNode = mapper.valueToTree(details);
((ObjectNode) node).setAll(serverNode);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public String toString() {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
String strJson = null;
try {
strJson = mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return strJson;
}
}
| 40.82967 | 139 | 0.61701 |
eaeff234520c7eaca238640fee83cacd97a3233a | 477 | package me.yoerger.geoff.edu.progClass.mod6;
import java.util.HashMap;
import java.util.Map;
public final class MovieUserManager {
private static Map<String, MovieUser> Usermap;
public MovieUserManager() {
Usermap = new HashMap<>();
}
public boolean newUser(String name, MovieUser user) {
if (Usermap.containsKey(name)) {
return false;
}
Usermap.put(name, user);
return true;
}
public MovieUser getUser(String name) {
return Usermap.get(name);
}
}
| 19.08 | 54 | 0.716981 |
7e9296d6121285fe169f626d44286ab79c97f96f | 4,553 | package gui.Manager;
import javax.swing.*;
import bankATM.*;
import bankATM.Currency;
import database.*;
import manager.*;
import transaction.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import java.sql.Date;
import java.util.*;
public class ManageTransactions {
public static void viewAllTransactions() {
JFrame frame = new JFrame("View All Transactions");
frame.setSize(650, 500);
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(null);
JButton back = new JButton("Back");
back.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
}
});
back.setBounds(50, 20, 75, 50);
panel.add(back);
JLabel displayCurrent = new JLabel("Display Recent Transactions: ");
displayCurrent.setSize(650, 500);
JTextArea textField = new JTextArea();
DBTransaction tObj = new DBTransaction();
ArrayList<Transaction> transactions = null;
try {
transactions = tObj.retrieveTransactions();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String str = "";
for (Transaction t : transactions) {
str += t.getId() + ": \n" + t + "\n\n";
}
textField.setText(str);
JScrollPane scroll = new JScrollPane(textField);
scroll.setBounds(10, 11, 455, 249); // <-- THIS
frame.getContentPane().add(scroll);
frame.setLocationRelativeTo(null);
panel.add(displayCurrent);
frame.setVisible(true);
}
public static void specificTransaction() {
JFrame frame = new JFrame("View All Transactions");
frame.setSize(650, 500);
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(null);
JButton back = new JButton("Back");
back.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
}
});
back.setBounds(50, 20, 75, 50);
panel.add(back);
Date specifiedDate = new Date(2020, 01, 01);
JButton chooseDates = new JButton("Choose date");
// all the possible dates are going to need to be connected from the back end
// here, possibly in the form of multiple JButtons
chooseDates.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JFrame frame = new JFrame("View All Transactions");
frame.setSize(650, 500);
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(null);
JButton back = new JButton("Back");
back.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
}
});
back.setBounds(50, 20, 75, 50);
panel.add(back);
JLabel displayCurrent = new JLabel("Display Transactions for Specified Date: ");
displayCurrent.setBounds(200, 70, 150, 40);
JTextArea textField = new JTextArea();
DBTransaction tObj = new DBTransaction();
ArrayList<Transaction> transactions = null;
try {
transactions = tObj.retrieveTransactions();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String str = "";
for (Transaction t : transactions) {
if (t.getCreated().equals(specifiedDate)) {
str += t.getId() + ": \n" + t + "\n\n";
}
}
textField.setText(str);
JScrollPane scroll = new JScrollPane(textField);
scroll.setBounds(10, 11, 455, 249); // <-- THIS
frame.getContentPane().add(scroll);
frame.setLocationRelativeTo(null);
panel.add(displayCurrent);
frame.setVisible(true);
}
});
chooseDates.setBounds(180, 70, 150, 40);
panel.add(chooseDates);
frame.setVisible(true);
}
}
| 27.427711 | 85 | 0.669009 |
c9233c197970ecc7c7a20cf00a6b3532b3d8d7b8 | 809 | package generics.E02;
class Holder4<T>{
private T a,b,c;
public Holder4(T a,T b,T c){
this.a = a;
this.b = b;
this.c = c;
}
public void setA(T a){ this.a = a;}
public void setB(T b){ this.b = b;}
public void setC(T c){ this.c = c;}
public T getA(){ return a;}
public T getB(){ return b;}
public T getC(){ return c;}
}
public class E02_Holder4{
public static void main(String[] args){
Holder4<String> h4 = new Holder4<String>("A","B","C");
System.out.println(h4.getA());
System.out.println(h4.getB());
System.out.println(h4.getC());
h4.setC("D");
System.out.println(h4.getC());
}
}
/*
java generics.E02.E02_Holder4
A
B
C
D
*/
| 14.981481 | 56 | 0.506799 |
07279aa9d19acdbd4df985e4799cc029714bd19e | 2,670 | /*
* Copyright (C) 2015-2019 Fabrice Bouyé
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
package api.web.gw2.mapping.v2.tokeninfo;
import api.web.gw2.mapping.core.EnumValueFactory;
import java.util.stream.IntStream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Unit test.
*
* @author Fabrice Bouyé
*/
public class TokenInfoUtilsTest {
public TokenInfoUtilsTest() {
}
@BeforeAll
public static void setUpClass() {
}
@AfterAll
public static void tearDownClass() {
}
@BeforeEach
public void setUp() {
}
@AfterEach
public void tearDown() {
}
/**
* Test of TokenInfoPermission.
*/
@Test
public void testFindTokenInfoPermission() {
System.out.println("findTokenInfoPermission");
final String[] values = {
"account", // NOI18N.
"characters", // NOI18N.
"inventories", // NOI18N.
"tradingpost", // NOI18N.
"builds", // NOI18N.
"unlocks", // NOI18N.
"pvp", // NOI18N.
"wallet", // NOI18N.
"progression", //NOI18N.
"guilds", //NOI18N.
null,
"" // NOI18N.
};
final TokenInfoPermission[] expResults = {
TokenInfoPermission.ACCOUNT,
TokenInfoPermission.CHARACTERS,
TokenInfoPermission.INVENTORIES,
TokenInfoPermission.TRADINGPOST,
TokenInfoPermission.BUILDS,
TokenInfoPermission.UNLOCKS,
TokenInfoPermission.PVP,
TokenInfoPermission.WALLET,
TokenInfoPermission.PROGRESSION,
TokenInfoPermission.GUILDS,
TokenInfoPermission.UNKNOWN,
TokenInfoPermission.UNKNOWN
};
assertEquals(values.length, expResults.length);
IntStream.range(0, values.length).
forEach(index -> {
final String value = values[index];
final TokenInfoPermission expResult = expResults[index];
final TokenInfoPermission result = EnumValueFactory.INSTANCE.mapEnumValue(TokenInfoPermission.class, value);
assertEquals(expResult, result);
});
}
}
| 28.404255 | 128 | 0.584644 |
a2aa94a0583a4ad07d8a04842feb088897c695ff | 2,553 | package io.vertx.up.media.parse;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
import io.vertx.up.atom.Epsilon;
import io.vertx.up.exception.WebException;
import java.util.Set;
@SuppressWarnings("unchecked")
public class TypedAtomic<T> implements Atomic<T> {
@Override
public Epsilon<T> ingest(final RoutingContext context,
final Epsilon<T> income)
throws WebException {
Object returnValue = null;
final Class<?> paramType = income.getArgType();
if (is(Session.class, paramType)) {
// Session Object
returnValue = context.session();
} else if (is(HttpServerRequest.class, paramType)) {
// Request Object
returnValue = context.request();
} else if (is(HttpServerResponse.class, paramType)) {
// Response Object
returnValue = context.response();
} else if (is(Vertx.class, paramType)) {
// Vertx Object
returnValue = context.vertx();
} else if (is(EventBus.class, paramType)) {
// Eventbus Object
returnValue = context.vertx().eventBus();
} else if (is(User.class, paramType)) {
// User Objbect
returnValue = context.user();
} else if (is(Set.class, paramType)) {
// FileUpload
final Class<?> type = paramType.getComponentType();
if (is(FileUpload.class, type)) {
returnValue = context.fileUploads();
}
} else if (is(JsonArray.class, paramType)) {
// JsonArray
returnValue = context.getBodyAsJsonArray();
} else if (is(JsonObject.class, paramType)) {
// JsonObject
returnValue = context.getBodyAsJson();
} else if (is(Buffer.class, paramType)) {
// Buffer
returnValue = context.getBody();
}
return null == returnValue ? income.setValue(null) : income.setValue((T) returnValue);
}
private boolean is(final Class<?> expected, final Class<?> paramType) {
return expected == paramType || expected.isAssignableFrom(paramType);
}
}
| 37.544118 | 94 | 0.61653 |
5eaaf73a2a4e9b26a102778a6cfc697f0384e5d7 | 2,371 | /*
* Copyright 2001-2013 Aspose Pty Ltd. All Rights Reserved.
*
* This file is part of Aspose.Slides. The source code in this file
* is only intended as a supplement to the documentation, and is provided
* "as is", without warranty of any kind, either expressed or implied.
*/
package com.aspose.tasks.examples.Projects;
import com.aspose.tasks.*;
import com.aspose.tasks.Project;
import com.aspose.tasks.examples.Utils;
import java.io.FileInputStream;
public class ReadProjectFiles
{
public static void main(String[] args) throws Exception
{
// The path to the documents directory.
String dataDir = Utils.getDataDir(ReadProjectFiles.class);
CheckIfProjectIsPasswordProtected(dataDir);
ReadProjectAsTemplate(dataDir);
ReadProjectFileFromStream(dataDir);
}
public static void CheckIfProjectIsPasswordProtected(String dataDir)
{
//ExStart: CheckIfProjectIsPasswordProtected
ProjectFileInfo info = Project.getProjectFileInfo(dataDir + "project.mpp");
System.out.println("Is file password protected?:" + info.isPasswordProtected());
//ExEnd: CheckIfProjectIsPasswordProtected
}
public static void ReadProjectAsTemplate(String dataDir)
{
// ExStart: ReadProjectAsTemplate
// For complete examples and data files, please go to https://github.com/aspose-tasks/Aspose.Tasks-for-Java
// Read existing project template file
Project project = new Project(dataDir + "ReadProjectFiles.mpt");
System.out.println("Name : " + project.get(Prj.NAME));
// ExEnd: ReadProjectAsTemplate
}
public static void ReadProjectFileFromStream(String dataDir)
{
// ExStart: ReadProjectFiles
// For complete examples and data files, please go to https://github.com/aspose-tasks/Aspose.Tasks-for-Java
try
{
FileInputStream prjStream = new FileInputStream(dataDir + "Project1.mpp");
Project existingProject = new Project(prjStream);
prjStream.close();
System.out.println("Calendar : " + existingProject.get(Prj.NAME));
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
// ExEnd: ReadProjectFiles
// Display result of conversion.
System.out.println("Process completed Successfully");
}
}
| 33.394366 | 112 | 0.688739 |
6ae73b1651fd14332454207121e81bec89bd0d01 | 1,568 | package com.ehensin.pt;
import java.io.Serializable;
import java.util.List;
import com.ehensin.pt.config.Task;
/**
* 发送给压力发生器generator运行时的参数
* */
public class RuntimeParameter implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/*运行时间周期,分为单位*/
int span;
/*多少时间定期汇总运行时数据,秒为单位*/
int period;
/*执行的并发用户数,即线程数*/
int concurrents;
/*执行任务的顺序,true为顺序执行,false为随机执行*/
boolean isSeq;
/*是否在本机记录日志信息*/
boolean isLog;
/*用户数据*/
List<Serializable> userData;
/*执行的任务列表*/
List<Task> tasks;
/*压力发生器url*/
String genUrl;
public int getSpan() {
return span;
}
public void setSpan(int span) {
this.span = span;
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public int getConcurrents() {
return concurrents;
}
public void setConcurrents(int concurrents) {
this.concurrents = concurrents;
}
public boolean isSeq() {
return isSeq;
}
public void setSeq(boolean isSeq) {
this.isSeq = isSeq;
}
public boolean isLog() {
return isLog;
}
public void setLog(boolean isLog) {
this.isLog = isLog;
}
public List<Serializable> getUserData() {
return userData;
}
public void setUserData(List<Serializable> userData) {
this.userData = userData;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
public String getGenUrl() {
return genUrl;
}
public void setGenUrl(String genUrl) {
this.genUrl = genUrl;
}
}
| 18.666667 | 55 | 0.670281 |
dc44c2de2895d11bddcc25a9d4a837222080dd1a | 1,397 | package com.jungdam.album.application;
import com.jungdam.album.domain.Album;
import com.jungdam.album.infrastructure.AlbumRepository;
import com.jungdam.error.dto.ErrorMessage;
import com.jungdam.error.exception.common.NotExistException;
import com.jungdam.member.domain.Member;
import com.jungdam.participant.domain.Participant;
import com.jungdam.participant.domain.vo.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AlbumService {
private final static Logger log = LoggerFactory.getLogger(AlbumService.class);
private final AlbumRepository albumRepository;
public AlbumService(AlbumRepository albumRepository) {
this.albumRepository = albumRepository;
}
@Transactional
public Album save(Album album, Member member) {
Participant participant = new Participant(member, Role.OWNER);
album.addParticipant(participant);
return albumRepository.save(album);
}
@Transactional(readOnly = true)
public Album findById(Long id) {
return albumRepository.findById(id)
.orElseThrow(() -> new NotExistException(ErrorMessage.NOT_EXIST_ALBUM).error(log));
}
@Transactional
public void delete(Album album) {
albumRepository.delete(album);
}
} | 31.75 | 95 | 0.758769 |
7e44139b38502efccf01d09131465446bb494b4b | 641 | package com.skynet.infrastructure;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
public class FileSensitiveWordsProvider implements SensitiveWordsProvider {
private String filePath;
public void setFilePath(String filePath) {
this.filePath = filePath;
}
@Override
public List<String> provide() throws Exception {
// File file = ResourceUtils.getFile(filePath);
// return Files.readAllLines(Paths.get(file.toURI()));
return Collections.EMPTY_LIST;
}
}
| 24.653846 | 75 | 0.730109 |
18ab97fcb6022894af0dd3d49a8c96b75155a703 | 1,306 | package com.stevekung.indicatia.utils.forge;
import com.stevekung.indicatia.config.IndicatiaConfig;
public class PlatformConfigImpl
{
public static boolean getOldArmorRender()
{
return IndicatiaConfig.GENERAL.enableOldArmorRender.get();
}
public static boolean getBlockHitAnimation()
{
return IndicatiaConfig.GENERAL.enableBlockhitAnimation.get();
}
public static boolean getCustomPlayerList()
{
return IndicatiaConfig.GENERAL.enableCustomPlayerList.get();
}
public static boolean getConfirmToDisconnect()
{
return IndicatiaConfig.GENERAL.enableConfirmToDisconnect.get();
}
public static boolean getHypixelChatMode()
{
return IndicatiaConfig.GENERAL.enableHypixelChatMode.get();
}
public static boolean getHypixelDropdownShortcut()
{
return IndicatiaConfig.GENERAL.enableHypixelDropdownShortcutGame.get();
}
public static boolean getRenderBossHealthBar()
{
return IndicatiaConfig.GENERAL.enableBossHealthBarRender.get();
}
public static boolean getAFKMessage()
{
return IndicatiaConfig.GENERAL.enableAFKMessage.get();
}
public static int getAFKMessageTime()
{
return IndicatiaConfig.GENERAL.afkMessageTime.get();
}
} | 25.607843 | 79 | 0.715161 |
b3e55da435e32b9c83fe39eb3224af8610c2f069 | 2,224 | package com.commands.sub;
import com.SMPFactions;
import com.factions.Faction;
import com.factions.FactionManager;
import com.players.FactionMember;
import com.players.FactionRole;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public class DemoteFaction {
public static void runSubCommand(Player player, OfflinePlayer victim) {
if (victim != null) {
FactionManager manager = SMPFactions.factionManager;
if (manager.doesPlayerHaveFaction(player)) {
FactionMember member = manager.getFactionMember(player);
if (member.getRole() == FactionRole.LEADER) {
Faction f = manager.getPlayerFaction(player);
Faction f2 = manager.getPlayerFaction((Player) victim);
if (member.getUUID() == victim.getUniqueId()) {
player.sendMessage("§cYou can't do that to yourself...");
return;
}
if (f == f2) {
FactionMember promotedMember = manager.getFactionMember((Player) victim);
manager.promotePlayer(promotedMember, member, f);
player.sendMessage("§aSuccessfully promoted " + victim.getName() + "!");
for (FactionMember fm : f.getMembers()) {
if (fm.getPlayer().isOnline())
fm.getPlayer().sendMessage("§a" + victim.getName() + " has been promoted!");
}
if (victim.isOnline())
((Player) victim).sendMessage("§aYou've been promoted! You are now " + promotedMember.getRole());
} else {
player.sendMessage("§cYou are not in the same faction as that player!");
}
} else {
player.sendMessage("§cYou must be the leader of the faction to do that!");
}
} else {
player.sendMessage("§cYou are not in a faction!");
}
} else {
player.sendMessage("§cThat player doesn't even exist bro...");
}
}
}
| 44.48 | 125 | 0.531475 |
4f059f301dc635bb6029884e8af3dc17d717929b | 4,202 | package com.movietrailer.core.services.impl;
import com.movietrailer.core.models.ImdbDataModel;
import com.movietrailer.core.models.MovieData;
import com.movietrailer.core.restclient.RestApiClient;
import com.movietrailer.core.restclient.RestInterceptor;
import com.movietrailer.core.services.EHCacheService;
import com.movietrailer.core.services.MovieService;
import com.movietrailer.core.services.config.MovieConfig;
import feign.Feign;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.ehcache.Cache;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.metatype.annotations.Designate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import static com.movietrailer.core.services.impl.EHCacheServiceImpl.DEFAULT_CACHE;
@Slf4j
@Component(service = MovieService.class, immediate = true)
@Designate(ocd = MovieConfig.class)
public class MovieServiceImpl implements MovieService {
@Reference
private EHCacheService ehcache;
private static final String TOP_MOVIES = "topMovies";
private String imdbApiKey;
private String imdbApiEndpoint;
private int limit;
@Activate
protected void activate(final MovieConfig config) {
this.imdbApiKey = config.imdbApiKey();
this.imdbApiEndpoint = config.imdbApiEndpoint();
this.limit = config.limit();
}
@Override
public List<MovieData> getTopMovies() {
final Cache<String, List<MovieData>> cache = ehcache.getCache(DEFAULT_CACHE);
if (cache.get(TOP_MOVIES) != null) {
return cache.get(TOP_MOVIES);
}
final List<MovieData> topTrailerList = new ArrayList<>();
final ImdbDataModel topMovies = getClient().getTopMovies(this.imdbApiKey);
if (CollectionUtils.isNotEmpty(topMovies.getItems())) {
topMovies.getItems().stream()
.sorted(Comparator.comparing(item -> Integer.valueOf(item.getRank())))
.limit(limit)
.forEachOrdered(item -> topTrailerList.add(getYoutubeVideo(item, getClient())));
cache.put(TOP_MOVIES, topTrailerList);
return topTrailerList;
}
log.info("No Top Movies found in IMDb");
return new ArrayList<>();
}
@Override
public List<MovieData> searchMovies(final String movieName) {
final Cache<String, List<MovieData>> cache = ehcache.getCache(DEFAULT_CACHE);
if (cache.get(movieName) != null) {
return cache.get(movieName);
}
List<MovieData> movieSearchList = new ArrayList<>();
final ImdbDataModel movieSearchResult = getClient().searchMovies(this.imdbApiKey, movieName);
if (movieSearchResult != null) {
movieSearchResult.getResults()
.stream()
.limit(limit)
.forEachOrdered(item -> movieSearchList.add(getYoutubeVideo(item, getClient())));
cache.put(movieName, movieSearchList);
return movieSearchList;
}
log.info("No movie found with name : {}", movieName);
return new ArrayList<>();
}
/**
* Method to retrieve youtube url.
*
* @param item
* @param client
*
* @return
*/
private MovieData getYoutubeVideo(final MovieData item, final RestApiClient client) {
final MovieData vts = client.getYoutubeTrailer(this.imdbApiKey, item.getId());
item.setVideoUrl(vts.getVideoUrl());
item.setYear(vts.getYear());
return item;
}
/**
* Feign Client
*
* @return
*/
private RestApiClient getClient() {
return Feign.builder()
.encoder(new JacksonEncoder())
.decoder(new JacksonDecoder())
.requestInterceptor(new RestInterceptor())
.target(RestApiClient.class, this.imdbApiEndpoint);
}
}
| 35.310924 | 110 | 0.665873 |
67a39e1f557343bf355ff1bab99de47ab89bc702 | 5,086 | package com.raoulvdberge.refinedstorage.apiimpl.network.node;
import com.raoulvdberge.refinedstorage.RS;
import com.raoulvdberge.refinedstorage.RSItems;
import com.raoulvdberge.refinedstorage.api.network.INetwork;
import com.raoulvdberge.refinedstorage.api.network.security.ISecurityCard;
import com.raoulvdberge.refinedstorage.api.network.security.ISecurityCardContainer;
import com.raoulvdberge.refinedstorage.api.network.security.Permission;
import com.raoulvdberge.refinedstorage.apiimpl.network.security.SecurityCard;
import com.raoulvdberge.refinedstorage.inventory.item.ItemHandlerBase;
import com.raoulvdberge.refinedstorage.inventory.item.validator.ItemValidatorBasic;
import com.raoulvdberge.refinedstorage.inventory.listener.ListenerNetworkNode;
import com.raoulvdberge.refinedstorage.item.ItemSecurityCard;
import com.raoulvdberge.refinedstorage.util.StackUtils;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.wrapper.CombinedInvWrapper;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class NetworkNodeSecurityManager extends NetworkNode implements ISecurityCardContainer {
public static final String ID = "security_manager";
private final List<ISecurityCard> cards = new ArrayList<>();
private ISecurityCard globalCard;
private final ItemHandlerBase cardsInv = new ItemHandlerBase(9 * 2, new ListenerNetworkNode(this), new ItemValidatorBasic(RSItems.SECURITY_CARD)) {
@Override
protected void onContentsChanged(int slot) {
super.onContentsChanged(slot);
if (!world.isRemote) {
invalidate();
}
if (network != null) {
network.getSecurityManager().invalidate();
}
}
};
private final ItemHandlerBase editCard = new ItemHandlerBase(1, new ListenerNetworkNode(this), new ItemValidatorBasic(RSItems.SECURITY_CARD));
public NetworkNodeSecurityManager(World world, BlockPos pos) {
super(world, pos);
}
@Override
public int getEnergyUsage() {
int usage = RS.INSTANCE.config.securityManagerUsage;
for (int i = 0; i < cardsInv.getSlots(); ++i) {
if (!cardsInv.getStackInSlot(i).isEmpty()) {
usage += RS.INSTANCE.config.securityManagerPerSecurityCardUsage;
}
}
return usage;
}
@Override
public void updateNetworkNode() {
super.updateNetworkNode();
if (ticks == 1) {
invalidate();
}
}
private void invalidate() {
this.cards.clear();
this.globalCard = null;
for (int i = 0; i < cardsInv.getSlots(); ++i) {
ItemStack stack = cardsInv.getStackInSlot(i);
if (!stack.isEmpty()) {
UUID uuid = ItemSecurityCard.getOwner(stack);
if (uuid == null) {
this.globalCard = createCard(stack, null);
continue;
}
this.cards.add(createCard(stack, uuid));
}
}
}
private ISecurityCard createCard(ItemStack stack, @Nullable UUID uuid) {
SecurityCard card = new SecurityCard(uuid);
for (Permission permission : Permission.values()) {
card.getPermissions().put(permission, ItemSecurityCard.hasPermission(stack, permission));
}
return card;
}
@Override
public void read(NBTTagCompound tag) {
super.read(tag);
StackUtils.readItems(cardsInv, 0, tag);
StackUtils.readItems(editCard, 1, tag);
}
@Override
public String getId() {
return ID;
}
@Override
public NBTTagCompound write(NBTTagCompound tag) {
super.write(tag);
StackUtils.writeItems(cardsInv, 0, tag);
StackUtils.writeItems(editCard, 1, tag);
return tag;
}
@Override
public void onConnectedStateChange(INetwork network, boolean state) {
super.onConnectedStateChange(network, state);
network.getSecurityManager().invalidate();
}
public ItemHandlerBase getCardsItems() {
return cardsInv;
}
public ItemHandlerBase getEditCard() {
return editCard;
}
public void updatePermission(Permission permission, boolean state) {
ItemStack card = getEditCard().getStackInSlot(0);
if (!card.isEmpty()) {
ItemSecurityCard.setPermission(card, permission, state);
}
}
@Override
public List<ISecurityCard> getCards() {
return cards;
}
@Nullable
@Override
public ISecurityCard getGlobalCard() {
return globalCard;
}
@Override
public IItemHandler getDrops() {
return new CombinedInvWrapper(cardsInv, editCard);
}
@Override
public boolean hasConnectivityState() {
return true;
}
}
| 29.398844 | 151 | 0.668109 |
a3121ffdb0da70c53fe325338760af4359c8ea69 | 5,745 | /*
* Copyright 2012 Splunk, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"): you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.splunk;
/**
* The {@code TcpSplunkInput} class represents a Splunk-processed "cooked" TCP
* data input. This differs from a raw TCP input in that this cooked TCP data is
* processed by Splunk and is not in raw form.
*/
public class TcpSplunkInput extends PortInput {
/**
* Class constructor.
*
* @param service The connected {@code Service} instance.
* @param path The cooked TCP input endpoint.
*/
TcpSplunkInput(Service service, String path) {
super(service, path);
}
/**
* Returns an object that contains the inbound cooked TCP connections.
*
* @return The TCP connections object.
*/
public TcpConnections connections() {
return new TcpConnections(service, path + "/connections");
}
/**
* Returns the style of host connection. Valid values are: "ip", "dns", and
* "none".
*
* @return The style of host connection, or {@code null} if not specified.
*/
public String getConnectionHost() {
return getString("connection_host", null);
}
/**
* Returns the group for this cooked TCP input.
*
* @return The group.
*/
public String getGroup() {
return getString("group");
}
/**
* Returns the source host for this cooked TCP input where this indexer
* gets its data.
*
* @return The source host, or {@code null} if not specified.
*/
public String getHost() {
return getString("host");
}
/**
* Returns the index name for this cooked TCP input.
*
* @return The index name, or {@code null} if not specified.
*/
public String getIndex() {
return getString("index");
}
/**
* Returns the input kind of this input.
*
* @return The input kind.
*/
public InputKind getKind() {
return InputKind.TcpSplunk;
}
/**
* Returns the queue for this cooked TCP input. Valid values are:
* "parsingQueue" and "indexQueue".
*
* @return The queue, or {@code null} if not specified.
*/
public String getQueue() {
return getString("queue", null);
}
/**
* @deprecated Returns the value of the {@code _rcvbuf} attribute for this
* cooked TCP input.
*
* @return The {@code _rcvbuf} value.
*/
public int getRcvBuf() {
return getInteger("_rcvbuf");
}
/**
* Returns the incoming host restriction for this cooked TCP input.
*
* @return The incoming host restriction, or {@code null} if not specified.
*/
public String getRestrictToHost() {
return getString("restrictToHost", null);
}
/**
* Returns the initial source key for this cooked TCP input. Typically this
* value is the input file path.
*
* @return The source, or {@code null} if not specified.
*/
public String getSource() {
return getString("source", null);
}
/**
* Returns the event source type for this cooked TCP input.
*
* @return The event source type, or {@code null} if not specified.
*/
public String getSourceType() {
return getString("sourceType", null);
}
/**
* Indicates whether this cooked TCP input is using secure socket layer
* (SSL).
*
* @return {@code true} if this input is using SSL, {@code false} if not.
*/
public boolean getSSL() {
return getBoolean("SSL", false);
}
/**
* Sets whether to use secure socket layer (SSL).
*
* @param SSL {@code true} to use SSL, {@code false} if not.
*/
public void setSSL(boolean SSL) {
setCacheValue("SSL", SSL);
}
/**
* Sets the value for the <b>from-host</b> field for the remote server that
* is sending data. Valid values are: <ul>
* <li>"ip": Sets the host to the IP address of the remote server sending
* data.</li>
* <li>"dns": Sets the host to the reverse DNS entry for the IP address of
* the remote server sending data.</li>
* <li>"none": Leaves the host as specified in inputs.conf, which is
* typically the Splunk system host name.</li></ul>
*
* @param connection_host The connection host information.
*/
public void setConnectionHost(String connection_host) {
setCacheValue("connection_host", connection_host);
}
/**
* Sets whether this input is enabled or disabled.
* <p>
* <b>Note:</b> Using this method requires you to restart Splunk before this
* setting takes effect. To avoid restarting Splunk, use the
* {@code Entity.disable} and {@code Entity.enable} methods instead, which
* take effect immediately.
*
* @param disabled {@code true} to disable this input, {@code false} to
* enable it.
*/
public void setDisabled(boolean disabled) {
setCacheValue("disabled", disabled);
}
/**
* Sets the host from which the indexer gets data.
*
* @param host The host.
*/
public void setHost(String host) {
setCacheValue("host", host);
}
}
| 28.869347 | 81 | 0.615492 |
3b5755618aa73f6f920c8826b164ece081621b82 | 2,202 | package com.vladsch.flexmark.ext.attributes;
import com.vladsch.flexmark.util.misc.CharPredicate;
import org.jetbrains.annotations.NotNull;
import static com.vladsch.flexmark.util.sequence.SequenceUtils.containsAny;
public enum AttributeValueQuotes {
AS_IS,
NO_QUOTES_SINGLE_PREFERRED,
NO_QUOTES_DOUBLE_PREFERRED,
SINGLE_PREFERRED,
DOUBLE_PREFERRED,
SINGLE_QUOTES,
DOUBLE_QUOTES,
;
final static CharPredicate P_SPACES_OR_QUOTES = CharPredicate.anyOf(" \t\n'\"");
final static CharPredicate P_SINGLE_QUOTES = CharPredicate.anyOf("'");
final static CharPredicate P_DOUBLE_QUOTES = CharPredicate.anyOf("\"");
@NotNull
public String quotesFor(@NotNull CharSequence text, @NotNull CharSequence defaultQuotes) {
switch (this) {
case NO_QUOTES_SINGLE_PREFERRED:
if (!containsAny(text, P_SPACES_OR_QUOTES)) {
return "";
} else if (!containsAny(text, P_SINGLE_QUOTES) || containsAny(text, P_DOUBLE_QUOTES)) {
return "'";
} else {
return "\"";
}
case NO_QUOTES_DOUBLE_PREFERRED:
if (!containsAny(text, P_SPACES_OR_QUOTES)) {
return "";
} else if (!containsAny(text, P_DOUBLE_QUOTES) || containsAny(text, P_SINGLE_QUOTES)) {
return "\"";
} else {
return "'";
}
case SINGLE_PREFERRED:
if (!containsAny(text, P_SINGLE_QUOTES) || containsAny(text, P_DOUBLE_QUOTES)) {
return "'";
} else {
return "\"";
}
case DOUBLE_PREFERRED:
if (!containsAny(text, P_DOUBLE_QUOTES) || containsAny(text, P_SINGLE_QUOTES)) {
return "\"";
} else {
return "'";
}
case SINGLE_QUOTES:
return "'";
case DOUBLE_QUOTES:
return "\"";
case AS_IS:
default:
return defaultQuotes.toString();
}
}
}
| 33.876923 | 103 | 0.540418 |
0f18cd82c3d2ee55045a5f25d538a47482c72aef | 2,974 | /**
* Copyright © 2008-2019, Province of British Columbia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ca.bc.gov.ols.geocoder.rest.messageconverters;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import ca.bc.gov.ols.geocoder.rest.exceptions.ErrorMessage;
/**
* Supports more than just HTML output types, this is the default exception format.
*
* @author chodgson
*
*/
@Component
public class HtmlErrorMessageConverter extends AbstractHttpMessageConverter<ErrorMessage> {
public HtmlErrorMessageConverter() {
super(MediaType.APPLICATION_XHTML_XML,
MediaType.TEXT_HTML,
new org.springframework.http.MediaType("text", "csv", Charset.forName("UTF-8")),
new org.springframework.http.MediaType("application", "gml+xml",
Charset.forName("UTF-8")),
new MediaType("application", "vnd.geo+json", Charset.forName("UTF-8")),
MediaType.APPLICATION_JSON,
new org.springframework.http.MediaType("application", "javascript",
Charset.forName("UTF-8")),
new org.springframework.http.MediaType("application", "zip",
Charset.forName("UTF-8")));
}
@Override
protected boolean supports(Class<?> clazz) {
return ErrorMessage.class.isAssignableFrom(clazz);
}
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return false;
}
@Override
protected ErrorMessage readInternal(Class<? extends ErrorMessage> clazz,
HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return null;
}
@Override
protected void writeInternal(ErrorMessage message, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
outputMessage.getHeaders().setContentType(MediaType.TEXT_HTML);
Writer out = new OutputStreamWriter(outputMessage.getBody(), "UTF-8");
out.write("<!DOCTYPE html>\r\n<html>\r\n<head></head>\r\n<body>\r\n");
out.write(message.getMessage());
out.write("</body>\r\n</html>");
out.flush();
}
}
| 34.988235 | 91 | 0.761264 |
8a0a99e86cbfdc15830352b62198e330618e5ad2 | 70,237 | package gregtech;
import forestry.api.recipes.ICentrifugeRecipe;
import forestry.api.recipes.ISqueezerRecipe;
import forestry.api.recipes.RecipeManagers;
import gregtech.api.GregTech_API;
import gregtech.api.enchants.Enchantment_EnderDamage;
import gregtech.api.enchants.Enchantment_Radioactivity;
import gregtech.api.enums.ConfigCategories;
import gregtech.api.enums.Dyes;
import gregtech.api.enums.Element;
import gregtech.api.enums.GT_Values;
import gregtech.api.enums.ItemList;
import gregtech.api.enums.Materials;
import gregtech.api.enums.OrePrefixes;
import gregtech.api.enums.Textures;
import gregtech.api.interfaces.internal.IGT_Mod;
import gregtech.api.objects.ItemData;
import gregtech.api.objects.MaterialStack;
import gregtech.api.util.GT_Config;
import gregtech.api.util.GT_ItsNotMyFaultException;
import gregtech.api.util.GT_LanguageManager;
import gregtech.api.util.GT_Log;
import gregtech.api.util.GT_ModHandler;
import gregtech.api.util.GT_OreDictUnificator;
import gregtech.api.util.GT_Recipe;
import gregtech.api.util.GT_RecipeRegistrator;
import gregtech.api.util.GT_SpawnEventHandler;
import gregtech.api.util.GT_Utility;
import gregtech.common.GT_DummyWorld;
import gregtech.common.GT_Network;
import gregtech.common.GT_Proxy;
import gregtech.common.GT_RecipeAdder;
import gregtech.common.entities.GT_Entity_Arrow;
import gregtech.common.entities.GT_Entity_Arrow_Potion;
import gregtech.common.items.behaviors.Behaviour_DataOrb;
import gregtech.loaders.load.GT_CoverBehaviorLoader;
import gregtech.loaders.load.GT_FuelLoader;
import gregtech.loaders.load.GT_ItemIterator;
import gregtech.loaders.load.GT_SonictronLoader;
import gregtech.loaders.misc.GT_Achievements;
import gregtech.loaders.misc.GT_Bees;
import gregtech.loaders.misc.GT_CoverLoader;
import gregtech.loaders.misc.OreProcessingConfiguration;
import gregtech.loaders.postload.GT_BlockResistanceLoader;
import gregtech.loaders.postload.GT_BookAndLootLoader;
import gregtech.loaders.postload.GT_CraftingRecipeLoader;
import gregtech.loaders.postload.GT_CropLoader;
import gregtech.loaders.postload.GT_ItemMaxStacksizeLoader;
import gregtech.loaders.postload.GT_MachineRecipeLoader;
import gregtech.loaders.postload.GT_MinableRegistrator;
import gregtech.loaders.postload.GT_RecyclerBlacklistLoader;
import gregtech.loaders.postload.GT_ScrapboxDropLoader;
import gregtech.loaders.postload.GT_Worldgenloader;
import gregtech.loaders.preload.GT_Loader_CircuitBehaviors;
import gregtech.loaders.preload.GT_Loader_ItemData;
import gregtech.loaders.preload.GT_Loader_Item_Block_And_Fluid;
import gregtech.loaders.preload.GT_Loader_MetaTileEntities;
import gregtech.loaders.preload.GT_Loader_OreDictionary;
import gregtech.loaders.preload.GT_Loader_OreProcessing;
import ic2.api.recipe.IRecipeInput;
import ic2.api.recipe.RecipeOutput;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.common.ChestGenHooks;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.oredict.OreDictionary;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.LoadController;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLModIdMappingEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartedEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.event.FMLServerStoppingEvent;
import cpw.mods.fml.common.registry.EntityRegistry;
//import forestry.factory.recipes.ISqueezerRecipe;
//import forestry.factory.tiles.TileCentrifuge;
//import forestry.factory.tiles.TileSqueezer;
@Mod(modid = "gregtech", name = "GregTech", version = "MC1710", useMetadata = false, dependencies = "required-after:IC2; after:Forestry; after:PFAAGeologica; after:Thaumcraft; after:Railcraft; after:appliedenergistics2; after:ThermalExpansion; after:TwilightForest; after:harvestcraft; after:magicalcrops; after:BuildCraft|Transport; after:BuildCraft|Silicon; after:BuildCraft|Factory; after:BuildCraft|Energy; after:BuildCraft|Core; after:BuildCraft|Builders; after:GalacticraftCore; after:GalacticraftMars; after:GalacticraftPlanets; after:ThermalExpansion|Transport; after:ThermalExpansion|Energy; after:ThermalExpansion|Factory; after:RedPowerCore; after:RedPowerBase; after:RedPowerMachine; after:RedPowerCompat; after:RedPowerWiring; after:RedPowerLogic; after:RedPowerLighting; after:RedPowerWorld; after:RedPowerControl; after:UndergroundBiomes;")
public class GT_Mod
implements IGT_Mod {
public static final int VERSION = 509;
public static final int REQUIRED_IC2 = 624;
@Mod.Instance("gregtech")
public static GT_Mod instance;
@SidedProxy(modId = "gregtech", clientSide = "gregtech.common.GT_Client", serverSide = "gregtech.common.GT_Server")
public static GT_Proxy gregtechproxy;
public static int MAX_IC2 = 2147483647;
public static GT_Achievements achievements;
private static long systemTimeA;
private static long systemTimeB;
static {
if ((509 != GregTech_API.VERSION) || (509 != GT_ModHandler.VERSION) || (509 != GT_OreDictUnificator.VERSION) || (509 != GT_Recipe.VERSION) || (509 != GT_Utility.VERSION) || (509 != GT_RecipeRegistrator.VERSION) || (509 != Element.VERSION) || (509 != Materials.VERSION) || (509 != OrePrefixes.VERSION)) {
throw new GT_ItsNotMyFaultException("One of your Mods included GregTech-API Files inside it's download, mention this to the Mod Author, who does this bad thing, and tell him/her to use reflection. I have added a Version check, to prevent Authors from breaking my Mod that way.");
}
}
private static void profileLog(Object o){
try {
String content;
File file = new File("GregtechTimingsTC.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("============================================================");
bw.write(System.lineSeparator());
bw.close();
}
if (o instanceof String){
content = (String) o;
}
else {
content = o.toString();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.write(System.lineSeparator());
bw.close();
System.out.println("Data Logged.");
} catch (IOException e) {
System.out.println("Data logging failed.");
}
}
public GT_Mod() {
Date date = new Date(systemTimeA=System.currentTimeMillis());
profileLog("Current Time - Constructor Call "+date.toString());
System.out.println("A.) Taking a copy of the system time - "+(FastDateFormat.getInstance().format(date)));
try {
Class.forName("ic2.core.IC2").getField("enableOreDictCircuit").set(null, Boolean.valueOf(true));
} catch (Throwable e) {
}
try {
Class.forName("ic2.core.IC2").getField("enableCraftingBucket").set(null, Boolean.valueOf(false));
} catch (Throwable e) {
}
try {
Class.forName("ic2.core.IC2").getField("enableEnergyInStorageBlockItems").set(null, Boolean.valueOf(false));
} catch (Throwable e) {
}
GT_Values.GT = this;
GT_Values.DW = new GT_DummyWorld();
GT_Values.NW = new GT_Network();
GregTech_API.sRecipeAdder = GT_Values.RA = new GT_RecipeAdder();
Textures.BlockIcons.VOID.name();
Textures.ItemIcons.VOID.name();
}
@Mod.EventHandler
public void onPreLoad(FMLPreInitializationEvent aEvent) {
Date date2 = new Date(systemTimeB=System.currentTimeMillis());
profileLog("Current Time - preInit Call "+date2.toString());
System.out.println("B.) Taking a copy of the system time - "+(FastDateFormat.getInstance().format(date2)));
if (GregTech_API.sPreloadStarted) {
return;
}
for (Runnable tRunnable : GregTech_API.sBeforeGTPreload) {
try {
tRunnable.run();
} catch (Throwable e) {
e.printStackTrace(GT_Log.err);
}
}
File tFile = new File(new File(aEvent.getModConfigurationDirectory(), "GregTech"), "GregTech.cfg");
Configuration tMainConfig = new Configuration(tFile);
tMainConfig.load();
tFile = new File(new File(aEvent.getModConfigurationDirectory(), "GregTech"), "IDs.cfg");
GT_Config.sConfigFileIDs = new Configuration(tFile);
GT_Config.sConfigFileIDs.load();
GT_Config.sConfigFileIDs.save();
GregTech_API.sRecipeFile = new GT_Config(new Configuration(new File(new File(aEvent.getModConfigurationDirectory(), "GregTech"), "Recipes.cfg")));
GregTech_API.sMachineFile = new GT_Config(new Configuration(new File(new File(aEvent.getModConfigurationDirectory(), "GregTech"), "MachineStats.cfg")));
GregTech_API.sWorldgenFile = new GT_Config(new Configuration(new File(new File(aEvent.getModConfigurationDirectory(), "GregTech"), "WorldGeneration.cfg")));
GregTech_API.sMaterialProperties = new GT_Config(new Configuration(new File(new File(aEvent.getModConfigurationDirectory(), "GregTech"), "MaterialProperties.cfg")));
GregTech_API.sUnification = new GT_Config(new Configuration(new File(new File(aEvent.getModConfigurationDirectory(), "GregTech"), "Unification.cfg")));
GregTech_API.sSpecialFile = new GT_Config(new Configuration(new File(new File(aEvent.getModConfigurationDirectory(), "GregTech"), "Other.cfg")));
GregTech_API.sOPStuff = new GT_Config(new Configuration(new File(new File(aEvent.getModConfigurationDirectory(), "GregTech"), "OverpoweredStuff.cfg")));
GregTech_API.sClientDataFile = new GT_Config(new Configuration(new File(aEvent.getModConfigurationDirectory().getParentFile(), "GregTech.cfg")));
GT_Log.mLogFile = new File(aEvent.getModConfigurationDirectory().getParentFile(), "logs/GregTech.log");
if (!GT_Log.mLogFile.exists()) {
try {
GT_Log.mLogFile.createNewFile();
} catch (Throwable e) {
}
}
try {
GT_Log.out = GT_Log.err = new PrintStream(GT_Log.mLogFile);
} catch (FileNotFoundException e) {
}
GT_Log.mOreDictLogFile = new File(aEvent.getModConfigurationDirectory().getParentFile(), "logs/OreDict.log");
if (!GT_Log.mOreDictLogFile.exists()) {
try {
GT_Log.mOreDictLogFile.createNewFile();
} catch (Throwable e) {
}
}
if (tMainConfig.get("general", "LoggingPlayerActivity", true).getBoolean(true)) {
GT_Log.mPlayerActivityLogFile = new File(aEvent.getModConfigurationDirectory().getParentFile(), "logs/PlayerActivity.log");
if (!GT_Log.mPlayerActivityLogFile.exists()) {
try {
GT_Log.mPlayerActivityLogFile.createNewFile();
} catch (Throwable e) {
}
}
try {
GT_Log.pal = new PrintStream(GT_Log.mPlayerActivityLogFile);
} catch (Throwable e) {
}
}
try {
List<String> tList = ((GT_Log.LogBuffer) GT_Log.ore).mBufferedOreDictLog;
GT_Log.ore.println("******************************************************************************");
GT_Log.ore.println("* This is the complete log of the GT5-Unofficial OreDictionary Handler. It *");
GT_Log.ore.println("* processes all OreDictionary entries and can sometimes cause errors. All *");
GT_Log.ore.println("* entries and errors are being logged. If you see an error please raise an *");
GT_Log.ore.println("* issue at https://github.com/Blood-Asp/GT5-Unofficial. *");
GT_Log.ore.println("******************************************************************************");
String tString;
for (Iterator i$ = tList.iterator(); i$.hasNext(); GT_Log.ore.println(tString)) {
tString = (String) i$.next();
}
} catch (Throwable e) {
}
gregtechproxy.onPreLoad();
GT_Log.out.println("GT_Mod: Setting Configs");
GT_Values.D1 = tMainConfig.get("general", "Debug", false).getBoolean(false);
GT_Values.D2 = tMainConfig.get("general", "Debug2", false).getBoolean(false);
GregTech_API.TICKS_FOR_LAG_AVERAGING = tMainConfig.get("general", "TicksForLagAveragingWithScanner", 25).getInt(25);
GregTech_API.MILLISECOND_THRESHOLD_UNTIL_LAG_WARNING = tMainConfig.get("general", "MillisecondsPassedInGTTileEntityUntilLagWarning", 100).getInt(100);
if (tMainConfig.get("general", "disable_STDOUT", false).getBoolean(false)) {
System.out.close();
}
if (tMainConfig.get("general", "disable_STDERR", false).getBoolean(false)) {
System.err.close();
}
GregTech_API.sMachineExplosions = tMainConfig.get("machines", "machines_explosion_damage", true).getBoolean(false);
GregTech_API.sMachineFlammable = tMainConfig.get("machines", "machines_flammable", true).getBoolean(false);
GregTech_API.sMachineNonWrenchExplosions = tMainConfig.get("machines", "explosions_on_nonwrenching", true).getBoolean(false);
GregTech_API.sMachineWireFire = tMainConfig.get("machines", "wirefire_on_explosion", true).getBoolean(false);
GregTech_API.sMachineFireExplosions = tMainConfig.get("machines", "fire_causes_explosions", true).getBoolean(false);
GregTech_API.sMachineRainExplosions = tMainConfig.get("machines", "rain_causes_explosions", true).getBoolean(false);
GregTech_API.sMachineThunderExplosions = tMainConfig.get("machines", "lightning_causes_explosions", true).getBoolean(false);
GregTech_API.sConstantEnergy = tMainConfig.get("machines", "constant_need_of_energy", true).getBoolean(false);
GregTech_API.sColoredGUI = tMainConfig.get("machines", "colored_guis_when_painted", true).getBoolean(false);
GregTech_API.sTimber = tMainConfig.get("general", "timber_axe", false).getBoolean(false);
GregTech_API.sDrinksAlwaysDrinkable = tMainConfig.get("general", "drinks_always_drinkable", false).getBoolean(false);
GregTech_API.sDoShowAllItemsInCreative = tMainConfig.get("general", "show_all_metaitems_in_creative_and_NEI", false).getBoolean(false);
GregTech_API.sMultiThreadedSounds = tMainConfig.get("general", "sound_multi_threading", false).getBoolean(false);
for (Dyes tDye : Dyes.values()) {
if ((tDye != Dyes._NULL) && (tDye.mIndex < 0)) {
tDye.mRGBa[0] = ((short) Math.min(255, Math.max(0, GregTech_API.sClientDataFile.get("ColorModulation." + tDye, "R", tDye.mRGBa[0]))));
tDye.mRGBa[1] = ((short) Math.min(255, Math.max(0, GregTech_API.sClientDataFile.get("ColorModulation." + tDye, "G", tDye.mRGBa[1]))));
tDye.mRGBa[2] = ((short) Math.min(255, Math.max(0, GregTech_API.sClientDataFile.get("ColorModulation." + tDye, "B", tDye.mRGBa[2]))));
}
}
gregtechproxy.mMaxEqualEntitiesAtOneSpot = tMainConfig.get("general", "MaxEqualEntitiesAtOneSpot", 3).getInt(3);
gregtechproxy.mSkeletonsShootGTArrows = tMainConfig.get("general", "SkeletonsShootGTArrows", 16).getInt(16);
gregtechproxy.mFlintChance = tMainConfig.get("general", "FlintAndSteelChance", 30).getInt(30);
gregtechproxy.mItemDespawnTime = tMainConfig.get("general", "ItemDespawnTime", 6000).getInt(6000);
gregtechproxy.mDisableVanillaOres = tMainConfig.get("general", "DisableVanillaOres", true).getBoolean(true);
gregtechproxy.mNerfDustCrafting = tMainConfig.get("general", "NerfDustCrafting", true).getBoolean(true);
gregtechproxy.mIncreaseDungeonLoot = tMainConfig.get("general", "IncreaseDungeonLoot", true).getBoolean(true);
gregtechproxy.mAxeWhenAdventure = tMainConfig.get("general", "AdventureModeStartingAxe", true).getBoolean(true);
gregtechproxy.mHardcoreCables = tMainConfig.get("general", "HardCoreCableLoss", false).getBoolean(false);
gregtechproxy.mSurvivalIntoAdventure = tMainConfig.get("general", "forceAdventureMode", false).getBoolean(false);
gregtechproxy.mHungerEffect = tMainConfig.get("general", "AFK_Hunger", false).getBoolean(false);
gregtechproxy.mHardRock = tMainConfig.get("general", "harderstone", false).getBoolean(false);
gregtechproxy.mInventoryUnification = tMainConfig.get("general", "InventoryUnification", true).getBoolean(true);
gregtechproxy.mGTBees = tMainConfig.get("general", "GTBees", true).getBoolean(true);
gregtechproxy.mCraftingUnification = tMainConfig.get("general", "CraftingUnification", true).getBoolean(true);
gregtechproxy.mNerfedWoodPlank = tMainConfig.get("general", "WoodNeedsSawForCrafting", true).getBoolean(true);
gregtechproxy.mNerfedVanillaTools = tMainConfig.get("general", "smallerVanillaToolDurability", true).getBoolean(true);
gregtechproxy.mSortToTheEnd = tMainConfig.get("general", "EnsureToBeLoadedLast", true).getBoolean(true);
gregtechproxy.mDisableIC2Cables = tMainConfig.get("general", "DisableIC2Cables", true).getBoolean(true);
gregtechproxy.mAchievements = tMainConfig.get("general", "EnableAchievements", true).getBoolean(true);
gregtechproxy.mAE2Integration = GregTech_API.sSpecialFile.get(ConfigCategories.general, "EnableAE2Integration", Loader.isModLoaded("appliedenergistics2"));
gregtechproxy.mNerfedCombs = tMainConfig.get("general", "NerfCombs", true).getBoolean(true);
gregtechproxy.mHideUnusedOres = tMainConfig.get("general", "HideUnusedOres", true).getBoolean(true);
gregtechproxy.mHideRecyclingRecipes = tMainConfig.get("general", "HideRecyclingRecipes", true).getBoolean(true);
GregTech_API.mOutputRF = GregTech_API.sOPStuff.get(ConfigCategories.general, "OutputRF", true);
GregTech_API.mInputRF = GregTech_API.sOPStuff.get(ConfigCategories.general, "InputRF", false);
GregTech_API.mEUtoRF = GregTech_API.sOPStuff.get(ConfigCategories.general, "100EUtoRF", 360);
GregTech_API.mRFtoEU = GregTech_API.sOPStuff.get(ConfigCategories.general, "100RFtoEU", 20);
GregTech_API.mRFExplosions = GregTech_API.sOPStuff.get(ConfigCategories.general, "RFExplosions", false);
GregTech_API.meIOLoaded = Loader.isModLoaded("EnderIO");
gregtechproxy.mChangeHarvestLevels = GregTech_API.sMaterialProperties.get("havestLevel", "activateHarvestLevelChange", false);
if(gregtechproxy.mChangeHarvestLevels){
gregtechproxy.mGraniteHavestLevel = (int) GregTech_API.sMaterialProperties.get("havestLevel", "graniteHarvestLevel", 3);
gregtechproxy.mMaxHarvestLevel=(int) Math.min(15, GregTech_API.sMaterialProperties.get("havestLevel", "maxLevel",7));
for(Materials tMaterial : Materials.values()){
if(tMaterial!=null&&tMaterial.mToolQuality>0&&tMaterial.mMetaItemSubID<gregtechproxy.mHarvestLevel.length&&tMaterial.mMetaItemSubID>=0){
gregtechproxy.mHarvestLevel[tMaterial.mMetaItemSubID] = GregTech_API.sMaterialProperties.get("materialHavestLevel", tMaterial.mDefaultLocalName,tMaterial.mToolQuality);
}
}}
if (tMainConfig.get("general", "hardermobspawners", true).getBoolean(true)) {
Blocks.mob_spawner.setHardness(500.0F).setResistance(6000000.0F);
}
gregtechproxy.mOnline = tMainConfig.get("general", "online", true).getBoolean(false);
gregtechproxy.mUpgradeCount = Math.min(64, Math.max(1, tMainConfig.get("features", "UpgradeStacksize", 4).getInt()));
for (OrePrefixes tPrefix : OrePrefixes.values()) {
if (tPrefix.mIsUsedForOreProcessing) {
tPrefix.mDefaultStackSize = ((byte) Math.min(64, Math.max(1, tMainConfig.get("features", "MaxOreStackSize", 64).getInt())));
} else if (tPrefix == OrePrefixes.plank) {
tPrefix.mDefaultStackSize = ((byte) Math.min(64, Math.max(16, tMainConfig.get("features", "MaxPlankStackSize", 64).getInt())));
} else if ((tPrefix == OrePrefixes.wood) || (tPrefix == OrePrefixes.treeLeaves) || (tPrefix == OrePrefixes.treeSapling) || (tPrefix == OrePrefixes.log)) {
tPrefix.mDefaultStackSize = ((byte) Math.min(64, Math.max(16, tMainConfig.get("features", "MaxLogStackSize", 64).getInt())));
} else if (tPrefix.mIsUsedForBlocks) {
tPrefix.mDefaultStackSize = ((byte) Math.min(64, Math.max(16, tMainConfig.get("features", "MaxOtherBlockStackSize", 64).getInt())));
}
}
//GT_Config.troll = (Calendar.getInstance().get(2) + 1 == 4) && (Calendar.getInstance().get(5) >= 1) && (Calendar.getInstance().get(5) <= 2);
Materials.init(GregTech_API.sMaterialProperties);
GT_Log.out.println("GT_Mod: Saving Main Config");
tMainConfig.save();
GT_Log.out.println("GT_Mod: Generating Lang-File");
GT_LanguageManager.sEnglishFile = new Configuration(new File(aEvent.getModConfigurationDirectory().getParentFile(), "GregTech.lang"));
GT_LanguageManager.sEnglishFile.load();
GT_Log.out.println("GT_Mod: Removing all original Scrapbox Drops.");
try {
GT_Utility.getField("ic2.core.item.ItemScrapbox$Drop", "topChance", true, true).set(null, Integer.valueOf(0));
((List) GT_Utility.getFieldContent(GT_Utility.getFieldContent("ic2.api.recipe.Recipes", "scrapboxDrops", true, true), "drops", true, true)).clear();
} catch (Throwable e) {
if (GT_Values.D1) {
e.printStackTrace(GT_Log.err);
}
}
GT_Log.out.println("GT_Mod: Adding Scrap with a Weight of 200.0F to the Scrapbox Drops.");
GT_ModHandler.addScrapboxDrop(200.0F, GT_ModHandler.getIC2Item("scrap", 1L));
EntityRegistry.registerModEntity(GT_Entity_Arrow.class, "GT_Entity_Arrow", 1, GT_Values.GT, 160, 1, true);
EntityRegistry.registerModEntity(GT_Entity_Arrow_Potion.class, "GT_Entity_Arrow_Potion", 2, GT_Values.GT, 160, 1, true);
new Enchantment_EnderDamage();
new Enchantment_Radioactivity();
new OreProcessingConfiguration(aEvent.getModConfigurationDirectory()).run();
new GT_Loader_OreProcessing().run();
new GT_Loader_OreDictionary().run();
new GT_Loader_ItemData().run();
new GT_Loader_Item_Block_And_Fluid().run();
new GT_Loader_MetaTileEntities().run();
new GT_Loader_CircuitBehaviors().run();
new GT_CoverBehaviorLoader().run();
new GT_SonictronLoader().run();
new GT_SpawnEventHandler();
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.gregtechrecipes, "SolarPanel", true)) {
GT_ModHandler.addCraftingRecipe(ItemList.Cover_SolarPanel.get(1L, new Object[0]), GT_ModHandler.RecipeBits.NOT_REMOVABLE | GT_ModHandler.RecipeBits.REVERSIBLE, new Object[]{"SGS", "CPC", Character.valueOf('C'), OrePrefixes.circuit.get(Materials.Basic), Character.valueOf('G'), new ItemStack(Blocks.glass_pane, 1), Character.valueOf('P'), OrePrefixes.plateAlloy.get(Materials.Carbon), Character.valueOf('S'), OrePrefixes.plate.get(Materials.Silicon)});
}
if (GregTech_API.sOPStuff.get(ConfigCategories.Recipes.gregtechrecipes, "SolarPanel8V", false)) {
GT_ModHandler.addCraftingRecipe(ItemList.Cover_SolarPanel_8V.get(1L, new Object[0]), GT_ModHandler.RecipeBits.NOT_REMOVABLE | GT_ModHandler.RecipeBits.REVERSIBLE, new Object[]{"SSS", "STS", "SSS", Character.valueOf('S'), ItemList.Cover_SolarPanel, Character.valueOf('T'), OrePrefixes.circuit.get(Materials.Advanced)});
}
if (GregTech_API.sOPStuff.get(ConfigCategories.Recipes.gregtechrecipes, "SolarPanelLV", false)) {
GT_ModHandler.addCraftingRecipe(ItemList.Cover_SolarPanel_LV.get(1L, new Object[0]), GT_ModHandler.RecipeBits.NOT_REMOVABLE | GT_ModHandler.RecipeBits.REVERSIBLE, new Object[]{" S ", "STS", " S ", Character.valueOf('S'), ItemList.Cover_SolarPanel_8V, Character.valueOf('T'), ItemList.Transformer_LV_ULV});
}
if (GregTech_API.sOPStuff.get(ConfigCategories.Recipes.gregtechrecipes, "SolarPanelMV", false)) {
GT_ModHandler.addCraftingRecipe(ItemList.Cover_SolarPanel_MV.get(1L, new Object[0]), GT_ModHandler.RecipeBits.NOT_REMOVABLE | GT_ModHandler.RecipeBits.REVERSIBLE, new Object[]{" S ", "STS", " S ", Character.valueOf('S'), ItemList.Cover_SolarPanel_LV, Character.valueOf('T'), ItemList.Transformer_MV_LV});
}
if (GregTech_API.sOPStuff.get(ConfigCategories.Recipes.gregtechrecipes, "SolarPanelHV", false)) {
GT_ModHandler.addCraftingRecipe(ItemList.Cover_SolarPanel_HV.get(1L, new Object[0]), GT_ModHandler.RecipeBits.NOT_REMOVABLE | GT_ModHandler.RecipeBits.REVERSIBLE, new Object[]{" S ", "STS", " S ", Character.valueOf('S'), ItemList.Cover_SolarPanel_MV, Character.valueOf('T'), ItemList.Transformer_HV_MV});
}
if (GregTech_API.sOPStuff.get(ConfigCategories.Recipes.gregtechrecipes, "SolarPanelEV", false)) {
GT_ModHandler.addCraftingRecipe(ItemList.Cover_SolarPanel_EV.get(1L, new Object[0]), GT_ModHandler.RecipeBits.NOT_REMOVABLE | GT_ModHandler.RecipeBits.REVERSIBLE, new Object[]{" S ", "STS", " S ", Character.valueOf('S'), ItemList.Cover_SolarPanel_HV, Character.valueOf('T'), ItemList.Transformer_EV_HV});
}
if (GregTech_API.sOPStuff.get(ConfigCategories.Recipes.gregtechrecipes, "SolarPanelIV", false)) {
GT_ModHandler.addCraftingRecipe(ItemList.Cover_SolarPanel_IV.get(1L, new Object[0]), GT_ModHandler.RecipeBits.NOT_REMOVABLE | GT_ModHandler.RecipeBits.REVERSIBLE, new Object[]{" S ", "STS", " S ", Character.valueOf('S'), ItemList.Cover_SolarPanel_EV, Character.valueOf('T'), ItemList.Transformer_IV_EV});
}
if (GregTech_API.sOPStuff.get(ConfigCategories.Recipes.gregtechrecipes, "SolarPanelLuV", false)) {
GT_ModHandler.addCraftingRecipe(ItemList.Cover_SolarPanel_LuV.get(1L, new Object[0]), GT_ModHandler.RecipeBits.NOT_REMOVABLE | GT_ModHandler.RecipeBits.REVERSIBLE, new Object[]{" S ", "STS", " S ", Character.valueOf('S'), ItemList.Cover_SolarPanel_IV, Character.valueOf('T'), ItemList.Transformer_LuV_IV});
}
if (GregTech_API.sOPStuff.get(ConfigCategories.Recipes.gregtechrecipes, "SolarPanelZPM", false)) {
GT_ModHandler.addCraftingRecipe(ItemList.Cover_SolarPanel_ZPM.get(1L, new Object[0]), GT_ModHandler.RecipeBits.NOT_REMOVABLE | GT_ModHandler.RecipeBits.REVERSIBLE, new Object[]{" S ", "STS", " S ", Character.valueOf('S'), ItemList.Cover_SolarPanel_LuV, Character.valueOf('T'), ItemList.Transformer_ZPM_LuV});
}
if (GregTech_API.sOPStuff.get(ConfigCategories.Recipes.gregtechrecipes, "SolarPanelUV", false)) {
GT_ModHandler.addCraftingRecipe(ItemList.Cover_SolarPanel_UV.get(1L, new Object[0]), GT_ModHandler.RecipeBits.NOT_REMOVABLE | GT_ModHandler.RecipeBits.REVERSIBLE, new Object[]{" S ", "STS", " S ", Character.valueOf('S'), ItemList.Cover_SolarPanel_ZPM, Character.valueOf('T'), ItemList.Transformer_UV_ZPM});
}
if (gregtechproxy.mSortToTheEnd) {
try {
GT_Log.out.println("GT_Mod: Sorting GregTech to the end of the Mod List for further processing.");
LoadController tLoadController = (LoadController) GT_Utility.getFieldContent(Loader.instance(), "modController", true, true);
List<ModContainer> tModList = tLoadController.getActiveModList();
List<ModContainer> tNewModsList = new ArrayList();
ModContainer tGregTech = null;
for (short i = 0; i < tModList.size(); i = (short) (i + 1)) {
ModContainer tMod = (ModContainer) tModList.get(i);
if (tMod.getModId().equalsIgnoreCase("gregtech")) {
tGregTech = tMod;
} else {
tNewModsList.add(tMod);
}
}
if (tGregTech != null) {
tNewModsList.add(tGregTech);
}
GT_Utility.getField(tLoadController, "activeModList", true, true).set(tLoadController, tNewModsList);
} catch (Throwable e) {
if (GT_Values.D1) {
e.printStackTrace(GT_Log.err);
}
}
}
GregTech_API.sPreloadFinished = true;
GT_Log.out.println("GT_Mod: Preload-Phase finished!");
GT_Log.ore.println("GT_Mod: Preload-Phase finished!");
for (Runnable tRunnable : GregTech_API.sAfterGTPreload) {
try {
tRunnable.run();
} catch (Throwable e) {
e.printStackTrace(GT_Log.err);
}
}
}
@Mod.EventHandler
public void onLoad(FMLInitializationEvent aEvent) {
if (GregTech_API.sLoadStarted) {
return;
}
for (Runnable tRunnable : GregTech_API.sBeforeGTLoad) {
try {
tRunnable.run();
} catch (Throwable e) {
e.printStackTrace(GT_Log.err);
}
}
new GT_Bees();
gregtechproxy.onLoad();
if (gregtechproxy.mSortToTheEnd) {
new GT_ItemIterator().run();
gregtechproxy.registerUnificationEntries();
new GT_FuelLoader().run();
}
GregTech_API.sLoadFinished = true;
GT_Log.out.println("GT_Mod: Load-Phase finished!");
GT_Log.ore.println("GT_Mod: Load-Phase finished!");
for (Runnable tRunnable : GregTech_API.sAfterGTLoad) {
try {
tRunnable.run();
} catch (Throwable e) {
e.printStackTrace(GT_Log.err);
}
}
}
@Mod.EventHandler
public void onPostLoad(FMLPostInitializationEvent aEvent) {
if (GregTech_API.sPostloadStarted) {
return;
}
for (Runnable tRunnable : GregTech_API.sBeforeGTPostload) {
try {
tRunnable.run();
} catch (Throwable e) {
e.printStackTrace(GT_Log.err);
}
}
gregtechproxy.onPostLoad();
if (gregtechproxy.mSortToTheEnd) {
gregtechproxy.registerUnificationEntries();
} else {
new GT_ItemIterator().run();
gregtechproxy.registerUnificationEntries();
new GT_FuelLoader().run();
}
new GT_BookAndLootLoader().run();
new GT_ItemMaxStacksizeLoader().run();
new GT_BlockResistanceLoader().run();
new GT_RecyclerBlacklistLoader().run();
new GT_MinableRegistrator().run();
new GT_MachineRecipeLoader().run();
new GT_ScrapboxDropLoader().run();
new GT_CropLoader().run();
new GT_Worldgenloader().run();
new GT_CoverLoader().run();
GT_RecipeRegistrator.registerUsagesForMaterials(new ItemStack(Blocks.planks, 1), null, false);
GT_RecipeRegistrator.registerUsagesForMaterials(new ItemStack(Blocks.cobblestone, 1), null, false);
GT_RecipeRegistrator.registerUsagesForMaterials(new ItemStack(Blocks.stone, 1), null, false);
GT_RecipeRegistrator.registerUsagesForMaterials(new ItemStack(Items.leather, 1), null, false);
GT_OreDictUnificator.addItemData(GT_ModHandler.getRecipeOutput(new ItemStack[]{null, GT_OreDictUnificator.get(OrePrefixes.ingot, Materials.Tin, 1L), null, GT_OreDictUnificator.get(OrePrefixes.ingot, Materials.Tin, 1L), null, GT_OreDictUnificator.get(OrePrefixes.ingot, Materials.Tin, 1L), null, null, null}), new ItemData(Materials.Tin, 10886400L, new MaterialStack[0]));
if (!GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.storageblockcrafting, "tile.glowstone", false)) {
GT_ModHandler.removeRecipe(new ItemStack[]{new ItemStack(Items.glowstone_dust, 1), new ItemStack(Items.glowstone_dust, 1), null, new ItemStack(Items.glowstone_dust, 1), new ItemStack(Items.glowstone_dust, 1)});
}
GT_ModHandler.removeRecipe(new ItemStack[]{new ItemStack(Blocks.wooden_slab, 1, 0), new ItemStack(Blocks.wooden_slab, 1, 1), new ItemStack(Blocks.wooden_slab, 1, 2)});
GT_ModHandler.addCraftingRecipe(new ItemStack(Blocks.wooden_slab, 6, 0), GT_ModHandler.RecipeBits.NOT_REMOVABLE, new Object[]{"WWW", Character.valueOf('W'), new ItemStack(Blocks.planks, 1, 0)});
GT_Log.out.println("GT_Mod: Activating OreDictionary Handler, this can take some time, as it scans the whole OreDictionary");
FMLLog.info("If your Log stops here, you were too impatient. Wait a bit more next time, before killing Minecraft with the Task Manager.", new Object[0]);
Date date = new Date();
profileLog("Current Time - Before activeOreDicthandler(): "+date.toString());
gregtechproxy.activateOreDictHandler();
FMLLog.info("Congratulations, you have been waiting long enough. Have a Cake.", new Object[0]);
GT_Log.out.println("GT_Mod: " + GT_ModHandler.sSingleNonBlockDamagableRecipeList.size() + " Recipes were left unused.");
if (GT_Values.D1) {
IRecipe tRecipe;
for (Iterator i$ = GT_ModHandler.sSingleNonBlockDamagableRecipeList.iterator(); i$.hasNext(); GT_Log.out.println("=> " + tRecipe.getRecipeOutput().getDisplayName())) {
tRecipe = (IRecipe) i$.next();
}
}
new GT_CraftingRecipeLoader().run();
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2forgehammer", true)) {
GT_ModHandler.removeRecipeByOutput(ItemList.IC2_ForgeHammer.getWildcard(1L, new Object[0]));
}
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item("machine", 1L));
GT_ModHandler.addCraftingRecipe(GT_ModHandler.getIC2Item("machine", 1L), GT_ModHandler.RecipeBits.BUFFERED | GT_ModHandler.RecipeBits.NOT_REMOVABLE | GT_ModHandler.RecipeBits.REVERSIBLE, new Object[]{"RRR", "RwR", "RRR", Character.valueOf('R'), OrePrefixes.plate.get(Materials.Iron)});
for (FluidContainerRegistry.FluidContainerData tData : FluidContainerRegistry.getRegisteredFluidContainerData()) {
if ((tData.filledContainer.getItem() == Items.potionitem) && (tData.filledContainer.getItemDamage() == 0)) {
GT_Recipe.GT_Recipe_Map.sFluidCannerRecipes.addRecipe(true, new ItemStack[]{ItemList.Bottle_Empty.get(1L, new Object[0])}, new ItemStack[]{new ItemStack(Items.potionitem, 1, 0)}, null, new FluidStack[]{Materials.Water.getFluid(250L)}, null, 4, 1, 0);
GT_Recipe.GT_Recipe_Map.sFluidCannerRecipes.addRecipe(true, new ItemStack[]{new ItemStack(Items.potionitem, 1, 0)}, new ItemStack[]{ItemList.Bottle_Empty.get(1L, new Object[0])}, null, null, null, 4, 1, 0);
} else {
GT_Recipe.GT_Recipe_Map.sFluidCannerRecipes.addRecipe(true, new ItemStack[]{tData.emptyContainer}, new ItemStack[]{tData.filledContainer}, null, new FluidStack[]{tData.fluid}, null, tData.fluid.amount / 62, 1, 0);
GT_Recipe.GT_Recipe_Map.sFluidCannerRecipes.addRecipe(true, new ItemStack[]{tData.filledContainer}, new ItemStack[]{GT_Utility.getContainerItem(tData.filledContainer, true)}, null, null, new FluidStack[]{tData.fluid}, tData.fluid.amount / 62, 1, 0);
}
}
try {
for (ICentrifugeRecipe tRecipe : RecipeManagers.centrifugeManager.recipes()) {
Map<ItemStack, Float> outputs = tRecipe.getAllProducts();
ItemStack[] tOutputs = new ItemStack[outputs.size()];
int[] tChances = new int[outputs.size()];
int i = 0;
for (Map.Entry<ItemStack, Float> entry : outputs.entrySet()) {
tChances[i] = (int) (entry.getValue() * 10000);
tOutputs[i] = entry.getKey().copy();
i++;
}
GT_Recipe.GT_Recipe_Map.sCentrifugeRecipes.addRecipe(true, new ItemStack[]{tRecipe.getInput()}, tOutputs, null, tChances, null, null, 128, 5, 0);
}
} catch (Throwable e) {
if (GT_Values.D1) {
e.printStackTrace(GT_Log.err);
}
}
try {
for (ISqueezerRecipe tRecipe : RecipeManagers.squeezerManager.recipes()) {
if ((tRecipe.getResources().length == 1) && (tRecipe.getFluidOutput() != null)) {
GT_Recipe.GT_Recipe_Map.sFluidExtractionRecipes.addRecipe(true, new ItemStack[]{tRecipe.getResources()[0]}, new ItemStack[]{tRecipe.getRemnants()}, null, new int[]{(int) (tRecipe.getRemnantsChance() * 10000)}, null, new FluidStack[]{tRecipe.getFluidOutput()}, 400, 2, 0);
}
}
} catch (Throwable e) {
if (GT_Values.D1) {
e.printStackTrace(GT_Log.err);
}
}
String tName = "";
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "blastfurnace"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "blockcutter"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "inductionFurnace"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "generator"), false)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "windMill"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "waterMill"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "solarPanel"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "centrifuge"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "electrolyzer"), false)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "compressor"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "electroFurnace"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "extractor"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "macerator"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "recycler"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "metalformer"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "orewashingplant"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "massFabricator"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (GregTech_API.sRecipeFile.get(ConfigCategories.Recipes.disabledrecipes, "ic2_" + (tName = "replicator"), true)) {
GT_ModHandler.removeRecipeByOutput(GT_ModHandler.getIC2Item(tName, 1L));
}
if (gregtechproxy.mNerfedVanillaTools) {
GT_Log.out.println("GT_Mod: Nerfing Vanilla Tool Durability");
Items.wooden_sword.setMaxDamage(12);
Items.wooden_pickaxe.setMaxDamage(12);
Items.wooden_shovel.setMaxDamage(12);
Items.wooden_axe.setMaxDamage(12);
Items.wooden_hoe.setMaxDamage(12);
Items.stone_sword.setMaxDamage(48);
Items.stone_pickaxe.setMaxDamage(48);
Items.stone_shovel.setMaxDamage(48);
Items.stone_axe.setMaxDamage(48);
Items.stone_hoe.setMaxDamage(48);
Items.iron_sword.setMaxDamage(256);
Items.iron_pickaxe.setMaxDamage(256);
Items.iron_shovel.setMaxDamage(256);
Items.iron_axe.setMaxDamage(256);
Items.iron_hoe.setMaxDamage(256);
Items.golden_sword.setMaxDamage(24);
Items.golden_pickaxe.setMaxDamage(24);
Items.golden_shovel.setMaxDamage(24);
Items.golden_axe.setMaxDamage(24);
Items.golden_hoe.setMaxDamage(24);
Items.diamond_sword.setMaxDamage(768);
Items.diamond_pickaxe.setMaxDamage(768);
Items.diamond_shovel.setMaxDamage(768);
Items.diamond_axe.setMaxDamage(768);
Items.diamond_hoe.setMaxDamage(768);
}
GT_Log.out.println("GT_Mod: Adding buffered Recipes.");
GT_ModHandler.stopBufferingCraftingRecipes();
GT_Log.out.println("GT_Mod: Saving Lang File.");
GT_LanguageManager.sEnglishFile.save();
GregTech_API.sPostloadFinished = true;
GT_Log.out.println("GT_Mod: PostLoad-Phase finished!");
GT_Log.ore.println("GT_Mod: PostLoad-Phase finished!");
for (Runnable tRunnable : GregTech_API.sAfterGTPostload) {
try {
tRunnable.run();
} catch (Throwable e) {
e.printStackTrace(GT_Log.err);
}
}
GT_Log.out.println("GT_Mod: Adding Fake Recipes for NEI");
if (ItemList.FR_Bee_Drone.get(1L, new Object[0]) != null) {
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.FR_Bee_Drone.getWildcard(1L, new Object[0])}, new ItemStack[]{ItemList.FR_Bee_Drone.getWithName(1L, "Scanned Drone", new Object[0])}, null, new FluidStack[]{Materials.Honey.getFluid(100L)}, null, 500, 2, 0);
}
if (ItemList.FR_Bee_Princess.get(1L, new Object[0]) != null) {
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.FR_Bee_Princess.getWildcard(1L, new Object[0])}, new ItemStack[]{ItemList.FR_Bee_Princess.getWithName(1L, "Scanned Princess", new Object[0])}, null, new FluidStack[]{Materials.Honey.getFluid(100L)}, null, 500, 2, 0);
}
if (ItemList.FR_Bee_Queen.get(1L, new Object[0]) != null) {
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.FR_Bee_Queen.getWildcard(1L, new Object[0])}, new ItemStack[]{ItemList.FR_Bee_Queen.getWithName(1L, "Scanned Queen", new Object[0])}, null, new FluidStack[]{Materials.Honey.getFluid(100L)}, null, 500, 2, 0);
}
if (ItemList.FR_Tree_Sapling.get(1L, new Object[0]) != null) {
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.FR_Tree_Sapling.getWildcard(1L, new Object[0])}, new ItemStack[]{ItemList.FR_Tree_Sapling.getWithName(1L, "Scanned Sapling", new Object[0])}, null, new FluidStack[]{Materials.Honey.getFluid(100L)}, null, 500, 2, 0);
}
if (ItemList.FR_Butterfly.get(1L, new Object[0]) != null) {
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.FR_Butterfly.getWildcard(1L, new Object[0])}, new ItemStack[]{ItemList.FR_Butterfly.getWithName(1L, "Scanned Butterfly", new Object[0])}, null, new FluidStack[]{Materials.Honey.getFluid(100L)}, null, 500, 2, 0);
}
if (ItemList.FR_Larvae.get(1L, new Object[0]) != null) {
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.FR_Larvae.getWildcard(1L, new Object[0])}, new ItemStack[]{ItemList.FR_Larvae.getWithName(1L, "Scanned Larvae", new Object[0])}, null, new FluidStack[]{Materials.Honey.getFluid(100L)}, null, 500, 2, 0);
}
if (ItemList.FR_Serum.get(1L, new Object[0]) != null) {
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.FR_Serum.getWildcard(1L, new Object[0])}, new ItemStack[]{ItemList.FR_Serum.getWithName(1L, "Scanned Serum", new Object[0])}, null, new FluidStack[]{Materials.Honey.getFluid(100L)}, null, 500, 2, 0);
}
if (ItemList.FR_Caterpillar.get(1L, new Object[0]) != null) {
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.FR_Caterpillar.getWildcard(1L, new Object[0])}, new ItemStack[]{ItemList.FR_Caterpillar.getWithName(1L, "Scanned Caterpillar", new Object[0])}, null, new FluidStack[]{Materials.Honey.getFluid(100L)}, null, 500, 2, 0);
}
if (ItemList.FR_PollenFertile.get(1L, new Object[0]) != null) {
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.FR_PollenFertile.getWildcard(1L, new Object[0])}, new ItemStack[]{ItemList.FR_PollenFertile.getWithName(1L, "Scanned Pollen", new Object[0])}, null, new FluidStack[]{Materials.Honey.getFluid(100L)}, null, 500, 2, 0);
}
if (ItemList.IC2_Crop_Seeds.get(1L, new Object[0]) != null) {
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.IC2_Crop_Seeds.getWildcard(1L, new Object[0])}, new ItemStack[]{ItemList.IC2_Crop_Seeds.getWithName(1L, "Scanned Seeds", new Object[0])}, null, null, null, 160, 8, 0);
}
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{new ItemStack(Items.written_book, 1, 32767)}, new ItemStack[]{ItemList.Tool_DataStick.getWithName(1L, "Scanned Book Data", new Object[0])}, ItemList.Tool_DataStick.getWithName(1L, "Stick to save it to", new Object[0]), null, null, 128, 32, 0);
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{new ItemStack(Items.filled_map, 1, 32767)}, new ItemStack[]{ItemList.Tool_DataStick.getWithName(1L, "Scanned Map Data", new Object[0])}, ItemList.Tool_DataStick.getWithName(1L, "Stick to save it to", new Object[0]), null, null, 128, 32, 0);
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.Tool_DataOrb.getWithName(1L, "Orb to overwrite", new Object[0])}, new ItemStack[]{ItemList.Tool_DataOrb.getWithName(1L, "Copy of the Orb", new Object[0])}, ItemList.Tool_DataOrb.getWithName(0L, "Orb to copy", new Object[0]), null, null, 512, 32, 0);
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.Tool_DataStick.getWithName(1L, "Stick to overwrite", new Object[0])}, new ItemStack[]{ItemList.Tool_DataStick.getWithName(1L, "Copy of the Stick", new Object[0])}, ItemList.Tool_DataStick.getWithName(0L, "Stick to copy", new Object[0]), null, null, 128, 32, 0);
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.Tool_DataStick.getWithName(1L, "Raw Prospection Data", new Object[0])}, new ItemStack[]{ItemList.Tool_DataStick.getWithName(1L, "Analyzed Prospection Data", new Object[0])}, null, null, null, 1000, 32, 0);
for (Materials tMaterial : Materials.VALUES) {
if ((tMaterial.mElement != null) && (!tMaterial.mElement.mIsIsotope) && (tMaterial != Materials.Magic) && (tMaterial.getMass() > 0L)) {
ItemStack tOutput = ItemList.Tool_DataOrb.get(1L, new Object[0]);
Behaviour_DataOrb.setDataTitle(tOutput, "Elemental-Scan");
Behaviour_DataOrb.setDataName(tOutput, tMaterial.mElement.name());
ItemStack tInput = GT_OreDictUnificator.get(OrePrefixes.dust, tMaterial, 1L);
if (tInput != null) {
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{tInput}, new ItemStack[]{tOutput}, ItemList.Tool_DataOrb.get(1L, new Object[0]), null, null, (int) (tMaterial.getMass() * 8192L), 32, 0);
GT_Recipe.GT_Recipe_Map.sRepicatorFakeRecipes.addFakeRecipe(false, null, new ItemStack[]{tInput}, new ItemStack[]{tOutput}, new FluidStack[]{Materials.UUMatter.getFluid(tMaterial.getMass())}, null, (int) (tMaterial.getMass() * 512L), 32, 0);
}
tInput = GT_OreDictUnificator.get(OrePrefixes.cell, tMaterial, 1L);
if (tInput != null) {
GT_Recipe.GT_Recipe_Map.sScannerFakeRecipes.addFakeRecipe(false, new ItemStack[]{tInput}, new ItemStack[]{tOutput}, ItemList.Tool_DataOrb.get(1L, new Object[0]), null, null, (int) (tMaterial.getMass() * 8192L), 32, 0);
GT_Recipe.GT_Recipe_Map.sRepicatorFakeRecipes.addFakeRecipe(false, null, new ItemStack[]{tInput}, new ItemStack[]{tOutput}, new FluidStack[]{Materials.UUMatter.getFluid(tMaterial.getMass())}, null, (int) (tMaterial.getMass() * 512L), 32, 0);
}
}
}
GT_Recipe.GT_Recipe_Map.sRockBreakerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.Display_ITS_FREE.getWithName(0L, "Place Lava on Side", new Object[0])}, new ItemStack[]{new ItemStack(Blocks.cobblestone, 1)}, null, null, null, 16, 32, 0);
GT_Recipe.GT_Recipe_Map.sRockBreakerFakeRecipes.addFakeRecipe(false, new ItemStack[]{ItemList.Display_ITS_FREE.getWithName(0L, "Place Lava on Top", new Object[0])}, new ItemStack[]{new ItemStack(Blocks.stone, 1)}, null, null, null, 16, 32, 0);
GT_Recipe.GT_Recipe_Map.sRockBreakerFakeRecipes.addFakeRecipe(false, new ItemStack[]{GT_OreDictUnificator.get(OrePrefixes.dust, Materials.Redstone, 1L)}, new ItemStack[]{new ItemStack(Blocks.obsidian, 1)}, null, null, null, 128, 32, 0);
for (Iterator i$ = GT_ModHandler.getMaceratorRecipeList().entrySet().iterator(); i$.hasNext(); ) {
Entry tRecipe = (Map.Entry) i$.next();
if (((RecipeOutput) tRecipe.getValue()).items.size() > 0) {
for (ItemStack tStack : ((IRecipeInput) tRecipe.getKey()).getInputs()) {
if (GT_Utility.isStackValid(tStack)) {
GT_Recipe.GT_Recipe_Map.sMaceratorRecipes.addFakeRecipe(true, new ItemStack[]{GT_Utility.copyAmount(((IRecipeInput) tRecipe.getKey()).getAmount(), new Object[]{tStack})}, new ItemStack[]{(ItemStack) ((RecipeOutput) tRecipe.getValue()).items.get(0)}, null, null, null, null, 400, 2, 0);
}
}
}
}
if(GregTech_API.mOutputRF||GregTech_API.mInputRF){
GT_Utility.checkAvailabilities();
if(!GT_Utility.RF_CHECK){
GregTech_API.mOutputRF = false;
GregTech_API.mInputRF = false;
}
}
achievements = new GT_Achievements();
Map.Entry<IRecipeInput, RecipeOutput> tRecipe;
GT_Log.out.println("GT_Mod: Loading finished, deallocating temporary Init Variables.");
GregTech_API.sBeforeGTPreload = null;
GregTech_API.sAfterGTPreload = null;
GregTech_API.sBeforeGTLoad = null;
GregTech_API.sAfterGTLoad = null;
GregTech_API.sBeforeGTPostload = null;
GregTech_API.sAfterGTPostload = null;
String axxxxx = null;
String axxxxxx = null;
String axxxxxxx = null;
Date date2 = new Date();
long timeOclock = System.currentTimeMillis();
try {
axxxxx = DurationFormatUtils.formatDurationHMS(timeOclock-systemTimeA);
axxxxxx = DurationFormatUtils.formatDurationHMS(timeOclock-systemTimeB);
axxxxxxx = DurationFormatUtils.formatDurationHMS(timeOclock-date.getTime());
}
catch (Throwable e){
}
profileLog("Time at last code call : "+date2.toString());
profileLog("Difference between final GT code call and Constructor: "+axxxxx);
profileLog("Difference between final GT code call and PreInit: "+axxxxxx);
profileLog("Difference between final GT code call and activeOreDicthandler(): "+axxxxxxx);
profileLog("============================================================");
}
@Mod.EventHandler
public void onServerStarting(FMLServerStartingEvent aEvent) {
for (Runnable tRunnable : GregTech_API.sBeforeGTServerstart) {
try {
tRunnable.run();
} catch (Throwable e) {
e.printStackTrace(GT_Log.err);
}
}
gregtechproxy.onServerStarting();
GT_Log.out.println("GT_Mod: Unificating outputs of all known Recipe Types.");
ArrayList<ItemStack> tStacks = new ArrayList(10000);
GT_Log.out.println("GT_Mod: IC2 Machines");
for (RecipeOutput tRecipe : ic2.api.recipe.Recipes.cannerBottle.getRecipes().values()) {
ItemStack tStack;
for (Iterator i$ = tRecipe.items.iterator(); i$.hasNext(); tStacks.add(tStack)) {
tStack = (ItemStack) i$.next();
}
}
for (RecipeOutput tRecipe : ic2.api.recipe.Recipes.centrifuge.getRecipes().values()) {
ItemStack tStack;
for (Iterator i$ = tRecipe.items.iterator(); i$.hasNext(); tStacks.add(tStack)) {
tStack = (ItemStack) i$.next();
}
}
for (RecipeOutput tRecipe : ic2.api.recipe.Recipes.compressor.getRecipes().values()) {
ItemStack tStack;
for (Iterator i$ = tRecipe.items.iterator(); i$.hasNext(); tStacks.add(tStack)) {
tStack = (ItemStack) i$.next();
}
}
for (RecipeOutput tRecipe : ic2.api.recipe.Recipes.extractor.getRecipes().values()) {
ItemStack tStack;
for (Iterator i$ = tRecipe.items.iterator(); i$.hasNext(); tStacks.add(tStack)) {
tStack = (ItemStack) i$.next();
}
}
for (RecipeOutput tRecipe : ic2.api.recipe.Recipes.macerator.getRecipes().values()) {
ItemStack tStack;
for (Iterator i$ = tRecipe.items.iterator(); i$.hasNext(); tStacks.add(tStack)) {
tStack = (ItemStack) i$.next();
}
}
for (RecipeOutput tRecipe : ic2.api.recipe.Recipes.metalformerCutting.getRecipes().values()) {
ItemStack tStack;
for (Iterator i$ = tRecipe.items.iterator(); i$.hasNext(); tStacks.add(tStack)) {
tStack = (ItemStack) i$.next();
}
}
for (RecipeOutput tRecipe : ic2.api.recipe.Recipes.metalformerExtruding.getRecipes().values()) {
ItemStack tStack;
for (Iterator i$ = tRecipe.items.iterator(); i$.hasNext(); tStacks.add(tStack)) {
tStack = (ItemStack) i$.next();
}
}
for (RecipeOutput tRecipe : ic2.api.recipe.Recipes.metalformerRolling.getRecipes().values()) {
ItemStack tStack;
for (Iterator i$ = tRecipe.items.iterator(); i$.hasNext(); tStacks.add(tStack)) {
tStack = (ItemStack) i$.next();
}
}
for (RecipeOutput tRecipe : ic2.api.recipe.Recipes.matterAmplifier.getRecipes().values()) {
ItemStack tStack;
for (Iterator i$ = tRecipe.items.iterator(); i$.hasNext(); tStacks.add(tStack)) {
tStack = (ItemStack) i$.next();
}
}
for (RecipeOutput tRecipe : ic2.api.recipe.Recipes.oreWashing.getRecipes().values()) {
ItemStack tStack;
for (Iterator i$ = tRecipe.items.iterator(); i$.hasNext(); tStacks.add(tStack)) {
tStack = (ItemStack) i$.next();
}
}
GT_Log.out.println("GT_Mod: Dungeon Loot");
for (WeightedRandomChestContent tContent : ChestGenHooks.getInfo("dungeonChest").getItems(new Random())) {
tStacks.add(tContent.theItemId);
}
for (WeightedRandomChestContent tContent : ChestGenHooks.getInfo("bonusChest").getItems(new Random())) {
tStacks.add(tContent.theItemId);
}
for (WeightedRandomChestContent tContent : ChestGenHooks.getInfo("villageBlacksmith").getItems(new Random())) {
tStacks.add(tContent.theItemId);
}
for (WeightedRandomChestContent tContent : ChestGenHooks.getInfo("strongholdCrossing").getItems(new Random())) {
tStacks.add(tContent.theItemId);
}
for (WeightedRandomChestContent tContent : ChestGenHooks.getInfo("strongholdLibrary").getItems(new Random())) {
tStacks.add(tContent.theItemId);
}
for (WeightedRandomChestContent tContent : ChestGenHooks.getInfo("strongholdCorridor").getItems(new Random())) {
tStacks.add(tContent.theItemId);
}
for (WeightedRandomChestContent tContent : ChestGenHooks.getInfo("pyramidJungleDispenser").getItems(new Random())) {
tStacks.add(tContent.theItemId);
}
for (WeightedRandomChestContent tContent : ChestGenHooks.getInfo("pyramidJungleChest").getItems(new Random())) {
tStacks.add(tContent.theItemId);
}
for (WeightedRandomChestContent tContent : ChestGenHooks.getInfo("pyramidDesertyChest").getItems(new Random())) {
tStacks.add(tContent.theItemId);
}
for (WeightedRandomChestContent tContent : ChestGenHooks.getInfo("mineshaftCorridor").getItems(new Random())) {
tStacks.add(tContent.theItemId);
}
GT_Log.out.println("GT_Mod: Smelting");
Object tStack;
for (Iterator i$ = FurnaceRecipes.smelting().getSmeltingList().values().iterator(); i$.hasNext(); tStacks.add((ItemStack) tStack)) {
tStack = i$.next();
}
if (gregtechproxy.mCraftingUnification) {
GT_Log.out.println("GT_Mod: Crafting Recipes");
for (Object tRecipe : CraftingManager.getInstance().getRecipeList()) {
if ((tRecipe instanceof IRecipe)) {
tStacks.add(((IRecipe) tRecipe).getRecipeOutput());
}
}
}
for (ItemStack tOutput : tStacks) {
if (gregtechproxy.mRegisteredOres.contains(tOutput)) {
FMLLog.severe("GT-ERR-01: @ " + tOutput.getUnlocalizedName() + " " + tOutput.getDisplayName(), new Object[0]);
FMLLog.severe("A Recipe used an OreDict Item as Output directly, without copying it before!!! This is a typical CallByReference/CallByValue Error", new Object[0]);
FMLLog.severe("Said Item will be renamed to make the invalid Recipe visible, so that you can report it properly.", new Object[0]);
FMLLog.severe("Please check all Recipes outputting this Item, and report the Recipes to their Owner.", new Object[0]);
FMLLog.severe("The Owner of the ==>RECIPE<==, NOT the Owner of the Item, which has been mentioned above!!!", new Object[0]);
FMLLog.severe("And ONLY Recipes which are ==>OUTPUTTING<== the Item, sorry but I don't want failed Bug Reports.", new Object[0]);
FMLLog.severe("GregTech just reports this Error to you, so you can report it to the Mod causing the Problem.", new Object[0]);
FMLLog.severe("Even though I make that Bug visible, I can not and will not fix that for you, that's for the causing Mod to fix.", new Object[0]);
FMLLog.severe("And speaking of failed Reports:", new Object[0]);
FMLLog.severe("Both IC2 and GregTech CANNOT be the CAUSE of this Problem, so don't report it to either of them.", new Object[0]);
FMLLog.severe("I REPEAT, BOTH, IC2 and GregTech CANNOT be the source of THIS BUG. NO MATTER WHAT.", new Object[0]);
FMLLog.severe("Asking in the IC2 Forums, which Mod is causing that, won't help anyone, since it is not possible to determine, which Mod it is.", new Object[0]);
FMLLog.severe("If it would be possible, then I would have had added the Mod which is causing it to the Message already. But it is not possible.", new Object[0]);
FMLLog.severe("Sorry, but this Error is serious enough to justify this Wall-O-Text and the partially allcapsed Language.", new Object[0]);
FMLLog.severe("Also it is a Ban Reason on the IC2-Forums to post this seriously.", new Object[0]);
tOutput.setStackDisplayName("ERROR! PLEASE CHECK YOUR LOG FOR 'GT-ERR-01'!");
} else {
GT_OreDictUnificator.setStack(tOutput);
}
}
GregTech_API.mServerStarted = true;
GT_Log.out.println("GT_Mod: ServerStarting-Phase finished!");
GT_Log.ore.println("GT_Mod: ServerStarting-Phase finished!");
for (Runnable tRunnable : GregTech_API.sAfterGTServerstart) {
try {
tRunnable.run();
} catch (Throwable e) {
e.printStackTrace(GT_Log.err);
}
}
}
@Mod.EventHandler
public void onServerStarted(FMLServerStartedEvent aEvent) {
gregtechproxy.onServerStarted();
}
@Mod.EventHandler
public void onIDChangingEvent(FMLModIdMappingEvent aEvent) {
GT_Utility.reInit();
GT_Recipe.reInit();
for (Iterator i$ = GregTech_API.sItemStackMappings.iterator(); i$.hasNext(); ) {
Map tMap = (Map) i$.next();
try {
GT_Utility.reMap(tMap);
} catch (Throwable e) {
e.printStackTrace(GT_Log.err);
}
}
}
// public void onIDChangingEvent(FMLModIdMappingEvent aEvent)
// {
// GT_Utility.reInit();
// GT_Recipe.reInit();
// Map<GT_ItemStack, ?> tMap;
// for (Iterator i$ = GregTech_API.sItemStackMappings.iterator(); i$.hasNext(); ) {
// tMap = (Map)i$.next();
// }
// }
@Mod.EventHandler
public void onServerStopping(FMLServerStoppingEvent aEvent) {
for (Runnable tRunnable : GregTech_API.sBeforeGTServerstop) {
try {
tRunnable.run();
} catch (Throwable e) {
e.printStackTrace(GT_Log.err);
}
}
gregtechproxy.onServerStopping();
try {
if ((GT_Values.D1) || (GT_Log.out != System.out)) {
GT_Log.out.println("*");
GT_Log.out.println("Printing List of all registered Objects inside the OreDictionary, now with free extra Sorting:");
GT_Log.out.println("*");
GT_Log.out.println("*");
GT_Log.out.println("*");
String[] tList = OreDictionary.getOreNames();
Arrays.sort(tList);
for (String tOreName : tList) {
int tAmount = OreDictionary.getOres(tOreName).size();
if (tAmount > 0) {
GT_Log.out.println((tAmount < 10 ? " " : "") + tAmount + "x " + tOreName);
}
}
GT_Log.out.println("*");
GT_Log.out.println("Printing List of all registered Objects inside the Fluid Registry, now with free extra Sorting:");
GT_Log.out.println("*");
GT_Log.out.println("*");
GT_Log.out.println("*");
tList = (String[]) FluidRegistry.getRegisteredFluids().keySet().toArray(new String[FluidRegistry.getRegisteredFluids().keySet().size()]);
Arrays.sort(tList);
for (String tFluidName : tList) {
GT_Log.out.println(tFluidName);
}
GT_Log.out.println("*");
GT_Log.out.println("*");
GT_Log.out.println("*");
GT_Log.out.println("Outputting all the Names inside the Biomeslist");
GT_Log.out.println("*");
GT_Log.out.println("*");
GT_Log.out.println("*");
for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) {
if (BiomeGenBase.getBiomeGenArray()[i] != null) {
GT_Log.out.println(BiomeGenBase.getBiomeGenArray()[i].biomeID + " = " + BiomeGenBase.getBiomeGenArray()[i].biomeName);
}
}
GT_Log.out.println("*");
GT_Log.out.println("*");
GT_Log.out.println("*");
GT_Log.out.println("Printing List of generatable Materials");
GT_Log.out.println("*");
GT_Log.out.println("*");
GT_Log.out.println("*");
for (int i = 0; i < GregTech_API.sGeneratedMaterials.length; i++) {
if (GregTech_API.sGeneratedMaterials[i] == null) {
GT_Log.out.println("Index " + i + ":" + null);
} else {
GT_Log.out.println("Index " + i + ":" + GregTech_API.sGeneratedMaterials[i]);
}
}
GT_Log.out.println("*");
GT_Log.out.println("*");
GT_Log.out.println("*");
GT_Log.out.println("END GregTech-Debug");
GT_Log.out.println("*");
GT_Log.out.println("*");
GT_Log.out.println("*");
}
} catch (Throwable e) {
if (GT_Values.D1) {
e.printStackTrace(GT_Log.err);
}
}
for (Runnable tRunnable : GregTech_API.sAfterGTServerstop) {
try {
tRunnable.run();
} catch (Throwable e) {
e.printStackTrace(GT_Log.err);
}
}
}
public boolean isServerSide() {
return gregtechproxy.isServerSide();
}
public boolean isClientSide() {
return gregtechproxy.isClientSide();
}
public boolean isBukkitSide() {
return gregtechproxy.isBukkitSide();
}
public EntityPlayer getThePlayer() {
return gregtechproxy.getThePlayer();
}
public int addArmor(String aArmorPrefix) {
return gregtechproxy.addArmor(aArmorPrefix);
}
public void doSonictronSound(ItemStack aStack, World aWorld, double aX, double aY, double aZ) {
gregtechproxy.doSonictronSound(aStack, aWorld, aX, aY, aZ);
}
}
| 63.562896 | 856 | 0.655452 |
11bdf84de3190c314ce3672d7af39063349bdd2e | 508 | package com.askjeffreyliu.teslaapi.room.dao;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import com.askjeffreyliu.teslaapi.model.Vehicle;
import java.util.List;
@Dao
public interface VehicleDao {
@Insert
void insert(Vehicle roomVehicle);
@Query("DELETE FROM vehicles_table")
void deleteAll();
@Query("SELECT * from vehicles_table ORDER BY vehicle_id ASC")
LiveData<List<Vehicle>> getAllVehicles();
}
| 19.538462 | 66 | 0.753937 |
5a8dffea2558d91c7d120c64a58f30dfb75bd81b | 2,935 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ibm.drl.hbcp.api;
/**
* This class encodes the format of the JSON object returned via the REST APIs
* for information extraction. The returned JSON has three fields -
* <ol>
* <li> the code of the attribute that is to be extracted, </li>
* <li> the name of the pdf file, </li>
* <li> the extracted value. </li>
* </ol>
*
* @author dganguly
*/
public class IUnitPOJO {
String type; // one of (C, I, O)
String code;
String docName;
String extractedValue;
String context;
String armId;
String armName;
public IUnitPOJO(String type, String docName, String value, String code, String context, String armId, String armName) {
this.type = type;
this.docName = docName;
this.extractedValue = value;
this.code = code;
this.context = context;
this.armId = armId;
this.armName = armName;
}
public IUnitPOJO(String type, String docName, String value, String code, String context) {
this.type = type;
this.docName = docName;
this.extractedValue = value;
this.code = code;
this.context = context;
}
public IUnitPOJO(String docName, String value, String code, String context) {
this.docName = docName;
this.extractedValue = value;
this.code = code;
this.context = context;
}
public String getCode() {
return this.code;
}
public void setCode(String code) { this.code = code; }
public String getDocName() {
return docName;
}
public String getExtractedValue() {
return extractedValue;
}
public String getContext() { return context; }
public String getArmId() { return armId; }
public String getArmName() { return armName; }
public String toString() {
StringBuffer buff = new StringBuffer();
buff
// id is <docname:attribid>
.append("{")
.append("\n")
//.append("\"_id\": \"")
//.append(docName)
//.append(":")
//.append(code)
//.append("\",")
//.append("\n")
.append("\"type\": \"")
.append(type)
.append("\",")
.append("\n")
.append("\"code\": \"")
.append(code)
.append("\",")
.append("\n")
.append("\"extractedValue\": \"")
.append(extractedValue)
.append("\",")
.append("\n")
.append("\"context\": \"")
.append(context)
.append("\"")
.append("\n")
.append("}")
;
return buff.toString();
}
}
| 27.175926 | 124 | 0.536627 |
eda7a9885f6ec14f981ab82e25abc9cc4ffa1fa9 | 2,740 | /*
* Copyright 2012, Moshe Waisberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.times.compass.preference;
import androidx.annotation.StyleRes;
/**
* Compass preferences.
*
* @author Moshe Waisberg
*/
public interface CompassPreferences {
/** Preference name for the compass bearing type. */
String KEY_COMPASS_BEARING = "compass.bearing";
/** Preference name for showing summaries. */
String KEY_SUMMARIES = "summaries.visible";
/** Preference name for the compass theme. */
String KEY_THEME_COMPASS = "theme.compass";
class Values {
/** Default summaries hidden. */
public static boolean SUMMARIES_DEFAULT = false;
/** The default bearing. */
public static String BEARING_DEFAULT;
/** Calculates the bearing for a Great Circle (shortest distance). */
public static String BEARING_GREAT_CIRCLE;
/** Calculates the bearing for a Rhumb Line (constant angle). */
public static String BEARING_RHUMB_LINE;
/** Original theme. */
public static String THEME_ORIGINAL;
/** Gold theme. */
public static String THEME_GOLD;
/** Silver theme. */
public static String THEME_SILVER;
/** Classic theme. */
public static String THEME_CLASSIC;
/** Default theme. */
public static String THEME_COMPASS_DEFAULT;
}
/**
* Get the theme value.
*
* @return the theme value.
*/
String getCompassThemeValue();
/**
* Get the theme.
*
* @param value the theme value.
* @return the theme resource id.
* @see #getCompassThemeValue()
*/
@StyleRes
int getCompassTheme(String value);
/**
* Get the theme.
*
* @return the theme resource id.
*/
@StyleRes
int getCompassTheme();
/**
* Get the type of bearing for calculating compass direction.
*
* @return the bearing type - either {@link Values#BEARING_GREAT_CIRCLE} or {@link Values#BEARING_RHUMB_LINE}.
*/
String getBearing();
/**
* Are summaries visible?
*
* @return {@code true} to show summaries.
*/
boolean isSummariesVisible();
}
| 28.541667 | 114 | 0.645985 |
ae9b010ccefaac0357b81aa0f75453dde76d6356 | 4,429 | package com.lingnan.convertor;
import com.lingnan.kv.BaseDimension;
import com.lingnan.kv.CommDimension;
import com.lingnan.kv.ContactDimension;
import com.lingnan.kv.DateDimension;
import com.lingnan.util.JDBCUtil;
import com.lingnan.util.LRUCache;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//获取时间和联系人维度对应的id
public class DimensionConvertorImpl implements IConvertor{
LRUCache lruCache = new LRUCache(3000);
@Override
public int getDimensionID(BaseDimension baseDimension) {
//从缓存获取数据,有数据则返回数据
String cacheKey = getCacheKey(baseDimension);
if(lruCache.containsKey(cacheKey)){
return lruCache.get(cacheKey);
}
// 从mysql中是否有值,如果没有,插入数据
String[] sqls = getSqls(baseDimension);
Connection connection = JDBCUtil.getConnection();
// 执行sql 先查看mysql中是否有值,如果没有,插入数据,再获取相应的id值
int id = -1;
try {
id = execSql(sqls,connection,baseDimension);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
if(id == -1) throw new RuntimeException("未匹配到相应的维度");
lruCache.put(cacheKey,id);
return id;
}
// 如果查询成功则返回id,失败则返回-1
private int execSql(String[] sqls,Connection connection,BaseDimension baseDimension) throws SQLException {
int id = -1;
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement(sqls[0]);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
// 第一次查询 查询到则直接返回
setArguments(preparedStatement,baseDimension);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
return resultSet.getInt(1);
}
// 查询不到则插入数据
preparedStatement = connection.prepareStatement(sqls[1]);
setArguments(preparedStatement,baseDimension);
preparedStatement.executeUpdate();
// 第二次查询
preparedStatement = connection.prepareStatement(sqls[0]);
setArguments(preparedStatement,baseDimension);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
return resultSet.getInt(1);
}
return id;
}
// 设置sql语句的参数 如果为时间维度的则插入三个参数,如果为联系人维度则插入两个参数
// 这个方法因为都是两个参数,所以插入查询都可以用这个方法设置参数
private void setArguments(PreparedStatement preparedStatement,BaseDimension baseDimension) throws SQLException {
if(baseDimension instanceof ContactDimension){
ContactDimension contactDimension = (ContactDimension) baseDimension;
preparedStatement.setString(1,contactDimension.getPhoneNum());
preparedStatement.setString(2,contactDimension.getName());
}else if (baseDimension instanceof DateDimension){
DateDimension dateDimension = (DateDimension) baseDimension;
preparedStatement.setInt(1,Integer.valueOf(dateDimension.getYear()));
preparedStatement.setInt(2,Integer.valueOf(dateDimension.getMonth()));
preparedStatement.setInt(3,Integer.valueOf(dateDimension.getDay()));
}
}
private String[] getSqls(BaseDimension baseDimension){
String[] sqls = new String[2];
if(baseDimension instanceof ContactDimension){
sqls[0] = "SELECT `id` FROM `tb_contacts` WHERE `telephone` = ? AND `name` = ?;";
sqls[1] = "INSERT INTO `tb_contacts` VALUES(NULL,?,?);";
}else if(baseDimension instanceof DateDimension){
sqls[0] = "SELECT `id` FROM `tb_dimension_date` WHERE `YEAR` = ? AND `MONTH` = ? AND `DAY` = ? ;";
sqls[1] = "INSERT INTO `tb_dimension_date` VALUES (NULL,?,?,?);";
}
return sqls;
}
private String getCacheKey(BaseDimension baseDimension){
StringBuffer sb = new StringBuffer();
if(baseDimension instanceof ContactDimension){
ContactDimension contactDimension = (ContactDimension) baseDimension;
sb.append(contactDimension.getPhoneNum());
}else if(baseDimension instanceof DateDimension){
DateDimension dateDimension = (DateDimension) baseDimension;
sb.append(dateDimension.getYear()).append(dateDimension.getMonth()).append(dateDimension.getDay());
}
return sb.toString();
}
}
| 36.908333 | 116 | 0.667419 |
cee25b60dd7359a06f60d80de93432292e5091c5 | 4,076 | package com.thebluealliance.androidclient.notifications;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.thebluealliance.androidclient.DefaultTestRunner;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.activities.ViewEventActivity;
import com.thebluealliance.androidclient.adapters.ViewEventFragmentPagerAdapter;
import com.thebluealliance.androidclient.database.writers.EventWriter;
import com.thebluealliance.androidclient.datafeed.framework.ModelMaker;
import com.thebluealliance.androidclient.gcm.notifications.AllianceSelectionNotification;
import com.thebluealliance.androidclient.gcm.notifications.NotificationTypes;
import com.thebluealliance.androidclient.helpers.MyTBAHelper;
import com.thebluealliance.androidclient.models.Event;
import com.thebluealliance.androidclient.models.StoredNotification;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.robolectric.RuntimeEnvironment;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@RunWith(DefaultTestRunner.class)
public class AllianceSelectionNotificationTest {
@Mock private Context mContext;
@Mock private EventWriter mWriter;
private AllianceSelectionNotification mNotification;
private JsonObject mData;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application.getApplicationContext();
mWriter = mock(EventWriter.class);
mData = ModelMaker.getModel(JsonObject.class, "notification_alliance_selection");
mNotification = new AllianceSelectionNotification(mData.toString(), mWriter);
}
@Test
public void testParseData() {
mNotification.parseMessageData();
assertEquals(mNotification.getEventKey(), "2014necmp");
Event event = mNotification.getEvent();
assertNotNull(event);
}
@Test
public void testDbWrite() {
mNotification.parseMessageData();
mNotification.updateDataLocally();
Event event = mNotification.getEvent();
verify(mWriter).write(eq(event), anyLong());
}
@Test(expected = JsonParseException.class)
public void testNoEvent() {
mData.remove("event");
mNotification = new AllianceSelectionNotification(mData.toString(), mWriter);
mNotification.parseMessageData();
}
@Test
public void testBuildNotification() {
mNotification.parseMessageData();
Notification notification = mNotification.buildNotification(mContext, null);
assertNotNull(notification);
StoredNotification stored = mNotification.getStoredNotification();
assertNotNull(stored);
assertEquals(stored.getType(), NotificationTypes.ALLIANCE_SELECTION);
assertEquals(stored.getTitle(), mContext.getString(R.string.notification_alliances_updated_title, "NECMP"));
assertEquals(stored.getBody(), mContext.getString(R.string.notification_alliances_updated, "New England"));
assertEquals(stored.getMessageData(), mData.toString());
assertEquals(stored.getIntent(), MyTBAHelper.serializeIntent(mNotification.getIntent(mContext)));
assertNotNull(stored.getTime());
}
@Test
public void testGetIntent() {
mNotification.parseMessageData();
Intent intent = mNotification.getIntent(mContext);
assertNotNull(intent);
assertEquals(intent.getComponent().getClassName(), "com.thebluealliance.androidclient.activities.ViewEventActivity");
assertEquals(intent.getStringExtra(ViewEventActivity.EVENTKEY), mNotification.getEventKey());
assertEquals(intent.getIntExtra(ViewEventActivity.TAB, -1), ViewEventFragmentPagerAdapter.TAB_ALLIANCES);
}
}
| 39.960784 | 125 | 0.766928 |
30f17a71d83654c0bf8e214d51491441853fbae8 | 1,612 | /*
* Copyright 2010 bufferings[at]gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package bufferings.ktr.wjr.client;
import bufferings.ktr.wjr.client.service.KtrWjrJsonServiceAsync;
import bufferings.ktr.wjr.client.service.KtrWjrServiceAsync;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.RootPanel;
/**
* The entry point class of Kotori Web JUnit Runner.
*
* @author bufferings[at]gmail.com
*/
public class KtrWjr implements EntryPoint {
private static final String INITIAL_PANEL_ID = "initialPanel";
/**
* {@inheritDoc}
*/
public void onModuleLoad() {
KtrWjrServiceAsync rpcService = new KtrWjrJsonServiceAsync();
WjrPresenter presenter =
new WjrPresenter(rpcService, new WjrLoadingView(), new WjrView());
RootPanel initialPanel = RootPanel.get(INITIAL_PANEL_ID);
if (initialPanel != null) {
initialPanel.getElement().removeFromParent();
}
presenter.go(RootLayoutPanel.get());
}
}
| 31.607843 | 73 | 0.717742 |
1db6a5a24498d3fdbe7c8f850085a7dabda96eb4 | 299 | package uk.nhs.nhsbsa.research.userresearchapp.forms;
@SuppressWarnings("serial")
public class ScreeningPurchasedDurationPPC extends AbstractForm {
private int duration;
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
}
| 18.6875 | 65 | 0.772575 |
036ba48fc778c5058411c76f29454e21cdc9383e | 1,887 | package perobobbot.oauth.tools;
import lombok.NonNull;
import perobobbot.data.service.BotService;
import perobobbot.data.service.ClientService;
import perobobbot.data.service.OAuthService;
import perobobbot.lang.Platform;
import perobobbot.oauth.ApiToken;
import perobobbot.oauth.OAuthRequirement;
import perobobbot.oauth.OAuthTokenService;
import perobobbot.oauth.TokenIdentifier;
import perobobbot.oauth.tools._private.SimpleApiTokenHelper;
import java.util.Optional;
public interface ApiTokenHelper extends OAuthTokenService {
/**
* @return true if the token has been refreshed, false otherwise
*/
boolean refreshToken();
/**
* Remove the token
*/
void deleteToken();
/**
* @return the token obtained during
*/
@NonNull Optional<ApiToken> getToken();
@Override
@NonNull
default ApiToken getCurrentApiToken() {
return getToken().orElseThrow(() -> new IllegalArgumentException("No token set"));
}
static ApiTokenHelper simple(
@NonNull ClientService clientService,
@NonNull OAuthService oAuthService,
@NonNull BotService botService,
@NonNull Platform platform,
@NonNull OAuthRequirement requirement
) {
return new SimpleApiTokenHelper(
clientService, oAuthService, botService, platform, requirement,null
);
}
static ApiTokenHelper simple(
@NonNull ClientService clientService,
@NonNull OAuthService oAuthService,
@NonNull BotService botService,
@NonNull Platform platform,
@NonNull OAuthRequirement requirement,
@NonNull TokenIdentifier tokenIdentifier
) {
return new SimpleApiTokenHelper(
clientService, oAuthService, botService, platform, requirement, tokenIdentifier
);
}
}
| 28.590909 | 95 | 0.686804 |
f8f9137a713de70f0b9a34a9ac50e4a30f7b4f4e | 30,150 | package com.glyart.asql.common.database;
import com.glyart.asql.common.context.ASQLContext;
import com.glyart.asql.common.defaults.DefaultBatchSetter;
import com.glyart.asql.common.defaults.DefaultCreator;
import com.glyart.asql.common.defaults.DefaultExtractor;
import com.glyart.asql.common.defaults.DefaultSetter;
import com.glyart.asql.common.functions.*;
import com.google.common.base.Preconditions;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.*;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.logging.Logger;
/**
* Represents the final interaction to a data source.
* <p>An instance of the DataTemplate class is linked to the ASQLContext which provided its instance.
* Knowing that, the DataTemplate class can <i>access and use</i> that ASQLContext members.</p>
*
* <p>This class:
* <ul>
* <li>works asynchronously, without overhead on the main thread</li>
* <li>executes all the <a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> operations on a data source</li>
* <li>handles exceptions</li>
* <li>gives not null <b>{@link CompletableFuture} objects that WILL STORE usable future results</b></li>
* <li>iterates over ResultSets</li>
* <li>deals with static and prepared statements</li>
* </ul>
*
* <p>Methods of this class use various callback interfaces. A reading of those is greatly suggested.
*
* <p>There shouldn't be the need for using the public constructor. Getting an instance of this class by using {@link ASQLContext#getDataTemplate()}
* should be enough.
* <br> Since the callback interfaces make DataTemplate's methods parameterizable, there should be no need to subclass DataTemplate.
* @param <T> The context who created this data template
* @see CompletableFuture
* @see BatchPreparedStatementSetter
* @see ParametrizedPreparedStatementSetter
* @see PreparedStatementCallback
* @see PreparedStatementCreator
* @see ResultSetExtractor
* @see RowMapper
* @see StatementCallback
*/
@SuppressWarnings("unused")
public class DataTemplate<T extends ASQLContext<?>> {
private final T context;
private final Logger logger;
public DataTemplate(T context) {
Preconditions.checkNotNull(context, "Context cannot be null.");
this.context = context;
this.logger = context.getLogger();
}
/**
* Executes a JDBC data access operation, implemented as {@link StatementCallback} callback, using an
* active connection.
* The callback CAN return a result object (if it exists), for example a single object or a collection of objects.
* @param callback a callback that holds the operation logic
* @param <S> the result type
* @return a never null CompletableFuture object which holds: an object returned by the callback, or null if it's not available
*/
public <S> CompletableFuture<S> execute(@NotNull StatementCallback<S> callback) {
Preconditions.checkNotNull(callback, "StatementCallback cannot be null.");
CompletableFuture<S> completableFuture = new CompletableFuture<>();
context.getScheduler().async(() -> {
Connection connection = getConnection();
if (connection == null) {
completableFuture.completeExceptionally(new SQLException("Could not retrieve connection."));
logger.severe("Could not retrieve a connection.");
return;
}
Statement statement = null;
try {
statement = connection.createStatement();
S result = callback.doInStatement(statement);
completableFuture.complete(result);
} catch (SQLException e) {
completableFuture.completeExceptionally(e);
} finally {
closeStatement(statement);
closeConnection(connection);
}
});
return completableFuture;
}
/**
* Performs a single update operation (like insert, delete, update).
* @param sql static SQL statement to execute
* @param getGeneratedKeys a boolean value
* @return a never null CompletableFuture object which holds: the number of the affected rows.
* If getGeneratedKeys is true, this method will return the key of the new generated row
*/
public CompletableFuture<Integer> update(@NotNull String sql, boolean getGeneratedKeys) {
Preconditions.checkNotNull(sql, "Sql statement cannot be null.");
return execute(statement -> {
int rows;
ResultSet set = null;
try {
if (getGeneratedKeys) {
statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
set = statement.getGeneratedKeys();
rows = set.next() ? set.getInt(1) : 0;
} else
rows = statement.executeUpdate(sql, Statement.NO_GENERATED_KEYS);
} finally {
closeResultSet(set);
}
return rows;
});
}
/**
* Executes a query given static SQL statement, then it reads the {@link ResultSet} using the {@link ResultSetExtractor} implementation.
* @param sql the query to execute
* @param extractor a callback that will extract all rows from the ResultSet
* @param <S> the result type
* @return a never null CompletableFuture object which holds: a result object (if it exists), according to the ResultSetExtractor implementation
*/
public <S> CompletableFuture<S> query(@NotNull String sql, ResultSetExtractor<S> extractor) {
return execute(statement -> {
ResultSet resultSet = null;
S result;
try {
resultSet = statement.executeQuery(sql);
result = extractor.extractData(resultSet);
} finally {
closeResultSet(resultSet);
}
return result;
});
}
/**
* Executes a query given static SQL statement, then it maps each
* ResultSet row to a result object using the {@link RowMapper} implementation.
* @param sql the query to execute
* @param rowMapper a callback that will map one object per ResultSet row
* @param <S> the result type
* @return a never null CompletableFuture object which holds: a result list containing mapped objects (if they exist)
*/
public <S> CompletableFuture<List<S>> queryForList(@NotNull String sql, RowMapper<S> rowMapper) {
return query(sql, new DefaultExtractor<>(rowMapper));
}
/**
* Executes a query given static SQL statement, then it maps the first
* ResultSet row to a result object using the {@link RowMapper} implementation.
*
* <p>Note: use of this method is discouraged when the query doesn't supply exactly one row.
* If more rows are supplied then this method will return only the first one.</p>
* @param sql the query to execute
* @param rowMapper a callback that will map the object per ResultSet row
* @param <S> the result type
* @return a never null CompletableFuture object which holds: a mapped result object (if it exists)
*/
public <S> CompletableFuture<S> queryForObject(@NotNull String sql, RowMapper<S> rowMapper) {
CompletableFuture<S> futureSinglet = new CompletableFuture<>();
context.getScheduler().async(() -> {
CompletableFuture<List<S>> listCompletableFuture = query(sql, new DefaultExtractor<>(rowMapper, 1));
listCompletableFuture.whenComplete((s, throwable) -> futureSinglet.complete(s.isEmpty() ? null : s.get(0)));
});
return futureSinglet;
}
/**
* Executes a JDBC data access operation, implemented as {@link PreparedStatementCallback} callback
* working on a PreparedStatement.
* The callback CAN return a result object (if it exists), for example a singlet or a collection of objects.
* @param creator a callback that creates a PreparedStatement object given a connection
* @param callback a callback that holds the operation logic
* @param <S> the result type
* @return a never null CompletableFuture object which holds: an object returned by the callback, or null if it's not available
*/
public <S> CompletableFuture<S> execute(@NotNull PreparedStatementCreator creator, @NotNull PreparedStatementCallback<S> callback) {
CompletableFuture<S> completableFuture = new CompletableFuture<>();
context.getScheduler().async(() -> {
Connection connection = getConnection();
if (connection == null) {
completableFuture.completeExceptionally(new SQLException("Could not retrieve connection."));
logger.severe("Could not retrieve a connection.");
return;
}
PreparedStatement ps = null;
try {
ps = creator.createPreparedStatement(connection);
completableFuture.complete(callback.doInPreparedStatement(ps));
} catch (SQLException e) {
completableFuture.completeExceptionally(e);
} finally {
closeStatement(ps);
closeConnection(connection);
}
});
return completableFuture;
}
/**
* Executes a JDBC data access operation, implemented as {@link PreparedStatementCallback} callback
* working on a PreparedStatement.
* The callback CAN return a result object (if it exists), for example a singlet or a collection of objects.
* @param sql the SQL statement to execute
* @param callback a callback that holds the operation logic
* @param <S> the result type
* @return a never null CompletableFuture object which holds: an object returned by the callback, or null if it's not available
*/
public <S> CompletableFuture<S> execute(@NotNull String sql, @NotNull PreparedStatementCallback<S> callback) {
return execute(new DefaultCreator(sql), callback);
}
/**
* Performs a single update operation (like insert, delete, update) using a {@link PreparedStatementCreator} to provide SQL
* and any required parameters. A {@link PreparedStatementSetter} can be passed as helper that sets bind parameters.
* @param creator a callback that provides the PreparedStatement with bind parameters
* @param setter a helper that sets bind parameters. If it's null then this will be an update with static SQL
* @param getGeneratedKey a boolean value
* @return a never null CompletableFuture object which holds: the number of the affected rows.
* If getGeneratedKeys is true, this method will return the key of the new generated row
*/
public CompletableFuture<Integer> update(@NotNull PreparedStatementCreator creator, @Nullable PreparedStatementSetter setter, boolean getGeneratedKey) {
return execute(creator, ps -> {
ResultSet set = null;
int rows;
try {
if (setter != null)
setter.setValues(ps);
if (getGeneratedKey) {
ps.executeUpdate();
set = ps.getGeneratedKeys();
rows = set.next() ? set.getInt(1) : 0;
} else
rows = ps.executeUpdate();
} finally {
closeResultSet(set);
}
return rows;
});
}
/**
* Performs a single update operation (like insert, delete, update) using a {@link PreparedStatementCreator} to
* to provide SQL and any required parameters.
* @param creator a callback that provides the PreparedStatement with required parameters
* @param getGeneratedKeys a boolean values
* @return a never null CompletableFuture object which holds: the number of the affected rows.
* If getGeneratedKeys is true, this method will return the key of the new generated row
*/
public CompletableFuture<Integer> update(@NotNull PreparedStatementCreator creator, boolean getGeneratedKeys) {
return update(creator, null, getGeneratedKeys);
}
/**
* Performs a single update operation (like insert, delete, update).
* A {@link PreparedStatementSetter} can be passed as helper that sets bind parameters.
* @param sql the SQL containing bind parameters
* @param setter a helper that sets bind parameters. If it's null then this will be an update with static SQL
* @param getGeneratedKey a boolean value
* @return a never null CompletableFuture object which holds: the number of the affected rows.
* If getGeneratedKeys is true, this method will return the key of the new generated row
*/
public CompletableFuture<Integer> update(@NotNull String sql, @Nullable PreparedStatementSetter setter, boolean getGeneratedKey) {
return update(new DefaultCreator(sql, getGeneratedKey), setter, getGeneratedKey);
}
/**
* Performs a single update operation (like insert, update or delete statement)
* via PreparedStatement, binding the given parameters.
* @param sql the SQL containing bind parameters
* @param params arguments to be bind to the given SQL
* @param getGeneratedKey a boolean value
* @return a never null CompletableFuture object which holds: the number of the affected rows.
* If getGeneratedKeys is true, this method will return the key of the new generated row
*/
public CompletableFuture<Integer> update(@NotNull String sql, Object[] params, boolean getGeneratedKey) {
return update(sql, new DefaultSetter(params), getGeneratedKey);
}
/**
* Performs multiple update operations using a single SQL statement.
* <p><b>NOTE: this method will be unusable if the driver doesn't support batch updates.</b></p>
* @param sql the SQL containing bind parameters. It will be
* reused because all statements in a batch use the same SQL
* @param batchSetter a callback that sets parameters on the PreparedStatement created by this method
* @return a CompletableFuture object. It can be used for knowing when the batch update is done and if an exception occurred
* @throws IllegalStateException if the driver doesn't support batch updates
* @see CompletableFuture#exceptionally(Function)
* @see CompletableFuture#whenComplete(BiConsumer)
* @see BatchPreparedStatementSetter
*/
public CompletableFuture<Void> batchUpdate(@NotNull String sql, @NotNull BatchPreparedStatementSetter batchSetter) throws IllegalStateException {
Preconditions.checkNotNull(sql, "Sql cannot be null.");
Preconditions.checkArgument(!sql.isEmpty(), "Sql cannot be empty.");
Preconditions.checkNotNull(batchSetter, "BatchPreparedStatementSetter cannot be null.");
return execute(sql, ps -> {
if (!ps.getConnection().getMetaData().supportsBatchUpdates())
throw new IllegalStateException("This driver doesn't support batch updates. This method will remain unusable until you choose a driver that supports batch updates.");
for (int i = 0; i < batchSetter.getBatchSize(); i++) {
batchSetter.setValues(ps, i);
ps.addBatch();
}
ps.executeBatch();
return null;
});
}
/**
* Performs multiple update operations using a single SQL statement.
* @param sql The SQL containing bind parameters. It will be
* reused because all statements in a batch use the same SQL
* @param batchArgs A list of object arrays containing the batch arguments
* @return A CompletableFuture object. It can be used for knowing when the batch update is done and if an exception occurred
* @throws IllegalStateException If the driver doesn't support batch updates
* @see CompletableFuture#isCompletedExceptionally()
*/
public CompletableFuture<Void> batchUpdate(@NotNull String sql, @Nullable List<Object[]> batchArgs) throws IllegalStateException {
Preconditions.checkNotNull(sql, "Sql cannot be null.");
Preconditions.checkArgument(!sql.isEmpty(), "Sql cannot be empty.");
if (batchArgs == null || batchArgs.isEmpty())
return CompletableFuture.completedFuture(null);
return batchUpdate(sql, new DefaultBatchSetter(batchArgs));
}
/**
* Performs multiple update operations using a single SQL statement.
* @param sql the SQL containing bind parameters. It will be
* reused because all statements in a batch use the same SQL
* @param batchArgs a list of objects containing the batch arguments
* @param paramsBatchSetter a callback that sets parameters on the PreparedStatement created by this method
* @param <S> the parameter type
* @return a CompletableFuture object. It can be used for knowing when the batch update is done and if an exception occurred
* @throws IllegalStateException if the driver doesn't support batch updates
* @see ParametrizedPreparedStatementSetter
*/
public <S> CompletableFuture<Void> batchUpdate(@NotNull String sql, @Nullable List<S> batchArgs, @NotNull ParametrizedPreparedStatementSetter<S> paramsBatchSetter) throws IllegalStateException {
Preconditions.checkNotNull(sql, "Sql cannot be null.");
Preconditions.checkArgument(!sql.isEmpty(), "Sql cannot be empty.");
Preconditions.checkNotNull(paramsBatchSetter, "ParametrizedPreparedStatementSetter cannot be null.");
if (batchArgs == null || batchArgs.isEmpty())
return CompletableFuture.completedFuture(null);
return execute(sql, ps -> {
if (!ps.getConnection().getMetaData().supportsBatchUpdates())
throw new IllegalStateException("This driver doesn't support batch updates. This method will remain unusable until you choose a driver that supports batch updates.");
for (S batchParam : batchArgs) {
paramsBatchSetter.setValues(ps, batchParam);
ps.addBatch();
}
ps.executeBatch();
return null;
});
}
/**
* Executes a query using a PreparedStatement, created by a {@link PreparedStatementCreator} and with his values set
* by a {@link PreparedStatementSetter}.
*
* <p>Most other query methods use this method, but application code will always
* work with either a creator or a setter.</p>
* @param creator a callback that creates a PreparedStatement
* @param setter a callback that sets values on the PreparedStatement. If null, the SQL will be treated as static SQL with no bind parameters
* @param extractor a callback that will extract results given a ResultSet
* @param <S> the result type
* @return a never null CompletableFuture object which holds: a result object (if it exists), according to the ResultSetExtractor implementation
* @see PreparedStatementSetter
*/
public <S> CompletableFuture<S> query(@NotNull PreparedStatementCreator creator, @Nullable PreparedStatementSetter setter, @NotNull ResultSetExtractor<S> extractor) {
Preconditions.checkNotNull(extractor, "ResultSetExtractor cannot be null.");
return execute(creator, ps -> {
S result;
ResultSet resultSet = null;
try {
if (setter != null)
setter.setValues(ps);
resultSet = ps.executeQuery();
result = extractor.extractData(resultSet);
} finally {
closeResultSet(resultSet);
}
return result;
});
}
/**
* Executes a query using a PreparedStatement, then reading the ResultSet with a {@link ResultSetExtractor} implementation.
* @param creator a callback that creates a PreparedStatement
* @param extractor a callback that will extract results given a ResultSet
* @param <S> the result type
* @return a never null CompletableFuture object which holds: a result object (if it exists), according to the ResultSetExtractor implementation
* @see PreparedStatementCreator
*/
public <S> CompletableFuture<S> query(@NotNull PreparedStatementCreator creator, @NotNull ResultSetExtractor<S> extractor) {
return query(creator, null, extractor);
}
/**
* Executes a query using a PreparedStatement, mapping each row to a result object via a {@link RowMapper} implementation.
* @param psc a callback that creates a PreparedStatement
* @param rowMapper a callback that will map one object per ResultSet row
* @param <S> the result type
* @return a never null CompletableFuture object which holds: a result list containing mapped objects (if they exist)
*/
public <S> CompletableFuture<List<S>> query(@NotNull PreparedStatementCreator psc, @NotNull RowMapper<S> rowMapper) {
return query(psc, new DefaultExtractor<>(rowMapper));
}
/**
* Executes a query using a SQL statement, then reading the ResultSet with a {@link ResultSetExtractor} implementation.
* @param sql the query to execute
* @param setter a callback that sets values on the PreparedStatement. If null, the SQL will be treated as static SQL with no bind parameters
* @param extractor a callback that will extract results given a ResultSet
* @param <S> the result type
* @return a never null CompletableFuture object which holds: a result object (if it exists), according to the ResultSetExtractor implementation
*/
public <S> CompletableFuture<S> query(@NotNull String sql, @Nullable PreparedStatementSetter setter, @NotNull ResultSetExtractor<S> extractor) {
return query(new DefaultCreator(sql), setter, extractor);
}
/**
* Executes a query using a SQL statement and a {@link PreparedStatementSetter} implementation that will bind values to the query.
* Each row of the ResultSet will be map to a result object via a RowMapper implementation.
* @param sql the query to execute
* @param pss a callback that sets values on the PreparedStatement. If null, the SQL will be treated as static SQL with no bind parameters
* @param rowMapper a callback that will map one object per ResultSet row
* @param <S> the result type
* @return a never null CompletableFuture object which holds: a result list containing mapped objects (if they exist)
*/
public <S> CompletableFuture<List<S>> query(@NotNull String sql, @Nullable PreparedStatementSetter pss, @NotNull RowMapper<S> rowMapper) {
return query(sql, pss, new DefaultExtractor<>(rowMapper));
}
/**
* Executes a query given a SQL statement: it will be used to create a PreparedStatement.
* Then a list of arguments will be bound to the query.
* The {@link ResultSetExtractor} implementation will read the ResultSet.
* @param sql the query to execute
* @param args arguments to bind to the query
* @param extractor a callback that will extract results given a ResultSet
* @param <S> the result type
* @return a never null CompletableFuture object which holds: a result object (if it exists), according to the ResultSetExtractor implementation
*/
public <S> CompletableFuture<S> query(@NotNull String sql, @Nullable Object[] args, @NotNull ResultSetExtractor<S> extractor) {
return query(sql, new DefaultSetter(args), extractor);
}
/**
* Executes a query given a SQL statement: it will be used to create a PreparedStatement.
* Then a list of arguments will be bound to the query.
* Each row of the ResultSet will be map to a result object via a {@link RowMapper} implementation.
* @param sql the query to execute
* @param args arguments to bind to the query
* @param rowMapper a callback that will map one object per ResultSet row
* @param <S> the result type
* @return a never null CompletableFuture object which holds: a result list containing mapped objects (if they exist)
*/
public <S> CompletableFuture<List<S>> queryForList(@NotNull String sql, @Nullable Object[] args, @NotNull RowMapper<S> rowMapper) {
return query(sql, args, new DefaultExtractor<>(rowMapper));
}
/**
* Executes a query given a SQL statement: it will be used to create a PreparedStatement.
* Then a list of arguments will be bound to the query.
* Each row of the ResultSet will be map to a result object via a {@link RowMapper} implementation.
*
* <p>Note: use of this method is discouraged when the query doesn't supply exactly one row.
* If more rows are supplied then this method will return only the first one.</p>
* @param sql the query to execute
* @param args arguments to bind to the query
* @param rowMapper a callback that will map one object per ResultSet row
* @param <S> the result type
* @return a never null CompletableFuture object which holds: a mapped result object (if it exist)
*/
public <S> CompletableFuture<S> queryForObject(@NotNull String sql, Object[] args, @NotNull RowMapper<S> rowMapper) {
CompletableFuture<S> futureSinglet = new CompletableFuture<>();
context.getScheduler().async(() -> {
CompletableFuture<List<S>> listCompletableFuture = query(sql, args, new DefaultExtractor<>(rowMapper, 1));
listCompletableFuture.whenComplete((s, throwable) -> futureSinglet.complete(s.isEmpty() ? null : s.get(0)));
});
return futureSinglet;
}
/**
* Gets a connection using {@link DataSourceHandler}'s implementation.
* This method's failures are fatal and definitely blocks {@link DataTemplate}'s access operations.
* If that occurs then an error will be logged.
* @return an active connection ready to be used (if it's available)
*/
@Nullable
protected Connection getConnection() {
DataSourceHandler handler = context.getDataSourceHandler();
Connection connection = null;
try {
if (handler.getStrategy() == Strategy.SIMPLE_CONNECTION)
handler.open(); // This handler doesn't manage a connection pool so we must open a connection first
else
connection = context.getDataSourceHandler().getConnection(); // Retrieving connection from the opened connection pool
} catch (SQLException e) {
return null;
}
return connection;
}
/**
* Gets a connection using {@link DataSourceHandler}'s implementation.
* The connection will be available by accessing the returned CompletableFuture object,
* with {@link CompletableFuture#whenComplete(BiConsumer)} method. Possible exceptions
* are stored inside that object and they can also be accessed by using whenComplete method.
* @return a never null CompletableFuture object which holds: an active connection ready to be used (if it's available)
* @see CompletableFuture#whenComplete(BiConsumer)
* @see CompletableFuture
*/
@NotNull
protected CompletableFuture<Connection> getFutureConnection() {
CompletableFuture<Connection> futureConnection = new CompletableFuture<>();
context.getScheduler().async(() -> {
DataSourceHandler handler = context.getDataSourceHandler();
Connection connection = null;
try {
if (handler.getStrategy() == Strategy.SIMPLE_CONNECTION)
handler.open(); // This handler doesn't manage a connection pool so we must open a connection first
else
connection = context.getDataSourceHandler().getConnection(); // Retrieving connection from the opened connection pool
} catch (SQLException e) {
futureConnection.completeExceptionally(e);
}
futureConnection.complete(connection);
});
return futureConnection;
}
/**
* Closes a connection using {@link DataSourceHandler}'s implementation.
* A failure from this method is not fatal but it will be logged as warning.
* @param connection the connection to close
*/
protected void closeConnection(@Nullable Connection connection) {
if (connection == null)
return;
DataSourceHandler handler = context.getDataSourceHandler();
try {
if (handler.getStrategy() == Strategy.SIMPLE_CONNECTION)
handler.close(); // A simple connection based handler must decide how to manage connection closure
else
connection.close(); // We mustn't close the connection pool but we can free the created connection
} catch (SQLException e) {
logger.warning(() -> e.getMessage() + " - Error code: " + e.getErrorCode());
}
}
/**
* Tries to close a statement (accepts PreparedStatement objects).
* A failure from this method is not fatal but it will be logged as warning.
* @param statement the statement to close
*/
protected void closeStatement(@Nullable Statement statement) {
if (statement == null)
return;
try {
statement.close();
} catch (SQLException e) {
logger.warning(() -> e.getMessage() + " - Error code: " + e.getErrorCode());
}
}
/**
* Tries to close a ResultSet object.
* A failure from this method is not fatal but it will be logged as warning.
* @param set the ResultSet to close
*/
protected void closeResultSet(@Nullable ResultSet set) {
if (set == null)
return;
try {
set.close();
} catch (SQLException e) {
logger.warning(() -> e.getMessage() + " - Error code: " + e.getErrorCode());
}
}
}
| 50.25 | 198 | 0.676119 |
968aebab92b8fb1e26f60f34681b8fb00f7033fe | 325 | package br.com.fiap.fiapBlood.service;
import br.com.fiap.fiapBlood.dto.geographic.GeographicPointsDTO;
public interface GeoLocationService {
GeographicPointsDTO getGeographicCoordinates(String street, String district, String city);
Double calculateDistance(double lat1, double lon1, double lat2, double lon2);
}
| 29.545455 | 94 | 0.809231 |
295ecd3c814460035cc3894fa221619dd3de6c03 | 363 | package androidx.core.os;
import android.content.res.Configuration;
import androidx.annotation.NonNull;
public final class ConfigurationCompat {
private ConfigurationCompat() {
}
@NonNull
public static LocaleListCompat getLocales(@NonNull Configuration configuration) {
return LocaleListCompat.wrap(configuration.getLocales());
}
}
| 24.2 | 85 | 0.760331 |
f7d3699bbfc3b1ea9750aedd63e8a5096aaec451 | 1,916 | /*
* Copyright 2016 qyh.me
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.qyh.blog.core.config;
/**
* 全局配置
*
* @author mhlx
*
*/
public class GlobalConfig {
/**
* 文件管理每页数量
*/
private int filePageSize;
/**
* 用户模板片段管理分页数量
*/
private int fragmentPageSize;
/**
* 用户自定义页面分页数量
*/
private int pagePageSize;
/**
* 文章页面分页数量
*/
private int articlePageSize;
/**
* 标签页面分页数量
*/
private int tagPageSize;
private int newsPageSize;
public int getFilePageSize() {
return filePageSize;
}
public void setFilePageSize(int filePageSize) {
this.filePageSize = filePageSize;
}
public int getFragmentPageSize() {
return fragmentPageSize;
}
public void setFragmentPageSize(int fragmentPageSize) {
this.fragmentPageSize = fragmentPageSize;
}
public int getPagePageSize() {
return pagePageSize;
}
public void setPagePageSize(int pagePageSize) {
this.pagePageSize = pagePageSize;
}
public int getArticlePageSize() {
return articlePageSize;
}
public void setArticlePageSize(int articlePageSize) {
this.articlePageSize = articlePageSize;
}
public int getTagPageSize() {
return tagPageSize;
}
public void setTagPageSize(int tagPageSize) {
this.tagPageSize = tagPageSize;
}
public int getNewsPageSize() {
return newsPageSize;
}
public void setNewsPageSize(int newsPageSize) {
this.newsPageSize = newsPageSize;
}
}
| 18.970297 | 75 | 0.719207 |
b186386dc767a48083c48e45faf483fc98ce28f8 | 933 | package mayfly.sys.module.sys.controller.vo;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import mayfly.core.util.TreeUtils;
import java.util.List;
import java.util.Objects;
/**
* @author meilin.huang
* @version 1.0
* @date 2019-07-27 21:55
*/
@Getter
@Setter
@ToString
public class ResourceListVO implements TreeUtils.TreeNode<Long> {
private Long id;
private Long pid;
private Integer type;
private String name;
private String code;
private Integer status;
private String meta;
private List<ResourceListVO> children;
@Override
public Long id() {
return this.getId();
}
@Override
public Long parentId() {
return this.pid;
}
@Override
public boolean root() {
return Objects.equals(this.pid, 0L);
}
@Override
public void setChildren(List children) {
this.children = children;
}
}
| 16.368421 | 65 | 0.660236 |
acff5b8b4a19b1b56597763d10b77f0187160773 | 881 | package cla.edg.project.yourong.events;
import cla.edg.eventscript.EventScript;
public class YourongProjectBook extends BaseYourongEventScript{
private static final EventScript SCRIPT = $("yourong project book")
/**
* 开始: 由某个用户提交一个项目申请
*/
.on_event("confirm project book").with("yourong book")
.comments("用户确认了项目建议书")
.event_ripple("change yourong project book status")
.event_ripple("yourong project book confirmed").to("project")
.on_event("reject project book").with("yourong book")
.comments("用户不同意项目建议书")
.event_ripple("change yourong project book status")
.event_ripple("yourong project book rejected").to("project")
.internal_only_bydefault()
.on_event("change yourong project book status").with("yourong book").with("status id")
;
@Override
public EventScript getScript() {
return SCRIPT;
}
}
| 27.53125 | 89 | 0.707151 |
0a3ad3cbbbfb76ae8c3d1a5e4b041f84a56187af | 83 | @NonNullApi
package dev.morphia.experimental;
import com.mongodb.lang.NonNullApi;
| 16.6 | 35 | 0.831325 |
4f5da61d96c0978ef9d78feb3387bb29743ad822 | 4,711 | package com.letv.mobile.core.time;
import android.support.v4.media.TransportMediator;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
@Deprecated
public class SntpClient {
private static final int NTP_MODE_CLIENT = 3;
private static final int NTP_PACKET_SIZE = 48;
private static final int NTP_PORT = 123;
private static final int NTP_VERSION = 3;
private static final long OFFSET_1900_TO_1970 = 2208988800L;
private static final int ORIGINATE_TIME_OFFSET = 24;
private static final int RECEIVE_TIME_OFFSET = 32;
private static final int TRANSMIT_TIME_OFFSET = 40;
private long mNtpTime = -1;
private long mNtpTimeReference = -1;
private long mRoundTripTime = -1;
public boolean requestTime(String host, int timeout) {
try {
DatagramSocket socket = new DatagramSocket();
socket.setSoTimeout(timeout);
byte[] buffer = new byte[NTP_PACKET_SIZE];
DatagramPacket request = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(host), NTP_PORT);
buffer[0] = (byte) 27;
long requestTime = System.currentTimeMillis();
long requestTicks = System.nanoTime() / 1000;
writeTimeStamp(buffer, 40, requestTime);
socket.send(request);
socket.receive(new DatagramPacket(buffer, buffer.length));
long responseTicks = System.nanoTime() / 1000;
long responseTime = requestTime + (responseTicks - requestTicks);
socket.close();
long originateTime = readTimeStamp(buffer, 24);
long receiveTime = readTimeStamp(buffer, 32);
long transmitTime = readTimeStamp(buffer, 40);
long roundTripTime = (responseTicks - requestTicks) - (transmitTime - receiveTime);
this.mNtpTime = responseTime + (((receiveTime - originateTime) + (transmitTime - responseTime)) / 2);
this.mNtpTimeReference = responseTicks;
this.mRoundTripTime = roundTripTime;
return true;
} catch (Exception e) {
return false;
}
}
public long getNtpTime() {
return this.mNtpTime;
}
public long getNtpTimeReference() {
return this.mNtpTimeReference / 1000;
}
public long getRoundTripTime() {
return this.mRoundTripTime;
}
public boolean isFetchedTime() {
return getNtpTime() != -1;
}
public long getCurrentTime() {
if (isFetchedTime()) {
return getNtpTime();
}
return -1;
}
private long read32(byte[] buffer, int offset) {
int i0;
int i1;
int i2;
int i3;
byte b0 = buffer[offset];
byte b1 = buffer[offset + 1];
byte b2 = buffer[offset + 2];
byte b3 = buffer[offset + 3];
if ((b0 & 128) == 128) {
i0 = (b0 & TransportMediator.KEYCODE_MEDIA_PAUSE) + 128;
} else {
byte i02 = b0;
}
if ((b1 & 128) == 128) {
i1 = (b1 & TransportMediator.KEYCODE_MEDIA_PAUSE) + 128;
} else {
byte i12 = b1;
}
if ((b2 & 128) == 128) {
i2 = (b2 & TransportMediator.KEYCODE_MEDIA_PAUSE) + 128;
} else {
byte i22 = b2;
}
if ((b3 & 128) == 128) {
i3 = (b3 & TransportMediator.KEYCODE_MEDIA_PAUSE) + 128;
} else {
byte i32 = b3;
}
return (((((long) i0) << 24) + (((long) i1) << 16)) + (((long) i2) << 8)) + ((long) i3);
}
private long readTimeStamp(byte[] buffer, int offset) {
return ((read32(buffer, offset) - OFFSET_1900_TO_1970) * 1000) + ((1000 * read32(buffer, offset + 4)) / 4294967296L);
}
private void writeTimeStamp(byte[] buffer, int offset, long time) {
long seconds = time / 1000;
long milliseconds = time - (1000 * seconds);
seconds += OFFSET_1900_TO_1970;
int i = offset + 1;
buffer[offset] = (byte) ((int) (seconds >> 24));
offset = i + 1;
buffer[i] = (byte) ((int) (seconds >> 16));
i = offset + 1;
buffer[offset] = (byte) ((int) (seconds >> 8));
offset = i + 1;
buffer[i] = (byte) ((int) seconds);
long fraction = (4294967296L * milliseconds) / 1000;
i = offset + 1;
buffer[offset] = (byte) ((int) (fraction >> 24));
offset = i + 1;
buffer[i] = (byte) ((int) (fraction >> 16));
i = offset + 1;
buffer[offset] = (byte) ((int) (fraction >> 8));
offset = i + 1;
buffer[i] = (byte) ((int) (Math.random() * 255.0d));
}
}
| 35.689394 | 125 | 0.570367 |
332433069c51492074454dad5c00812624a23681 | 899 | package com.hibo.cms.quartz.util.tigger;
import java.util.HashMap;
import java.util.Map;
/**
* <p>标题:</p>
* <p>功能: </p>
* <p>版权: Copyright © 2015 HIBO</p>
* <p>公司: 北京瀚铂科技有限公司</p>
* <p>创建日期:2015年9月7日 下午1:41:36</p>
* <p>类全名:com.hibo.cms.quartz.util.tigger.TiggerStaticValue</p>
* 作者:周雷
* 初审:
* 复审:
*/
public class TiggerStaticValue {
public static Map<Integer,String> JOB_STATUS = new HashMap<Integer, String>();
static{
//-1:None:Trigger已经完成,且不会在执行,或者找不到该触发器,或者Trigger已经被删除
JOB_STATUS.put(-1, "未执行");
//0:NORMAL:正常状态
JOB_STATUS.put(0, "正常运行");
//1:PAUSED:暂停状态
JOB_STATUS.put(1, "暂停运行");
//2:COMPLETE:触发器完成,但是任务可能还正在执行中
JOB_STATUS.put(2, "完成,仍运行中");
//4:BLOCKED:线程阻塞状态
JOB_STATUS.put(4, "阻塞状态");
//5:ERROR:出现错误
JOB_STATUS.put(5, "错误状态");
//8:调度器关闭
JOB_STATUS.put(8, "调度器关闭");
}
public static Map<String,Object> JOB_INFO = new HashMap<String,Object>();
}
| 23.657895 | 79 | 0.661846 |
30707d68ec67567e78d3f1a0129d65b5006f9e02 | 7,483 | package info.loenwind.mves.api.simple;
import info.loenwind.mves.MvesMod;
import info.loenwind.mves.api.IEnergyAcceptor;
import info.loenwind.mves.api.IEnergyOffer;
import info.loenwind.mves.api.IEnergyStack;
import info.loenwind.mves.api.IEnergySupplier;
import info.loenwind.mves.api.IEnergyTransporter;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
/**
* An abstract base class for energy transporters.
* <p>
* All kinds of goodies in here. You should try to use this as base class if you
* roll your own transporter. Or at least have a good look at this code.
*
*/
public abstract class SimpleEnergyTransporterBase implements IEnergyTransporter {
/**
* Entry point to transport from all sides to all sides.
* <p>
* Call one of the transport()s once per tick in your update().
*/
public int transport(World world, BlockPos blockPos) {
return transport(world, blockPos, EnumSet.allOf(EnumFacing.class), EnumSet.allOf(EnumFacing.class));
}
/**
* Entry point to transport from the given input sides to the given output
* sides.
* <p>
* Call one of the transport()s once per tick in your update().
*/
public int transport(World world, BlockPos blockPos, EnumSet<EnumFacing> directionsIn, EnumSet<EnumFacing> directionsOut) {
List<IEnergyStack> stacks = collect(world, blockPos, directionsIn);
if (stacks.isEmpty()) {
return 0;
} else {
return push(world, blockPos, directionsOut, createOffer(stacks));
}
}
/**
* Convert a list of energy stacks into an energy offer. Overwrite this to use
* another offer class.
*/
protected IEnergyOffer createOffer(List<IEnergyStack> stacks) {
return new SimpleEnergyOffer(stacks);
}
/**
* Collects energy stacks from the neighbors in the given directions.
*/
protected List<IEnergyStack> collect(World world, BlockPos blockPos, EnumSet<EnumFacing> directions) {
List<IEnergyStack> result = new ArrayList<>();
for (EnumFacing direction : directions) {
IEnergyStack energyStack = collectFromSupplier(world, blockPos.offset(direction), direction.getOpposite());
if (energyStack != null) {
result.add(energyStack);
}
}
return result;
}
/**
* Try to collect an energy stack from the given block. The BlockPos is that
* of the block to collect from, the EnumFacing is relative to that block
* (which means opposite to your side). Return null if no energy stack could
* be collected, or if it would have been empty.
* <p>
* This checks:
* <ul>
* <li>That the block's chunk is loaded
* <li>That the chunk is not empty (short-circuit)
* <li>That there is a tile entity
* <li>That the tile entity has a world object
* <li>That it provides an energy supplier on the given side
* <li>That an energy offer is returned
* <li>That it contains energy
* </ul>
*/
protected IEnergyStack collectFromSupplier(World world, BlockPos blockPos, EnumFacing direction) {
if (world.isBlockLoaded(blockPos, false)) {
TileEntity tileEntity = world.getTileEntity(blockPos);
if (tileEntity != null && tileEntity.hasWorldObj()) {
IEnergySupplier energySupplier = tileEntity.getCapability(MvesMod.CAP_EnergySupplier, direction);
if (energySupplier != null) {
IEnergyStack energyStack = energySupplier.get();
if (energyStack != null && energyStack.getStackSize() > 0) {
return energyStack;
}
}
}
}
return null;
}
/**
* Pushes energy offers to energy acceptors and relays in the given
* directions.
*/
protected int push(World world, BlockPos blockPos, EnumSet<EnumFacing> directions, IEnergyOffer offer) {
int result = 0;
for (EnumFacing direction : directions) {
result += offerToAcceptor(world, blockPos.offset(direction), direction.getOpposite(), offer);
if (result >= offer.getLimit()) {
return result;
}
}
for (EnumFacing direction : directions) {
result += offerToRelay(world, blockPos.offset(direction), direction.getOpposite(), offer);
if (result >= offer.getLimit()) {
return result;
}
}
return result;
}
/**
* Try to push an energy offer to the energy acceptor of the given block. The
* BlockPos is that of the block to push to, the EnumFacing is relative to
* that block (which means opposite to your side). Returns the amount of
* energy that was pushed.
* <p>
* This checks:
* <ul>
* <li>That the block's chunk is loaded
* <li>That the chunk is not empty (short-circuit)
* <li>That there is a tile entity
* <li>That the tile entity has a world object
* <li>That it provides an energy acceptor on the given side
* <li>That the acceptor doesn't take more energy than as offered
* </ul>
*/
protected int offerToAcceptor(World world, BlockPos blockPos, EnumFacing direction, IEnergyOffer offer) {
if (world.isBlockLoaded(blockPos, false)) {
TileEntity tileEntity = world.getTileEntity(blockPos);
if (tileEntity != null && tileEntity.hasWorldObj() && tileEntity.hasCapability(MvesMod.CAP_EnergyAcceptor, direction)) {
IEnergyAcceptor energyAcceptor = tileEntity.getCapability(MvesMod.CAP_EnergyAcceptor, direction);
if (energyAcceptor != null) {
int taken = energyAcceptor.offerEnergy(offer);
if (taken > offer.getLimit()) {
MvesMod.LOG.warn("Block at " + blockPos + " was offered " + offer.getLimit() + " but it took " + taken);
explode(blockPos, direction);
}
return taken;
}
}
}
return 0;
}
/**
* Try to push an energy offer to the energy relay of the given block. The
* BlockPos is that of the block to push to, the EnumFacing is relative to
* that block (which means opposite to your side). Returns the amount of
* energy that was pushed.
* <p>
* This checks:
* <ul>
* <li>That the block's chunk is loaded
* <li>That the chunk is not empty (short-circuit)
* <li>That there is a tile entity
* <li>That the tile entity has a world object
* <li>That it provides an energy relay on the given side
* <li>That the relay doesn't take more energy than as offered
* </ul>
*/
protected int offerToRelay(World world, BlockPos blockPos, EnumFacing direction, IEnergyOffer offer) {
if (world.isBlockLoaded(blockPos, false)) {
TileEntity tileEntity = world.getTileEntity(blockPos);
if (tileEntity != null && tileEntity.hasWorldObj() && tileEntity.hasCapability(MvesMod.CAP_EnergyTransporter, direction)) {
IEnergyTransporter energyTransporter = tileEntity.getCapability(MvesMod.CAP_EnergyTransporter, direction);
if (energyTransporter != null) {
int taken = energyTransporter.relayEnergy(offer);
if (taken > offer.getLimit()) {
explode(blockPos, direction);
}
return taken;
}
}
}
return 0;
}
/**
* This is called when an acceptor or relay takes more energy than it was
* offered.
*/
protected abstract void explode(BlockPos offendingBlock, EnumFacing offendingDirection);
@Override
public int relayEnergy(IEnergyOffer offer) {
return 0;
}
}
| 36.149758 | 129 | 0.682213 |
7d53af63f68616bd7b59ce27d3ddddbfc9042654 | 3,421 | /*
* Copyright (C) 2019 StarChart-Labs@github.com Authors
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package org.starchartlabs.flare.plugins.test.model;
import java.util.Optional;
import org.starchartlabs.flare.plugins.model.Credentials;
import org.starchartlabs.flare.plugins.model.DefaultCredentialSource;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DefaultCredentialSourceTest {
@Test(expectedExceptions = NullPointerException.class)
public void constructNullUsername() throws Exception {
new DefaultCredentialSource(null, "password");
}
@Test(expectedExceptions = NullPointerException.class)
public void constructNullPassword() throws Exception {
new DefaultCredentialSource("username", null);
}
@Test
public void loadCredentials() throws Exception {
DefaultCredentialSource result = new DefaultCredentialSource("username", "password");
Optional<Credentials> credentials = result.loadCredentials();
Assert.assertNotNull(credentials);
Assert.assertTrue(credentials.isPresent());
Assert.assertEquals(credentials.get().getUsername(), "username");
Assert.assertEquals(credentials.get().getPassword(), "password");
}
@Test
public void hashCodeEqualWhenDataEqual() throws Exception {
DefaultCredentialSource result1 = new DefaultCredentialSource("username", "password");
DefaultCredentialSource result2 = new DefaultCredentialSource("username", "password");
Assert.assertEquals(result1.hashCode(), result2.hashCode());
}
@Test
public void equalsNull() throws Exception {
DefaultCredentialSource result = new DefaultCredentialSource("username", "password");
Assert.assertFalse(result.equals(null));
}
// Test is specifically for the mis-matched type case - warning is invalid
@Test
@SuppressWarnings("unlikely-arg-type")
public void equalsDifferentClass() throws Exception {
DefaultCredentialSource result = new DefaultCredentialSource("username", "password");
Assert.assertFalse(result.equals("string"));
}
@Test
public void equalsSelf() throws Exception {
DefaultCredentialSource result = new DefaultCredentialSource("username", "password");
Assert.assertTrue(result.equals(result));
}
@Test
public void equalsDifferentData() throws Exception {
DefaultCredentialSource result1 = new DefaultCredentialSource("username1", "password");
DefaultCredentialSource result2 = new DefaultCredentialSource("username2", "password");
Assert.assertFalse(result1.equals(result2));
}
@Test
public void equalsSameData() throws Exception {
DefaultCredentialSource result1 = new DefaultCredentialSource("username", "password");
DefaultCredentialSource result2 = new DefaultCredentialSource("username", "password");
Assert.assertTrue(result1.equals(result2));
}
@Test
public void toStringTest() throws Exception {
DefaultCredentialSource obj = new DefaultCredentialSource("username", "password");
String result = obj.toString();
Assert.assertNotNull(result);
Assert.assertTrue(result.contains("credentials=" + obj.loadCredentials().get().toString()));
}
}
| 34.908163 | 100 | 0.718796 |
a41b7392582eed53a4ffd8094bbcc799ec7c5a91 | 4,366 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.remoting.exchange.Response;
import org.apache.dubbo.remoting.exchange.support.DefaultFuture2;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.CancellationContext;
public class ClientStream extends AbstractClientStream implements Stream {
protected ClientStream(URL url) {
super(url);
}
@Override
protected InboundTransportObserver createInboundTransportObserver() {
return new ClientStreamInboundTransportObserverImpl();
}
@Override
protected void doOnStartCall() {
Response response = new Response(getRequestId(), TripleConstant.TRI_VERSION);
AppResponse result = getMethodDescriptor().isServerStream() ? callServerStream() : callBiStream();
response.setResult(result);
DefaultFuture2.received(getConnection(), response);
}
private AppResponse callServerStream() {
StreamObserver<Object> obServer = (StreamObserver<Object>) getRpcInvocation().getArguments()[1];
obServer = attachCancelContext(obServer, getCancellationContext());
subscribe(obServer);
inboundMessageObserver().onNext(getRpcInvocation().getArguments()[0]);
inboundMessageObserver().onCompleted();
return new AppResponse();
}
private AppResponse callBiStream() {
StreamObserver<Object> obServer = (StreamObserver<Object>) getRpcInvocation().getArguments()[0];
obServer = attachCancelContext(obServer, getCancellationContext());
subscribe(obServer);
return new AppResponse(inboundMessageObserver());
}
private <T> StreamObserver<T> attachCancelContext(StreamObserver<T> observer, CancellationContext context) {
if (observer instanceof CancelableStreamObserver) {
CancelableStreamObserver<T> streamObserver = (CancelableStreamObserver<T>) observer;
streamObserver.setCancellationContext(context);
return streamObserver;
}
return observer;
}
private class ClientStreamInboundTransportObserverImpl extends InboundTransportObserver {
private boolean error = false;
@Override
public void onData(byte[] data, boolean endStream) {
execute(() -> {
try {
final Object resp = deserializeResponse(data);
outboundMessageSubscriber().onNext(resp);
} catch (Throwable throwable) {
onError(throwable);
}
});
}
@Override
public void onError(GrpcStatus status) {
onError(status.asException());
}
@Override
public void onComplete() {
execute(() -> {
getState().setServerEndStreamReceived();
final GrpcStatus status = extractStatusFromMeta(getHeaders());
if (GrpcStatus.Code.isOk(status.code.code)) {
outboundMessageSubscriber().onCompleted();
} else {
onError(status.cause);
}
});
}
private void onError(Throwable throwable) {
if (error) {
return;
}
error = true;
if (!getState().serverSendStreamReceived()) {
cancel(throwable);
}
outboundMessageSubscriber().onError(throwable);
}
}
}
| 37.316239 | 112 | 0.65552 |
3d5436ece55ce8de5f86dd477409871b5525cb19 | 4,614 | package field;
import com.trident.crypto.field.exception.MultiplicativeGroupException;
import com.trident.crypto.field.operator.FiniteFieldElementArithmetics;
import java.math.BigInteger;
import java.util.Random;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/*
* Copyright 2018 trident.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
* @author trident
*/
public class PrimeFieldArithmeticsTest {
private FiniteFieldElementArithmetics arithmetics;
private int generator;
private BigInteger biGenerator;
private int times;
private Random random;
@Before
public void init(){
generator = 1009;
times = 1000;
biGenerator = new BigInteger(Integer.toString(generator));
arithmetics = FiniteFieldElementArithmetics.createFieldElementArithmetics(biGenerator);
System.out.println(arithmetics.getField());
random = new Random();
}
@Test
public void testAddition(){
for(int i=0;i<times;i++){
BigInteger x = new BigInteger(Integer.toString(random.nextInt(generator)));
BigInteger y = new BigInteger(Integer.toString(random.nextInt(generator)));
BigInteger res = x.add(y).mod(biGenerator);
Assert.assertEquals(res.compareTo(arithmetics.add(arithmetics.getElementFactory().createFrom(x), arithmetics.getElementFactory().createFrom(y))),0);
}
}
@Test
public void testSubstraction(){
for(int i=0;i<times;i++){
BigInteger x = new BigInteger(Integer.toString(random.nextInt(generator)));
BigInteger y = new BigInteger(Integer.toString(random.nextInt(generator)));
BigInteger res = x.subtract(y).mod(biGenerator);
BigInteger lres = arithmetics.sub(arithmetics.getElementFactory().createFrom(x), arithmetics.getElementFactory().createFrom(y));
Assert.assertEquals(res.compareTo(lres),0);
}
}
@Test
public void testMultiplication(){
for(int i=0;i<times;i++){
BigInteger x = new BigInteger(Integer.toString(random.nextInt(generator)));
BigInteger y = new BigInteger(Integer.toString(random.nextInt(generator)));
if(!(x.mod(biGenerator).equals(BigInteger.ZERO)||y.mod(biGenerator).equals(BigInteger.ZERO))){
BigInteger res = x.multiply(y).mod(biGenerator);
BigInteger lres = arithmetics.mul(arithmetics.getElementFactory().createFrom(x), arithmetics.getElementFactory().createFrom(y));
Assert.assertEquals(res.compareTo(lres),0);
}
}
}
@Test
public void testInverse(){
for(int i=0;i<times;i++){
BigInteger x = new BigInteger(Integer.toString(random.nextInt(generator)));
if(!(x.mod(biGenerator).equals(BigInteger.ZERO))){
BigInteger res = x.mod(biGenerator).modInverse(biGenerator);
BigInteger lres = arithmetics.inv(arithmetics.getElementFactory().createFrom(x));
Assert.assertEquals(res.compareTo(lres),0);
}
}
}
@Test
public void testComplement(){
for(int i=0;i<times;i++){
BigInteger x = new BigInteger(Integer.toString(random.nextInt(generator)));
BigInteger res = x.negate().mod(biGenerator);
BigInteger lres = arithmetics.complement(arithmetics.getElementFactory().createFrom(x));
Assert.assertEquals(res.compareTo(lres),0);
}
}
@Test(expected = MultiplicativeGroupException.class)
public void testMulMultiplicativeException(){
BigInteger x = BigInteger.ZERO;
arithmetics.mul(arithmetics.getElementFactory().createFrom(x), arithmetics.getElementFactory().createFrom(x));
}
@Test(expected = MultiplicativeGroupException.class)
public void testInvMultiplicativeException(){
BigInteger x = BigInteger.ZERO;
arithmetics.inv(arithmetics.getElementFactory().createFrom(x));
}
}
| 38.773109 | 160 | 0.669484 |
2e16abcaaa276e4b9d31b23d2d388442976d0788 | 1,798 | package com.mastercard.fld.api.manage;
import java.io.IOException;
import com.mastercard.fld.api.fld.ApiCallback;
import com.mastercard.fld.api.fld.ApiException;
import com.mastercard.fld.api.fld.api.ConfirmedFraudManagementApi;
import com.mastercard.fld.api.fld.model.FraudDeleteAndConfirm;
import com.mastercard.fld.api.fld.model.FraudState;
import com.mastercard.fld.api.fld.model.SafeFraudProvider;
import com.mastercard.fld.utility.LoggerUtil;
import com.mastercard.fld.utility.RequestHelper;
import okhttp3.Call;
import okhttp3.Response;
public class DeleteFraud {
private RequestHelper helper = new RequestHelper();
public static void main(String[] args) {
DeleteFraud call = new DeleteFraud();
call.deleteFraud(call.createRequest());
}
public Response deleteFraud(FraudDeleteAndConfirm request) {
ApiCallback callback = helper.getCallback();
Response response = null;
helper.initiateNonEncryptClient();
ConfirmedFraudManagementApi fraudApi = new ConfirmedFraudManagementApi(helper.getClient());
try {
Call call = fraudApi.fraudStateCall(request, callback);
response = helper.apiCall(call);
LoggerUtil.logResponse(fraudApi.getApiClient().getBasePath() + "/fraud-states", "put", response);
} catch (ApiException | IOException exception) {
return null;
}
return response;
}
public FraudDeleteAndConfirm createRequest() {
FraudDeleteAndConfirm request = new FraudDeleteAndConfirm();
request.setTimestamp("2021-07-04T20:34:37-06:00");
request.setAuditControlNumber("292328194169030");
request.setRefId("aab34943-eabd-42y6-87wd-69c19792bdd6");
request.setIcaNumber("3043");
request.setProviderId(SafeFraudProvider.NUMBER_10);
request.setOperationType(FraudState.FDD);
request.setMemo("Request Description");
return request;
}
}
| 33.924528 | 100 | 0.784205 |
d6321b53cfe1fadd096aaef68776c06b34946019 | 27,895 | /*
*
* Copyright 2018 Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package io.github.robwin.swagger.test;
import io.swagger.models.ArrayModel;
import io.swagger.models.Info;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.RefModel;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.CookieParameter;
import io.swagger.models.parameters.FormParameter;
import io.swagger.models.parameters.HeaderParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.parameters.PathParameter;
import io.swagger.models.parameters.QueryParameter;
import io.swagger.models.parameters.RefParameter;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.assertj.core.api.SoftAssertions;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by raceconditions on 3/17/16.
*/
class ConsumerDrivenValidator extends AbstractContractValidator {
private SoftAssertions softAssertions;
private SwaggerAssertionConfig assertionConfig;
private Swagger actual;
private SchemaObjectResolver schemaObjectResolver; // provide means to fall back from local to global properties
ConsumerDrivenValidator(Swagger actual, SwaggerAssertionConfig assertionConfig) {
this.actual = actual;
this.assertionConfig = assertionConfig;
softAssertions = new SoftAssertions();
}
@Override
public void validateSwagger(Swagger expected, SchemaObjectResolver schemaObjectResolver) {
this.schemaObjectResolver = schemaObjectResolver;
validateInfo(actual.getInfo(), expected.getInfo());
// Check Paths
if (isAssertionEnabled(SwaggerAssertionType.PATHS)) {
final Set<String> filter = assertionConfig.getPathsToIgnoreInExpected();
final Map<String, Path> expectedPaths = findExpectedPaths(expected, assertionConfig);
final Map<String, Path> actualPaths = getPathsIncludingBasePath(actual);
validatePaths(actualPaths, removeAllFromMap(expectedPaths, filter));
}
// Check Definitions
if (isAssertionEnabled(SwaggerAssertionType.DEFINITIONS)) {
final Set<String> filter = assertionConfig.getDefinitionsToIgnoreInExpected();
validateDefinitions(actual.getDefinitions(), removeAllFromMap(expected.getDefinitions(), filter));
}
softAssertions.assertAll();
}
private void validateInfo(Info actualInfo, Info expectedInfo) {
// Version. OFF by default.
if (isAssertionEnabled(SwaggerAssertionType.VERSION)) {
softAssertions.assertThat(actualInfo.getVersion()).as("Checking Version").isEqualTo(expectedInfo.getVersion());
}
// Everything (but potentially brittle, therefore OFF by default)
if (isAssertionEnabled(SwaggerAssertionType.INFO)) {
softAssertions.assertThat(actualInfo).as("Checking Info").isEqualToComparingFieldByField(expectedInfo);
}
}
private void validatePaths(Map<String, Path> actualPaths, Map<String, Path> expectedPaths) {
if (MapUtils.isNotEmpty(expectedPaths)) {
softAssertions.assertThat(actualPaths).as("Checking Paths").isNotEmpty();
if (MapUtils.isNotEmpty(actualPaths)) {
softAssertions.assertThat(actualPaths.keySet()).as("Checking Paths").containsAll(expectedPaths.keySet());
for (Map.Entry<String, Path> actualPathEntry : actualPaths.entrySet()) {
Path expectedPath = expectedPaths.get(actualPathEntry.getKey());
Path actualPath = actualPathEntry.getValue();
String pathName = actualPathEntry.getKey();
validatePath(pathName, actualPath, expectedPath);
}
}
} else {
softAssertions.assertThat(actualPaths).as("Checking Paths").isNullOrEmpty();
}
}
private void validateDefinitions(Map<String, Model> actualDefinitions, Map<String, Model> expectedDefinitions) {
if (MapUtils.isNotEmpty(expectedDefinitions)) {
softAssertions.assertThat(actualDefinitions).as("Checking Definitions").isNotEmpty();
if (MapUtils.isNotEmpty(actualDefinitions)) {
softAssertions.assertThat(actualDefinitions.keySet()).as("Checking Definitions").containsAll(expectedDefinitions.keySet());
for (Map.Entry<String, Model> expectedDefinitionEntry : expectedDefinitions.entrySet()) {
Model expectedDefinition = expectedDefinitionEntry.getValue();
Model actualDefinition = actualDefinitions.get(expectedDefinitionEntry.getKey());
String definitionName = expectedDefinitionEntry.getKey();
validateDefinition(definitionName, actualDefinition, expectedDefinition);
}
}
}
}
private void validatePath(String pathName, Path actualPath, Path expectedPath) {
if (expectedPath != null) {
softAssertions.assertThat(actualPath.getOperations().size()).as("Checking number of operations of path '%s'", pathName).isGreaterThanOrEqualTo(expectedPath.getOperations().size());
validateOperation(actualPath.getGet(), expectedPath.getGet(), pathName, "GET");
validateOperation(actualPath.getDelete(), expectedPath.getDelete(), pathName, "DELETE");
validateOperation(actualPath.getPost(), expectedPath.getPost(), pathName, "POST");
validateOperation(actualPath.getPut(), expectedPath.getPut(), pathName, "PUT");
validateOperation(actualPath.getPatch(), expectedPath.getPatch(), pathName, "PATCH");
validateOperation(actualPath.getOptions(), expectedPath.getOptions(), pathName, "OPTIONS");
}
}
private void validateDefinition(String definitionName, Model actualDefinition, Model expectedDefinition) {
if (expectedDefinition != null && actualDefinition != null) {
validateModel(actualDefinition, expectedDefinition, String.format("Checking model of definition '%s", definitionName));
validateDefinitionProperties(schemaObjectResolver.resolvePropertiesFromActual(actualDefinition),
schemaObjectResolver.resolvePropertiesFromExpected(expectedDefinition),
definitionName);
if (expectedDefinition instanceof ModelImpl) {
validateDefinitionRequiredProperties(((ModelImpl) actualDefinition).getRequired(),
((ModelImpl) expectedDefinition).getRequired(),
definitionName);
}
}
}
private void validateDefinitionRequiredProperties(List<String> actualRequiredProperties, List<String> expectedRequiredProperties, String definitionName) {
if (CollectionUtils.isNotEmpty(expectedRequiredProperties)) {
softAssertions.assertThat(actualRequiredProperties).as("Checking required properties of definition '%s'", definitionName).isNotEmpty();
if (CollectionUtils.isNotEmpty(actualRequiredProperties)) {
final Set<String> filteredExpectedProperties = filterWhitelistedPropertyNames(definitionName, new HashSet<>(expectedRequiredProperties));
softAssertions.assertThat(actualRequiredProperties).as("Checking required properties of definition '%s'", definitionName).hasSameElementsAs(filteredExpectedProperties);
}
} else {
softAssertions.assertThat(actualRequiredProperties).as("Checking required properties of definition '%s'", definitionName).isNullOrEmpty();
}
}
private void validateModel(Model actualDefinition, Model expectedDefinition, String message) {
if (isAssertionEnabled(SwaggerAssertionType.MODELS)) {
if (expectedDefinition instanceof ModelImpl) {
// TODO Validate ModelImpl
softAssertions.assertThat(actualDefinition).as(message).isExactlyInstanceOf(ModelImpl.class);
} else if (expectedDefinition instanceof RefModel) {
// TODO Validate RefModel
softAssertions.assertThat(actualDefinition).as(message).isExactlyInstanceOf(RefModel.class);
} else if (expectedDefinition instanceof ArrayModel) {
ArrayModel arrayModel = (ArrayModel) expectedDefinition;
// TODO Validate ArrayModel
softAssertions.assertThat(actualDefinition).as(message).isExactlyInstanceOf(ArrayModel.class);
} else {
// TODO Validate all model types
softAssertions.assertThat(actualDefinition).isExactlyInstanceOf(expectedDefinition.getClass());
}
}
}
private void validateDefinitionProperties(Map<String, Property> actualDefinitionProperties, Map<String, Property> expectedDefinitionProperties, String definitionName) {
if (MapUtils.isNotEmpty(expectedDefinitionProperties)) {
softAssertions.assertThat(actualDefinitionProperties).as("Checking properties of definition '%s", definitionName).isNotEmpty();
if (MapUtils.isNotEmpty(actualDefinitionProperties)) {
final Set<String> filteredExpectedProperties = filterWhitelistedPropertyNames(definitionName, expectedDefinitionProperties.keySet());
softAssertions.assertThat(actualDefinitionProperties.keySet()).as("Checking properties of definition '%s'", definitionName).containsAll(filteredExpectedProperties);
for (Map.Entry<String, Property> expectedDefinitionPropertyEntry : expectedDefinitionProperties.entrySet()) {
Property expectedDefinitionProperty = expectedDefinitionPropertyEntry.getValue();
Property actualDefinitionProperty = actualDefinitionProperties.get(expectedDefinitionPropertyEntry.getKey());
String propertyName = expectedDefinitionPropertyEntry.getKey();
validateProperty(actualDefinitionProperty, expectedDefinitionProperty, String.format("Checking property '%s' of definition '%s'", propertyName, definitionName));
}
}
} else {
softAssertions.assertThat(actualDefinitionProperties).as("Checking properties of definition '%s", definitionName).isNullOrEmpty();
}
}
private void validateProperty(Property actualProperty, Property expectedProperty, String message) {
// TODO Validate Property schema
if (expectedProperty != null && isAssertionEnabled(SwaggerAssertionType.PROPERTIES)) {
if (expectedProperty instanceof RefProperty) {
if (isAssertionEnabled(SwaggerAssertionType.REF_PROPERTIES)) {
RefProperty refProperty = (RefProperty) expectedProperty;
softAssertions.assertThat(actualProperty).as(message).isExactlyInstanceOf(RefProperty.class);
// TODO Validate RefProperty
}
} else if (expectedProperty instanceof ArrayProperty) {
if (isAssertionEnabled(SwaggerAssertionType.ARRAY_PROPERTIES)) {
ArrayProperty arrayProperty = (ArrayProperty) expectedProperty;
softAssertions.assertThat(actualProperty).as(message).isExactlyInstanceOf(ArrayProperty.class);
// TODO Validate ArrayProperty
}
} else if (expectedProperty instanceof StringProperty) {
if (isAssertionEnabled(SwaggerAssertionType.STRING_PROPERTIES)) {
StringProperty expectedStringProperty = (StringProperty) expectedProperty;
softAssertions.assertThat(actualProperty).as(message).isExactlyInstanceOf(StringProperty.class);
// TODO Validate StringProperty
if (actualProperty instanceof StringProperty) {
StringProperty actualStringProperty = (StringProperty) expectedProperty;
List<String> expectedEnums = expectedStringProperty.getEnum();
if (CollectionUtils.isNotEmpty(expectedEnums)) {
softAssertions.assertThat(actualStringProperty.getEnum()).hasSameElementsAs(expectedEnums);
} else {
softAssertions.assertThat(actualStringProperty.getEnum()).isNullOrEmpty();
}
}
}
} else {
// TODO Validate all other properties
softAssertions.assertThat(actualProperty).as(message).isExactlyInstanceOf(expectedProperty.getClass());
}
}
}
private void validateOperation(Operation actualOperation, Operation expectedOperation, String path, String httpMethod) {
String message = String.format("Checking '%s' operation of path '%s'", httpMethod, path);
if (expectedOperation != null) {
if (actualOperation != null) {
softAssertions.assertThat(actualOperation).as(message).isNotNull();
//Validate consumes
validateList(schemaObjectResolver.getActualConsumes(actualOperation),
schemaObjectResolver.getExpectedConsumes(expectedOperation),
String.format("Checking '%s' of '%s' operation of path '%s'", "consumes", httpMethod, path));
//Validate produces
validateList(schemaObjectResolver.getActualProduces(actualOperation),
schemaObjectResolver.getExpectedProduces(expectedOperation),
String.format("Checking '%s' of '%s' operation of path '%s'", "produces", httpMethod, path));
//Validate parameters
validateParameters(actualOperation.getParameters(), expectedOperation.getParameters(), httpMethod, path);
//Validate responses
validateResponses(actualOperation.getResponses(), expectedOperation.getResponses(), httpMethod, path);
}
}
}
private void validateParameters(List<Parameter> actualOperationParameters, List<Parameter> expectedOperationParameters, String httpMethod, String path) {
String message = String.format("Checking parameters of '%s' operation of path '%s'.", httpMethod, path);
Map<String, Parameter> actualParametersMap = new HashMap<>();
for (final Parameter parameter : actualOperationParameters) {
actualParametersMap.put(parameterUniqueKey(parameter), parameter);
}
// All expectedParameters must be there and must match.
for (final Parameter expectedParameter : expectedOperationParameters) {
final String parameterName = expectedParameter.getName();
Parameter actualParameter = actualParametersMap.remove(parameterUniqueKey(expectedParameter));
String actualParameterNotNullMessage = String.format("%s Expected parameter with name='%s' and in='%s' is missing", message, expectedParameter.getName(), expectedParameter.getIn());
softAssertions.assertThat(actualParameter).as(actualParameterNotNullMessage).isNotNull();
validateParameter(actualParameter, expectedParameter, parameterName, httpMethod, path);
}
// If there are any extra parameters, these are OK, as long as they are optional.
for (final Parameter extraParameter : actualParametersMap.values()) {
String extraParameterNotOptionalMessage = String.format("%s Unexpected parameter with name='%s' and in='%s' is missing", message, extraParameter.getName(), extraParameter.getIn());
softAssertions.assertThat(extraParameter.getRequired()).as(extraParameterNotOptionalMessage).isFalse();
}
}
/**
* Generates a unique key for a parameter.
* <p>
* From <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject" target="_top">OpenAPI Specification</a>
* "A unique parameter is defined by a combination of a name and location."
*
* @param parameter the parameter to generate a unique key for
* @return a unique key based on name and location ({@link Parameter#getIn()})
*/
private String parameterUniqueKey(Parameter parameter) {
return parameter.getName() + parameter.getIn();
}
private void validateParameter(Parameter actualParameter, Parameter expectedParameter, String parameterName, String httpMethod, String path) {
if (expectedParameter != null) {
String message = String.format("Checking parameter '%s' of '%s' operation of path '%s'", parameterName, httpMethod, path);
softAssertions.assertThat(actualParameter).as(message).isExactlyInstanceOf(expectedParameter.getClass());
if (expectedParameter instanceof BodyParameter && actualParameter instanceof BodyParameter) {
BodyParameter actualBodyParameter = (BodyParameter) expectedParameter;
BodyParameter expectedBodyParameter = (BodyParameter) expectedParameter;
validateModel(actualBodyParameter.getSchema(), expectedBodyParameter.getSchema(), String.format("Checking model of parameter '%s' of '%s' operation of path '%s'", parameterName, httpMethod, path));
} else if (expectedParameter instanceof PathParameter && actualParameter instanceof PathParameter) {
PathParameter actualPathParameter = (PathParameter) actualParameter;
PathParameter expectedPathParameter = (PathParameter) expectedParameter;
softAssertions.assertThat(actualPathParameter.getType()).as(message).isEqualTo(expectedPathParameter.getType());
List<String> expectedEnums = expectedPathParameter.getEnum();
if (CollectionUtils.isNotEmpty(expectedEnums)) {
softAssertions.assertThat(actualPathParameter.getEnum()).as(message).hasSameElementsAs(expectedEnums);
} else {
softAssertions.assertThat(actualPathParameter.getEnum()).as(message).isNullOrEmpty();
}
} else if (expectedParameter instanceof QueryParameter && actualParameter instanceof QueryParameter) {
QueryParameter actualQueryParameter = (QueryParameter) actualParameter;
QueryParameter expectedQueryParameter = (QueryParameter) expectedParameter;
softAssertions.assertThat(actualQueryParameter.getType()).as(message).isEqualTo(expectedQueryParameter.getType());
List<String> expectedEnums = expectedQueryParameter.getEnum();
if (CollectionUtils.isNotEmpty(expectedEnums)) {
softAssertions.assertThat(actualQueryParameter.getEnum()).as(message).hasSameElementsAs(expectedEnums);
} else {
softAssertions.assertThat(actualQueryParameter.getEnum()).as(message).isNullOrEmpty();
}
} else if (expectedParameter instanceof HeaderParameter && actualParameter instanceof HeaderParameter) {
HeaderParameter actualHeaderParameter = (HeaderParameter) actualParameter;
HeaderParameter expectedHeaderParameter = (HeaderParameter) expectedParameter;
softAssertions.assertThat(actualHeaderParameter.getType()).as(message).isEqualTo(expectedHeaderParameter.getType());
List<String> expectedEnums = expectedHeaderParameter.getEnum();
if (CollectionUtils.isNotEmpty(expectedEnums)) {
softAssertions.assertThat(actualHeaderParameter.getEnum()).as(message).hasSameElementsAs(expectedEnums);
} else {
softAssertions.assertThat(actualHeaderParameter.getEnum()).as(message).isNullOrEmpty();
}
} else if (expectedParameter instanceof FormParameter && actualParameter instanceof FormParameter) {
FormParameter actualFormParameter = (FormParameter) actualParameter;
FormParameter expectedFormParameter = (FormParameter) expectedParameter;
softAssertions.assertThat(actualFormParameter.getType()).as(message).isEqualTo(expectedFormParameter.getType());
List<String> expectedEnums = expectedFormParameter.getEnum();
if (CollectionUtils.isNotEmpty(expectedEnums)) {
softAssertions.assertThat(actualFormParameter.getEnum()).as(message).hasSameElementsAs(expectedEnums);
} else {
softAssertions.assertThat(actualFormParameter.getEnum()).as(message).isNullOrEmpty();
}
} else if (expectedParameter instanceof CookieParameter && actualParameter instanceof CookieParameter) {
CookieParameter actualCookieParameter = (CookieParameter) actualParameter;
CookieParameter expectedCookieParameter = (CookieParameter) expectedParameter;
softAssertions.assertThat(actualCookieParameter.getType()).as(message).isEqualTo(expectedCookieParameter.getType());
List<String> expectedEnums = expectedCookieParameter.getEnum();
if (CollectionUtils.isNotEmpty(expectedEnums)) {
softAssertions.assertThat(actualCookieParameter.getEnum()).as(message).hasSameElementsAs(expectedEnums);
} else {
softAssertions.assertThat(actualCookieParameter.getEnum()).as(message).isNullOrEmpty();
}
} else if (expectedParameter instanceof RefParameter && actualParameter instanceof RefParameter) {
RefParameter expectedRefParameter = (RefParameter) expectedParameter;
RefParameter actualRefParameter = (RefParameter) actualParameter;
softAssertions.assertThat(actualRefParameter.getSimpleRef()).as(message).isEqualTo(expectedRefParameter.getSimpleRef());
}
}
}
private void validateResponses(Map<String, Response> actualOperationResponses, Map<String, Response> expectedOperationResponses, String httpMethod, String path) {
String message = String.format("Checking responses of '%s' operation of path '%s'", httpMethod, path);
if (MapUtils.isNotEmpty(expectedOperationResponses)) {
softAssertions.assertThat(actualOperationResponses).as(message).isNotEmpty();
if (MapUtils.isNotEmpty(actualOperationResponses)) {
softAssertions.assertThat(actualOperationResponses.keySet()).as(message).hasSameElementsAs(expectedOperationResponses.keySet());
for (Map.Entry<String, Response> actualResponseEntry : actualOperationResponses.entrySet()) {
Response expectedResponse = expectedOperationResponses.get(actualResponseEntry.getKey());
Response actualResponse = actualResponseEntry.getValue();
String responseName = actualResponseEntry.getKey();
validateResponse(actualResponse, expectedResponse, responseName, httpMethod, path);
}
}
} else {
softAssertions.assertThat(actualOperationResponses).as(message).isNullOrEmpty();
}
}
private void validateResponse(Response actualResponse, Response expectedResponse, String responseName, String httpMethod, String path) {
if (expectedResponse != null) {
validateProperty(actualResponse.getSchema(), expectedResponse.getSchema(), String.format("Checking response schema of response '%s' of '%s' operation of path '%s'", responseName, httpMethod, path));
validateResponseHeaders(actualResponse.getHeaders(), expectedResponse.getHeaders(), responseName, httpMethod, path);
}
}
private void validateResponseHeaders(Map<String, Property> actualResponseHeaders, Map<String, Property> expectedResponseHeaders, String responseName, String httpMethod, String path) {
String message = String.format("Checking response headers of response '%s' of '%s' operation of path '%s'", responseName, httpMethod, path);
if (MapUtils.isNotEmpty(expectedResponseHeaders)) {
softAssertions.assertThat(actualResponseHeaders).as(message).isNotEmpty();
if (MapUtils.isNotEmpty(actualResponseHeaders)) {
softAssertions.assertThat(actualResponseHeaders.keySet()).as(message).containsAll(expectedResponseHeaders.keySet());
for (Map.Entry<String, Property> expectedResponseHeaderEntry : expectedResponseHeaders.entrySet()) {
Property expectedResponseHeader = expectedResponseHeaderEntry.getValue();
Property actualResponseHeader = actualResponseHeaders.get(expectedResponseHeaderEntry.getKey());
String responseHeaderName = expectedResponseHeaderEntry.getKey();
validateProperty(actualResponseHeader, expectedResponseHeader, String.format("Checking response header '%s' of response '%s' of '%s' operation of path '%s'", responseHeaderName, responseName, httpMethod, path));
}
}
} else {
softAssertions.assertThat(actualResponseHeaders).as(message).isNullOrEmpty();
}
}
private void validateList(List<String> actualList, List<String> expectedList, String message) {
if (CollectionUtils.isNotEmpty(expectedList)) {
softAssertions.assertThat(actualList).as(message).isNotEmpty();
if (CollectionUtils.isNotEmpty(actualList)) {
softAssertions.assertThat(actualList).as(message).containsAll(expectedList);
}
} else {
softAssertions.assertThat(actualList).as(message).isNullOrEmpty();
}
}
private boolean isAssertionEnabled(final SwaggerAssertionType assertionType) {
return assertionConfig.swaggerAssertionEnabled(assertionType);
}
private Set<String> filterWhitelistedPropertyNames(String definitionName, Set<String> expectedPropertyNames) {
Set<String> result = new HashSet<>(expectedPropertyNames.size());
final Set<String> ignoredPropertyNames = assertionConfig.getPropertiesToIgnoreInExpected();
for (String property : expectedPropertyNames) {
if (!ignoredPropertyNames.contains(definitionName + '.' + property)) {
result.add(property);
}
}
return result;
}
private <K, V> Map<K, V> removeAllFromMap(Map<K, V> map, Set<K> keysToExclude) {
final LinkedHashMap<K, V> result = new LinkedHashMap<>(map);
result.keySet().removeAll(keysToExclude);
return result;
}
}
| 62.126949 | 231 | 0.687865 |
2b8de85d94701f97249c5467b0a4e32585a7642a | 30,771 | /**
* Autogenerated by Thrift Compiler (0.13.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.suboat.contrib.rpc.wallet;
@SuppressWarnings({ "cast", "rawtypes", "serial", "unchecked", "unused" })
/**
* 特定参数: 解冻一笔流水 有效条件: 必填项必填
*/
public class ArgUnfreeze implements org.apache.thrift.TBase<ArgUnfreeze, ArgUnfreeze._Fields>, java.io.Serializable,
Cloneable, Comparable<ArgUnfreeze> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(
"ArgUnfreeze");
private static final org.apache.thrift.protocol.TField ACCESSION_FIELD_DESC = new org.apache.thrift.protocol.TField(
"accession", org.apache.thrift.protocol.TType.STRING, (short) 1);
private static final org.apache.thrift.protocol.TField IS_SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(
"isSuccess", org.apache.thrift.protocol.TType.BOOL, (short) 2);
private static final org.apache.thrift.protocol.TField COMMENT_FIELD_DESC = new org.apache.thrift.protocol.TField(
"comment", org.apache.thrift.protocol.TType.STRING, (short) 3);
private static final org.apache.thrift.protocol.TField TRIGGER_FIELD_DESC = new org.apache.thrift.protocol.TField(
"trigger", org.apache.thrift.protocol.TType.STRING, (short) 4);
private static final org.apache.thrift.protocol.TField REL_UID_FIELD_DESC = new org.apache.thrift.protocol.TField(
"relUid", org.apache.thrift.protocol.TType.STRING, (short) 5);
private static final org.apache.thrift.protocol.TField TX_ID_FIELD_DESC = new org.apache.thrift.protocol.TField(
"txId", org.apache.thrift.protocol.TType.STRING, (short) 6);
private static final org.apache.thrift.protocol.TField TASK_ID_FIELD_DESC = new org.apache.thrift.protocol.TField(
"taskId", org.apache.thrift.protocol.TType.STRING, (short) 7);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new ArgUnfreezeStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new ArgUnfreezeTupleSchemeFactory();
public @org.apache.thrift.annotation.Nullable java.lang.String accession; // required
public boolean isSuccess; // required
public @org.apache.thrift.annotation.Nullable java.lang.String comment; // optional
public @org.apache.thrift.annotation.Nullable java.lang.String trigger; // optional
public @org.apache.thrift.annotation.Nullable java.lang.String relUid; // optional
public @org.apache.thrift.annotation.Nullable java.lang.String txId; // optional
public @org.apache.thrift.annotation.Nullable java.lang.String taskId; // optional
/**
* The set of fields this struct contains, along with convenience methods for finding
* and manipulating them.
*/
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
ACCESSION((short) 1, "accession"), IS_SUCCESS((short) 2, "isSuccess"), COMMENT((short) 3, "comment"), TRIGGER(
(short) 4,
"trigger"), REL_UID((short) 5, "relUid"), TX_ID((short) 6, "txId"), TASK_ID((short) 7, "taskId");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch (fieldId) {
case 1: // ACCESSION
return ACCESSION;
case 2: // IS_SUCCESS
return IS_SUCCESS;
case 3: // COMMENT
return COMMENT;
case 4: // TRIGGER
return TRIGGER;
case 5: // REL_UID
return REL_UID;
case 6: // TX_ID
return TX_ID;
case 7: // TASK_ID
return TASK_ID;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception if it is
* not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null)
throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __ISSUCCESS_ISSET_ID = 0;
private byte __isset_bitfield = 0;
private static final _Fields optionals[] = { _Fields.COMMENT, _Fields.TRIGGER, _Fields.REL_UID, _Fields.TX_ID,
_Fields.TASK_ID };
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(
_Fields.class);
tmpMap.put(_Fields.ACCESSION,
new org.apache.thrift.meta_data.FieldMetaData("accession",
org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.IS_SUCCESS,
new org.apache.thrift.meta_data.FieldMetaData("isSuccess",
org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
tmpMap.put(_Fields.COMMENT,
new org.apache.thrift.meta_data.FieldMetaData("comment",
org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.TRIGGER,
new org.apache.thrift.meta_data.FieldMetaData("trigger",
org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.REL_UID,
new org.apache.thrift.meta_data.FieldMetaData("relUid",
org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.TX_ID,
new org.apache.thrift.meta_data.FieldMetaData("txId", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.TASK_ID,
new org.apache.thrift.meta_data.FieldMetaData("taskId",
org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ArgUnfreeze.class, metaDataMap);
}
public ArgUnfreeze() {
}
public ArgUnfreeze(java.lang.String accession, boolean isSuccess) {
this();
this.accession = accession;
this.isSuccess = isSuccess;
setIsSuccessIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public ArgUnfreeze(ArgUnfreeze other) {
__isset_bitfield = other.__isset_bitfield;
if (other.isSetAccession()) {
this.accession = other.accession;
}
this.isSuccess = other.isSuccess;
if (other.isSetComment()) {
this.comment = other.comment;
}
if (other.isSetTrigger()) {
this.trigger = other.trigger;
}
if (other.isSetRelUid()) {
this.relUid = other.relUid;
}
if (other.isSetTxId()) {
this.txId = other.txId;
}
if (other.isSetTaskId()) {
this.taskId = other.taskId;
}
}
public ArgUnfreeze deepCopy() {
return new ArgUnfreeze(this);
}
@Override
public void clear() {
this.accession = null;
setIsSuccessIsSet(false);
this.isSuccess = false;
this.comment = null;
this.trigger = null;
this.relUid = null;
this.txId = null;
this.taskId = null;
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getAccession() {
return this.accession;
}
public ArgUnfreeze setAccession(@org.apache.thrift.annotation.Nullable java.lang.String accession) {
this.accession = accession;
return this;
}
public void unsetAccession() {
this.accession = null;
}
/**
* Returns true if field accession is set (has been assigned a value) and false
* otherwise
*/
public boolean isSetAccession() {
return this.accession != null;
}
public void setAccessionIsSet(boolean value) {
if (!value) {
this.accession = null;
}
}
public boolean isIsSuccess() {
return this.isSuccess;
}
public ArgUnfreeze setIsSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
setIsSuccessIsSet(true);
return this;
}
public void unsetIsSuccess() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __ISSUCCESS_ISSET_ID);
}
/**
* Returns true if field isSuccess is set (has been assigned a value) and false
* otherwise
*/
public boolean isSetIsSuccess() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __ISSUCCESS_ISSET_ID);
}
public void setIsSuccessIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __ISSUCCESS_ISSET_ID, value);
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getComment() {
return this.comment;
}
public ArgUnfreeze setComment(@org.apache.thrift.annotation.Nullable java.lang.String comment) {
this.comment = comment;
return this;
}
public void unsetComment() {
this.comment = null;
}
/**
* Returns true if field comment is set (has been assigned a value) and false
* otherwise
*/
public boolean isSetComment() {
return this.comment != null;
}
public void setCommentIsSet(boolean value) {
if (!value) {
this.comment = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getTrigger() {
return this.trigger;
}
public ArgUnfreeze setTrigger(@org.apache.thrift.annotation.Nullable java.lang.String trigger) {
this.trigger = trigger;
return this;
}
public void unsetTrigger() {
this.trigger = null;
}
/**
* Returns true if field trigger is set (has been assigned a value) and false
* otherwise
*/
public boolean isSetTrigger() {
return this.trigger != null;
}
public void setTriggerIsSet(boolean value) {
if (!value) {
this.trigger = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getRelUid() {
return this.relUid;
}
public ArgUnfreeze setRelUid(@org.apache.thrift.annotation.Nullable java.lang.String relUid) {
this.relUid = relUid;
return this;
}
public void unsetRelUid() {
this.relUid = null;
}
/**
* Returns true if field relUid is set (has been assigned a value) and false otherwise
*/
public boolean isSetRelUid() {
return this.relUid != null;
}
public void setRelUidIsSet(boolean value) {
if (!value) {
this.relUid = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getTxId() {
return this.txId;
}
public ArgUnfreeze setTxId(@org.apache.thrift.annotation.Nullable java.lang.String txId) {
this.txId = txId;
return this;
}
public void unsetTxId() {
this.txId = null;
}
/**
* Returns true if field txId is set (has been assigned a value) and false otherwise
*/
public boolean isSetTxId() {
return this.txId != null;
}
public void setTxIdIsSet(boolean value) {
if (!value) {
this.txId = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getTaskId() {
return this.taskId;
}
public ArgUnfreeze setTaskId(@org.apache.thrift.annotation.Nullable java.lang.String taskId) {
this.taskId = taskId;
return this;
}
public void unsetTaskId() {
this.taskId = null;
}
/**
* Returns true if field taskId is set (has been assigned a value) and false otherwise
*/
public boolean isSetTaskId() {
return this.taskId != null;
}
public void setTaskIdIsSet(boolean value) {
if (!value) {
this.taskId = null;
}
}
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case ACCESSION:
if (value == null) {
unsetAccession();
}
else {
setAccession((java.lang.String) value);
}
break;
case IS_SUCCESS:
if (value == null) {
unsetIsSuccess();
}
else {
setIsSuccess((java.lang.Boolean) value);
}
break;
case COMMENT:
if (value == null) {
unsetComment();
}
else {
setComment((java.lang.String) value);
}
break;
case TRIGGER:
if (value == null) {
unsetTrigger();
}
else {
setTrigger((java.lang.String) value);
}
break;
case REL_UID:
if (value == null) {
unsetRelUid();
}
else {
setRelUid((java.lang.String) value);
}
break;
case TX_ID:
if (value == null) {
unsetTxId();
}
else {
setTxId((java.lang.String) value);
}
break;
case TASK_ID:
if (value == null) {
unsetTaskId();
}
else {
setTaskId((java.lang.String) value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case ACCESSION:
return getAccession();
case IS_SUCCESS:
return isIsSuccess();
case COMMENT:
return getComment();
case TRIGGER:
return getTrigger();
case REL_UID:
return getRelUid();
case TX_ID:
return getTxId();
case TASK_ID:
return getTaskId();
}
throw new java.lang.IllegalStateException();
}
/**
* Returns true if field corresponding to fieldID is set (has been assigned a value)
* and false otherwise
*/
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case ACCESSION:
return isSetAccession();
case IS_SUCCESS:
return isSetIsSuccess();
case COMMENT:
return isSetComment();
case TRIGGER:
return isSetTrigger();
case REL_UID:
return isSetRelUid();
case TX_ID:
return isSetTxId();
case TASK_ID:
return isSetTaskId();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that == null)
return false;
if (that instanceof ArgUnfreeze)
return this.equals((ArgUnfreeze) that);
return false;
}
public boolean equals(ArgUnfreeze that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_accession = true && this.isSetAccession();
boolean that_present_accession = true && that.isSetAccession();
if (this_present_accession || that_present_accession) {
if (!(this_present_accession && that_present_accession))
return false;
if (!this.accession.equals(that.accession))
return false;
}
boolean this_present_isSuccess = true;
boolean that_present_isSuccess = true;
if (this_present_isSuccess || that_present_isSuccess) {
if (!(this_present_isSuccess && that_present_isSuccess))
return false;
if (this.isSuccess != that.isSuccess)
return false;
}
boolean this_present_comment = true && this.isSetComment();
boolean that_present_comment = true && that.isSetComment();
if (this_present_comment || that_present_comment) {
if (!(this_present_comment && that_present_comment))
return false;
if (!this.comment.equals(that.comment))
return false;
}
boolean this_present_trigger = true && this.isSetTrigger();
boolean that_present_trigger = true && that.isSetTrigger();
if (this_present_trigger || that_present_trigger) {
if (!(this_present_trigger && that_present_trigger))
return false;
if (!this.trigger.equals(that.trigger))
return false;
}
boolean this_present_relUid = true && this.isSetRelUid();
boolean that_present_relUid = true && that.isSetRelUid();
if (this_present_relUid || that_present_relUid) {
if (!(this_present_relUid && that_present_relUid))
return false;
if (!this.relUid.equals(that.relUid))
return false;
}
boolean this_present_txId = true && this.isSetTxId();
boolean that_present_txId = true && that.isSetTxId();
if (this_present_txId || that_present_txId) {
if (!(this_present_txId && that_present_txId))
return false;
if (!this.txId.equals(that.txId))
return false;
}
boolean this_present_taskId = true && this.isSetTaskId();
boolean that_present_taskId = true && that.isSetTaskId();
if (this_present_taskId || that_present_taskId) {
if (!(this_present_taskId && that_present_taskId))
return false;
if (!this.taskId.equals(that.taskId))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetAccession()) ? 131071 : 524287);
if (isSetAccession())
hashCode = hashCode * 8191 + accession.hashCode();
hashCode = hashCode * 8191 + ((isSuccess) ? 131071 : 524287);
hashCode = hashCode * 8191 + ((isSetComment()) ? 131071 : 524287);
if (isSetComment())
hashCode = hashCode * 8191 + comment.hashCode();
hashCode = hashCode * 8191 + ((isSetTrigger()) ? 131071 : 524287);
if (isSetTrigger())
hashCode = hashCode * 8191 + trigger.hashCode();
hashCode = hashCode * 8191 + ((isSetRelUid()) ? 131071 : 524287);
if (isSetRelUid())
hashCode = hashCode * 8191 + relUid.hashCode();
hashCode = hashCode * 8191 + ((isSetTxId()) ? 131071 : 524287);
if (isSetTxId())
hashCode = hashCode * 8191 + txId.hashCode();
hashCode = hashCode * 8191 + ((isSetTaskId()) ? 131071 : 524287);
if (isSetTaskId())
hashCode = hashCode * 8191 + taskId.hashCode();
return hashCode;
}
@Override
public int compareTo(ArgUnfreeze other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.valueOf(isSetAccession()).compareTo(other.isSetAccession());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetAccession()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.accession, other.accession);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetIsSuccess()).compareTo(other.isSetIsSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetIsSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.isSuccess, other.isSuccess);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetComment()).compareTo(other.isSetComment());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetComment()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.comment, other.comment);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetTrigger()).compareTo(other.isSetTrigger());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTrigger()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.trigger, other.trigger);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetRelUid()).compareTo(other.isSetRelUid());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetRelUid()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.relUid, other.relUid);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetTxId()).compareTo(other.isSetTxId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTxId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.txId, other.txId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetTaskId()).compareTo(other.isSetTaskId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTaskId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.taskId, other.taskId);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("ArgUnfreeze(");
boolean first = true;
sb.append("accession:");
if (this.accession == null) {
sb.append("null");
}
else {
sb.append(this.accession);
}
first = false;
if (!first)
sb.append(", ");
sb.append("isSuccess:");
sb.append(this.isSuccess);
first = false;
if (isSetComment()) {
if (!first)
sb.append(", ");
sb.append("comment:");
if (this.comment == null) {
sb.append("null");
}
else {
sb.append(this.comment);
}
first = false;
}
if (isSetTrigger()) {
if (!first)
sb.append(", ");
sb.append("trigger:");
if (this.trigger == null) {
sb.append("null");
}
else {
sb.append(this.trigger);
}
first = false;
}
if (isSetRelUid()) {
if (!first)
sb.append(", ");
sb.append("relUid:");
if (this.relUid == null) {
sb.append("null");
}
else {
sb.append(this.relUid);
}
first = false;
}
if (isSetTxId()) {
if (!first)
sb.append(", ");
sb.append("txId:");
if (this.txId == null) {
sb.append("null");
}
else {
sb.append(this.txId);
}
first = false;
}
if (isSetTaskId()) {
if (!first)
sb.append(", ");
sb.append("taskId:");
if (this.taskId == null) {
sb.append("null");
}
else {
sb.append(this.taskId);
}
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(out)));
}
catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is
// wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(in)));
}
catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class ArgUnfreezeStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public ArgUnfreezeStandardScheme getScheme() {
return new ArgUnfreezeStandardScheme();
}
}
private static class ArgUnfreezeStandardScheme extends org.apache.thrift.scheme.StandardScheme<ArgUnfreeze> {
public void read(org.apache.thrift.protocol.TProtocol iprot, ArgUnfreeze struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true) {
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // ACCESSION
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.accession = iprot.readString();
struct.setAccessionIsSet(true);
}
else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // IS_SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.isSuccess = iprot.readBool();
struct.setIsSuccessIsSet(true);
}
else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // COMMENT
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.comment = iprot.readString();
struct.setCommentIsSet(true);
}
else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // TRIGGER
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.trigger = iprot.readString();
struct.setTriggerIsSet(true);
}
else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 5: // REL_UID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.relUid = iprot.readString();
struct.setRelUidIsSet(true);
}
else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 6: // TX_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.txId = iprot.readString();
struct.setTxIdIsSet(true);
}
else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 7: // TASK_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.taskId = iprot.readString();
struct.setTaskIdIsSet(true);
}
else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the
// validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, ArgUnfreeze struct)
throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.accession != null) {
oprot.writeFieldBegin(ACCESSION_FIELD_DESC);
oprot.writeString(struct.accession);
oprot.writeFieldEnd();
}
oprot.writeFieldBegin(IS_SUCCESS_FIELD_DESC);
oprot.writeBool(struct.isSuccess);
oprot.writeFieldEnd();
if (struct.comment != null) {
if (struct.isSetComment()) {
oprot.writeFieldBegin(COMMENT_FIELD_DESC);
oprot.writeString(struct.comment);
oprot.writeFieldEnd();
}
}
if (struct.trigger != null) {
if (struct.isSetTrigger()) {
oprot.writeFieldBegin(TRIGGER_FIELD_DESC);
oprot.writeString(struct.trigger);
oprot.writeFieldEnd();
}
}
if (struct.relUid != null) {
if (struct.isSetRelUid()) {
oprot.writeFieldBegin(REL_UID_FIELD_DESC);
oprot.writeString(struct.relUid);
oprot.writeFieldEnd();
}
}
if (struct.txId != null) {
if (struct.isSetTxId()) {
oprot.writeFieldBegin(TX_ID_FIELD_DESC);
oprot.writeString(struct.txId);
oprot.writeFieldEnd();
}
}
if (struct.taskId != null) {
if (struct.isSetTaskId()) {
oprot.writeFieldBegin(TASK_ID_FIELD_DESC);
oprot.writeString(struct.taskId);
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class ArgUnfreezeTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public ArgUnfreezeTupleScheme getScheme() {
return new ArgUnfreezeTupleScheme();
}
}
private static class ArgUnfreezeTupleScheme extends org.apache.thrift.scheme.TupleScheme<ArgUnfreeze> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, ArgUnfreeze struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetAccession()) {
optionals.set(0);
}
if (struct.isSetIsSuccess()) {
optionals.set(1);
}
if (struct.isSetComment()) {
optionals.set(2);
}
if (struct.isSetTrigger()) {
optionals.set(3);
}
if (struct.isSetRelUid()) {
optionals.set(4);
}
if (struct.isSetTxId()) {
optionals.set(5);
}
if (struct.isSetTaskId()) {
optionals.set(6);
}
oprot.writeBitSet(optionals, 7);
if (struct.isSetAccession()) {
oprot.writeString(struct.accession);
}
if (struct.isSetIsSuccess()) {
oprot.writeBool(struct.isSuccess);
}
if (struct.isSetComment()) {
oprot.writeString(struct.comment);
}
if (struct.isSetTrigger()) {
oprot.writeString(struct.trigger);
}
if (struct.isSetRelUid()) {
oprot.writeString(struct.relUid);
}
if (struct.isSetTxId()) {
oprot.writeString(struct.txId);
}
if (struct.isSetTaskId()) {
oprot.writeString(struct.taskId);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, ArgUnfreeze struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(7);
if (incoming.get(0)) {
struct.accession = iprot.readString();
struct.setAccessionIsSet(true);
}
if (incoming.get(1)) {
struct.isSuccess = iprot.readBool();
struct.setIsSuccessIsSet(true);
}
if (incoming.get(2)) {
struct.comment = iprot.readString();
struct.setCommentIsSet(true);
}
if (incoming.get(3)) {
struct.trigger = iprot.readString();
struct.setTriggerIsSet(true);
}
if (incoming.get(4)) {
struct.relUid = iprot.readString();
struct.setRelUidIsSet(true);
}
if (incoming.get(5)) {
struct.txId = iprot.readString();
struct.setTxIdIsSet(true);
}
if (incoming.get(6)) {
struct.taskId = iprot.readString();
struct.setTaskIdIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY
: TUPLE_SCHEME_FACTORY).getScheme();
}
}
| 27.49866 | 151 | 0.693835 |
e780ee78c50ce4c317cbbfb8965cccaecd0cec68 | 4,061 | package com.powerdata.openpa.impl;
/*
* Copyright (c) 2016, PowerData Corporation, Incremental Systems Corporation
* All rights reserved.
* Licensed under the BSD-3 Clause License.
* See full license at https://powerdata.github.io/openpa/LICENSE.md
*/
import com.powerdata.openpa.Bus;
import com.powerdata.openpa.BusList;
import com.powerdata.openpa.ColumnMeta;
import com.powerdata.openpa.PAModelException;
import com.powerdata.openpa.TwoTermDev;
import com.powerdata.openpa.TwoTermDevListIfc;
public abstract class TwoTermDevListI<T extends TwoTermDev> extends
InServiceListI<T> implements TwoTermDevListIfc<T>
{
BusList _buses;
IntData _fbus, _tbus;
FloatData _fp, _fq, _tp, _tq;
protected TwoTermDevListI(){super();}
protected TwoTermDevListI(PAModelI model, int[] keys, TwoTermDevEnum le) throws PAModelException
{
super(model, keys, le);
_buses = model.getBuses();
setFields(le);
}
protected TwoTermDevListI(PAModelI model, int size, TwoTermDevEnum le) throws PAModelException
{
super(model, size, le);
_buses = model.getBuses();
setFields(le);
}
private void setFields(TwoTermDevEnum le)
{
_fbus = new IntData(le.fbus());
_tbus = new IntData(le.tbus());
_fp = new FloatData(le.fp());
_fq = new FloatData(le.fq());
_tp = new FloatData(le.tp());
_tq = new FloatData(le.tq());
}
@Override
public Bus getFromBus(int ndx) throws PAModelException
{
return _buses.get(_fbus.get(ndx));
}
@Override
public void setFromBus(int ndx, Bus b) throws PAModelException
{
_fbus.set(ndx, b.getIndex());
}
@Override
public Bus[] getFromBus() throws PAModelException
{
return _buses.toArray(_fbus.get());
}
@Override
public void setFromBus(Bus[] b) throws PAModelException
{
_fbus.set(_buses.getIndexes(b));
}
@Override
public Bus getToBus(int ndx) throws PAModelException
{
return _buses.get(_tbus.get(ndx));
}
@Override
public void setToBus(int ndx, Bus b) throws PAModelException
{
_tbus.set(ndx, b.getIndex());
}
@Override
public Bus[] getToBus() throws PAModelException
{
return _buses.toArray(_tbus.get());
}
@Override
public void setToBus(Bus[] b) throws PAModelException
{
_tbus.set(_buses.getIndexes(b));
}
@Override
public float getFromP(int ndx) throws PAModelException
{
return _fp.get(ndx);
}
@Override
public void setFromP(int ndx, float mw) throws PAModelException
{
_fp.set(ndx, mw);
}
@Override
public float[] getFromP() throws PAModelException
{
return _fp.get();
}
@Override
public void setFromP(float[] mw) throws PAModelException
{
_fp.set(mw);
}
@Override
public float getFromQ(int ndx) throws PAModelException
{
return _fq.get(ndx);
}
@Override
public void setFromQ(int ndx, float mvar) throws PAModelException
{
_fq.set(ndx, mvar);
}
@Override
public float[] getFromQ() throws PAModelException
{
return _fq.get();
}
@Override
public void setFromQ(float[] mvar) throws PAModelException
{
_fq.set(mvar);
}
@Override
public float getToP(int ndx) throws PAModelException
{
return _tp.get(ndx);
}
@Override
public void setToP(int ndx, float mw) throws PAModelException
{
_tp.set(ndx, mw);
}
@Override
public float[] getToP() throws PAModelException
{
return _tp.get();
}
@Override
public void setToP(float[] mw) throws PAModelException
{
_tp.set(mw);
}
@Override
public float getToQ(int ndx) throws PAModelException
{
return _tq.get(ndx);
}
@Override
public void setToQ(int ndx, float mvar) throws PAModelException
{
_tq.set(ndx, mvar);
}
@Override
public float[] getToQ() throws PAModelException
{
return _tq.get();
}
@Override
public void setToQ(float[] mvar) throws PAModelException
{
_tq.set(mvar);
}
interface TwoTermDevEnum extends InServiceEnum
{
ColumnMeta fbus();
ColumnMeta tbus();
ColumnMeta fp();
ColumnMeta fq();
ColumnMeta tp();
ColumnMeta tq();
}
public int[] getFromBusIndexes() throws PAModelException {return _fbus.get();}
public int[] getToBusIndexes() throws PAModelException {return _tbus.get();}
}
| 21.041451 | 97 | 0.719773 |
ea61673291a7fc499f5075171b903856ac163341 | 5,707 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 University of Manchester
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package uk.ac.manchester.cs.mekon.network;
import java.util.*;
import uk.ac.manchester.cs.mekon.model.*;
import uk.ac.manchester.cs.mekon_util.*;
/**
* @author Colin Puleston
*/
class StructureSubsumptionTester {
private LinksTester linksTester = new LinksTester();
private NumbersTester numbersTester = new NumbersTester();
private StringsTester stringsTester = new StringsTester();
private KSetMap<NNode, NNode> testing = new KSetMap<NNode, NNode>();
private KSetMap<NNode, NNode> subsumptions = new KSetMap<NNode, NNode>();
private abstract class FeaturesTester<V, F extends NFeature<V>> {
boolean subsumptions(NNode node1, NNode node2) {
List<F> features2 = getValueFeatures(node2);
for (F feature1 : getValueFeatures(node1)) {
if (!anySubsumptions(feature1, features2)) {
return false;
}
}
return true;
}
boolean valueSubsumptions(F feature1, F feature2) {
List<V> values2 = feature2.getValues();
for (V value1 : feature1.getValues()) {
if (!anyValueSubsumptions(value1, values2)) {
return false;
}
}
return true;
}
boolean anyValueSubsumptions(F feature1, F feature2) {
List<V> values2 = feature2.getValues();
for (V value1 : feature1.getValues()) {
if (anyValueSubsumptions(value1, values2)) {
return true;
}
}
return false;
}
abstract List<F> getFeatures(NNode node);
abstract boolean valueSubsumption(V value1, V value2);
private List<F> getValueFeatures(NNode node) {
List<F> valueFeatures = new ArrayList<F>();
for (F feature : getFeatures(node)) {
if (feature.hasValues()) {
valueFeatures.add(feature);
}
}
return valueFeatures;
}
private boolean anySubsumptions(F feature1, List<F> features2) {
for (F feature2 : features2) {
if (subsumption(feature1, feature2)) {
return true;
}
}
return false;
}
private boolean subsumption(F feature1, F feature2) {
return equalTypes(feature1, feature2)
&& valueSubsumptions(feature1, feature2);
}
private boolean anyValueSubsumptions(V value1, List<V> values2) {
for (V value2 : values2) {
if (valueSubsumption(value1, value2)) {
return true;
}
}
return false;
}
private boolean equalTypes(F feature1, F feature2) {
return feature1.getType().equals(feature2.getType());
}
}
private class LinksTester extends FeaturesTester<NNode, NLink> {
boolean valueSubsumptions(NLink feature1, NLink feature2) {
if (feature1.disjunctionLink() && !feature2.disjunctionLink()) {
return anyValueSubsumptions(feature1, feature2);
}
return super.valueSubsumptions(feature1, feature2);
}
List<NLink> getFeatures(NNode node) {
return node.getLinks();
}
boolean valueSubsumption(NNode value1, NNode value2) {
return StructureSubsumptionTester.this.subsumption(value1, value2);
}
}
private class NumbersTester extends FeaturesTester<INumber, NNumber> {
List<NNumber> getFeatures(NNode node) {
return node.getNumbers();
}
boolean valueSubsumption(INumber value1, INumber value2) {
return value1.getType().subsumes(value2.getType());
}
}
private class StringsTester extends FeaturesTester<String, NString> {
List<NString> getFeatures(NNode node) {
return node.getStrings();
}
boolean valueSubsumption(String value1, String value2) {
return value1.equals(value2);
}
}
boolean subsumption(NNode node1, NNode node2) {
if (testing.getSet(node1).contains(node2)) {
return true;
}
if (subsumptions.getSet(node1).contains(node2)) {
return true;
}
boolean subsumption = false;
testing.add(node1, node2);
if (nodeSubsumption(node1, node2)) {
subsumption = true;
subsumptions.add(node1, node2);
}
testing.remove(node1, node2);
return subsumption;
}
private boolean nodeSubsumption(NNode node1, NNode node2) {
if (node1.instanceRef()) {
if (!node2.instanceRef()) {
return false;
}
return node1.getInstanceRef().equals(node2.getInstanceRef());
}
return typeSubsumption(node1, node2)
&& linksTester.subsumptions(node1, node2)
&& numbersTester.subsumptions(node1, node2)
&& stringsTester.subsumptions(node1, node2);
}
private boolean typeSubsumption(NNode node1, NNode node2) {
CFrame cFrame1 = node1.getCFrame();
CFrame cFrame2 = node2.getCFrame();
if (cFrame1 != null && cFrame2 != null) {
return cFrame1.subsumes(cFrame2);
}
return node2.getTypeDisjuncts().containsAll(node1.getTypeDisjuncts());
}
}
| 22.380392 | 80 | 0.705274 |
2471889fe14e1ac2d1a8db6913d90ce86ed2e371 | 996 | package io.reactivex.internal.disposables;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Cancellable;
import io.reactivex.plugins.RxJavaPlugins;
import java.util.concurrent.atomic.AtomicReference;
public final class CancellableDisposable extends AtomicReference<Cancellable> implements Disposable {
private static final long serialVersionUID = 5718521705281392066L;
public CancellableDisposable(Cancellable cancellable) {
super(cancellable);
}
public boolean isDisposed() {
return get() == null;
}
public void dispose() {
if (get() != null) {
Cancellable c = (Cancellable) getAndSet(null);
if (c != null) {
try {
c.cancel();
} catch (Exception ex) {
Exceptions.throwIfFatal(ex);
RxJavaPlugins.onError(ex);
}
}
}
}
}
| 29.294118 | 101 | 0.623494 |
22b04c4c554c5dd7d60567aa68f7bc1ec1cbcb1b | 6,796 | package com.soaer.mqtt;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.UUID;
import javax.net.ssl.SSLSocketFactory;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* keytool -importcert -trustcacerts -alias <aliasName> -file <ca>.crt -keystore ca_trust.keystore
* openssl pkcs12 -export -in <client>.crt -inkey <client>.key -name cli -out <client>.p12
* keytool -importkeystore -deststorepass <your password> -destkeystore <keystore> -srckeystore <client>.p12
* -srcstoretype PKCS12
* <p>
* mosquitto_sub -h test.mosquitto.org -p 8884 -t "topic111111" --cafile mosquitto.org.crt --cert client.crt --key
* client.key
* mosquitto_sub -h test.mosquitto.org -p 8883 -t "topic111111" --cafile mosquitto.org.crt
*
*
* Created by Sunny on 2018/10/24.
*/
public class MqttConnectionTest {
//无加密信道
private static String U0;
//双向加密信道
private static String U1;
//单向加密信道
private static String U2;
private static String CLIENT_ID;
//ca证书的keystore地址
private String caKeystorePath;
//client证书的keystore地址
private String clientKeystorePath;
private static String PASSWORD;
private static final String TLS_V_1_2 = "TLSv1.2";
/**
* 使用公共的mqtt服务器,证书可以在官方网站下载
*/
@Before
public void setUp() {
U0 = "tcp://test.mosquitto.org";
U1 = "ssl://test.mosquitto.org:8883";
U2 = "ssl://test.mosquitto.org:8884";
CLIENT_ID = "BaiduBceMQTTTest";
URL resPath = this.getClass().getResource("/");
caKeystorePath = resPath.getPath() + File.separator + "mqtt" + File.separator + "ca.keystore";
clientKeystorePath = resPath.getPath() + File.separator + "mqtt" + File.separator + "client.keystore";
PASSWORD = "11111111";
}
/**
* 单向认证测试
*
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws KeyManagementException
* @throws MqttException
*/
@Test
public void mqttSendTestWithTLS() throws IOException, CertificateException, NoSuchAlgorithmException,
KeyStoreException, KeyManagementException, MqttException, InterruptedException {
SSLSocketFactory factory = Mqtt.getFactory(readCaKeyStore());
Assert.assertNotNull(factory);
pubMessage(factory, U1);
}
/**
* 双向认证测试
*
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws KeyManagementException
* @throws MqttException
* @throws InterruptedException
* @throws UnrecoverableKeyException
*/
@Test
public void mqttSendTestWithClientTLS()
throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException,
KeyManagementException, MqttException, InterruptedException, UnrecoverableKeyException {
SSLSocketFactory factory = Mqtt.getFactory(readCaKeyStore(), readClientKeyStore(), PASSWORD);
Assert.assertNotNull(factory);
pubMessage(factory, U2);
}
public static class A implements MqttCallback {
public void connectionLost(Throwable throwable) {
}
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
}
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
}
public static class B implements IMqttActionListener {
public void onSuccess(IMqttToken iMqttToken) {
}
public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
}
}
public void pubMessage(SSLSocketFactory factory, String serverURI) throws MqttException, InterruptedException {
Mqtt connection = new Mqtt(serverURI, CLIENT_ID + UUID.randomUUID().toString(), null, null,
factory, new A(), new B());
connection.openConnection();
//测试发布需要先判断是否连接上远程MQTT Broker
int i = 10;
while (i > 0) {
if (connection.isConnected()) {
Message message = new Message();
message.setPayload("baidu test mqtt message".getBytes());
message.setQos(1);
message.setTopic("topic111111");
connection.publishMessage(message);
connection.publishMessage(message);
connection.publishMessage(message);
connection.publishMessage(message);
connection.publishMessage(message);
connection.publishMessage(message);
break;
}
Thread.sleep(2000);
i--;
}
}
/**
* 获取ca keystore文件
*
* @return
*/
private KeyStore readCaKeyStore() {
KeyStore keystore = null;
FileInputStream is = null;
try {
is = new FileInputStream(caKeystorePath);
keystore = KeyStore.getInstance("JKS");
String keypwd = PASSWORD;
keystore.load(is, keypwd.toCharArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return keystore;
}
/**
* 获取client keystore文件
*
* @return
*/
private KeyStore readClientKeyStore() {
KeyStore keystore = null;
FileInputStream is = null;
try {
is = new FileInputStream(clientKeystorePath);
keystore = KeyStore.getInstance("jks");
String keypwd = PASSWORD;
keystore.load(is, keypwd.toCharArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return keystore;
}
} | 30.890909 | 115 | 0.629488 |
51b26ecffa1b944e89e262dc52f8807bb18b4eb8 | 1,402 | package de.unistuttgart.ims.coref.annotator.action;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.Action;
import javax.swing.SwingUtilities;
import org.eclipse.collections.api.list.ImmutableList;
import org.eclipse.collections.impl.factory.Lists;
import org.kordamp.ikonli.materialdesign.MaterialDesign;
import de.unistuttgart.ims.coref.annotator.Annotator;
import de.unistuttgart.ims.coref.annotator.DocumentWindow;
import de.unistuttgart.ims.coref.annotator.Strings;
import de.unistuttgart.ims.coref.annotator.uima.MergeFilesPlugin;
public class FileMergeOpenAction extends IkonAction {
private static final long serialVersionUID = 1L;
public FileMergeOpenAction() {
super(Strings.ACTION_FILE_MERGE, MaterialDesign.MDI_SOURCE_MERGE);
putValue(Action.SHORT_DESCRIPTION, Annotator.getString(Strings.ACTION_FILE_MERGE_TOOLTIP));
}
@Override
public void actionPerformed(ActionEvent e) {
Annotator.app.fileOpenDialog(null, Annotator.app.getPluginManager().getDefaultIOPlugin(), true, files -> {
ImmutableList<File> fileList = Lists.immutable.of(files);
MergeFilesPlugin pl = new MergeFilesPlugin();
pl.setFiles(fileList);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
DocumentWindow dw = Annotator.app.open(fileList.getFirst(), pl, "");
dw.setFile(null);
}
});
}, o -> {
}, "");
}
}
| 29.208333 | 108 | 0.772468 |
9bef65d2e515e183226ece64e23019155e310ebc | 1,010 | // Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;
import java.io.Serializable;
import com.leansoft.nano.annotation.*;
import java.util.List;
import java.util.Date;
/**
*
* Defines the options available for an automated listing rule that
* keeps a minimum number of items on the site.
*
*/
public class SellingManagerAutoListMinActiveItemsType implements Serializable {
private static final long serialVersionUID = -1L;
@Element(name = "MinActiveItemCount")
@Order(value=0)
public Integer minActiveItemCount;
@Element(name = "ListTimeFrom")
@Order(value=1)
public Date listTimeFrom;
@Element(name = "ListTimeTo")
@Order(value=2)
public Date listTimeTo;
@Element(name = "SpacingIntervalInMinutes")
@Order(value=3)
public Integer spacingIntervalInMinutes;
@Element(name = "ListingHoldInventoryLevel")
@Order(value=4)
public Integer listingHoldInventoryLevel;
@AnyElement
@Order(value=5)
public List<Object> any;
} | 22.444444 | 79 | 0.744554 |
0a0cf21d67046b19ba5fbdc34c6c6dfbfce2cd76 | 1,512 | package com.github.seanyinx.testbed.spring;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import com.github.seanyinx.testbed.base.services.UserService;
import com.github.seanyinx.testbed.spring.domain.UserEntity;
import com.github.seanyinx.testbed.spring.infrastructure.UserRepo;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Session2_DatabaseTest {
@Autowired
private UserRepo userRepo;
@MockBean
private UserService userService;
@Test
public void shouldFindUserById() throws Exception {
Optional<UserEntity> user = userRepo.findById(1L);
assertThat(user).isPresent();
assertThat(user.get().getName()).isEqualTo("jack");
}
@Test
public void shouldDeleteUserById() throws Exception {
userRepo.deleteById(1L);
Optional<UserEntity> user = userRepo.findById(1L);
assertThat(user).isNotPresent();
}
@Test
public void shouldUpdateUserById() throws Exception {
userRepo.save(new UserEntity(1L, "mike"));
Optional<UserEntity> user = userRepo.findById(1L);
assertThat(user).isPresent();
assertThat(user.get().getId()).isOne();
assertThat(user.get().getName()).isEqualTo("mike");
}
}
| 27 | 66 | 0.76455 |
06b628ec1d59e2eb22ee1b7a51a418370e0e1e22 | 6,192 | /**
* @author alexanderweiss
* @date 19.11.2015
*/
package com.github.alexanderwe.bananaj.model.report;
import java.time.LocalDateTime;
import org.json.JSONObject;
import com.github.alexanderwe.bananaj.model.MailchimpObject;
import com.github.alexanderwe.bananaj.model.campaign.Bounce;
import com.github.alexanderwe.bananaj.model.campaign.CampaignType;
import com.github.alexanderwe.bananaj.utils.DateConverter;
/**
* Object for representing a report of a campaign
* @author alexanderweiss
*
*/
public class Report extends MailchimpObject {
private String campaignTitle;
private CampaignType type;
private String listId;
private boolean listIsActive;
private String listName;
private String subjectLine;
private String previewText;
private int emailsSent;
private int abuseReport;
private int unsubscribed;
private LocalDateTime sendtime;
//private String rss_last_send;
private Bounce bounces;
private Forward forwards;
private Open opens;
private Click clicks;
private FacebookLikes facebookLikes;
private IndustryStats industryStats;
private ReportListStats listStats;
//private Object ab_split;
//private List<Object> timewarp;
//private List<Object> timeseries;
//private Object share_report;
private Ecommerce ecommerce;
//private Object delivery_status;
public Report(JSONObject jsonObj) {
super(jsonObj.getString("id"), null);
campaignTitle = jsonObj.getString("campaign_title");
type = CampaignType.valueOf(jsonObj.getString("type").toUpperCase());
listId = jsonObj.getString("list_id");
listIsActive = jsonObj.getBoolean("list_is_active");
listName = jsonObj.getString("list_name");
subjectLine = jsonObj.getString("subject_line");
previewText = jsonObj.getString("preview_text");
emailsSent = jsonObj.getInt("emails_sent");
abuseReport = jsonObj.getInt("abuse_reports");
unsubscribed = jsonObj.getInt("unsubscribed");
sendtime = DateConverter.getInstance().createDateFromISO8601(jsonObj.getString("send_time"));
bounces = new Bounce(jsonObj.getJSONObject("bounces"));
forwards = new Forward(jsonObj.getJSONObject("forwards"));
clicks = new Click(jsonObj.getJSONObject("clicks"));
opens = new Open(jsonObj.getJSONObject("opens"));
if (jsonObj.has("facebook_likes")) {
facebookLikes = new FacebookLikes(jsonObj.getJSONObject("facebook_likes"));
}
if (jsonObj.has("industry_stats")) {
industryStats = new IndustryStats(jsonObj.getJSONObject("industry_stats"));
}
if (jsonObj.has("list_stats")) {
this.listStats = new ReportListStats(jsonObj.getJSONObject("list_stats"));
}
if (jsonObj.has("ecommerce")) {
ecommerce = new Ecommerce(jsonObj.getJSONObject("ecommerce"));
}
}
/**
* @return The total number of emails sent for the campaign.
*/
public int getEmailsSent() {
return emailsSent;
}
/**
* @return The title of the campaign.
*/
public String getCampaignTitle() {
return campaignTitle;
}
/**
* @return The number of abuse reports generated for this campaign.
*/
public int getAbuseReport() {
return abuseReport;
}
/**
* @return The total number of unsubscribed members for this campaign.
*/
public int getUnsubscribed() {
return unsubscribed;
}
/**
* @return The date and time a campaign was sent.
*/
public LocalDateTime getSendTime() {
return sendtime;
}
/**
* @return The bounce summary for the campaign.
*/
public Bounce getBounces() {
return bounces;
}
/**
* @return The forwards and forward activity for the campaign.
*/
public Forward getForwards() {
return forwards;
}
/**
* @return The click activity for the campaign.
*/
public Click getClicks() {
return clicks;
}
/**
* @return The open activity for the campaign.
*/
public Open getOpens() {
return opens;
}
/**
* @return Campaign engagement on Facebook.
*/
public FacebookLikes getFacebookLikes() {
return facebookLikes;
}
/**
* @return The average campaign statistics for your industry.
*/
public IndustryStats getIndustryStats() {
return industryStats;
}
/**
* @return The average campaign statistics for your list. Null if it hasn't been calculated it yet for the list.
*/
public ReportListStats getListStats() {
return listStats;
}
/**
* @return E-Commerce stats for a campaign.
*/
public Ecommerce getEcommerce() {
return ecommerce;
}
/**
* @return The type of campaign (regular, plain-text, ab_split, rss, automation, variate, or auto).
*/
public CampaignType getType() {
return type;
}
/**
* @return The unique list id.
*/
public String getListId() {
return listId;
}
/**
* @return The status of the list used, namely if it's deleted or disabled.
*/
public boolean isListIsActive() {
return listIsActive;
}
/**
* @return The name of the list.
*/
public String getListName() {
return listName;
}
/**
* @return The subject line for the campaign.
*/
public String getSubjectLine() {
return subjectLine;
}
/**
* @return The preview text for the campaign.
*/
public String getPreviewText() {
return previewText;
}
/**
* @return The date and time a campaign was sent
*/
public LocalDateTime getSendtime() {
return sendtime;
}
@Override
public String toString(){
return "Report of campaign: " + getId() + " " + this.getCampaignTitle() + System.lineSeparator() +
"Total emails sent: " + getEmailsSent() + System.lineSeparator() +
"Total abuse reports: " + getAbuseReport() + System.lineSeparator() +
"Total unsubscribed: " + getUnsubscribed() + System.lineSeparator() +
"Time sent: " + getSendTime() + System.lineSeparator() +
getForwards().toString() + System.lineSeparator() +
getOpens().toString() + System.lineSeparator() +
getBounces().toString() + System.lineSeparator() +
getClicks().toString() + System.lineSeparator() +
(getFacebookLikes() != null ? getFacebookLikes().toString() + System.lineSeparator() : "") +
(getIndustryStats() != null ? getIndustryStats().toString() + System.lineSeparator() : "") +
(getListStats() != null ? getListStats().toString() + System.lineSeparator() : "") +
(getEcommerce() != null ? getEcommerce().toString() : "");
}
}
| 26.016807 | 113 | 0.707526 |
cd407796b4f927a2f07f1fc67f59c5be8c7a1482 | 4,150 | package jetbrains.mps.lang.quotation.scripts;
/*Generated by MPS */
import jetbrains.mps.lang.script.runtime.BaseMigrationScript;
import jetbrains.mps.lang.script.runtime.AbstractMigrationRefactoring;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.lang.core.behavior.PropertyAttribute__BehaviorDescriptor;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.mps.openapi.model.SNodeReference;
import org.jetbrains.mps.openapi.persistence.PersistenceFacade;
import org.jetbrains.mps.openapi.language.SInterfaceConcept;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import org.jetbrains.mps.openapi.language.SConcept;
import org.jetbrains.mps.openapi.language.SProperty;
public final class MigrateEnumPropertyAttributes_Antiquotation_MigrationScript extends BaseMigrationScript {
public MigrateEnumPropertyAttributes_Antiquotation_MigrationScript() {
super("Manual migration for enum property attributes");
this.addRefactoring(new AbstractMigrationRefactoring() {
@Override
public String getName() {
return "Migrate by hand (some type errors have to be fixed manually)";
}
@Override
public String getAdditionalInfo() {
return "Migrate by hand (some type errors have to be fixed manually)";
}
@Override
public SAbstractConcept getApplicableConcept() {
return CONCEPTS.StringToTypedValueMigrationInfo$em;
}
@Override
public boolean isApplicableInstanceNode(SNode node) {
return !(SPropertyOperations.getBoolean(node, PROPS.stringValueMigrated$2KQs)) || SNodeOperations.isInstanceOf(SNodeOperations.getParent(PropertyAttribute__BehaviorDescriptor.getPropertyDeclaration_id121FNPYBLc9.invoke(SNodeOperations.as(node, CONCEPTS.PropertyAttribute$Gb))), CONCEPTS.EnumPropertyMigrationInfo$O3);
}
@Override
public void doUpdateInstanceNode(SNode node) {
SPropertyOperations.assign(node, PROPS.stringValueMigrated$2KQs, true);
SNode propAttribute = SNodeOperations.as(node, CONCEPTS.PropertyAttribute$Gb);
if (SNodeOperations.isInstanceOf(SNodeOperations.getParent(PropertyAttribute__BehaviorDescriptor.getPropertyDeclaration_id121FNPYBLc9.invoke(propAttribute)), CONCEPTS.EnumPropertyMigrationInfo$O3)) {
SPropertyOperations.assign(propAttribute, PROPS.enumUsageMigrated$64YW, true);
}
}
@Override
public boolean isShowAsIntention() {
return true;
}
});
}
@Nullable
@Override
public SNodeReference getScriptNode() {
return PersistenceFacade.getInstance().createNodeReference("r:d6a9a174-4d02-4a9a-af5a-24f4aae65f24(jetbrains.mps.lang.quotation.scripts)/979583239732347490");
}
private static final class CONCEPTS {
/*package*/ static final SInterfaceConcept StringToTypedValueMigrationInfo$em = MetaAdapterFactory.getInterfaceConcept(0x3a13115c633c4c5cL, 0xbbcc75c4219e9555L, 0x384b195d1ed21709L, "jetbrains.mps.lang.quotation.structure.StringToTypedValueMigrationInfo");
/*package*/ static final SConcept PropertyAttribute$Gb = MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da56L, "jetbrains.mps.lang.core.structure.PropertyAttribute");
/*package*/ static final SConcept EnumPropertyMigrationInfo$O3 = MetaAdapterFactory.getConcept(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x5a14f1035942a5abL, "jetbrains.mps.lang.structure.structure.EnumPropertyMigrationInfo");
}
private static final class PROPS {
/*package*/ static final SProperty stringValueMigrated$2KQs = MetaAdapterFactory.getProperty(0x3a13115c633c4c5cL, 0xbbcc75c4219e9555L, 0x384b195d1ed21709L, 0x1e2950a3c41b89ecL, "stringValueMigrated");
/*package*/ static final SProperty enumUsageMigrated$64YW = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da56L, 0x1081af3d7e9d6a2fL, "enumUsageMigrated");
}
}
| 56.849315 | 325 | 0.801446 |
dc5c14e502237d79b953c6844a9cb8f83afc2ee7 | 164 | package software.amazon.athena.workgroup;
class Configuration extends BaseConfiguration {
public Configuration() {
super("aws-athena-workgroup.json");
}
}
| 20.5 | 47 | 0.756098 |
9608b1ad5428a26aa03916775474bb58aafff586 | 1,330 | package test.modules.main;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class FutureTest {
public static void main(String[] args) {
completableTestBasic();
completableTestApply();
}
private static void completableTestApply() {
CompletableFuture<String> loadString = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (Exception e) {
System.err.println(e);
}
return "The String";
});
try {
System.out.println("Waiting for loadString...");
String s = loadString.getNow(null);
System.out.println("Load string: " + s);
s = loadString.thenApplyAsync(t -> {
System.out.println("The string was : " + t);
return "apply : " + t;
}).get();
System.out.println("Load string: " + s);
} catch (Exception e) {
System.err.println(e);
}
}
private static void completableTestBasic() {
CompletableFuture<Void> sleep = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (Exception e) {
System.err.println(e);
}
return;
});
try {
System.out.println("Waiting for sleep...");
sleep.get();
System.out.println("Sleep over");
} catch (Exception e) {
System.err.println(e);
}
}
}
| 24.181818 | 79 | 0.621053 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.